From 3b2dbd3650ea812f00b4d1a9e4e18a5bc7420ab5 Mon Sep 17 00:00:00 2001 From: KxmischesDomi Date: Thu, 10 Feb 2022 18:22:00 +0100 Subject: [PATCH 001/119] Add Quiz Challenge --- language/files/de.json | 28 + language/files/en.json | 28 + .../challenge/quiz/QuizChallenge.java | 571 ++++++++++++++++++ .../challenges/ChallengeLoader.java | 1 + .../plugin/utils/misc/TriFunction.java | 16 + plugin/src/main/resources/plugin.yml | 3 + 6 files changed, 647 insertions(+) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriFunction.java diff --git a/language/files/de.json b/language/files/de.json index cc492c4e7..fb7eee23a 100644 --- a/language/files/de.json +++ b/language/files/de.json @@ -208,6 +208,34 @@ "Was geht denn jetzt ab" ], + "quiz-right-answer": "§e{0} §7ist die §arichtige §7Antwort!", + "quiz-right-answer-other": "§e{0} §7hat die Frage §arichtig §7beantwortet", + + "quiz-wrong-answer": "§e{0} §7ist eine §cfalsche §7Antwort!", + "quiz-wrong-answer-other": "§e{0} §7hat die Frage §cfalsch beantwortet", + "quiz-time-up": "Die Zeit ist §cabgelaufen§7!", + "quiz-cancel": "Die Frage wurde §cabgebrochen§7!", + + "quiz-right-answer-was": "Die richtige Antwort lautete: §e{0}", + "quiz-right-answer-was-multiple": "Die richtigen Antworten lauteten: §e{0}", + + "quiz-question-often-have": "Wie oft hast du §e{0}§7{1}?", + "quiz-question-often-be": "Wie oft bist du §e{0}§7{1}?", + "quiz-question-far-be": "Wie weit bist du {0}?", + "quiz-question-most": "Was hast du von diesen {1} am meisten {0}?", + "quiz-question-damage-have": "Wie viel Schaden hast du {0}", + "quiz-question-damage-taken-have": "Wie viel Schaden hast du durch {0}", + + "quiz-verb-traveled": "gelaufen", + "quiz-verb-jumped": "gesprungen", + "quiz-verb-sneaked": "geschlichen", + "quiz-verb-killed": "getötet", + "quiz-verb-damaged": "zugefügt", + "quiz-verb-broken": "abgebaut", + "quiz-verb-placed": "platziert", + "quiz-verb-dropped": "gedropped", + "quiz-verb-suffered": "erlitten", + "bossbar-timer-paused": "§8» §7Der Timer ist §cnoch pausiert", "bossbar-mob-transformation": "§8» §7Letzer Mob §8§l┃ §a{0}", "bossbar-biome-time-left": "§8» §7Zeit übrig in §e{0} §8§l┃ §a{1}s", diff --git a/language/files/en.json b/language/files/en.json index 42100b992..3c2012514 100644 --- a/language/files/en.json +++ b/language/files/en.json @@ -209,6 +209,34 @@ "What's going on now?!" ], + "quiz-right-answer": "§e{0} §7is the §aright §7answer!", + "quiz-right-answer-other": "§e{0} §7answered the question §acorrectly§7!", + + "quiz-wrong-answer": "§e{0} §7is a §cwrong §7answer!", + "quiz-wrong-answer-other": "§e{0} §7answered the question §cincorrectly§7!", + "quiz-time-up": "The time is §cup§7!", + "quiz-cancel": "The question was §ccancelled§7!", + + "quiz-right-answer-was": "The right answer was: §e{0}", + "quiz-right-answer-was-multiple": "the right answers were: §e{0}", + + "quiz-question-often-have": "How often have you{1} §e{0}?", + "quiz-question-often-be": "How often did you{1} §e{0}?", + "quiz-question-far-be": "Wie far did you {0}?", + "quiz-question-most": "What do you have the most of these {1} {0}?", + "quiz-question-damage-have": "How much damage have you {0}", + "quiz-question-damage-taken-have": "How much damage have you taken from {0}", + + "quiz-verb-traveled": "walk", + "quiz-verb-jumped": "jump", + "quiz-verb-sneaked": "sneak", + "quiz-verb-killed": "killed", + "quiz-verb-damaged": "hurt", + "quiz-verb-broken": "broken", + "quiz-verb-placed": "placed", + "quiz-verb-dropped": "dropped", + "quiz-verb-suffered": "suffered", + "bossbar-timer-paused": "§8» §7The timer is §cstill paused", "bossbar-mob-transformation": "§8» §7Last mob §8§l┃ §a{0}", "bossbar-biome-time-left": "§8» §7Time left in §e{0} §8§l┃ §a{1}s", diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java new file mode 100644 index 000000000..da10aaf5f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -0,0 +1,571 @@ +package net.codingarea.challenges.plugin.challenges.implementation.challenge.quiz; + +import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.anweisen.utilities.common.collection.IRandom; +import net.anweisen.utilities.common.config.Document; +import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.quiz.QuizChallenge.IQuestion.Question; +import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; +import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; +import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; +import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.misc.BlockUtils; +import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.challenges.plugin.utils.misc.TriFunction; +import org.bukkit.Material; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeInstance; +import org.bukkit.boss.BarColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerToggleSneakEvent; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; +import java.util.Map.Entry; +import java.util.stream.Collectors; + +/** + * @author KxmischesDomi | https://github.com/kxmischesdomi + * @since 2.0 + */ +public class QuizChallenge extends TimedChallenge implements PlayerCommand, TabCompleter { + + private static QuizChallenge instance; + + private final Prefix prefix = Prefix.forName("quiz", "§6Quiz"); + private final IRandom random = IRandom.create(); + + private IQuestion currentQuestion; + private Player currentQuestionedPlayer; + private int timeLeft; + + public QuizChallenge() { + super(MenuType.CHALLENGES, 1, 20, 5); + instance = this; + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BARRIER); + } + + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + if (currentQuestion == null) { + bossbar.setColor(BarColor.YELLOW); + bossbar.setTitle(Message.forName("bossbar-quiz-waiting").asString()); + return; + } + String time = "§e" + timeLeft + " §7" + (timeLeft == 1 ? Message.forName("second").asString() : Message.forName("seconds").asString()); + if (currentQuestionedPlayer != player) { + bossbar.setColor(BarColor.GREEN); + bossbar.setTitle(Message.forName("bossbar-quiz-question-other").asString(time, NameHelper.getName(currentQuestionedPlayer))); + return; + } + bossbar.setColor(BarColor.RED); + bossbar.setTitle(Message.forName("bossbar-quiz-question").asString(time)); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return ChallengeHelper.getTimeRangeSettingsDescription(this, 60 * 3, 60); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 * 3 - 60, getValue() * 60 * 3 + 60); + } + + @Override + protected int getSecondsUntilNextActivation() { + return random.around(getValue() * 60 * 3, 60); + } + + private void broadcastMessage(@Nonnull String questionedPlayerMessage, @Nonnull String othersMessage, Object... args) { + broadcast(player1 -> { + if (currentQuestionedPlayer == player1) { + Message.forName(questionedPlayerMessage).send(player1, prefix, args); + } else { + Message.forName(othersMessage).send(player1, prefix, NameHelper.getName(currentQuestionedPlayer)); + } + }); + } + + @Override + protected void onTimeActivation() { + + SavedStatistic[] statistics = SavedStatistic.values(); + SavedStatistic statistic = statistics[random.nextInt(statistics.length)]; + + IQuestion[] questions = statistic.getQuestions(); + currentQuestion = questions[random.nextInt(questions.length)]; + + List ingamePlayers = ChallengeHelper.getIngamePlayers(); + currentQuestionedPlayer = ingamePlayers.get(random.nextInt(ingamePlayers.size())); + + List answers = currentQuestion.createAnswers(statistic, currentQuestionedPlayer); + if (answers.isEmpty()) { + onTimeActivation(); + return; + } + timeLeft = 60; + + bossbar.update(); + } + + @ScheduledTask(ticks = 20, async = false) + public void onSecond() { + if (currentQuestion == null) return; + if (!currentQuestionedPlayer.isOnline() || ignorePlayer(currentQuestionedPlayer)) { + Message.forName("quiz-cancel").broadcast(prefix); + cancelQuestion(); + } + + timeLeft--; + + if (timeLeft <= 0) { + Message.forName("quiz-time-up").broadcast(prefix); + cancelQuestion(); + } + + bossbar.update(); + } + + private void cancelQuestion() { + restartTimer(); + + List rightAnswers = currentQuestion.getRightAnswers(); + Message.forName("quiz-right-answer-was" + (rightAnswers.size() != 1 ? "-multiple" : "")).send(currentQuestionedPlayer, prefix, StringUtils.getArrayAsString(rightAnswers.toArray(new String[0]), "§7, §e")); + SoundSample.BREAK.play(currentQuestionedPlayer); + + currentQuestion = null; + AttributeInstance attribute = currentQuestionedPlayer.getAttribute(Attribute.GENERIC_MAX_HEALTH); + + if (attribute.getBaseValue() == 2) { + kill(currentQuestionedPlayer); + attribute.setBaseValue(20); + return; + } + + attribute.setBaseValue(attribute.getBaseValue() - 2); + } + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + + if (currentQuestion == null || currentQuestionedPlayer != player) { + // TODO: REMOVE RESTART TIMER HERE + restartTimer(3); + SoundSample.BASS_OFF.play(player); + return; + } + + if (args.length == 0) { + Message.forName("syntax").send(player, prefix, "guess "); + return; + } + + String answer = StringUtils.getArrayAsString(args, " "); + if (!currentQuestion.isRightAnswer(answer)) { + broadcastMessage("quiz-wrong-answer", "quiz-wrong-answer-other", answer); + cancelQuestion(); + bossbar.update(); + return; + } + + broadcastMessage("quiz-right-answer", "quiz-right-answer-other", answer); + SoundSample.LEVEL_UP.play(player); + currentQuestion = null; + bossbar.update(); + restartTimer(); + } + + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String s, @Nonnull String[] strings) { + return new ArrayList<>(); + } + + interface IQuestion { + + List createAnswers(@Nonnull SavedStatistic statistic, @Nonnull Player player); + List getRightAnswers(); + boolean isRightAnswer(@Nonnull String answer); + + static void sendMessage(@Nonnull String question, @Nonnull List answers) { + Player player = instance.currentQuestionedPlayer; + + player.sendMessage(" "); + player.sendMessage("§e" + question); + player.sendMessage(" "); + + for (String answer : answers) { + player.sendMessage("§8-> §e" + answer); + } + + player.sendMessage(" "); + } + + class Question implements IQuestion { + + private final TriFunction, List> questionCreator; + private List currentRightAnswers; + + public Question(TriFunction, List> questionCreator) { + this.questionCreator = questionCreator; + } + + @Override + public List createAnswers(@Nonnull SavedStatistic statistic, @Nonnull Player player) { + ArrayList answers = new ArrayList<>(); + currentRightAnswers = questionCreator.apply(statistic, player, answers); + return answers; + } + + @Override + public boolean isRightAnswer(@Nonnull String answer) { + return currentRightAnswers != null && currentRightAnswers.contains(answer); + } + + @Override + public List getRightAnswers() { + return currentRightAnswers; + } + + } + + } + + private interface SavedStatistic { + + IntegerStatistic BLOCKS_MOVED = new IntegerStatistic("blocks-traveled", "traveled", "far", "be"); + IntegerStatistic JUMPED = new IntegerStatistic("jumped", "jumped", "often", "be"); + IntegerStatistic SNEAKED = new IntegerStatistic("sneaked", "sneaked", "often", "be"); + DocumentCountStatistic MOB_KILLED = new DocumentCountStatistic("mob-killed", "killed", "often", "have"); + DocumentCountStatistic MOB_DAMAGED = new DocumentCountStatistic("mobs-damaged", "damaged", "damage", "have"); + DocumentCountStatistic BLOCKS_PLACED = new DocumentCountStatistic("blocks-placed", "placed", "often", "have"); + DocumentCountStatistic BLOCKS_DESTROYED = new DocumentCountStatistic("blocks-destroyed", "broken", "often", "have"); + DocumentCountStatistic ITEMS_DROPPED = new DocumentCountStatistic("items-dropped", "dropped", "often", "have"); + DocumentCountStatistic DAMAGE_TAKEN = new DocumentCountStatistic("damage-taken", "suffered", "damage-taken", "have"); + + String getKey(); + String getVerb(); + String getQuestionVerb(); + String getQuestionSuffix(); + IQuestion[] getQuestions(); + + static SavedStatistic[] values() { + return new SavedStatistic[] { BLOCKS_MOVED, JUMPED, SNEAKED, MOB_DAMAGED, MOB_KILLED, BLOCKS_PLACED, BLOCKS_DESTROYED, ITEMS_DROPPED, DAMAGE_TAKEN }; + } + + default Message getVerbMessage() { + return Message.forName("quiz-verb-" + getVerb()); + } + + class IntegerStatistic implements SavedStatistic { + + private final static Question INTEGER_QUESTION = new Question((statistic, player, answers) -> { + IntegerStatistic integerStatistic = (IntegerStatistic) statistic; + int rightAnswer = integerStatistic.getStatistic(player); + + for (int i = rightAnswer; i < rightAnswer + 4; i++) { + answers.add(i + ""); + } + + IQuestion.sendMessage(Message.forName("quiz-question-" + statistic.getQuestionSuffix() + "-" + statistic.getQuestionVerb()).asString(statistic.getVerbMessage(), ""), answers); + + return Collections.singletonList(rightAnswer + ""); + }); + + private final String key; + private final String questionVerb; + private final String questionSuffix; + private final String verb; + + public IntegerStatistic(String key, String verbMessage, String questionSuffix, String questionVerb) { + this.key = key; + this.verb = verbMessage; + this.questionSuffix = questionSuffix; + this.questionVerb = questionVerb; + } + + @Override + public String getKey() { + return key; + } + + @Override + public String getVerb() { + return verb; + } + + @Override + public String getQuestionVerb() { + return questionVerb; + } + + @Override + public String getQuestionSuffix() { + return questionSuffix; + } + + @Override + public IQuestion[] getQuestions() { + return new Question[] { INTEGER_QUESTION }; + } + + public void increaseStatistic(@Nonnull Player player) { + increaseStatistic(player, 1); + } + + public void increaseStatistic(@Nonnull Player player, int amount) { + instance.getPlayerData(player).set(key, getStatistic(player) + amount); + } + + public int getStatistic(@Nonnull Player player) { + return instance.getPlayerData(player).getInt(key); + } + + } + + abstract class DocumentStatistic implements SavedStatistic { + + private final String key; + + public DocumentStatistic(String key) { + this.key = key; + } + + @Override + public String getKey() { + return key; + } + + public Document getDocument(@Nonnull Player player) { + return instance.getPlayerData(player).getDocument(key); + } + + } + + class DocumentCountStatistic extends DocumentStatistic { + + private final static Question CHOOSE_QUESTION = new Question((statistic, player, answers) -> { + DocumentCountStatistic documentCountStatistic = (DocumentCountStatistic) statistic; + Document document = documentCountStatistic.getDocument(player); + + Map entries = new HashMap<>(); + + ArrayList keysLeft = new ArrayList<>(document.keys()); + + if (keysLeft.isEmpty() || keysLeft.size() == 1) return null; + + Collections.shuffle(keysLeft); + for (byte i = 0; i < 4; i++) { + if (keysLeft.isEmpty()) break; + String key = keysLeft.remove(0); + entries.put(key, documentCountStatistic.getStatistic(player, key)); + } + + answers.addAll(entries.keySet()); + + double highestValue = -1; + List highestEntries = new ArrayList<>(); + + for (Entry entry : entries.entrySet()) { + if (highestValue == -1) { + highestEntries.add(entry.getKey()); + highestValue = entry.getValue(); + } else if (highestValue == entry.getValue()) { + highestEntries.add(entry.getKey()); + } else if (highestValue < entry.getValue()) { + highestEntries.clear(); + highestEntries.add(entry.getKey()); + highestValue = entry.getValue(); + } + } + + + List newAnswers = answers.stream().map(StringUtils::getEnumName).collect(Collectors.toList()); + answers.clear(); + answers.addAll(newAnswers); + + highestEntries = highestEntries.stream().map(StringUtils::getEnumName).collect(Collectors.toList()); + + IQuestion.sendMessage(Message.forName("quiz-question-most").asString(statistic.getVerbMessage(), answers.size()), answers); + + return highestEntries; + }), + COUNT_QUESTIONS = new Question((statistic, player, answers) -> { + DocumentCountStatistic documentCountStatistic = (DocumentCountStatistic) statistic; + Document document = documentCountStatistic.getDocument(player); + + ArrayList keys = new ArrayList<>(document.keys()); + + if (keys.isEmpty()) { + return null; + } + + String key = keys.get(instance.random.nextInt(keys.size())); + double rightAnswer = documentCountStatistic.getStatistic(player, key); + + if (rightAnswer % 1 == 0) { + rightAnswer = (int) rightAnswer; + } + + for (double i = rightAnswer; i < rightAnswer + 4; i++) { + answers.add(i + ""); + } + + IQuestion.sendMessage(Message.forName("quiz-question-" + statistic.getQuestionSuffix() + "-" + statistic.getQuestionVerb()).asString(StringUtils.getEnumName(key), " " + statistic.getVerbMessage().asString()), answers); + + return new ArrayList<>(Collections.singleton(rightAnswer + "")); + }); + + private final String verb; + private final String questionSuffix; + private final String questionVerb; + + public DocumentCountStatistic(String key, String verbMessage, String questionSuffix, String questionVerb) { + super(key); + this.verb = verbMessage; + this.questionSuffix = questionSuffix; + this.questionVerb = questionVerb; + } + + public void increaseStatistic(@Nonnull Player player, @Nonnull String key) { + increaseStatistic(player, key, 1); + } + + public void increaseStatistic(@Nonnull Player player, @Nonnull String key, double amount) { + getDocument(player).set(key, getStatistic(player, key) + amount); + } + + public double getStatistic(@Nonnull Player player, @Nonnull String key) { + return getDocument(player).getDouble(key); + } + + @Override + public String getVerb() { + return verb; + } + + @Override + public String getQuestionVerb() { + return questionVerb; + } + + @Override + public String getQuestionSuffix() { + return questionSuffix; + } + + @Override + public IQuestion[] getQuestions() { + return new IQuestion[] { CHOOSE_QUESTION, COUNT_QUESTIONS }; + } + + } + + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onJump(@Nonnull PlayerJumpEvent event) { + if (!shouldExecuteEffect()) return; + if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; + SavedStatistic.JUMPED.increaseStatistic(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onJump(@Nonnull PlayerToggleSneakEvent event) { + if (!shouldExecuteEffect()) return; + if (!event.isSneaking()) return; + if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; + SavedStatistic.SNEAKED.increaseStatistic(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onEntityKill(@Nonnull EntityDamageByEntityEvent event) { + if (!shouldExecuteEffect()) return; + + if (!(event.getDamager() instanceof Player)) return; + Player player = (Player) event.getDamager(); + if (ignorePlayer(player)) return; + + if (!(event.getEntity() instanceof LivingEntity)) return; + + SavedStatistic.MOB_DAMAGED.increaseStatistic(player, event.getEntity().getType().name(), ChallengeHelper.getFinalDamage(event)); + + LivingEntity entity = (LivingEntity) event.getEntity(); + if (entity.getHealth() - ChallengeHelper.getFinalDamage(event) > 0) return; + + SavedStatistic.MOB_KILLED.increaseStatistic(player, event.getEntity().getType().name()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + SavedStatistic.BLOCKS_PLACED.increaseStatistic(event.getPlayer(), event.getBlockPlaced().getType().name()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + SavedStatistic.BLOCKS_DESTROYED.increaseStatistic(event.getPlayer(), event.getBlock().getType().name()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + if (BlockUtils.isSameBlockIgnoreHeight(event.getFrom(), event.getTo())) return; + SavedStatistic.BLOCKS_MOVED.increaseStatistic(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(@Nonnull PlayerDropItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + SavedStatistic.ITEMS_DROPPED.increaseStatistic(event.getPlayer(), event.getItemDrop().getItemStack().getType().name()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(@Nonnull EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return;; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + SavedStatistic.DAMAGE_TAKEN.increaseStatistic(player, event.getCause().name(), ChallengeHelper.getFinalDamage(event)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java index 831a1b51f..c5ef2c036 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java @@ -153,6 +153,7 @@ public void load() { register(FoodLaunchChallenge.class); register(UncraftItemsChallenge.class); + registerWithCommand(QuizChallenge.class, "guess"); // Goal register(KillEnderDragonGoal.class); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriFunction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriFunction.java new file mode 100644 index 000000000..88021f775 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriFunction.java @@ -0,0 +1,16 @@ +package net.codingarea.challenges.plugin.utils.misc; + +import java.util.Objects; +import java.util.function.Function; + +@FunctionalInterface +public interface TriFunction { + + R apply(A a, B b, C c); + + default TriFunction andThen(Function after) { + Objects.requireNonNull(after); + return (A a, B b, C c) -> after.apply(apply(a, b, c)); + } + +} \ No newline at end of file diff --git a/plugin/src/main/resources/plugin.yml b/plugin/src/main/resources/plugin.yml index f2294fcaf..5cc584077 100644 --- a/plugin/src/main/resources/plugin.yml +++ b/plugin/src/main/resources/plugin.yml @@ -187,3 +187,6 @@ commands: openmissingitems: usage: "/openmissingitems" description: "Reopens the missing items inventory" + guess: + usage: "/guess " + description: "Used to guess at quiz challenge" From 3fe98ae3db2a2e2a4e7276bb34a0b9b574b8ecd7 Mon Sep 17 00:00:00 2001 From: KxmischesDomi Date: Wed, 16 Feb 2022 18:06:45 +0100 Subject: [PATCH 002/119] Fix some minor question translation issues --- language/files/de.json | 6 +++-- .../challenge/quiz/QuizChallenge.java | 26 +++++++++++-------- .../challenges/ChallengeLoader.java | 1 + 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/language/files/de.json b/language/files/de.json index fb7eee23a..abad936c4 100644 --- a/language/files/de.json +++ b/language/files/de.json @@ -208,6 +208,8 @@ "Was geht denn jetzt ab" ], + "quiz-how-to": "Schreibe deine Antwort mit §e/guess ", + "quiz-right-answer": "§e{0} §7ist die §arichtige §7Antwort!", "quiz-right-answer-other": "§e{0} §7hat die Frage §arichtig §7beantwortet", @@ -223,8 +225,8 @@ "quiz-question-often-be": "Wie oft bist du §e{0}§7{1}?", "quiz-question-far-be": "Wie weit bist du {0}?", "quiz-question-most": "Was hast du von diesen {1} am meisten {0}?", - "quiz-question-damage-have": "Wie viel Schaden hast du {0}", - "quiz-question-damage-taken-have": "Wie viel Schaden hast du durch {0}", + "quiz-question-damage-have": "Wie viel Schaden hast du {0}{1}?", + "quiz-question-damage-taken-have": "Wie viel Schaden hast du durch {0}{1}?", "quiz-verb-traveled": "gelaufen", "quiz-verb-jumped": "gesprungen", diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index da10aaf5f..a6ab3907d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.quiz; import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; import net.anweisen.utilities.common.collection.IRandom; import net.anweisen.utilities.common.config.Document; import net.anweisen.utilities.common.misc.StringUtils; @@ -252,7 +253,14 @@ public List createAnswers(@Nonnull SavedStatistic statistic, @Nonnull Pl @Override public boolean isRightAnswer(@Nonnull String answer) { - return currentRightAnswers != null && currentRightAnswers.contains(answer); + if (currentRightAnswers == null) return false; + + for (String currentRightAnswer : currentRightAnswers) { + if (currentRightAnswer.equalsIgnoreCase(answer)) { + return true; + } + } + return false; } @Override @@ -412,15 +420,14 @@ class DocumentCountStatistic extends DocumentStatistic { } } - List newAnswers = answers.stream().map(StringUtils::getEnumName).collect(Collectors.toList()); answers.clear(); answers.addAll(newAnswers); - highestEntries = highestEntries.stream().map(StringUtils::getEnumName).collect(Collectors.toList()); - IQuestion.sendMessage(Message.forName("quiz-question-most").asString(statistic.getVerbMessage(), answers.size()), answers); + highestEntries = highestEntries.stream().map(StringUtils::getEnumName).collect(Collectors.toList()); + return highestEntries; }), COUNT_QUESTIONS = new Question((statistic, player, answers) -> { @@ -434,13 +441,9 @@ class DocumentCountStatistic extends DocumentStatistic { } String key = keys.get(instance.random.nextInt(keys.size())); - double rightAnswer = documentCountStatistic.getStatistic(player, key); - - if (rightAnswer % 1 == 0) { - rightAnswer = (int) rightAnswer; - } + int rightAnswer = (int) documentCountStatistic.getStatistic(player, key); - for (double i = rightAnswer; i < rightAnswer + 4; i++) { + for (int i = rightAnswer; i < rightAnswer + 4; i++) { answers.add(i + ""); } @@ -536,10 +539,11 @@ public void onBlockPlace(@Nonnull BlockPlaceEvent event) { SavedStatistic.BLOCKS_PLACED.increaseStatistic(event.getPlayer(), event.getBlockPlaced().getType().name()); } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onBlockBreak(@Nonnull BlockBreakEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; + if (BukkitReflectionUtils.isAir(event.getBlock().getType())) return; SavedStatistic.BLOCKS_DESTROYED.increaseStatistic(event.getPlayer(), event.getBlock().getType().name()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java index c5ef2c036..6f4d88ff0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.implementation.challenge.*; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.quiz.QuizChallenge; import net.codingarea.challenges.plugin.challenges.implementation.goal.*; import net.codingarea.challenges.plugin.challenges.implementation.setting.*; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; From c44f2d68c5e1820936b1eec555dd3ed24aab3037 Mon Sep 17 00:00:00 2001 From: KxmischesDomi Date: Wed, 16 Feb 2022 18:10:02 +0100 Subject: [PATCH 003/119] Add /guess information --- language/files/en.json | 2 ++ .../challenges/implementation/challenge/quiz/QuizChallenge.java | 1 + 2 files changed, 3 insertions(+) diff --git a/language/files/en.json b/language/files/en.json index 3c2012514..c938e5520 100644 --- a/language/files/en.json +++ b/language/files/en.json @@ -209,6 +209,8 @@ "What's going on now?!" ], + "quiz-how-to": "Write your answer with §e/guess ", + "quiz-right-answer": "§e{0} §7is the §aright §7answer!", "quiz-right-answer-other": "§e{0} §7answered the question §acorrectly§7!", diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index a6ab3907d..1919beb0f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -138,6 +138,7 @@ protected void onTimeActivation() { onTimeActivation(); return; } + Message.forName("quiz-how-to").send(currentQuestionedPlayer, Prefix.CHALLENGES); timeLeft = 60; bossbar.update(); From 1a3ea512bdd528c6832c977063f284b69a52cc8a Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Mon, 13 Jan 2025 15:59:03 +0100 Subject: [PATCH 004/119] implement Delay Damage Challenge --- language/files/de.json | 5 ++ language/files/en.json | 5 ++ .../damage/DelayDamageChallenge.java | 86 +++++++++++++++++++ .../challenges/ChallengeLoader.java | 13 +-- 4 files changed, 98 insertions(+), 11 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java diff --git a/language/files/de.json b/language/files/de.json index d92a6884a..1576c197d 100644 --- a/language/files/de.json +++ b/language/files/de.json @@ -1238,6 +1238,11 @@ "*Chunks*, in denen sich *Spieler* befinden,", "werden nach gegebener *Zeit* komplett *gelöscht*" ], + "item-delay-damage-description": [ + "§4Verzögerter Schaden", + "Der *schaden* von allen *Spielern* ist", + "zusammenaddiert und wird nach einer bestimmten *Zeit* hinzugefügt." + ], "item-dragon-goal": [ "§5Enderdrache", "Töte den *Enderdrachen* um zu gewinnen" diff --git a/language/files/en.json b/language/files/en.json index 351203878..e7bbc9aa7 100644 --- a/language/files/en.json +++ b/language/files/en.json @@ -1218,6 +1218,11 @@ "*Chunks* that players are in *delete*", "completely after the given *time*" ], + "item-delay-damage-description": [ + "§4Damage delay", + "All *damage* from all *players* is", + "added up and dealt after *5 minutes*." + ], "item-dragon-goal": [ "§5Ender Dragon", "Kill the *Ender Dragon* to win" diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java new file mode 100644 index 000000000..073d69b6e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java @@ -0,0 +1,86 @@ +package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; + +import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.entity.EntityDamageEvent; +import org.jetbrains.annotations.NotNull; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; + +/** + * @author rollocraft | https://github.com/rollocraft + * @since 2.3.2 + */ + +@Since("2.3.2") +public class DelayDamageChallenge extends TimedChallenge { + private boolean canGetDamage = false; + + private final Map damageMap = new HashMap<>(); + + public DelayDamageChallenge() { + super(MenuType.CHALLENGES, 1, 64, 4, false); + setCategory(SettingCategory.DAMAGE); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue() * 30; + } + + @Override + protected void onTimeActivation() { + + double totalDamage = damageMap.values().stream().mapToDouble(Double::doubleValue).sum(); + int playerCount = damageMap.size(); + + if (playerCount > 0) { + canGetDamage = true; + for (Player player : Bukkit.getOnlinePlayers()) { + player.damage(totalDamage); + Message.forName(("extreme-force-battle-took-damage")).send(player, Prefix.DAMAGE, totalDamage / 2); + } + canGetDamage = false; + } + + + damageMap.clear(); + restartTimer(); + } + + @Override + public @NotNull ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.REDSTONE, Message.forName("item-delay-damage-description")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue() * 30); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerDamage(@Nonnull EntityDamageEvent event) { + if (canGetDamage) return; + if (!(event.getEntity() instanceof Player)) return; + + Player player = (Player) event.getEntity(); + double damage = event.getFinalDamage(); + + damageMap.put(player, damageMap.getOrDefault(player, 0.0) + damage); + event.setCancelled(true); + } +} \ No newline at end of file diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java index 94cf138a9..da9d8c593 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java @@ -2,17 +2,7 @@ import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.AdvancementDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.BlockBreakDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.BlockPlaceDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.DamagePerBlockChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.DamagePerItemChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.DeathOnFallChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.FreezeChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.JumpDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.ReversedDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.SneakDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.WaterAllergyChallenge; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.*; import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.BlockEffectChallenge; import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.ChunkRandomEffectChallenge; import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.EntityRandomEffectChallenge; @@ -207,6 +197,7 @@ public void enable() { register(DeathOnFallChallenge.class); register(ReversedDamageChallenge.class); register(FreezeChallenge.class); + register(DelayDamageChallenge.class); // Effect register(ChunkRandomEffectChallenge.class); From c01a9b7a8ad437a01a62a65b68a11155f25e809c Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Fri, 17 Jan 2025 18:03:30 +0100 Subject: [PATCH 005/119] Moved Time: Messages out of the Config --- language/files/de.json | 3 +++ language/files/en.json | 3 +++ .../management/scheduler/timer/ChallengeTimer.java | 13 ++++++------- plugin/src/main/resources/config.yml | 3 --- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/language/files/de.json b/language/files/de.json index 1576c197d..9a6558190 100644 --- a/language/files/de.json +++ b/language/files/de.json @@ -34,6 +34,9 @@ "new-challenge": "§a§lNeu!", "feature-disabled": "Diese Funktion ist derzeit §cdeaktiviert", "challenge-disabled": "Diese Challenge ist derzeit §cdeaktiviert", + "stopped-message": "§8• §7Timer §c§lpaused §8•", + "count-up-message": "§8• §7Time: §a§l{0} §8•", + "count-down-message": "§8• §7Time: §c§l{0} §8•", "timer-not-started": "Der Timer wurde noch §cnicht gestartet", "timer-was-started": "Der Timer wurde §agestartet", "timer-was-paused": "Der Timer wurde §cpausiert", diff --git a/language/files/en.json b/language/files/en.json index e7bbc9aa7..59d385655 100644 --- a/language/files/en.json +++ b/language/files/en.json @@ -34,6 +34,9 @@ "new-challenge": "§a§lNew!", "feature-disabled": "This function is currently §cdeactivated", "challenge-disabled": "This challenge is currently §cdeactivated", + "stopped-message": "§8• §7Timer §c§lpaused §8•", + "count-up-message": "§8• §7Time: §a§l{0} §8•", + "count-down-message": "§8• §7Time: §c§l{0} §8•", "timer-not-started": "The timer §chasn't been started", "timer-was-started": "The timer has been §astarted", "timer-was-paused": "The timer has been §cpaused", diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java index fdfeb3470..b8790babd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java @@ -33,7 +33,7 @@ public final class ChallengeTimer { @Getter private final TimerFormat format; - private final String stoppedMessage, upMessage, downMessage; + private final Message stoppedMessage, upMessage, downMessage; private final boolean specificStartSounds, defaultStartSound; @Getter private long time = 0; @@ -52,9 +52,9 @@ public ChallengeTimer() { // Load format + messages Document timerConfig = pluginConfig.getDocument("timer"); - stoppedMessage = timerConfig.getString("stopped-message", ""); - upMessage = timerConfig.getString("count-up-message", ""); - downMessage = timerConfig.getString("count-down-message", ""); + stoppedMessage = Message.forName("stopped-message"); + upMessage = Message.forName("count-up-message"); + downMessage = Message.forName("count-down-message"); Document formatConfig = timerConfig.getDocument("format"); format = new TimerFormat(formatConfig); @@ -165,10 +165,9 @@ public void updateActionbar() { @Nonnull private String getActionbar() { - String message = !paused || (!countingUp && time > 0) ? (countingUp ? upMessage : downMessage) : stoppedMessage; + Message message = !paused || (!countingUp && time > 0) ? (countingUp ? upMessage : downMessage) : stoppedMessage; String time = getFormattedTime(); - message = message.replace("{time}", time); - return isSmallCaps() ? FontUtils.toSmallCaps(message) : message; + return message.asString(time); } private boolean isSmallCaps() { diff --git a/plugin/src/main/resources/config.yml b/plugin/src/main/resources/config.yml index e8148167a..67b64224c 100644 --- a/plugin/src/main/resources/config.yml +++ b/plugin/src/main/resources/config.yml @@ -34,9 +34,6 @@ language: "de" small-caps: false timer: - stopped-message: "§8• §7Timer §c§lpaused §8•" - count-up-message: "§8• §7Time: §a§l{time} §8•" - count-down-message: "§8• §7Time: §c§l{time} §8•" format: seconds: "{mm}:{ss}" minutes: "{mm}:{ss}" From 1cc781cf06242f6df7c8b240e7cfa4e3e8bfd8bd Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Fri, 17 Jan 2025 15:21:12 +0100 Subject: [PATCH 006/119] Refactored GENERIC_MAX_HEALT --- .../custom/settings/action/impl/HealEntityAction.java | 2 +- .../implementation/challenge/ZeroHeartsChallenge.java | 4 ++-- .../challenge/damage/DelayDamageChallenge.java | 6 ++++-- .../challenge/randomizer/RandomizedHPChallenge.java | 6 +++--- .../implementation/challenge/world/LoopChallenge.java | 2 +- .../challenges/implementation/goal/GetFullHealthGoal.java | 4 ++-- .../challenges/implementation/setting/MaxHealthSetting.java | 2 +- .../challenges/implementation/setting/OldPvPSetting.java | 2 +- .../implementation/setting/SplitHealthSetting.java | 2 +- .../challenges/plugin/spigot/command/HealCommand.java | 2 +- 10 files changed, 17 insertions(+), 15 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java index 6e0f923d3..08d9ad2bb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java @@ -35,7 +35,7 @@ public void executeFor(Entity entity, Map subActions) { int amount = Integer.parseInt(subActions.get("amount")[0]); if (entity instanceof LivingEntity) { LivingEntity livingEntity = (LivingEntity) entity; - AttributeInstance attribute = livingEntity.getAttribute(Attribute.GENERIC_MAX_HEALTH); + AttributeInstance attribute = livingEntity.getAttribute(Attribute.MAX_HEALTH); if (attribute == null) return; double newHealth = Math.min(livingEntity.getHealth() + amount, attribute.getBaseValue()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index 2226d2969..c06a74998 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -47,7 +47,7 @@ protected void onEnable() { }); bossbar.show(); Bukkit.getOnlinePlayers().forEach(player -> { - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); + AttributeInstance attribute = player.getAttribute(Attribute.MAX_HEALTH); if (attribute == null) return; attribute.setBaseValue(0); }); @@ -73,7 +73,7 @@ protected void onValueChange() { @ScheduledTask(ticks = 20, async = false) public void onSecond() { broadcast(player -> { - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); + AttributeInstance attribute = player.getAttribute(Attribute.MAX_HEALTH); if (attribute == null) return; attribute.setBaseValue(0); }); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java index 073d69b6e..43ef7c184 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java @@ -74,11 +74,13 @@ protected String[] getSettingsDescription() { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerDamage(@Nonnull EntityDamageEvent event) { - if (canGetDamage) return; + if (!shouldExecuteEffect()) return; if (!(event.getEntity() instanceof Player)) return; + if (ignorePlayer((Player) event.getEntity())) return; + if (canGetDamage) return; - Player player = (Player) event.getEntity(); double damage = event.getFinalDamage(); + Player player = (Player) event.getEntity(); damageMap.put(player, damageMap.getOrDefault(player, 0.0) + damage); event.setCancelled(true); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java index ef17e54dc..b00e6b490 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java @@ -74,7 +74,7 @@ private void randomizeEntityHealth(@Nonnull LivingEntity entity) { return; } int health = random.nextInt(getValue() * 100) + 1; - entity.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(health); + entity.getAttribute(Attribute.MAX_HEALTH).setBaseValue(health); entity.setHealth(health); } @@ -94,7 +94,7 @@ private void resetExistingEntityHealth() { EntityType type = entity.getType(); double health = entityDefaultHealth.getOrDefault(type, getDefaultHealth(type)); entityDefaultHealth.put(type, health); - AttributeInstance attribute = entity.getAttribute(Attribute.GENERIC_MAX_HEALTH); + AttributeInstance attribute = entity.getAttribute(Attribute.MAX_HEALTH); if (attribute == null) return; attribute.setBaseValue(health); entity.setHealth(health); @@ -108,7 +108,7 @@ private double getDefaultHealth(@Nonnull EntityType entityType) { entity.remove(); if (!(entity instanceof LivingEntity)) return 0; AttributeInstance attribute = ((LivingEntity) entity) - .getAttribute(Attribute.GENERIC_MAX_HEALTH); + .getAttribute(Attribute.MAX_HEALTH); if (attribute == null) return 10; return attribute.getBaseValue(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index ee017e3c4..241c8919d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -321,7 +321,7 @@ private boolean decreaseDurability() { private boolean isTool(@Nonnull ItemStack itemStack) { if (itemStack.getItemMeta() != null) { try { - Collection attributeModifiers = itemStack.getItemMeta().getAttributeModifiers(Attribute.GENERIC_ATTACK_DAMAGE); + Collection attributeModifiers = itemStack.getItemMeta().getAttributeModifiers(Attribute.ATTACK_DAMAGE); return attributeModifiers == null || !attributeModifiers.isEmpty(); } catch (NullPointerException exception) { return false; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index fda44a704..e02db2242 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -52,7 +52,7 @@ protected void onValueChange() { public void getWinnersOnEnd(@NotNull List winners) { for (Player player : Bukkit.getOnlinePlayers()) { if (ignorePlayer(player)) continue; - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); + AttributeInstance attribute = player.getAttribute(Attribute.MAX_HEALTH); if (attribute != null) { if (player.getHealth() >= attribute.getBaseValue()) { winners.add(player); @@ -83,7 +83,7 @@ public void onHealthChange(EntityRegainHealthEvent event) { if (!(event.getEntity() instanceof Player)) return; if (!shouldExecuteEffect()) return; if (ignorePlayer((Player) event.getEntity())) return; - AttributeInstance attribute = ((Player) event.getEntity()).getAttribute(Attribute.GENERIC_MAX_HEALTH); + AttributeInstance attribute = ((Player) event.getEntity()).getAttribute(Attribute.MAX_HEALTH); Bukkit.getScheduler().runTask(plugin, () -> { if (attribute != null && ((Player) event.getEntity()).getHealth() >= attribute.getBaseValue()) { ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index 2056682be..151f58eb9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -79,7 +79,7 @@ public void onJoin(@Nonnull PlayerJoinEvent event) { } private void updateHealth(Player player) { - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); + AttributeInstance attribute = player.getAttribute(Attribute.MAX_HEALTH); if (attribute == null) return; // This should never happen because its a generic attribute, but just in case int newMaxHealth = getMaxHealth(player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java index 14202e27b..1cb01b196 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java @@ -72,7 +72,7 @@ public void onSweepDamage(@Nonnull EntityDamageEvent event) { } protected void setAttackSpeed(@Nonnull Player player, double value) { - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_ATTACK_SPEED); + AttributeInstance attribute = player.getAttribute(Attribute.ATTACK_SPEED); if (attribute == null) return; attribute.setBaseValue(value); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index 8b0bf4581..1c91ba073 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -92,7 +92,7 @@ public void setHealth(@Nonnull Player player, @Nullable EntityDamageEvent damage if (currentPlayer.equals(player)) continue; double health = player.getHealth(); - AttributeInstance attribute = currentPlayer.getAttribute(Attribute.GENERIC_MAX_HEALTH); + AttributeInstance attribute = currentPlayer.getAttribute(Attribute.MAX_HEALTH); if (attribute == null) return; if (health > attribute.getValue()) { health = attribute.getValue(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java index e406f136b..2560e98d2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java @@ -41,7 +41,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { boolean otherPlayers = false; for (Player player : targets) { Message.forName("command-heal-healed").send(player, Prefix.CHALLENGES); - AttributeInstance attribute = player.getAttribute(Attribute.GENERIC_MAX_HEALTH); + AttributeInstance attribute = player.getAttribute(Attribute.MAX_HEALTH); if (attribute == null) { player.setHealth(20); } else { From be19ea10f16a8089863672a41e519842eca479f6 Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Fri, 17 Jan 2025 18:27:23 +0100 Subject: [PATCH 007/119] Fixed all Errors with the upgrade to 1.21.4 --- .../challenge/force/ForceBiomeChallenge.java | 7 ++++++- .../goal/forcebattle/ForceBiomeBattleGoal.java | 12 ++++++++++-- pom.xml | 2 +- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java index 91d58f858..9ab4bfea8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java @@ -15,6 +15,8 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; import org.bukkit.block.Biome; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; @@ -26,6 +28,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Arrays; +import java.util.Objects; import java.util.function.BiConsumer; /** @@ -137,11 +140,13 @@ public void onMove(@Nonnull PlayerMoveEvent event) { public void loadGameState(@NotNull Document document) { super.loadGameState(document); if (document.contains("target")) { - biome = document.getEnum("target", Biome.class); + String biomeName = document.getString("target"); + biome = Registry.BIOME.get(NamespacedKey.minecraft(Objects.requireNonNull(biomeName).toLowerCase())); setState(biome == null ? WAITING : COUNTDOWN); } } + @Override public void writeGameState(@NotNull Document document) { super.writeGameState(document); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java index aed021546..2bfeca5f5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java @@ -8,10 +8,13 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.Registry; import org.bukkit.block.Biome; import org.jetbrains.annotations.NotNull; import java.util.List; +import java.util.Objects; import java.util.stream.Collectors; /** @@ -38,14 +41,19 @@ protected BiomeTarget[] getTargetsPossibleToFind() { @Override public BiomeTarget getTargetFromDocument(Document document, String path) { - return new BiomeTarget(document.getEnum(path, Biome.class)); + return new BiomeTarget(Registry.BIOME.get(NamespacedKey.minecraft(Objects.requireNonNull(document.getString(path)).toLowerCase()))); } @Override public List getListFromDocument(Document document, String path) { - return document.getEnumList(path, Biome.class).stream().map(BiomeTarget::new).collect(Collectors.toList()); + return document.getStringList(path).stream() + .map(biomeName -> new BiomeTarget( + Registry.BIOME.get(NamespacedKey.minecraft(biomeName.toLowerCase())) + )) + .collect(Collectors.toList()); } + @Override protected Message getLeaderboardTitleMessage() { return Message.forName("force-biome-battle-leaderboard"); diff --git a/pom.xml b/pom.xml index 7ebbd174f..a2d103724 100644 --- a/pom.xml +++ b/pom.xml @@ -18,7 +18,7 @@ 1.3.15 - 1.21-R0.1-SNAPSHOT + 1.21.4-R0.1-SNAPSHOT From a64028bb663013a58a51ce3548c106c928fea1f5 Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Sat, 18 Jan 2025 11:29:22 +0100 Subject: [PATCH 008/119] Added dynamic Language changing via Command --- .../challenges/plugin/Challenges.java | 3 +- .../plugin/content/loader/LanguageLoader.java | 9 ++++ .../spigot/command/LanguageCommand.java | 45 +++++++++++++++++++ .../listener/PlayerConnectionListener.java | 2 +- plugin/src/main/resources/plugin.yml | 8 +++- 5 files changed, 64 insertions(+), 3 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java index 67ac12569..3bc0e9c60 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java @@ -53,7 +53,7 @@ public final class Challenges extends BukkitModule { private ChallengeTimer challengeTimer; private LoaderRegistry loaderRegistry; private MetricsLoader metricsLoader; - private GameWorldStorage gameWorldStorage; + private GameWorldStorage gameWorldStorage; private GeneratorWorldPortalManager generatorWorldPortalManager; @Nonnull @@ -174,6 +174,7 @@ private void registerCommands() { registerCommand(new ForwardingCommand("time set midnight"), "midnight"); registerCommand(new ResultCommand(), "result"); registerCommand(new SkipTimerCommand(), "skiptimer"); + registerCommand(new LanguageCommand(), "setlanguage"); registerListenerCommand(new GodModeCommand(), "godmode"); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index 828d867d1..bdd71312e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -56,6 +56,15 @@ protected void load() { loadDefault(); } + public void reload(String language) { + this.language = language; + read(); + download(); + init(); + Challenges.getInstance().getScoreboardManager().updateAll(); + Challenges.getInstance().getConfigManager().getSettingsConfig().set("language", language); + } + private void loadDefault() { download(); init(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java new file mode 100644 index 000000000..bd5d6c03c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java @@ -0,0 +1,45 @@ +package net.codingarea.challenges.plugin.spigot.command; + +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.loader.LanguageLoader; +import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; +import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; +import net.codingarea.challenges.plugin.utils.misc.Utils; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.List; + +public class LanguageCommand implements SenderCommand, Completer { + + @Override + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { + if (args.length < 1) { + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "setlang "); + return; + } + switch (args[0].toLowerCase()) { + case "german": + case "deutsch": + case "de": + Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).reload("de"); + break; + case "english": + case "englisch": + case "en": + Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).reload("en"); + break; + default: + sender.sendMessage("§cUnsupportet language!"); + } + } + + @Override + public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { + return Utils.filterRecommendations(args[0], "german", "english"); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index 89bccee4d..bf0d05b2c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -57,7 +57,7 @@ public void onJoin(@Nonnull PlayerJoinEvent event) { if (Challenges.getInstance().isFirstInstall()) { player.sendMessage(""); player.sendMessage(Prefix.CHALLENGES + "§7Thanks for downloading §e§lChallenges§7!"); - player.sendMessage(Prefix.CHALLENGES + "§7You can change the language in the §econfig.yml"); + player.sendMessage(Prefix.CHALLENGES + "§7You can change the language in the settings or with /setlang [language]"); player.sendMessage(Prefix.CHALLENGES + "§7For more join our discord §ediscord.gg/74Ay5zF"); } diff --git a/plugin/src/main/resources/plugin.yml b/plugin/src/main/resources/plugin.yml index ef3993ea9..3b4c8eacc 100644 --- a/plugin/src/main/resources/plugin.yml +++ b/plugin/src/main/resources/plugin.yml @@ -224,4 +224,10 @@ commands: description: "Disable damage for a player" permission: "challenges.godmode" aliases: - - "god" \ No newline at end of file + - "god" + setlanguage: + usage: "/setlanguage [language]" + description: "Changes the language" + permission: "challenges.setlanguage" + aliases: + - "setlang" \ No newline at end of file From c97920cea213bb7c6a6c5a616a866da7e3f67c71 Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Sat, 18 Jan 2025 13:23:10 +0100 Subject: [PATCH 009/119] Added A Setting to Change Language --- language/files/de.json | 6 ++ language/files/en.json | 6 ++ .../setting/LanguageSetting.java | 70 +++++++++++++++++++ .../challenges/ChallengeLoader.java | 5 +- .../spigot/command/LanguageCommand.java | 4 ++ .../plugin/utils/item/ItemBuilder.java | 20 +++++- 6 files changed, 106 insertions(+), 5 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java diff --git a/language/files/de.json b/language/files/de.json index 9a6558190..b2720194b 100644 --- a/language/files/de.json +++ b/language/files/de.json @@ -526,6 +526,12 @@ "Der *maximale Radius*, in dem sich die", "Positionen befinden können" ], + "item-language-setting": [ + "§bSprache", + "Setze die *Sprache*" + ], + "item-language-setting-german": "§fDeutsch", + "item-language-setting-english": "§fEnglish", "item-difficulty-setting": [ "§aSchwierigkeit", "Stellt die *Schwierigkeitsstufe* ein" diff --git a/language/files/en.json b/language/files/en.json index 59d385655..6b0b8990c 100644 --- a/language/files/en.json +++ b/language/files/en.json @@ -525,6 +525,12 @@ "§aDifficulty", "Sets the *Difficulty*" ], + "item-language-setting": [ + "§bLanguage", + "Sets the *Language*" + ], + "item-language-setting-german": "§fDeutsch", + "item-language-setting-english": "§fEnglish", "item-one-life-setting": [ "§cOne Teamlife", "*Everyone* dies when *one player dies*" diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java new file mode 100644 index 000000000..b202be2ca --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java @@ -0,0 +1,70 @@ +package net.codingarea.challenges.plugin.challenges.implementation.setting; + +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.loader.LanguageLoader; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.utils.item.DefaultItem; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import org.bukkit.Material; +import javax.annotation.Nonnull; +import java.net.MalformedURLException; +import java.net.URL; + +public class LanguageSetting extends Modifier { + + public static final int ENGLISH = 1; + public static final int GERMAN = 2; + + public static final URL GERMAN_SKULL; + public static final URL ENGLISH_SKULL; + + static { + try { + GERMAN_SKULL = new URL("http://textures.minecraft.net/texture/5e7899b4806858697e283f084d9173fe487886453774626b24bd8cfecc77b3f"); + ENGLISH_SKULL = new URL("http://textures.minecraft.net/texture/46c9923bebd9ad90a80a0731c3f3b9db729b0785015e18e3ec07e4e91099be06"); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + + public LanguageSetting() { + super(MenuType.SETTINGS, 1, 2, ENGLISH); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.KNOWLEDGE_BOOK, Message.forName("item-language-setting")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + ItemBuilder.SkullBuilder GermanSkull = new ItemBuilder.SkullBuilder(GERMAN_SKULL); + ItemBuilder.SkullBuilder EnglishSkull = new ItemBuilder.SkullBuilder(ENGLISH_SKULL); + if (getValue() == GERMAN) + //TODO: Wie macht man diesen Pfeil? → Prefix falsch! + return GermanSkull.setName(DefaultItem.getItemPrefix() + Message.forName("item-language-setting-german")).hideAttributes(); + return EnglishSkull.setName(DefaultItem.getItemPrefix() + Message.forName("item-language-setting-english")).hideAttributes(); + } + + @Override + public void playValueChangeTitle() { + switch (getValue()) { + case GERMAN: + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-language-setting-german")); + Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).reload("de"); + break; + case ENGLISH: + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-language-setting-english")); + Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).reload("en"); + break; + default: + ChallengeHelper.playToggleChallengeTitle(this, false); + } + } + +} \ No newline at end of file diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java index da9d8c593..00c967b31 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java @@ -114,14 +114,14 @@ public void enable() { register(RespawnSetting.class); register(SplitHealthSetting.class); register(DamageDisplaySetting.class); - register(PregameMovementSetting.class); + register(LanguageSetting.class); + register(PregameMovementSetting.class); register(DeathMessageSetting.class); register(HealthDisplaySetting.class); registerWithCommand(PositionSetting.class, "position"); register(DeathPositionSetting.class); register(PlayerGlowSetting.class); - register(SoupSetting.class); register(NoHungerSetting.class); register(NoItemDamageSetting.class); @@ -146,6 +146,7 @@ public void enable() { register(SlotLimitSetting.class); register(OldPvPSetting.class); register(TotemSaveDeathSetting.class); + register(SoupSetting.class); // Challenges diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java index bd5d6c03c..db921058d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java @@ -13,6 +13,10 @@ import java.util.List; +/** + * @author rollocraft | https://github.com/rollocraft + * @since 2.3.2 + */ public class LanguageCommand implements SenderCommand, Completer { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index 341ac8904..8a036b51c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -8,6 +8,7 @@ import net.codingarea.challenges.plugin.content.ItemDescription; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.misc.DatabaseHelper; +import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.DyeColor; import org.bukkit.Material; @@ -18,13 +19,13 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.*; import org.bukkit.potion.PotionEffect; +import org.bukkit.profile.PlayerProfile; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.Collection; -import java.util.List; -import java.util.UUID; +import java.net.URL; +import java.util.*; /** * @author anweisen | https://github.com/anweisen @@ -317,6 +318,19 @@ public SkullBuilder(@Nonnull UUID ownerUUID, @Nonnull String ownerName, @Nonnull setOwner(ownerUUID, ownerName); } + public SkullBuilder(@Nonnull URL base64) { + super(new ItemStack(Material.PLAYER_HEAD) {{ + SkullMeta meta = (SkullMeta) getItemMeta(); + + PlayerProfile profile = Bukkit.createPlayerProfile(UUID.randomUUID()); + profile.getTextures().setSkin(base64); + + meta.setOwnerProfile(profile); + + setItemMeta(meta); + }}); + } + @Nonnull @Deprecated @DeprecatedSince("2.0") From 1b6ac70520bbc704e5bc68a1d03a94129805578e Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Fri, 28 Mar 2025 22:37:13 +0100 Subject: [PATCH 010/119] Merged Quiz Challenge --- .../implementation/challenge/quiz/QuizChallenge.java | 2 +- .../codingarea/challenges/plugin/utils/misc/BlockUtils.java | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index 1919beb0f..4e49fe476 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -170,7 +170,7 @@ private void cancelQuestion() { SoundSample.BREAK.play(currentQuestionedPlayer); currentQuestion = null; - AttributeInstance attribute = currentQuestionedPlayer.getAttribute(Attribute.GENERIC_MAX_HEALTH); + AttributeInstance attribute = currentQuestionedPlayer.getAttribute(Attribute.MAX_HEALTH); if (attribute.getBaseValue() == 2) { kill(currentQuestionedPlayer); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java index c79abf8e1..dfbf273fd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java @@ -58,6 +58,12 @@ public static boolean isSameChunk(@Nonnull Chunk chunk1, @Nonnull Chunk chunk2) return chunk1.getX() == chunk2.getX() && chunk1.getZ() == chunk2.getZ(); } + public static boolean isSameBlockIgnoreHeight(@Nullable Location loc1, @Nullable Location loc2) { + if (loc1 == null || loc2 == null) return false; + return loc1.getBlockX() == loc2.getBlockX() + && loc1.getBlockZ() == loc2.getBlockZ(); + } + /** * @param block middle block * @return the block above, under, in the front, behind, to the left and to the right of the middle block From 708f8bbc2d74caca3e43b263a959534ddaf87ec4 Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Sat, 29 Mar 2025 09:21:07 +0100 Subject: [PATCH 011/119] Fixed Skulls --- .../plugin/utils/item/DefaultItem.java | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java index 4f865e494..2a79a3825 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java @@ -1,5 +1,7 @@ package net.codingarea.challenges.plugin.utils.item; +import java.net.MalformedURLException; +import java.net.URL; import java.util.UUID; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.SkullBuilder; @@ -26,12 +28,24 @@ public static String getItemPrefix() { @Nonnull public static ItemBuilder navigateBack() { - return new SkullBuilder(ARROW_LEFT_UUID, "MHF_ArrowLeft").setName(Message.forName("navigate-back")).hideAttributes(); + URL BACK_SKULL; + try { + BACK_SKULL = new URL("http://textures.minecraft.net/texture/bd69e06e5dadfd84e5f3d1c21063f2553b2fa945ee1d4d7152fdc5425bc12a9"); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + return new SkullBuilder(BACK_SKULL).setName(Message.forName("navigate-back")).hideAttributes(); } @Nonnull public static ItemBuilder navigateNext() { - return new SkullBuilder(ARROW_RIGHT_UUID, "MHF_ArrowRight").setName(Message.forName("navigate-next")).hideAttributes(); + URL NEXT_SKULL; + try { + NEXT_SKULL = new URL("http://textures.minecraft.net/texture/19bf3292e126a105b54eba713aa1b152d541a1d8938829c56364d178ed22bf"); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + return new SkullBuilder(NEXT_SKULL).setName(Message.forName("navigate-next")).hideAttributes(); } @Nonnull From ca05eed83ea0e8b4c35a19626321bfc06ab58ef3 Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Sat, 29 Mar 2025 09:21:30 +0100 Subject: [PATCH 012/119] Removed a duped entry --- language/files/en.json | 1 - 1 file changed, 1 deletion(-) diff --git a/language/files/en.json b/language/files/en.json index 6b0b8990c..5d4cb4ed2 100644 --- a/language/files/en.json +++ b/language/files/en.json @@ -318,7 +318,6 @@ "bossbar-dont-stop-running": "§8» §7Move in §8┃ §e{0}", "bossbar-five-hundred-blocks": "§8» §fBlocks Walked §8┃ §7{0} §8/ §7{1}", "bossbar-level-border": "§8» §7Border size §8┃ §7{0}", - "bossbar-level-border": "§8» §7Border size §8┃ §7{0}", "bossbar-race-goal-info": "§8» §fGoal §8┃ §7X: {0} §8/ §7Z: {1} §8┃ §e{2} Blocks", "bossbar-race-goal": "§8» §fGoal §8┃ §7X: {0} §8/ §7Z: {1}", "bossbar-first-at-height-goal": "§8» §fGoal §8┃ §7Y: {0}", From 9e5f8847cde7449602ffea082057227947550464 Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Thu, 10 Apr 2025 21:01:02 +0200 Subject: [PATCH 013/119] Added a Message to remind the Player to have Permissions --- .../plugin/spigot/listener/PlayerConnectionListener.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index bf0d05b2c..4a83acfa6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -53,6 +53,10 @@ public void onJoin(@Nonnull PlayerJoinEvent event) { MinecraftNameWrapper.ENTITY_EFFECT, 17, 1, 2); Challenges.getInstance().getScoreboardManager().handleJoin(player); + if (Challenges.getInstance().isFirstInstall()) { + player.sendMessage(Prefix.CHALLENGES + "§7To use this plugin you need to have permissions. Give yourself permissions in the Server Console with: /op [name]"); + } + if (player.hasPermission("challenges.gui")) { if (Challenges.getInstance().isFirstInstall()) { player.sendMessage(""); From 8a40cc2b498ddfe49af202e12c07c8165179f3d1 Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Thu, 10 Apr 2025 21:12:04 +0200 Subject: [PATCH 014/119] Next Config Version --- plugin/src/main/resources/plugin.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/src/main/resources/plugin.yml b/plugin/src/main/resources/plugin.yml index 963e3fdd3..1bceae874 100644 --- a/plugin/src/main/resources/plugin.yml +++ b/plugin/src/main/resources/plugin.yml @@ -1,5 +1,5 @@ name: Challenges -version: 2.3.2 +version: 2.3.3 author: CodingArea authors: - anweisen From 31970b68def29899a005b103784559468d7d3acb Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Thu, 10 Apr 2025 21:13:17 +0200 Subject: [PATCH 015/119] Next Config Version --- plugin/src/main/resources/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/src/main/resources/config.yml b/plugin/src/main/resources/config.yml index 67b64224c..1d4c0c2f3 100644 --- a/plugin/src/main/resources/config.yml +++ b/plugin/src/main/resources/config.yml @@ -22,7 +22,7 @@ # The config-version is even with the version of the default config. # You will be notified, when this version is older than the of the default in the plugin jar. # We recommend regenerating the config to get access to new features / settings. -config-version: "2.2.0" +config-version: "2.2.1" # Currently supported by default # - en (English) From ddb998f2d1ba63ca40ae65c4e5cf833a2005fc0d Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Thu, 10 Apr 2025 21:28:36 +0200 Subject: [PATCH 016/119] Removed the Hard Coded Messages --- .github/workflows/maven-build.yml | 2 +- language/files/de.json | 6 ++++++ language/files/en.json | 6 ++++++ .../challenges/plugin/spigot/command/LanguageCommand.java | 2 +- .../plugin/spigot/listener/PlayerConnectionListener.java | 4 ++-- 5 files changed, 16 insertions(+), 4 deletions(-) diff --git a/.github/workflows/maven-build.yml b/.github/workflows/maven-build.yml index 502bbefef..888de9791 100644 --- a/.github/workflows/maven-build.yml +++ b/.github/workflows/maven-build.yml @@ -22,7 +22,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: mvn -B package --file pom.xml - name: Capture build artifacts - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v3 with: name: Artifacts path: | diff --git a/language/files/de.json b/language/files/de.json index b2720194b..4762dbaac 100644 --- a/language/files/de.json +++ b/language/files/de.json @@ -69,6 +69,12 @@ "§cEs fehlen keine Einstellungen in der Config.", "§cDu kannst die Version ohne bedenken selbst auf §c§l{0} §cstellen." ], + "unsuported-language": [ + "§cDiese Sprache §7(§e{0}§7) wird nicht unterstützt" + ], + "not-op":[ + "§7Um dieses Plugin zu nutzen, musst du die Berechtigung haben. Gib dir die Berechtigung in der Serverkonsole mit: /op [name]" + ], "join-message": "§e{0} §7hat den Server §abetreten", "quit-message": "§e{0} §7hat den Server §cverlassen", "timer-paused-message": [ diff --git a/language/files/en.json b/language/files/en.json index 5d4cb4ed2..9b7e2344d 100644 --- a/language/files/en.json +++ b/language/files/en.json @@ -69,6 +69,12 @@ "§cThere are no missing config settings.", "§cYou can manually update it to §c§l{0}" ], + "unsuported-language": [ + "§cThe language §7(§e{0}§7) is not supported" + ], + "not-op":[ + "§7To use this plugin you need to have permissions. Give yourself permissions in the Server Console with: /op [name]" + ], "join-message": "§e{0} §7has §ajoined §7the server", "quit-message": "§e{0} §7has §cleft §7the server", "timer-paused-message": [ diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java index db921058d..186da232c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java @@ -37,7 +37,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).reload("en"); break; default: - sender.sendMessage("§cUnsupportet language!"); + Message.forName("unsuported-language").send(sender, Prefix.CHALLENGES, args[0]); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index 4a83acfa6..103d4577e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -53,8 +53,8 @@ public void onJoin(@Nonnull PlayerJoinEvent event) { MinecraftNameWrapper.ENTITY_EFFECT, 17, 1, 2); Challenges.getInstance().getScoreboardManager().handleJoin(player); - if (Challenges.getInstance().isFirstInstall()) { - player.sendMessage(Prefix.CHALLENGES + "§7To use this plugin you need to have permissions. Give yourself permissions in the Server Console with: /op [name]"); + if (Challenges.getInstance().isFirstInstall() && !player.hasPermission("challenges.gui")) { + Message.forName("not-op").send(player, Prefix.CHALLENGES); } if (player.hasPermission("challenges.gui")) { From 8502fe9b85b7ee449a2eba5ad5ff0f5a8fa2fd90 Mon Sep 17 00:00:00 2001 From: Rollocraft <70059106+Rollocraft@users.noreply.github.com> Date: Thu, 10 Apr 2025 21:30:29 +0200 Subject: [PATCH 017/119] Update maven-build.yml to upload-artifacts@v4 --- .github/workflows/maven-build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/maven-build.yml b/.github/workflows/maven-build.yml index 888de9791..07d7ac626 100644 --- a/.github/workflows/maven-build.yml +++ b/.github/workflows/maven-build.yml @@ -22,9 +22,9 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: mvn -B package --file pom.xml - name: Capture build artifacts - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: Artifacts path: | plugin/target/Challenges.jar - mongo-connector/target/Challenges-MongoConnector.jar \ No newline at end of file + mongo-connector/target/Challenges-MongoConnector.jar From 05cdc3b4274b8a788af4e4abe07045bce8984982 Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Fri, 11 Apr 2025 08:06:03 +0200 Subject: [PATCH 018/119] Refactor bossbar messages to use getItemDisplayName for improved readability --- .../goal/CollectAllItemsGoal.java | 52 +++++++++++++++---- .../setting/LanguageSetting.java | 1 - 2 files changed, 41 insertions(+), 12 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index b5ba68447..a94e89a0e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -31,6 +31,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; /** * @author anweisen | https://github.com/anweisen @@ -79,15 +80,17 @@ private void nextItem() { @Override protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - if (currentItem == null) { - bossbar.setTitle(Message.forName("bossbar-all-items-finished").asString()); - return; - } - - bossbar.setTitle(Message.forName("bossbar-all-items-current-max").asComponent(currentItem, totalItemsCount - itemsToFind.size() + 1, totalItemsCount)); - }); - bossbar.show(); + bossbar.setContent((bossbar, player) -> { + if (currentItem == null) { + bossbar.setTitle(Message.forName("bossbar-all-items-finished").asString()); + return; + } + bossbar.setTitle(Message.forName("bossbar-all-items-current-max").asComponent( + getItemDisplayName(currentItem), + totalItemsCount - itemsToFind.size() + 1, + totalItemsCount)); + }); + bossbar.show(); } @Override @@ -108,7 +111,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) thr return; } - Message.forName("all-items-skipped").broadcast(Prefix.CHALLENGES, currentItem); + Message.forName("all-items-skipped").broadcast(Prefix.CHALLENGES, getItemDisplayName(currentItem)); SoundSample.PLING.broadcast(); nextItem(); bossbar.update(); @@ -142,7 +145,7 @@ protected void handleNewItem(@Nullable Material material, @Nonnull Player player if (!shouldExecuteEffect()) return; if (ignorePlayer(player)) return; if (currentItem != material) return; - Message.forName("all-items-found").broadcast(Prefix.CHALLENGES, currentItem, NameHelper.getName(player)); + Message.forName("all-items-found").broadcast(Prefix.CHALLENGES, getItemDisplayName(currentItem) , NameHelper.getName(player)); SoundSample.PLING.broadcast(); nextItem(); bossbar.update(); @@ -185,4 +188,31 @@ public int getTotalItemsCount() { return totalItemsCount; } + private String getItemDisplayName(@Nullable Material material) { + if (material == null) return "Unbekannt"; + + String name = material.name(); + + if (name.contains("SMITHING_TEMPLATE")) { + String prefix = name.replace("_SMITHING_TEMPLATE", ""); + String formattedPrefix = Arrays.stream(prefix.split("_")) + .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) + .collect(Collectors.joining(" ")); + + return formattedPrefix + " Smithing template"; + } + + if (name.endsWith("_BANNER_PATTERN")) { + String prefix = name.replace("_BANNER_PATTERN", ""); + String formattedPrefix = Arrays.stream(prefix.split("_")) + .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) + .collect(Collectors.joining(" ")); + + return formattedPrefix + " Banner Pattern"; + } + + return Arrays.stream(name.split("_")) + .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) + .collect(Collectors.joining(" ")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java index b202be2ca..538e49154 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java @@ -46,7 +46,6 @@ public ItemBuilder createSettingsItem() { ItemBuilder.SkullBuilder GermanSkull = new ItemBuilder.SkullBuilder(GERMAN_SKULL); ItemBuilder.SkullBuilder EnglishSkull = new ItemBuilder.SkullBuilder(ENGLISH_SKULL); if (getValue() == GERMAN) - //TODO: Wie macht man diesen Pfeil? → Prefix falsch! return GermanSkull.setName(DefaultItem.getItemPrefix() + Message.forName("item-language-setting-german")).hideAttributes(); return EnglishSkull.setName(DefaultItem.getItemPrefix() + Message.forName("item-language-setting-english")).hideAttributes(); } From 5e6643a5d73c803256c4c8963dd06520e6e68f03 Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Fri, 11 Apr 2025 16:40:36 +0200 Subject: [PATCH 019/119] Add MinecraftVersion enum and Version interface for version checking --- .../bukkit/misc/Version/MinecraftVersion.java | 118 ++++++++++++++++++ .../utils/bukkit/misc/Version/Version.java | 108 ++++++++++++++++ .../misc/Version/VersionComparator.java | 13 ++ .../bukkit/misc/Version/VersionInfo.java | 79 ++++++++++++ 4 files changed, 318 insertions(+) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java new file mode 100644 index 000000000..cfca3a718 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java @@ -0,0 +1,118 @@ +package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; + +import org.bukkit.Bukkit; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; + +/** + * @author anweisen | https://github.com/anweisen + * @since 1.0 + */ +public enum MinecraftVersion implements Version { + + V1_0, // 1.0 + V1_1, // 1.1 + V1_2_1, // 1.2.1 + V1_3_1, // 1.3.1 + V1_4_2, // 1.4.2 + V1_5, // 1.5 + V1_6, // 1.6 + V1_7, // 1.7 + V1_7_2, // 1.7.2 + V1_8, // 1.8 + V1_9, // 1.9 + V1_10, // 1.10 + V1_11, // 1.11 + V1_12, // 1.12 + V1_13, // 1.13 + V1_14, // 1.14 + V1_15, // 1.15 + V1_16, // 1.16 + V1_16_5, // 1.16.5 + V1_17, // 1.17 + V1_18, // 1.18 + V1_19, // 1.19 + V1_20, // 1.20 + V1_20_1, // 1.20.1 + V1_20_2, // 1.20.2 + V1_20_3, // 1.20.3 + V1_20_4, // 1.20.4 + V1_20_5, // 1.20.5 + V1_21, // 1.21 + V1_21_1, // 1.21.1 + V1_21_2, // 1.21.2 + V1_21_3, // 1.21.3 + V1_21_4, // 1.21.4 + V1_21_5 // 1.21.5 + ; + + private final int major, minor, revision; + + MinecraftVersion() { + + String name = this.name().substring(1); + String[] version = name.split("_"); + + if (version.length != 2 && version.length != 3) + throw new IllegalArgumentException("Name '" + name() + "' does not match pattern: V{major}_{minor}_[revision]"); + + major = Integer.parseInt(version[0]); + minor = Integer.parseInt(version[1]); + revision = version.length > 2 ? Integer.parseInt(version[2]) : 0; + + } + + @Override + public int getMajor() { + return major; + } + + @Override + public int getMinor() { + return minor; + } + + @Override + public int getRevision() { + return revision; + } + + @Override + public String toString() { + return this.format(); + } + + @Nonnull + @CheckReturnValue + public static Version parseExact(@Nonnull String bukkitVersion) { + bukkitVersion = bukkitVersion.substring(0, bukkitVersion.indexOf("-")); + return Version.parse(bukkitVersion); + } + + @Nonnull + @CheckReturnValue + public static Version findNearest(@Nonnull Version realVersion) { + return Version.findNearest(realVersion, values()); + } + + private static Version currentExact; + private static Version current; + + @Nonnull + @CheckReturnValue + public static Version currentExact() { + if (currentExact == null) + currentExact = parseExact(Bukkit.getBukkitVersion()); + return currentExact; + } + + @Nonnull + @CheckReturnValue + public static Version current() { + if (current == null) + current = findNearest(currentExact()); + return current; + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java new file mode 100644 index 000000000..871775ea2 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java @@ -0,0 +1,108 @@ +package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import net.anweisen.utilities.common.annotations.Since; + +public interface Version { + @Nonnegative + int getMajor(); + + @Nonnegative + int getMinor(); + + @Nonnegative + int getRevision(); + + default boolean isNewerThan(@Nonnull Version other) { + return this.intValue() > other.intValue(); + } + + default boolean isNewerOrEqualThan(@Nonnull Version other) { + return this.intValue() >= other.intValue(); + } + + default boolean isOlderThan(@Nonnull Version other) { + return this.intValue() < other.intValue(); + } + + default boolean isOlderOrEqualThan(@Nonnull Version other) { + return this.intValue() <= other.intValue(); + } + + default boolean equals(@Nonnull Version other) { + return this.intValue() == other.intValue(); + } + + @Nonnull + default String format() { + int revision = this.getRevision(); + return revision > 0 ? String.format("%s.%s.%s", this.getMajor(), this.getMinor(), revision) : String.format("%s.%s", this.getMajor(), this.getMinor()); + } + + default int intValue() { + int major = this.getMajor(); + int minor = this.getMinor(); + int revision = this.getRevision(); + if (major > 99) { + throw new IllegalStateException("Malformed version: major is greater than 99"); + } else if (minor > 99) { + throw new IllegalStateException("Malformed version: minor is greater than 99"); + } else if (revision > 99) { + throw new IllegalStateException("Malformed version: revision is greater than 99"); + } else { + return revision + minor * 100 + major * 10000; + } + } + + @Nonnull + @CheckReturnValue + static Version parse(@Nullable String input) { + return parse(input, new VersionInfo(1, 0, 0)); + } + + @CheckReturnValue + static Version parse(@Nullable String input, Version def) { + return VersionInfo.parse(input, def); + } + + @Nonnull + @CheckReturnValue + static Version parseExceptionally(@Nullable String input) { + return VersionInfo.parseExceptionally(input); + } + + @Nonnull + @CheckReturnValue + static Version getAnnotatedSince(@Nonnull Object object) { + return (Version)(!object.getClass().isAnnotationPresent(Since.class) ? new VersionInfo(1, 0, 0) : parse(((Since)object.getClass().getAnnotation(Since.class)).value())); + } + + @Nonnull + @CheckReturnValue + static V findNearest(@Nonnull Version target, @Nonnull V[] sortedVersionsArray) { + List versions = new ArrayList(Arrays.asList(sortedVersionsArray)); + Collections.reverse(versions); + + for(V version : versions) { + if (!version.isNewerThan(target)) { + return version; + } + } + + throw new IllegalArgumentException("No version found for '" + target + "'"); + } + + @Nonnull + @CheckReturnValue + static Comparator comparator() { + return new VersionComparator(); + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java new file mode 100644 index 000000000..65849ddd0 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java @@ -0,0 +1,13 @@ +package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; + +import java.util.Comparator; +import javax.annotation.Nonnull; + +public class VersionComparator implements Comparator { + public VersionComparator() { + } + + public int compare(@Nonnull Version v1, @Nonnull Version v2) { + return v1.equals(v2) ? 0 : (v1.isNewerThan(v2) ? 1 : -1); + } +} \ No newline at end of file diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java new file mode 100644 index 000000000..f5d1ae911 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java @@ -0,0 +1,79 @@ +package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; + +import java.util.Objects; +import javax.annotation.Nullable; +import net.anweisen.utilities.common.logging.ILogger; + +public class VersionInfo implements Version { + protected static final ILogger logger = ILogger.forThisClass(); + private final int major; + private final int minor; + private final int revision; + + public VersionInfo() { + this(1, 0, 0); + } + + public VersionInfo(int major, int minor, int revision) { + this.major = major; + this.minor = minor; + this.revision = revision; + } + + public int getMajor() { + return this.major; + } + + public int getMinor() { + return this.minor; + } + + public int getRevision() { + return this.revision; + } + + public boolean equals(Object other) { + if (this == other) { + return true; + } else { + return !(other instanceof Version) ? false : this.equals((Version)other); + } + } + + public int hashCode() { + return Objects.hash(new Object[]{this.major, this.minor, this.revision}); + } + + public String toString() { + return this.format(); + } + + public static Version parseExceptionally(@Nullable String input) { + if (input == null) { + throw new IllegalArgumentException("Version cannot be null"); + } else { + String[] array = input.split("\\."); + if (array.length == 0) { + throw new IllegalArgumentException("Version cannot be empty"); + } else { + try { + int major = Integer.parseInt(array[0]); + int minor = array.length >= 2 ? Integer.parseInt(array[1]) : 0; + int revision = array.length >= 3 ? Integer.parseInt(array[2]) : 0; + return new VersionInfo(major, minor, revision); + } catch (Exception ex) { + throw new IllegalArgumentException("Cannot parse Version: " + input + " (" + ex.getMessage() + ")"); + } + } + } + } + + public static Version parse(@Nullable String input, Version def) { + try { + return parseExceptionally(input); + } catch (Exception ex) { + logger.error("Could not parse version for input {}", new Object[]{ex.getMessage()}); + return def; + } + } +} \ No newline at end of file From 9fd72be1b5d3cd05c37c2bb38917dd179b1a10e1 Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Fri, 11 Apr 2025 16:41:47 +0200 Subject: [PATCH 020/119] Update health attribute retrieval for Minecraft version compatibility --- .../action/impl/HealEntityAction.java | 9 ++++++- .../challenge/ZeroHeartsChallenge.java | 15 +++++++++-- .../challenge/quiz/QuizChallenge.java | 8 +++++- .../randomizer/RandomizedHPChallenge.java | 26 ++++++++++++++++--- .../challenge/world/LoopChallenge.java | 11 +++++++- .../goal/GetFullHealthGoal.java | 15 +++++++++-- .../setting/MaxHealthSetting.java | 7 ++++- .../implementation/setting/OldPvPSetting.java | 8 +++++- .../setting/SplitHealthSetting.java | 8 +++++- .../plugin/spigot/command/HealCommand.java | 8 +++++- 10 files changed, 100 insertions(+), 15 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java index 08d9ad2bb..57c9e0b2b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; +import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; @@ -35,7 +36,13 @@ public void executeFor(Entity entity, Map subActions) { int amount = Integer.parseInt(subActions.get("amount")[0]); if (entity instanceof LivingEntity) { LivingEntity livingEntity = (LivingEntity) entity; - AttributeInstance attribute = livingEntity.getAttribute(Attribute.MAX_HEALTH); + AttributeInstance attribute; + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { + attribute = livingEntity.getAttribute(Attribute.valueOf("MAX_HEALTH")); + } else { + attribute = livingEntity.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); + } + if (attribute == null) return; double newHealth = Math.min(livingEntity.getHealth() + amount, attribute.getBaseValue()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index c06a74998..71dbf31af 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -8,6 +8,7 @@ import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; +import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Bukkit; @@ -47,7 +48,12 @@ protected void onEnable() { }); bossbar.show(); Bukkit.getOnlinePlayers().forEach(player -> { - AttributeInstance attribute = player.getAttribute(Attribute.MAX_HEALTH); + AttributeInstance attribute; + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { + attribute = player.getAttribute(Attribute.valueOf("MAX_HEALTH")); + } else { + attribute = player.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); + } if (attribute == null) return; attribute.setBaseValue(0); }); @@ -73,7 +79,12 @@ protected void onValueChange() { @ScheduledTask(ticks = 20, async = false) public void onSecond() { broadcast(player -> { - AttributeInstance attribute = player.getAttribute(Attribute.MAX_HEALTH); + AttributeInstance attribute; + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { + attribute = player.getAttribute(Attribute.valueOf("MAX_HEALTH")); + } else { + attribute = player.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); + } if (attribute == null) return; attribute.setBaseValue(0); }); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index 4e49fe476..914094238 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -15,6 +15,7 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; +import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; @@ -170,7 +171,12 @@ private void cancelQuestion() { SoundSample.BREAK.play(currentQuestionedPlayer); currentQuestion = null; - AttributeInstance attribute = currentQuestionedPlayer.getAttribute(Attribute.MAX_HEALTH); + AttributeInstance attribute; + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { + attribute = currentQuestionedPlayer.getAttribute(Attribute.valueOf("MAX_HEALTH")); + } else { + attribute = currentQuestionedPlayer.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); + } if (attribute.getBaseValue() == 2) { kill(currentQuestionedPlayer); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java index b00e6b490..d612923c2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java @@ -6,6 +6,8 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.Version; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; import org.bukkit.Color; @@ -74,7 +76,12 @@ private void randomizeEntityHealth(@Nonnull LivingEntity entity) { return; } int health = random.nextInt(getValue() * 100) + 1; - entity.getAttribute(Attribute.MAX_HEALTH).setBaseValue(health); + AttributeInstance attribute; + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { + entity.getAttribute(Attribute.valueOf("MAX_HEALTH")).setBaseValue(health); + } else { + entity.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")).setBaseValue(health); + } entity.setHealth(health); } @@ -94,7 +101,14 @@ private void resetExistingEntityHealth() { EntityType type = entity.getType(); double health = entityDefaultHealth.getOrDefault(type, getDefaultHealth(type)); entityDefaultHealth.put(type, health); - AttributeInstance attribute = entity.getAttribute(Attribute.MAX_HEALTH); + + AttributeInstance attribute; + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { + attribute = entity.getAttribute(Attribute.valueOf("MAX_HEALTH")); + } else { + attribute = entity.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); + } + if (attribute == null) return; attribute.setBaseValue(health); entity.setHealth(health); @@ -107,8 +121,12 @@ private double getDefaultHealth(@Nonnull EntityType entityType) { Entity entity = world.spawnEntity(new Location(world, 0, 0, 0), entityType); entity.remove(); if (!(entity instanceof LivingEntity)) return 0; - AttributeInstance attribute = ((LivingEntity) entity) - .getAttribute(Attribute.MAX_HEALTH); + AttributeInstance attribute; + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { + attribute = ((LivingEntity) entity).getAttribute(Attribute.valueOf("MAX_HEALTH")); + } else { + attribute = ((LivingEntity) entity).getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); + } if (attribute == null) return 10; return attribute.getBaseValue(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index 241c8919d..c843e3d28 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -13,6 +13,7 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; +import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import org.bukkit.Location; @@ -321,8 +322,16 @@ private boolean decreaseDurability() { private boolean isTool(@Nonnull ItemStack itemStack) { if (itemStack.getItemMeta() != null) { try { - Collection attributeModifiers = itemStack.getItemMeta().getAttributeModifiers(Attribute.ATTACK_DAMAGE); + Attribute attribute; + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { + attribute = Attribute.valueOf("MAX_HEALTH"); + } else { + attribute = Attribute.valueOf("GENERIC_MAX_HEALTH"); + } + Collection attributeModifiers = itemStack.getItemMeta().getAttributeModifiers(attribute); return attributeModifiers == null || !attributeModifiers.isEmpty(); + + //TODO: TEST! } catch (NullPointerException exception) { return false; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index e02db2242..65329ae15 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -8,6 +8,7 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; +import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -52,7 +53,12 @@ protected void onValueChange() { public void getWinnersOnEnd(@NotNull List winners) { for (Player player : Bukkit.getOnlinePlayers()) { if (ignorePlayer(player)) continue; - AttributeInstance attribute = player.getAttribute(Attribute.MAX_HEALTH); + AttributeInstance attribute; + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { + attribute = player.getAttribute(Attribute.valueOf("MAX_HEALTH")); + } else { + attribute = player.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); + } if (attribute != null) { if (player.getHealth() >= attribute.getBaseValue()) { winners.add(player); @@ -83,7 +89,12 @@ public void onHealthChange(EntityRegainHealthEvent event) { if (!(event.getEntity() instanceof Player)) return; if (!shouldExecuteEffect()) return; if (ignorePlayer((Player) event.getEntity())) return; - AttributeInstance attribute = ((Player) event.getEntity()).getAttribute(Attribute.MAX_HEALTH); + AttributeInstance attribute; + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { + attribute = ((Player) event.getEntity()).getAttribute(Attribute.valueOf("MAX_HEALTH")); + } else { + attribute = ((Player) event.getEntity()).getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); + } Bukkit.getScheduler().runTask(plugin, () -> { if (attribute != null && ((Player) event.getEntity()).getHealth() >= attribute.getBaseValue()) { ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index 151f58eb9..09d883c5d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -79,7 +79,12 @@ public void onJoin(@Nonnull PlayerJoinEvent event) { } private void updateHealth(Player player) { - AttributeInstance attribute = player.getAttribute(Attribute.MAX_HEALTH); + AttributeInstance attribute; + if (net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion.current().isNewerOrEqualThan(net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion.V1_21_2)) { + attribute = player.getAttribute(Attribute.valueOf("MAX_HEALTH")); + } else { + attribute = player.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); + } if (attribute == null) return; // This should never happen because its a generic attribute, but just in case int newMaxHealth = getMaxHealth(player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java index 1cb01b196..fbb5947a5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java @@ -4,6 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.attribute.Attribute; @@ -72,7 +73,12 @@ public void onSweepDamage(@Nonnull EntityDamageEvent event) { } protected void setAttackSpeed(@Nonnull Player player, double value) { - AttributeInstance attribute = player.getAttribute(Attribute.ATTACK_SPEED); + AttributeInstance attribute; + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { + attribute = player.getAttribute(Attribute.valueOf("ATTACK_SPEED")); + } else { + attribute = player.getAttribute(Attribute.valueOf("GENERIC_ATTACK_SPEED")); + } if (attribute == null) return; attribute.setBaseValue(value); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index 1c91ba073..5621891b2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -4,6 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; import org.bukkit.Bukkit; @@ -92,7 +93,12 @@ public void setHealth(@Nonnull Player player, @Nullable EntityDamageEvent damage if (currentPlayer.equals(player)) continue; double health = player.getHealth(); - AttributeInstance attribute = currentPlayer.getAttribute(Attribute.MAX_HEALTH); + AttributeInstance attribute; + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { + attribute = player.getAttribute(Attribute.valueOf("MAX_HEALTH")); + } else { + attribute = player.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); + } if (attribute == null) return; if (health > attribute.getValue()) { health = attribute.getValue(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java index 2560e98d2..b2df6bd4a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java @@ -4,6 +4,7 @@ import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; +import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; @@ -41,7 +42,12 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { boolean otherPlayers = false; for (Player player : targets) { Message.forName("command-heal-healed").send(player, Prefix.CHALLENGES); - AttributeInstance attribute = player.getAttribute(Attribute.MAX_HEALTH); + AttributeInstance attribute; + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { + attribute = player.getAttribute(Attribute.valueOf("MAX_HEALTH")); + } else { + attribute = player.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); + } if (attribute == null) { player.setHealth(20); } else { From 29fed731ca75d0c5cd2610fe9280b68625e28ee7 Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Fri, 11 Apr 2025 16:42:35 +0200 Subject: [PATCH 021/119] Tested --- .../challenges/implementation/challenge/world/LoopChallenge.java | 1 - 1 file changed, 1 deletion(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index c843e3d28..56d2d73ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -331,7 +331,6 @@ private boolean isTool(@Nonnull ItemStack itemStack) { Collection attributeModifiers = itemStack.getItemMeta().getAttributeModifiers(attribute); return attributeModifiers == null || !attributeModifiers.isEmpty(); - //TODO: TEST! } catch (NullPointerException exception) { return false; } From 61808cf9da73c3310f53131992860f32faa2c16d Mon Sep 17 00:00:00 2001 From: EinfachBeez Date: Sat, 12 Apr 2025 12:35:52 +0200 Subject: [PATCH 022/119] fix: chunk deletion challenges move event --- .../challenge/world/ChunkDeletionChallenge.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java index 9116bda68..82e68bb0f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import de.dytanic.cloudnet.driver.event.EventListener; import java.util.HashMap; import net.anweisen.utilities.common.collection.pair.Tuple; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; @@ -18,6 +17,8 @@ import org.bukkit.block.Block; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; @@ -87,7 +88,7 @@ public void onSecond() { bossbar.update(); } - @EventListener + @EventHandler(priority = EventPriority.HIGH) public void onPlayerMove(PlayerMoveEvent event) { if (event.getTo() == null || !checkIfAllowed(event.getPlayer())) { return; From d57582a793ba5d260b07028e8d94c2064d4beffb Mon Sep 17 00:00:00 2001 From: EinfachBeez Date: Sat, 12 Apr 2025 13:06:39 +0200 Subject: [PATCH 023/119] refactor: use 2-line spacing --- .../damage/DelayDamageChallenge.java | 100 +++++++++--------- 1 file changed, 51 insertions(+), 49 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java index 43ef7c184..d8bc6aee1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java @@ -27,62 +27,64 @@ @Since("2.3.2") public class DelayDamageChallenge extends TimedChallenge { - private boolean canGetDamage = false; - private final Map damageMap = new HashMap<>(); + private boolean canGetDamage = false; + private final Map damageMap = new HashMap<>(); - public DelayDamageChallenge() { - super(MenuType.CHALLENGES, 1, 64, 4, false); - setCategory(SettingCategory.DAMAGE); - } - - @Override - protected int getSecondsUntilNextActivation() { - return getValue() * 30; - } - - @Override - protected void onTimeActivation() { - - double totalDamage = damageMap.values().stream().mapToDouble(Double::doubleValue).sum(); - int playerCount = damageMap.size(); + public DelayDamageChallenge() { + super(MenuType.CHALLENGES, 1, 64, 4, false); + setCategory(SettingCategory.DAMAGE); + } - if (playerCount > 0) { - canGetDamage = true; - for (Player player : Bukkit.getOnlinePlayers()) { - player.damage(totalDamage); - Message.forName(("extreme-force-battle-took-damage")).send(player, Prefix.DAMAGE, totalDamage / 2); - } - canGetDamage = false; - } + @Override + protected int getSecondsUntilNextActivation() { + return getValue() * 30; + } + @Override + protected void onTimeActivation() { - damageMap.clear(); - restartTimer(); - } + double totalDamage = damageMap.values().stream() + .mapToDouble(Double::doubleValue) + .sum(); - @Override - public @NotNull ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.REDSTONE, Message.forName("item-delay-damage-description")); - } + int playerCount = damageMap.size(); - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 30); + if (playerCount > 0) { + canGetDamage = true; + for (Player player : Bukkit.getOnlinePlayers()) { + player.damage(totalDamage); + Message.forName(("extreme-force-battle-took-damage")).send(player, Prefix.DAMAGE, totalDamage / 2); + } + canGetDamage = false; } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerDamage(@Nonnull EntityDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - if (ignorePlayer((Player) event.getEntity())) return; - if (canGetDamage) return; - - double damage = event.getFinalDamage(); - Player player = (Player) event.getEntity(); - - damageMap.put(player, damageMap.getOrDefault(player, 0.0) + damage); - event.setCancelled(true); - } + damageMap.clear(); + restartTimer(); + } + + @Override + public @NotNull ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.REDSTONE, Message.forName("item-delay-damage-description")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue() * 30); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerDamage(@Nonnull EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + if (ignorePlayer((Player) event.getEntity())) return; + if (canGetDamage) return; + + double damage = event.getFinalDamage(); + Player player = (Player) event.getEntity(); + + damageMap.put(player, damageMap.getOrDefault(player, 0.0) + damage); + event.setCancelled(true); + } } \ No newline at end of file From f100b7a8542f1427509ffbf7b04d58b9fd6da6b7 Mon Sep 17 00:00:00 2001 From: EinfachBeez Date: Sat, 12 Apr 2025 13:07:26 +0200 Subject: [PATCH 024/119] refactor: use lombok in LanguageLoader, remove deprecated JsonParser object --- .../plugin/content/loader/LanguageLoader.java | 30 +++++++------------ 1 file changed, 10 insertions(+), 20 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index bdd71312e..dbfad9f25 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -4,6 +4,7 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import lombok.Getter; import net.anweisen.utilities.bukkit.utils.logging.Logger; import net.anweisen.utilities.common.collection.IOUtils; import net.anweisen.utilities.common.config.Document; @@ -27,17 +28,14 @@ public final class LanguageLoader extends ContentLoader { public static final String DEFAULT_LANGUAGE = "en"; public static final String DIRECT_FILE_PATH = "direct-language-file"; - private static final JsonParser parser = new JsonParser(); + @Getter + private static volatile boolean loaded = false; + @Getter + private String language; + @Getter + private boolean smallCapsFont; - private static volatile boolean loaded = false; - private String language; - private boolean smallCapsFont; - - public static boolean isLoaded() { - return loaded; - } - - @Override + @Override protected void load() { Document config = Challenges.getInstance().getConfigDocument(); @@ -89,7 +87,7 @@ private void init() { private void download() { try { - JsonArray languages = parser.parse(IOUtils.toString(getGitHubUrl("language/languages.json"))).getAsJsonArray(); + JsonArray languages = JsonParser.parseString(IOUtils.toString(getGitHubUrl("language/languages.json"))).getAsJsonArray(); Logger.debug("Fetched languages {}", languages); for (JsonElement element : languages) { try { @@ -137,7 +135,7 @@ private void readLanguage(@Nonnull File file) { } int messages = 0; - JsonObject read = parser.parse(FileUtils.newBufferedReader(file)).getAsJsonObject(); + JsonObject read = JsonParser.parseReader(FileUtils.newBufferedReader(file)).getAsJsonObject(); for (Entry entry : read.entrySet()) { Message message = Message.forName(entry.getKey()); JsonElement element = entry.getValue(); @@ -160,12 +158,4 @@ private void readLanguage(@Nonnull File file) { } } - public String getLanguage() { - return language; - } - - public boolean isSmallCapsFont() { - return smallCapsFont; - } - } From edecdd4564b6e073bf630b89949c3dda3c7a19af Mon Sep 17 00:00:00 2001 From: EinfachBeez Date: Sat, 12 Apr 2025 13:28:28 +0200 Subject: [PATCH 025/119] feat: add /language as /setlang alias --- plugin/src/main/resources/plugin.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/plugin/src/main/resources/plugin.yml b/plugin/src/main/resources/plugin.yml index 1bceae874..c331983af 100644 --- a/plugin/src/main/resources/plugin.yml +++ b/plugin/src/main/resources/plugin.yml @@ -230,4 +230,5 @@ commands: description: "Changes the language" permission: "challenges.setlanguage" aliases: - - "setlang" \ No newline at end of file + - "setlang" + - "language" \ No newline at end of file From 9d4ae5af46077c7d4c195f36ed11ddcb0ee1173b Mon Sep 17 00:00:00 2001 From: EinfachBeez Date: Sat, 12 Apr 2025 13:38:35 +0200 Subject: [PATCH 026/119] refactor: use https --- .../codingarea/challenges/plugin/utils/item/DefaultItem.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java index 2a79a3825..477c39c80 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java @@ -30,7 +30,7 @@ public static String getItemPrefix() { public static ItemBuilder navigateBack() { URL BACK_SKULL; try { - BACK_SKULL = new URL("http://textures.minecraft.net/texture/bd69e06e5dadfd84e5f3d1c21063f2553b2fa945ee1d4d7152fdc5425bc12a9"); + BACK_SKULL = new URL("https://textures.minecraft.net/texture/bd69e06e5dadfd84e5f3d1c21063f2553b2fa945ee1d4d7152fdc5425bc12a9"); } catch (MalformedURLException e) { throw new RuntimeException(e); } @@ -41,7 +41,7 @@ public static ItemBuilder navigateBack() { public static ItemBuilder navigateNext() { URL NEXT_SKULL; try { - NEXT_SKULL = new URL("http://textures.minecraft.net/texture/19bf3292e126a105b54eba713aa1b152d541a1d8938829c56364d178ed22bf"); + NEXT_SKULL = new URL("https://textures.minecraft.net/texture/19bf3292e126a105b54eba713aa1b152d541a1d8938829c56364d178ed22bf"); } catch (MalformedURLException e) { throw new RuntimeException(e); } From 759214c1fc342ba64c8185f386808fc820db3e40 Mon Sep 17 00:00:00 2001 From: "coding-area-renovate[bot]" <206263745+coding-area-renovate[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 10:29:27 +0000 Subject: [PATCH 027/119] chore(deps): update dependency org.apache.maven.plugins:maven-shade-plugin to v3.6.0 --- mongo-connector/pom.xml | 2 +- plugin/pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/mongo-connector/pom.xml b/mongo-connector/pom.xml index 6406c776f..eaf8e5da5 100644 --- a/mongo-connector/pom.xml +++ b/mongo-connector/pom.xml @@ -105,7 +105,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.0 package diff --git a/plugin/pom.xml b/plugin/pom.xml index c30129dad..37e2de5f2 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -161,7 +161,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.0 package From be2c01f500642143df7a830c6ae151179e71c7ef Mon Sep 17 00:00:00 2001 From: "coding-area-renovate[bot]" <206263745+coding-area-renovate[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 10:29:23 +0000 Subject: [PATCH 028/119] chore(deps): update dependency org.apache.maven.plugins:maven-resources-plugin to v3.3.1 --- mongo-connector/pom.xml | 2 +- plugin/pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/mongo-connector/pom.xml b/mongo-connector/pom.xml index eaf8e5da5..a6cedbe5c 100644 --- a/mongo-connector/pom.xml +++ b/mongo-connector/pom.xml @@ -130,7 +130,7 @@ org.apache.maven.plugins maven-resources-plugin - 3.2.0 + 3.3.1 copy-license diff --git a/plugin/pom.xml b/plugin/pom.xml index 37e2de5f2..97d4cac20 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -188,7 +188,7 @@ org.apache.maven.plugins maven-resources-plugin - 3.2.0 + 3.3.1 copy-license From 742813ad7ce022fe2edbbdf29e437043522ee14d Mon Sep 17 00:00:00 2001 From: "coding-area-renovate[bot]" <206263745+coding-area-renovate[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 10:29:32 +0000 Subject: [PATCH 029/119] chore(deps): update dependency org.apache.maven.plugins:maven-source-plugin to v3.3.1 --- mongo-connector/pom.xml | 2 +- plugin/pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/mongo-connector/pom.xml b/mongo-connector/pom.xml index a6cedbe5c..4e568ffac 100644 --- a/mongo-connector/pom.xml +++ b/mongo-connector/pom.xml @@ -90,7 +90,7 @@ org.apache.maven.plugins maven-source-plugin - 3.2.1 + 3.3.1 attach-sources diff --git a/plugin/pom.xml b/plugin/pom.xml index 97d4cac20..7ca987af2 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -146,7 +146,7 @@ org.apache.maven.plugins maven-source-plugin - 3.2.1 + 3.3.1 attach-sources From 2b2707ccc9f08f0dd7bd39ac17181f49d1dcc674 Mon Sep 17 00:00:00 2001 From: "coding-area-renovate[bot]" <206263745+coding-area-renovate[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 10:29:18 +0000 Subject: [PATCH 030/119] chore(deps): update dependency org.apache.maven.plugins:maven-compiler-plugin to v3.14.0 --- mongo-connector/pom.xml | 2 +- plugin/pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/mongo-connector/pom.xml b/mongo-connector/pom.xml index 4e568ffac..02619db2e 100644 --- a/mongo-connector/pom.xml +++ b/mongo-connector/pom.xml @@ -79,7 +79,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.10.0 + 3.14.0 1.8 1.8 diff --git a/plugin/pom.xml b/plugin/pom.xml index 7ca987af2..4b864193e 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -127,7 +127,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.10.0 + 3.14.0 1.8 1.8 From 26fb5ad043fb06f29b3960b6be71db04a2ce8d66 Mon Sep 17 00:00:00 2001 From: "coding-area-renovate[bot]" <206263745+coding-area-renovate[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 10:28:57 +0000 Subject: [PATCH 031/119] chore(deps): update jetbrains/qodana-action action to v4.2.5 --- .github/workflows/qodana.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/qodana.yml b/.github/workflows/qodana.yml index fe725d137..31cbd7a2a 100644 --- a/.github/workflows/qodana.yml +++ b/.github/workflows/qodana.yml @@ -9,4 +9,4 @@ jobs: - name: Checkout uses: actions/checkout@v2 - name: Qodana Scan - uses: JetBrains/qodana-action@v4.2.2 \ No newline at end of file + uses: JetBrains/qodana-action@v4.2.5 \ No newline at end of file From 63208a0c5895a48bebef6b4a02d1a87a919e4c38 Mon Sep 17 00:00:00 2001 From: "coding-area-renovate[bot]" <206263745+coding-area-renovate[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 10:29:07 +0000 Subject: [PATCH 032/119] fix(deps): update dependency org.projectlombok:lombok to v1.18.38 --- plugin/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugin/pom.xml b/plugin/pom.xml index 4b864193e..baafb84a0 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -75,7 +75,7 @@ org.projectlombok lombok - 1.18.34 + 1.18.38 provided @@ -136,7 +136,7 @@ org.projectlombok lombok - 1.18.34 + 1.18.38 From bf8824255389d8df115cb7abeb5abec9674d303a Mon Sep 17 00:00:00 2001 From: "coding-area-renovate[bot]" <206263745+coding-area-renovate[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 10:29:02 +0000 Subject: [PATCH 033/119] fix(deps): update dependency org.mongodb:mongodb-driver to v3.12.14 --- mongo-connector/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mongo-connector/pom.xml b/mongo-connector/pom.xml index 02619db2e..cc17f0e40 100644 --- a/mongo-connector/pom.xml +++ b/mongo-connector/pom.xml @@ -30,7 +30,7 @@ org.mongodb mongodb-driver - 3.12.8 + 3.12.14 From aa593bb754d37fede7161f0ac619fd72ea65827b Mon Sep 17 00:00:00 2001 From: "coding-area-renovate[bot]" <206263745+coding-area-renovate[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 10:29:41 +0000 Subject: [PATCH 034/119] fix(deps): update dependency de.dytanic.cloudnet:cloudnet-driver to v3.4.5-release --- plugin/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/pom.xml b/plugin/pom.xml index baafb84a0..caaf01ec1 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -43,7 +43,7 @@ de.dytanic.cloudnet cloudnet-driver - 3.3.0-RELEASE + 3.4.5-RELEASE provided From fb3669566384ed376cb780f0e6faeec9e5c9b1ec Mon Sep 17 00:00:00 2001 From: "coding-area-renovate[bot]" <206263745+coding-area-renovate[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 10:29:36 +0000 Subject: [PATCH 035/119] fix(deps): update dependency de.dytanic.cloudnet:cloudnet-bridge to v3.4.5-release --- plugin/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/pom.xml b/plugin/pom.xml index caaf01ec1..49a44ba2d 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -49,7 +49,7 @@ de.dytanic.cloudnet cloudnet-bridge - 3.3.0-RELEASE + 3.4.5-RELEASE provided From 1369019d45e30d22efa20551dadd1e442a2d5ce2 Mon Sep 17 00:00:00 2001 From: "coding-area-renovate[bot]" <206263745+coding-area-renovate[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 20:15:30 +0000 Subject: [PATCH 036/119] chore(deps): update actions/checkout action to v4 --- .github/workflows/maven-build.yml | 2 +- .github/workflows/qodana.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/maven-build.yml b/.github/workflows/maven-build.yml index 07d7ac626..c6d0d8082 100644 --- a/.github/workflows/maven-build.yml +++ b/.github/workflows/maven-build.yml @@ -12,7 +12,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Set up JDK 17 uses: actions/setup-java@v1 with: diff --git a/.github/workflows/qodana.yml b/.github/workflows/qodana.yml index 31cbd7a2a..1d5ec3156 100644 --- a/.github/workflows/qodana.yml +++ b/.github/workflows/qodana.yml @@ -7,6 +7,6 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Qodana Scan uses: JetBrains/qodana-action@v4.2.5 \ No newline at end of file From 1b27d441f6a559f1314e7147271abed110f1136b Mon Sep 17 00:00:00 2001 From: "coding-area-renovate[bot]" <206263745+coding-area-renovate[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 20:15:59 +0000 Subject: [PATCH 037/119] chore(deps): update actions/setup-java action to v4 --- .github/workflows/maven-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven-build.yml b/.github/workflows/maven-build.yml index c6d0d8082..ec7317125 100644 --- a/.github/workflows/maven-build.yml +++ b/.github/workflows/maven-build.yml @@ -14,7 +14,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up JDK 17 - uses: actions/setup-java@v1 + uses: actions/setup-java@v4 with: java-version: 17 - name: Build with Maven From 95eef3575d407d696cd1f7d5275d68462182e4ad Mon Sep 17 00:00:00 2001 From: CronixZero <47929140+CronixZero@users.noreply.github.com> Date: Tue, 15 Apr 2025 14:11:02 +0200 Subject: [PATCH 038/119] fix: Set Distribution for JDK Action --- .github/workflows/maven-build.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/maven-build.yml b/.github/workflows/maven-build.yml index ec7317125..d980699d1 100644 --- a/.github/workflows/maven-build.yml +++ b/.github/workflows/maven-build.yml @@ -17,6 +17,7 @@ jobs: uses: actions/setup-java@v4 with: java-version: 17 + distribution: amazoncorretto - name: Build with Maven env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From dd97e188edf9e128bce956a2c2a2f3f0d665efa2 Mon Sep 17 00:00:00 2001 From: CronixZero <47929140+CronixZero@users.noreply.github.com> Date: Tue, 15 Apr 2025 14:12:06 +0200 Subject: [PATCH 039/119] fix: Use the right distribution name for setup JDK --- .github/workflows/maven-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven-build.yml b/.github/workflows/maven-build.yml index d980699d1..27375443d 100644 --- a/.github/workflows/maven-build.yml +++ b/.github/workflows/maven-build.yml @@ -17,7 +17,7 @@ jobs: uses: actions/setup-java@v4 with: java-version: 17 - distribution: amazoncorretto + distribution: corretto - name: Build with Maven env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From b18b7ba7baf3fcb5556cbb41d2b5f0bb84e49cb8 Mon Sep 17 00:00:00 2001 From: "coding-area-renovate[bot]" <206263745+coding-area-renovate[bot]@users.noreply.github.com> Date: Tue, 15 Apr 2025 20:44:32 +0200 Subject: [PATCH 040/119] chore(deps): update jetbrains/qodana-action action to v2024 (#79) * chore(deps): update jetbrains/qodana-action action to v2024 * fix(CI): Qodana now runs a Qodana Token and displays Errors directly in the code * fix(CI): Use recommended Qodana Linter * feat(CI): Use Qodana Auto Apply Fixes * feat(CI): Qodana Push Fixes to create PR * chore(CI): Update 'upload-sarif' to v3 * fix(CI): Remove Linter to use Test Version of Qodana * fix(CI): Simply remove upload serif --------- Co-authored-by: coding-area-renovate[bot] <206263745+coding-area-renovate[bot]@users.noreply.github.com> Co-authored-by: CronixZero <47929140+CronixZero@users.noreply.github.com> Co-authored-by: CronixZero --- .github/workflows/code_quality.yml | 29 +++++++++++++++++++++++++++++ .github/workflows/qodana.yml | 12 ------------ qodana.yml | 5 +++-- 3 files changed, 32 insertions(+), 14 deletions(-) create mode 100644 .github/workflows/code_quality.yml delete mode 100644 .github/workflows/qodana.yml diff --git a/.github/workflows/code_quality.yml b/.github/workflows/code_quality.yml new file mode 100644 index 000000000..d46b2211e --- /dev/null +++ b/.github/workflows/code_quality.yml @@ -0,0 +1,29 @@ +name: Qodana +on: + workflow_dispatch: + pull_request: + push: + +permissions: + contents: write + pull-requests: write + checks: write + +jobs: + qodana: + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + checks: write + steps: + - uses: actions/checkout@v3 + with: + ref: ${{ github.event.pull_request.head.sha }} # to check out the actual pull request commit, not the merge commit + fetch-depth: 0 # a full history is required for pull request analysis + - name: 'Qodana Scan' + uses: JetBrains/qodana-action@v2024.3 + env: + QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }} + with: + push-fixes: pull-request diff --git a/.github/workflows/qodana.yml b/.github/workflows/qodana.yml deleted file mode 100644 index 1d5ec3156..000000000 --- a/.github/workflows/qodana.yml +++ /dev/null @@ -1,12 +0,0 @@ -name: Qodana - Code Inspection -on: - push: - -jobs: - qodana: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Qodana Scan - uses: JetBrains/qodana-action@v4.2.5 \ No newline at end of file diff --git a/qodana.yml b/qodana.yml index 31e254679..d017ce4c4 100644 --- a/qodana.yml +++ b/qodana.yml @@ -1,4 +1,5 @@ version: "1.0" -failThreshold: 999 +#linter: jetbrains/qodana-jvm-community:2024.3 +fixesStrategy: apply profile: - name: qodana.starter + name: qodana.recommended From d5e671a13f4c151a170fc9ea747f661f9f208eec Mon Sep 17 00:00:00 2001 From: "coding-area-renovate[bot]" <206263745+coding-area-renovate[bot]@users.noreply.github.com> Date: Tue, 15 Apr 2025 18:44:52 +0000 Subject: [PATCH 041/119] chore(deps): update actions/checkout action to v4 --- .github/workflows/code_quality.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/code_quality.yml b/.github/workflows/code_quality.yml index d46b2211e..b3e26625a 100644 --- a/.github/workflows/code_quality.yml +++ b/.github/workflows/code_quality.yml @@ -17,7 +17,7 @@ jobs: pull-requests: write checks: write steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: ref: ${{ github.event.pull_request.head.sha }} # to check out the actual pull request commit, not the merge commit fetch-depth: 0 # a full history is required for pull request analysis From 33ded1b685d0dbe9fcf83b01f6cf30d0fdfff003 Mon Sep 17 00:00:00 2001 From: Dominik Date: Thu, 17 Apr 2025 23:31:43 +0200 Subject: [PATCH 042/119] feat: AttributeWrapper --- .../action/impl/HealEntityAction.java | 10 ++----- .../challenge/ZeroHeartsChallenge.java | 19 ++++-------- .../challenge/quiz/QuizChallenge.java | 18 +++++------ .../randomizer/RandomizedHPChallenge.java | 30 +++++-------------- .../challenge/world/LoopChallenge.java | 12 +++----- .../goal/GetFullHealthGoal.java | 17 +++-------- .../setting/MaxHealthSetting.java | 10 ++----- .../implementation/setting/OldPvPSetting.java | 10 ++----- .../setting/SplitHealthSetting.java | 10 ++----- .../plugin/spigot/command/HealCommand.java | 10 ++----- .../spigot/generator/VoidMapGenerator.java | 4 +-- .../bukkit/misc/Version/MinecraftVersion.java | 2 +- .../utils/bukkit/misc/Version/Version.java | 2 +- .../misc/Version/VersionComparator.java | 4 +-- .../bukkit/misc/wrapper/AttributeWrapper.java | 23 ++++++++++++++ 15 files changed, 71 insertions(+), 110 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/wrapper/AttributeWrapper.java diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java index 57c9e0b2b..481823ef1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java @@ -2,7 +2,8 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; @@ -36,12 +37,7 @@ public void executeFor(Entity entity, Map subActions) { int amount = Integer.parseInt(subActions.get("amount")[0]); if (entity instanceof LivingEntity) { LivingEntity livingEntity = (LivingEntity) entity; - AttributeInstance attribute; - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { - attribute = livingEntity.getAttribute(Attribute.valueOf("MAX_HEALTH")); - } else { - attribute = livingEntity.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); - } + AttributeInstance attribute = livingEntity.getAttribute(AttributeWrapper.MAX_HEALTH); if (attribute == null) return; double newHealth = Math.min(livingEntity.getHealth() + amount, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index 71dbf31af..33b85cbb4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -8,7 +8,8 @@ import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Bukkit; @@ -48,12 +49,7 @@ protected void onEnable() { }); bossbar.show(); Bukkit.getOnlinePlayers().forEach(player -> { - AttributeInstance attribute; - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { - attribute = player.getAttribute(Attribute.valueOf("MAX_HEALTH")); - } else { - attribute = player.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); - } + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); if (attribute == null) return; attribute.setBaseValue(0); }); @@ -79,12 +75,7 @@ protected void onValueChange() { @ScheduledTask(ticks = 20, async = false) public void onSecond() { broadcast(player -> { - AttributeInstance attribute; - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { - attribute = player.getAttribute(Attribute.valueOf("MAX_HEALTH")); - } else { - attribute = player.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); - } + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); if (attribute == null) return; attribute.setBaseValue(0); }); @@ -124,4 +115,4 @@ public void onEntityPotionEffect(@Nonnull EntityPotionEffectEvent event) { Message.forName("zero-hearts-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index 914094238..214a8e015 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -15,7 +15,8 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; -import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; @@ -111,7 +112,7 @@ public void playValueChangeTitle() { protected int getSecondsUntilNextActivation() { return random.around(getValue() * 60 * 3, 60); } - + private void broadcastMessage(@Nonnull String questionedPlayerMessage, @Nonnull String othersMessage, Object... args) { broadcast(player1 -> { if (currentQuestionedPlayer == player1) { @@ -169,15 +170,10 @@ private void cancelQuestion() { List rightAnswers = currentQuestion.getRightAnswers(); Message.forName("quiz-right-answer-was" + (rightAnswers.size() != 1 ? "-multiple" : "")).send(currentQuestionedPlayer, prefix, StringUtils.getArrayAsString(rightAnswers.toArray(new String[0]), "§7, §e")); SoundSample.BREAK.play(currentQuestionedPlayer); - - currentQuestion = null; - AttributeInstance attribute; - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { - attribute = currentQuestionedPlayer.getAttribute(Attribute.valueOf("MAX_HEALTH")); - } else { - attribute = currentQuestionedPlayer.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); - } + currentQuestion = null; + AttributeInstance attribute = currentQuestionedPlayer.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return; if (attribute.getBaseValue() == 2) { kill(currentQuestionedPlayer); attribute.setBaseValue(20); @@ -209,7 +205,7 @@ public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exc bossbar.update(); return; } - + broadcastMessage("quiz-right-answer", "quiz-right-answer-other", answer); SoundSample.LEVEL_UP.play(player); currentQuestion = null; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java index d612923c2..8d6d841ab 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java @@ -6,8 +6,8 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; -import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.Version; +import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; import org.bukkit.Color; @@ -76,13 +76,10 @@ private void randomizeEntityHealth(@Nonnull LivingEntity entity) { return; } int health = random.nextInt(getValue() * 100) + 1; - AttributeInstance attribute; - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { - entity.getAttribute(Attribute.valueOf("MAX_HEALTH")).setBaseValue(health); - } else { - entity.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")).setBaseValue(health); - } entity.setHealth(health); + AttributeInstance attribute = entity.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return; + attribute.setBaseValue(health); } private void randomizeExistingEntityHealth() { @@ -102,13 +99,7 @@ private void resetExistingEntityHealth() { double health = entityDefaultHealth.getOrDefault(type, getDefaultHealth(type)); entityDefaultHealth.put(type, health); - AttributeInstance attribute; - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { - attribute = entity.getAttribute(Attribute.valueOf("MAX_HEALTH")); - } else { - attribute = entity.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); - } - + AttributeInstance attribute = entity.getAttribute(AttributeWrapper.MAX_HEALTH); if (attribute == null) return; attribute.setBaseValue(health); entity.setHealth(health); @@ -121,12 +112,7 @@ private double getDefaultHealth(@Nonnull EntityType entityType) { Entity entity = world.spawnEntity(new Location(world, 0, 0, 0), entityType); entity.remove(); if (!(entity instanceof LivingEntity)) return 0; - AttributeInstance attribute; - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { - attribute = ((LivingEntity) entity).getAttribute(Attribute.valueOf("MAX_HEALTH")); - } else { - attribute = ((LivingEntity) entity).getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); - } + AttributeInstance attribute = ((LivingEntity) entity).getAttribute(AttributeWrapper.MAX_HEALTH); if (attribute == null) return 10; return attribute.getBaseValue(); } @@ -154,4 +140,4 @@ protected String[] getSettingsDescription() { return Message.forName("item-max-health-description").asArray(getValue() * 50); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index 56d2d73ed..0982c2576 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -13,7 +13,8 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; -import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import org.bukkit.Location; @@ -322,12 +323,7 @@ private boolean decreaseDurability() { private boolean isTool(@Nonnull ItemStack itemStack) { if (itemStack.getItemMeta() != null) { try { - Attribute attribute; - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { - attribute = Attribute.valueOf("MAX_HEALTH"); - } else { - attribute = Attribute.valueOf("GENERIC_MAX_HEALTH"); - } + Attribute attribute = AttributeWrapper.MAX_HEALTH; Collection attributeModifiers = itemStack.getItemMeta().getAttributeModifiers(attribute); return attributeModifiers == null || !attributeModifiers.isEmpty(); @@ -377,4 +373,4 @@ private boolean decreaseItem() { } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index 65329ae15..f0ddfbf14 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -8,7 +8,8 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -53,12 +54,7 @@ protected void onValueChange() { public void getWinnersOnEnd(@NotNull List winners) { for (Player player : Bukkit.getOnlinePlayers()) { if (ignorePlayer(player)) continue; - AttributeInstance attribute; - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { - attribute = player.getAttribute(Attribute.valueOf("MAX_HEALTH")); - } else { - attribute = player.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); - } + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); if (attribute != null) { if (player.getHealth() >= attribute.getBaseValue()) { winners.add(player); @@ -89,13 +85,8 @@ public void onHealthChange(EntityRegainHealthEvent event) { if (!(event.getEntity() instanceof Player)) return; if (!shouldExecuteEffect()) return; if (ignorePlayer((Player) event.getEntity())) return; - AttributeInstance attribute; - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { - attribute = ((Player) event.getEntity()).getAttribute(Attribute.valueOf("MAX_HEALTH")); - } else { - attribute = ((Player) event.getEntity()).getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); - } Bukkit.getScheduler().runTask(plugin, () -> { + AttributeInstance attribute = ((Player) event.getEntity()).getAttribute(AttributeWrapper.MAX_HEALTH); if (attribute != null && ((Player) event.getEntity()).getHealth() >= attribute.getBaseValue()) { ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index 09d883c5d..1275caf10 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -9,8 +9,7 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.bukkit.nms.NMSProvider; -import net.codingarea.challenges.plugin.utils.bukkit.nms.type.CraftPlayer; +import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.attribute.Attribute; @@ -79,12 +78,7 @@ public void onJoin(@Nonnull PlayerJoinEvent event) { } private void updateHealth(Player player) { - AttributeInstance attribute; - if (net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion.current().isNewerOrEqualThan(net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion.V1_21_2)) { - attribute = player.getAttribute(Attribute.valueOf("MAX_HEALTH")); - } else { - attribute = player.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); - } + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); if (attribute == null) return; // This should never happen because its a generic attribute, but just in case int newMaxHealth = getMaxHealth(player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java index fbb5947a5..812befd74 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java @@ -4,7 +4,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.attribute.Attribute; @@ -73,12 +74,7 @@ public void onSweepDamage(@Nonnull EntityDamageEvent event) { } protected void setAttackSpeed(@Nonnull Player player, double value) { - AttributeInstance attribute; - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { - attribute = player.getAttribute(Attribute.valueOf("ATTACK_SPEED")); - } else { - attribute = player.getAttribute(Attribute.valueOf("GENERIC_ATTACK_SPEED")); - } + AttributeInstance attribute = player.getAttribute(AttributeWrapper.ATTACK_SPEED); if (attribute == null) return; attribute.setBaseValue(value); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index 5621891b2..e156b535d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -5,6 +5,7 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; import org.bukkit.Bukkit; @@ -93,12 +94,7 @@ public void setHealth(@Nonnull Player player, @Nullable EntityDamageEvent damage if (currentPlayer.equals(player)) continue; double health = player.getHealth(); - AttributeInstance attribute; - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { - attribute = player.getAttribute(Attribute.valueOf("MAX_HEALTH")); - } else { - attribute = player.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); - } + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); if (attribute == null) return; if (health > attribute.getValue()) { health = attribute.getValue(); @@ -113,4 +109,4 @@ public void setHealth(@Nonnull Player player, @Nullable EntityDamageEvent damage } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java index b2df6bd4a..c9c4bc7c2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java @@ -4,7 +4,8 @@ import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; -import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; +import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; @@ -42,12 +43,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { boolean otherPlayers = false; for (Player player : targets) { Message.forName("command-heal-healed").send(player, Prefix.CHALLENGES); - AttributeInstance attribute; - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21_2)) { - attribute = player.getAttribute(Attribute.valueOf("MAX_HEALTH")); - } else { - attribute = player.getAttribute(Attribute.valueOf("GENERIC_MAX_HEALTH")); - } + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); if (attribute == null) { player.setHealth(20); } else { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java index 20214c166..c2d29a2ba 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java @@ -38,7 +38,7 @@ public class VoidMapGenerator extends ChunkGenerator { // public void loadStrongholds(World world) { // // for (int i = 0; i < 3; i++) { -// Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { +// Bukkit.getScheduler().runTaskLater(Challenges.getInstance().getPlugin(), () -> { // Location portal = world // .locateNearestStructure(new Location(world, 0, 0, 0), StructureType.STRONGHOLD, 180, // true); @@ -60,7 +60,7 @@ public ChunkData generateChunkData(@Nonnull World world, @Nonnull Random random, // if (portalChunks == null) { // portalChunks = Lists.newLinkedList(); -// Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { +// Bukkit.getScheduler().runTask(Challenges.getInstance().getPlugin(), () -> { // loadStrongholds(world); // }); // } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java index cfca3a718..bc7e1afcd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; +package net.codingarea.challenges.plugin.utils.bukkit.misc.version; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java index 871775ea2..3b2d48418 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; +package net.codingarea.challenges.plugin.utils.bukkit.misc.version; import java.util.ArrayList; import java.util.Arrays; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java index 65849ddd0..205a5cbfe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; +package net.codingarea.challenges.plugin.utils.bukkit.misc.version; import java.util.Comparator; import javax.annotation.Nonnull; @@ -10,4 +10,4 @@ public VersionComparator() { public int compare(@Nonnull Version v1, @Nonnull Version v2) { return v1.equals(v2) ? 0 : (v1.isNewerThan(v2) ? 1 : -1); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/wrapper/AttributeWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/wrapper/AttributeWrapper.java new file mode 100644 index 000000000..5b5abbdb8 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/wrapper/AttributeWrapper.java @@ -0,0 +1,23 @@ +package net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper; + +import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; +import org.bukkit.attribute.Attribute; + +public class AttributeWrapper { + + public static final Attribute MAX_HEALTH = wrap("MAX_HEALTH", "GENERIC_MAX_HEALTH"), + ATTACK_SPEED = wrap("ATTACK_SPEED", "GENERIC_ATTACK_SPEED"); + + public static Attribute wrap(String name, String legacyName) { + return wrap(name, legacyName, MinecraftVersion.V1_21_2); + } + + public static Attribute wrap(String name, String legacyName, MinecraftVersion since) { + if (MinecraftVersion.current().isNewerOrEqualThan(since)) { + return Attribute.valueOf(name); + } else { + return Attribute.valueOf(legacyName); + } + } + +} From a210a38abf559d92dd5135c8e86937411866a3ca Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 18 Apr 2025 09:53:07 +0200 Subject: [PATCH 043/119] feat: base64 skulls --- .../setting/LanguageSetting.java | 90 +++++++--------- .../setting/SplitHealthSetting.java | 2 - .../inventory/PlayerInventoryManager.java | 3 +- .../spigot/command/LeaderboardCommand.java | 3 +- .../plugin/spigot/command/StatsCommand.java | 3 +- .../bukkit/misc/Version/VersionInfo.java | 4 +- .../plugin/utils/item/DefaultItem.java | 22 +--- .../plugin/utils/item/ItemBuilder.java | 101 +++++++----------- 8 files changed, 92 insertions(+), 136 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java index 538e49154..16003a6db 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java @@ -15,55 +15,47 @@ public class LanguageSetting extends Modifier { - public static final int ENGLISH = 1; - public static final int GERMAN = 2; - - public static final URL GERMAN_SKULL; - public static final URL ENGLISH_SKULL; - - static { - try { - GERMAN_SKULL = new URL("http://textures.minecraft.net/texture/5e7899b4806858697e283f084d9173fe487886453774626b24bd8cfecc77b3f"); - ENGLISH_SKULL = new URL("http://textures.minecraft.net/texture/46c9923bebd9ad90a80a0731c3f3b9db729b0785015e18e3ec07e4e91099be06"); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } + public static final int ENGLISH = 1; + public static final int GERMAN = 2; + + public static final String GERMAN_SKULL = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNWU3ODk5YjQ4MDY4NTg2OTdlMjgzZjA4NGQ5MTczZmU0ODc4ODY0NTM3NzQ2MjZiMjRiZDhjZmVjYzc3YjNmIn19fQ", + ENGLISH_SKULL = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvODgzMWM3M2Y1NDY4ZTg4OGMzMDE5ZTI4NDdlNDQyZGZhYTg4ODk4ZDUwY2NmMDFmZDJmOTE0YWY1NDRkNTM2OCJ9fX0"; + + public LanguageSetting() { + super(MenuType.SETTINGS, 1, 2, ENGLISH); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.KNOWLEDGE_BOOK, Message.forName("item-language-setting")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + String texture = getValue() == GERMAN ? GERMAN_SKULL : ENGLISH_SKULL; + return new ItemBuilder.SkullBuilder(DefaultItem.getItemPrefix() + Message.forName(getSettingName())).setBase64Texture(texture).hideAttributes(); + } + + @Override + public void playValueChangeTitle() { + switch (getValue()) { + case GERMAN: + Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).reload("de"); + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName(getSettingName())); + break; + case ENGLISH: + Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).reload("en"); + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName(getSettingName())); + break; + default: + ChallengeHelper.playToggleChallengeTitle(this, false); } + } - public LanguageSetting() { - super(MenuType.SETTINGS, 1, 2, ENGLISH); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.KNOWLEDGE_BOOK, Message.forName("item-language-setting")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - ItemBuilder.SkullBuilder GermanSkull = new ItemBuilder.SkullBuilder(GERMAN_SKULL); - ItemBuilder.SkullBuilder EnglishSkull = new ItemBuilder.SkullBuilder(ENGLISH_SKULL); - if (getValue() == GERMAN) - return GermanSkull.setName(DefaultItem.getItemPrefix() + Message.forName("item-language-setting-german")).hideAttributes(); - return EnglishSkull.setName(DefaultItem.getItemPrefix() + Message.forName("item-language-setting-english")).hideAttributes(); - } - - @Override - public void playValueChangeTitle() { - switch (getValue()) { - case GERMAN: - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-language-setting-german")); - Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).reload("de"); - break; - case ENGLISH: - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-language-setting-english")); - Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).reload("en"); - break; - default: - ChallengeHelper.playToggleChallengeTitle(this, false); - } - } + private String getSettingName() { + return getValue() == GERMAN ? "item-language-setting-german" : "item-language-setting-english"; + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index e156b535d..a12386d82 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -4,14 +4,12 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.bukkit.misc.Version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Material; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java index 86dbe5052..7ffdeb017 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java @@ -247,7 +247,8 @@ private Triple, String>[] createItemPairs(@Nonnull P ItemStack stack; if (item.getMaterial() == Material.PLAYER_HEAD) { - stack = new SkullBuilder(player.getUniqueId(), player.getName(), Message.forName(item.getMessage()).asString()).build(); + stack = new SkullBuilder(Message.forName(item.getMessage()).asString()) + .setOwner(player.getUniqueId(), player.getName()).build(); } else { stack = new ItemBuilder(item.getMaterial(), Message.forName(item.getMessage()).asString()).build(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java index 343fca319..1e9024ae2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java @@ -103,7 +103,8 @@ private void openMenu0(@Nonnull Player player, @Nonnull Statistic statistic, int int slot = slots[i - offset]; PlayerStats stats = leaderboard.get(i); String coloredName = cloudSupport.isNameSupport() && cloudSupport.hasNameFor(stats.getPlayerUUID()) ? cloudSupport.getColoredName(stats.getPlayerUUID()) : stats.getPlayerName(); - ItemBuilder item = new SkullBuilder(stats.getPlayerUUID(), stats.getPlayerName()).setName(Message.forName("stats-leaderboard-display") + ItemBuilder item = new SkullBuilder().setOwner(stats.getPlayerUUID(), stats.getPlayerName()) + .setName(Message.forName("stats-leaderboard-display") .asArray(coloredName, statistic.formatChat(stats.getStatisticValue(statistic)), statisticName, i + 1)); inventory.cloneLastAndAdd().setItem(slot, item.hideAttributes()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java index 057a6289b..a07af3445 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java @@ -17,6 +17,7 @@ import net.codingarea.challenges.plugin.utils.misc.StatsHelper; import net.codingarea.challenges.plugin.utils.misc.Utils; import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import javax.annotation.Nonnull; @@ -99,7 +100,7 @@ private void open(@Nonnull Player player, @Nonnull UUID uuid, @Nonnull String na AnimatedInventory inventory = new AnimatedInventory(InventoryTitleManager.getStatsTitle(name), 5 * 9, MenuPosition.HOLDER); StatsHelper.setAccent(inventory, 3); - inventory.cloneLastAndAdd().setItem(13, new SkullBuilder(uuid, name, Message.forName("stats-of").asString(coloredName)).build()); + inventory.cloneLastAndAdd().setItem(13, new SkullBuilder(Message.forName("stats-of").asString(coloredName)).setOwner(uuid, name).build()); LeaderboardInfo info = Challenges.getInstance().getStatsManager().getLeaderboardInfo(uuid); createInventory(stats, info, inventory, StatsHelper.getSlots(2)); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java index f5d1ae911..17b50e494 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; +package net.codingarea.challenges.plugin.utils.bukkit.misc.version; import java.util.Objects; import javax.annotation.Nullable; @@ -76,4 +76,4 @@ public static Version parse(@Nullable String input, Version def) { return def; } } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java index 477c39c80..b7fb9d587 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java @@ -16,10 +16,8 @@ */ public final class DefaultItem { - // Owner: MHF_ArrowLeft - private static final UUID ARROW_LEFT_UUID = UUID.fromString("a68f0b64-8d14-4000-a95f-4b9ba14f8df9"); - // Owner: MHF_ArrowRight - private static final UUID ARROW_RIGHT_UUID = UUID.fromString("50c8510b-5ea0-4d60-be9a-7d542d6cd156"); + private static final String ARROW_LEFT = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjAwNmVjMWVjYTJmMjY4NWY3MGU2NTQxMWNmZTg4MDhhMDg4ZjdjZjA4MDg3YWQ4ZWVjZTk2MTgzNjEwNzBlMyJ9fX0=", + ARROW_RIGHT = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZmY5ZTE5ZTVmMmNlMzQ4OGMyOTU4MmI2ZDI2MDE1MDA2MjZlOGRiMmE4OGNkMTgxNjQ0MzJmZWYyZTM0ZGU2YiJ9fX0="; @Nonnull public static String getItemPrefix() { @@ -28,24 +26,12 @@ public static String getItemPrefix() { @Nonnull public static ItemBuilder navigateBack() { - URL BACK_SKULL; - try { - BACK_SKULL = new URL("https://textures.minecraft.net/texture/bd69e06e5dadfd84e5f3d1c21063f2553b2fa945ee1d4d7152fdc5425bc12a9"); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - return new SkullBuilder(BACK_SKULL).setName(Message.forName("navigate-back")).hideAttributes(); + return new SkullBuilder().setBase64Texture(ARROW_LEFT).setName(Message.forName("navigate-back")).hideAttributes(); } @Nonnull public static ItemBuilder navigateNext() { - URL NEXT_SKULL; - try { - NEXT_SKULL = new URL("https://textures.minecraft.net/texture/19bf3292e126a105b54eba713aa1b152d541a1d8938829c56364d178ed22bf"); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - return new SkullBuilder(NEXT_SKULL).setName(Message.forName("navigate-next")).hideAttributes(); + return new SkullBuilder().setBase64Texture(ARROW_RIGHT).setName(Message.forName("navigate-next")).hideAttributes(); } @Nonnull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index 8a036b51c..24ca1b091 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -1,5 +1,7 @@ package net.codingarea.challenges.plugin.utils.item; +import com.google.gson.JsonParser; +import lombok.NonNull; import net.anweisen.utilities.bukkit.utils.item.BannerPattern; import net.anweisen.utilities.bukkit.utils.misc.GameProfileUtils; import net.anweisen.utilities.common.annotations.DeprecatedSince; @@ -8,10 +10,7 @@ import net.codingarea.challenges.plugin.content.ItemDescription; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.misc.DatabaseHelper; -import org.bukkit.Bukkit; -import org.bukkit.Color; -import org.bukkit.DyeColor; -import org.bukkit.Material; +import org.bukkit.*; import org.bukkit.block.banner.Pattern; import org.bukkit.block.banner.PatternType; import org.bukkit.enchantments.Enchantment; @@ -20,11 +19,14 @@ import org.bukkit.inventory.meta.*; import org.bukkit.potion.PotionEffect; import org.bukkit.profile.PlayerProfile; +import org.bukkit.profile.PlayerTextures; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import java.net.MalformedURLException; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.util.*; /** @@ -278,80 +280,55 @@ public SkullBuilder() { super(Material.PLAYER_HEAD); } - /** - * @deprecated Use uuid and name to be able to access database cached textures to reduce loading time - */ - @Deprecated - @DeprecatedSince("2.0") - public SkullBuilder(@Nonnull String owner) { - super(Material.PLAYER_HEAD); - setOwner(owner); + public SkullBuilder(Message message) { + super(Material.PLAYER_HEAD, message); } - /** - * @deprecated Use uuid and name to be able to access database cached textures to reduce loading time - */ - @Deprecated - @DeprecatedSince("2.0") - public SkullBuilder(@Nonnull String owner, @Nonnull String name, @Nonnull String... lore) { + public SkullBuilder(String name, String... lore) { super(Material.PLAYER_HEAD, name, lore); - setOwner(owner); - } - - public SkullBuilder(@Nonnull UUID ownerUUID, @Nonnull String ownerName) { - super(Material.PLAYER_HEAD); - setOwner(ownerUUID, ownerName); } - public SkullBuilder(@Nonnull UUID ownerUUID, @Nonnull String ownerName, @Nonnull Message message) { - super(Material.PLAYER_HEAD, message); - setOwner(ownerUUID, ownerName); - } - - public SkullBuilder(@Nonnull UUID ownerUUID, @Nonnull String ownerName, @Nonnull ItemDescription description) { - super(Material.PLAYER_HEAD, description); - setOwner(ownerUUID, ownerName); + @NonNull + public ItemBuilder.SkullBuilder setOwner(@NonNull OfflinePlayer owner) { + getMeta().setOwningPlayer(owner); + return this; } - public SkullBuilder(@Nonnull UUID ownerUUID, @Nonnull String ownerName, @Nonnull String name, @Nonnull String... lore) { - super(Material.PLAYER_HEAD, name, lore); - setOwner(ownerUUID, ownerName); + @NonNull + public ItemBuilder.SkullBuilder setOwner(@NonNull UUID uuid, @NonNull String name) { + PlayerProfile profile = Bukkit.createPlayerProfile(uuid, name); + getMeta().setOwnerProfile(profile); + return this; } - public SkullBuilder(@Nonnull URL base64) { - super(new ItemStack(Material.PLAYER_HEAD) {{ - SkullMeta meta = (SkullMeta) getItemMeta(); - - PlayerProfile profile = Bukkit.createPlayerProfile(UUID.randomUUID()); - profile.getTextures().setSkin(base64); + public ItemBuilder.SkullBuilder setTexture(@NonNull String textureUrl) { + UUID uuid = UUID.nameUUIDFromBytes(textureUrl.getBytes()); - meta.setOwnerProfile(profile); + PlayerProfile profile = Bukkit.createPlayerProfile(uuid); + PlayerTextures texture = profile.getTextures(); - setItemMeta(meta); - }}); - } + try { + texture.setSkin(new URL(textureUrl)); + } catch (MalformedURLException e) { + throw new IllegalArgumentException("Invalid texture url", e); + } - @Nonnull - @Deprecated - @DeprecatedSince("2.0") - @ReplaceWith("setOwner(UUID)") - public ItemBuilder.SkullBuilder setOwner(@Nonnull String owner) { - getMeta().setOwner(owner); + profile.setTextures(texture); + getMeta().setOwnerProfile(profile); return this; } - @Nonnull - public ItemBuilder.SkullBuilder setOwner(@Nonnull UUID uuid, @Nonnull String name) { - if (Challenges.getInstance().getDatabaseManager().isEnabled()) { - String textures = DatabaseHelper.getTextures(uuid); - if (textures != null) { - GameProfileUtils.applyTextures(getMeta(), uuid, name, textures); - return this; - } - } + public ItemBuilder.SkullBuilder setBase64Texture(@NonNull String base64Texture) { + String textureUrlJson = new String(Base64.getDecoder().decode(base64Texture), + StandardCharsets.UTF_8); - setOwner(name); - return this; + String textureUrl = JsonParser.parseString(textureUrlJson) + .getAsJsonObject() + .get("textures").getAsJsonObject() + .get("SKIN").getAsJsonObject() + .get("url").getAsString(); + + return setTexture(textureUrl); } @Nonnull From c4b313eba4f5078e8333c0b3416de9e3926c0cf4 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 18 Apr 2025 10:01:12 +0200 Subject: [PATCH 044/119] style: remove author headers --- .../challenges/mongoconnector/MongoConnector.java | 5 +---- .../net/codingarea/challenges/plugin/ChallengeAPI.java | 4 ---- .../java/net/codingarea/challenges/plugin/Challenges.java | 5 ----- .../plugin/challenges/custom/CustomChallenge.java | 4 ---- .../challenges/custom/settings/ChallengeExecutionData.java | 4 ---- .../challenges/custom/settings/ChallengeSetting.java | 4 ---- .../challenges/custom/settings/CustomSettingsLoader.java | 4 ---- .../plugin/challenges/custom/settings/FallbackNames.java | 4 ---- .../challenges/custom/settings/IChallengeSetting.java | 4 ---- .../plugin/challenges/custom/settings/SettingType.java | 4 ---- .../challenges/custom/settings/action/ChallengeAction.java | 4 ---- .../custom/settings/action/EntityTargetAction.java | 4 ---- .../custom/settings/action/IChallengeAction.java | 4 ---- .../custom/settings/action/IEntityTargetAction.java | 4 ---- .../custom/settings/action/PlayerTargetAction.java | 4 ---- .../settings/action/impl/AddPermanentEffectAction.java | 4 ---- .../settings/action/impl/BoostEntityInAirAction.java | 4 ---- .../custom/settings/action/impl/CancelEventAction.java | 4 ---- .../settings/action/impl/ChangeWorldBorderAction.java | 4 ---- .../custom/settings/action/impl/ClearInventoryAction.java | 4 ---- .../custom/settings/action/impl/DamageEntityAction.java | 4 ---- .../custom/settings/action/impl/DropRandomItemAction.java | 4 ---- .../custom/settings/action/impl/ExecuteCommandAction.java | 4 ---- .../custom/settings/action/impl/FreezeAction.java | 4 ---- .../custom/settings/action/impl/HealEntityAction.java | 4 ---- .../custom/settings/action/impl/HungerPlayerAction.java | 4 ---- .../custom/settings/action/impl/InvertHealthAction.java | 4 ---- .../custom/settings/action/impl/JumpAndRunAction.java | 4 ---- .../custom/settings/action/impl/KillEntityAction.java | 4 ---- .../custom/settings/action/impl/ModifyMaxHealthAction.java | 4 ---- .../custom/settings/action/impl/PlaceStructureAction.java | 4 ---- .../custom/settings/action/impl/PotionEffectAction.java | 4 ---- .../custom/settings/action/impl/RandomHotBarAction.java | 4 ---- .../custom/settings/action/impl/RandomItemAction.java | 4 ---- .../custom/settings/action/impl/RandomMobAction.java | 4 ---- .../settings/action/impl/RandomPotionEffectAction.java | 4 ---- .../settings/action/impl/RemoveRandomItemAction.java | 4 ---- .../custom/settings/action/impl/SpawnEntityAction.java | 4 ---- .../custom/settings/action/impl/SwapRandomItemAction.java | 4 ---- .../custom/settings/action/impl/SwapRandomMobAction.java | 4 ---- .../settings/action/impl/UncraftInventoryAction.java | 4 ---- .../custom/settings/action/impl/WaterMLGAction.java | 4 ---- .../custom/settings/action/impl/WinChallengeAction.java | 4 ---- .../challenges/custom/settings/sub/SubSettingsBuilder.java | 4 ---- .../challenges/custom/settings/sub/ValueSetting.java | 4 ---- .../settings/sub/builder/ChooseItemSubSettingsBuilder.java | 4 ---- .../sub/builder/ChooseMultipleItemSubSettingBuilder.java | 4 ---- .../settings/sub/builder/EmptySubSettingsBuilder.java | 4 ---- .../settings/sub/builder/GeneratorSubSettingsBuilder.java | 4 ---- .../settings/sub/builder/TextInputSubSettingsBuilder.java | 4 ---- .../settings/sub/builder/ValueSubSettingsBuilder.java | 4 ---- .../custom/settings/sub/impl/BooleanSetting.java | 4 ---- .../custom/settings/sub/impl/ModifierSetting.java | 4 ---- .../custom/settings/trigger/ChallengeTrigger.java | 4 ---- .../custom/settings/trigger/IChallengeTrigger.java | 4 ---- .../custom/settings/trigger/impl/AdvancementTrigger.java | 4 ---- .../custom/settings/trigger/impl/BreakBlockTrigger.java | 4 ---- .../custom/settings/trigger/impl/ConsumeItemTrigger.java | 4 ---- .../custom/settings/trigger/impl/CraftItemTrigger.java | 4 ---- .../custom/settings/trigger/impl/DropItemTrigger.java | 4 ---- .../settings/trigger/impl/EntityDamageByPlayerTrigger.java | 4 ---- .../custom/settings/trigger/impl/EntityDamageTrigger.java | 4 ---- .../custom/settings/trigger/impl/EntityDeathTrigger.java | 4 ---- .../custom/settings/trigger/impl/GainXPTrigger.java | 4 ---- .../custom/settings/trigger/impl/GetItemTrigger.java | 4 ---- .../custom/settings/trigger/impl/HungerTrigger.java | 4 ---- .../custom/settings/trigger/impl/InLiquidTrigger.java | 4 ---- .../custom/settings/trigger/impl/IntervallTrigger.java | 4 ---- .../custom/settings/trigger/impl/LevelUpTrigger.java | 4 ---- .../custom/settings/trigger/impl/MoveBlockTrigger.java | 4 ---- .../custom/settings/trigger/impl/MoveCameraTrigger.java | 4 ---- .../custom/settings/trigger/impl/MoveDownTrigger.java | 4 ---- .../custom/settings/trigger/impl/MoveUpTrigger.java | 4 ---- .../custom/settings/trigger/impl/PickupItemTrigger.java | 4 ---- .../custom/settings/trigger/impl/PlaceBlockTrigger.java | 4 ---- .../custom/settings/trigger/impl/PlayerJumpTrigger.java | 4 ---- .../custom/settings/trigger/impl/PlayerSneakTrigger.java | 4 ---- .../trigger/impl/StandsNotOnSpecificBlockTrigger.java | 4 ---- .../trigger/impl/StandsOnSpecificBlockTrigger.java | 4 ---- .../implementation/challenge/DamageTeleportChallenge.java | 6 +----- .../implementation/challenge/ZeroHeartsChallenge.java | 4 ---- .../challenge/damage/AdvancementDamageChallenge.java | 6 +----- .../challenge/damage/BlockBreakDamageChallenge.java | 7 +------ .../challenge/damage/BlockPlaceDamageChallenge.java | 7 +------ .../challenge/damage/DamagePerBlockChallenge.java | 6 +----- .../challenge/damage/DeathOnFallChallenge.java | 6 +----- .../challenge/damage/DelayDamageChallenge.java | 7 +------ .../implementation/challenge/damage/FreezeChallenge.java | 6 +----- .../challenge/damage/JumpDamageChallenge.java | 6 +----- .../challenge/damage/ReversedDamageChallenge.java | 6 +----- .../challenge/damage/SneakDamageChallenge.java | 6 +----- .../challenge/damage/WaterAllergyChallenge.java | 6 +----- .../challenge/effect/BlockEffectChallenge.java | 6 +----- .../challenge/effect/ChunkRandomEffectChallenge.java | 4 ---- .../challenge/effect/EntityRandomEffectChallenge.java | 4 ---- .../challenge/effect/InfectionChallenge.java | 6 +----- .../challenge/effect/PermanentEffectOnDamageChallenge.java | 6 +----- .../challenge/effect/RandomPotionEffectChallenge.java | 6 +----- .../challenge/entities/AllMobsToDeathPoint.java | 6 +----- .../challenge/entities/BlockMobsChallenge.java | 4 ---- .../challenge/entities/DupedSpawningChallenge.java | 6 +----- .../challenge/entities/HydraNormalChallenge.java | 6 +----- .../challenge/entities/HydraPlusChallenge.java | 6 +----- .../challenge/entities/InvisibleMobsChallenge.java | 6 +----- .../challenge/entities/MobSightDamageChallenge.java | 6 +----- .../challenge/entities/MobTransformationChallenge.java | 6 +----- .../challenge/entities/MobsRespawnInEndChallenge.java | 4 ---- .../challenge/entities/NewEntityOnJumpChallenge.java | 6 +----- .../challenge/entities/StoneSightChallenge.java | 6 +----- .../challenge/extraworld/JumpAndRunChallenge.java | 4 ---- .../challenge/extraworld/WaterMLGChallenge.java | 6 +----- .../challenge/force/ForceBiomeChallenge.java | 4 ---- .../challenge/force/ForceBlockChallenge.java | 4 ---- .../challenge/force/ForceHeightChallenge.java | 4 ---- .../implementation/challenge/force/ForceItemChallenge.java | 4 ---- .../implementation/challenge/force/ForceMobChallenge.java | 4 ---- .../challenge/inventory/DamageInventoryClearChallenge.java | 6 +----- .../challenge/inventory/MissingItemsChallenge.java | 6 +----- .../challenge/inventory/MovementItemRemovingChallenge.java | 4 ---- .../challenge/inventory/NoDupedItemsChallenge.java | 6 +----- .../challenge/inventory/PermanentItemChallenge.java | 6 +----- .../challenge/inventory/PickupItemLaunchChallenge.java | 4 ---- .../challenge/inventory/UncraftItemsChallenge.java | 6 +----- .../challenge/miscellaneous/EnderGamesChallenge.java | 4 ---- .../challenge/miscellaneous/FoodLaunchChallenge.java | 4 ---- .../challenge/miscellaneous/FoodOnceChallenge.java | 6 +----- .../challenge/miscellaneous/InvertHealthChallenge.java | 4 ---- .../challenge/miscellaneous/LowDropRateChallenge.java | 4 ---- .../challenge/miscellaneous/NoExpChallenge.java | 6 +----- .../miscellaneous/NoSharedAdvancementsChallenge.java | 4 ---- .../challenge/miscellaneous/NoTradingChallenge.java | 6 +----- .../challenge/miscellaneous/OneDurabilityChallenge.java | 6 +----- .../challenge/movement/AlwaysRunningChallenge.java | 4 ---- .../challenge/movement/DontStopRunningChallenge.java | 6 +----- .../challenge/movement/FiveHundredBlocksChallenge.java | 4 ---- .../challenge/movement/HigherJumpsChallenge.java | 4 ---- .../challenge/movement/HungerPerBlockChallenge.java | 6 +----- .../implementation/challenge/movement/MoveMouseDamage.java | 4 ---- .../challenge/movement/OnlyDirtChallenge.java | 6 +----- .../challenge/movement/OnlyDownChallenge.java | 6 +----- .../challenge/movement/TrafficLightChallenge.java | 4 ---- .../implementation/challenge/quiz/QuizChallenge.java | 4 ---- .../challenge/randomizer/BlockRandomizerChallenge.java | 4 ---- .../challenge/randomizer/CraftingRandomizerChallenge.java | 4 ---- .../challenge/randomizer/HotBarRandomizerChallenge.java | 4 ---- .../challenge/randomizer/MobRandomizerChallenge.java | 6 +----- .../challenge/randomizer/RandomChallengeChallenge.java | 4 ---- .../challenge/randomizer/RandomEventChallenge.java | 4 ---- .../challenge/randomizer/RandomItemChallenge.java | 4 ---- .../challenge/randomizer/RandomItemDroppingChallenge.java | 6 +----- .../challenge/randomizer/RandomItemRemovingChallenge.java | 6 +----- .../challenge/randomizer/RandomItemSwappingChallenge.java | 6 +----- .../challenge/randomizer/RandomTeleportOnHitChallenge.java | 4 ---- .../challenge/randomizer/RandomizedHPChallenge.java | 4 ---- .../challenge/time/MaxBiomeTimeChallenge.java | 6 +----- .../challenge/time/MaxHeightTimeChallenge.java | 6 +----- .../challenge/world/AllBlocksDisappearChallenge.java | 4 ---- .../implementation/challenge/world/AnvilRainChallenge.java | 6 +----- .../challenge/world/BedrockPathChallenge.java | 7 +------ .../challenge/world/BedrockWallChallenge.java | 7 +------ .../challenge/world/BlockFlyInAirChallenge.java | 4 ---- .../challenge/world/BlocksDisappearAfterTimeChallenge.java | 6 +----- .../challenge/world/ChunkDeconstructionChallenge.java | 6 +----- .../challenge/world/FloorIsLavaChallenge.java | 7 +------ .../implementation/challenge/world/IceFloorChallenge.java | 6 +----- .../challenge/world/LevelBorderChallenge.java | 4 ---- .../implementation/challenge/world/LoopChallenge.java | 4 ---- .../challenge/world/RepeatInChunkChallenge.java | 4 ---- .../implementation/challenge/world/SnakeChallenge.java | 4 ---- .../challenge/world/SurfaceHoleChallenge.java | 7 +------ .../implementation/challenge/world/TsunamiChallenge.java | 7 +------ .../implementation/damage/DamageRuleSetting.java | 6 +----- .../challenges/implementation/goal/AllAdvancementGoal.java | 4 ---- .../implementation/goal/CollectAllItemsGoal.java | 4 ---- .../implementation/goal/CollectHorseAmorGoal.java | 4 ---- .../implementation/goal/CollectIceBlocksGoal.java | 4 ---- .../implementation/goal/CollectMostDeathsGoal.java | 4 ---- .../challenges/implementation/goal/CollectMostExpGoal.java | 4 ---- .../implementation/goal/CollectMostItemsGoal.java | 4 ---- .../challenges/implementation/goal/CollectSwordsGoal.java | 4 ---- .../challenges/implementation/goal/CollectWoodGoal.java | 6 +----- .../implementation/goal/CollectWorkstationsGoal.java | 4 ---- .../plugin/challenges/implementation/goal/EatCakeGoal.java | 4 ---- .../plugin/challenges/implementation/goal/EatMostGoal.java | 4 ---- .../challenges/implementation/goal/FindElytraGoal.java | 4 ---- .../challenges/implementation/goal/FinishRaidGoal.java | 6 +----- .../challenges/implementation/goal/FirstOneToDieGoal.java | 4 ---- .../challenges/implementation/goal/GetFullHealthGoal.java | 4 ---- .../challenges/implementation/goal/KillAllBossesGoal.java | 6 +----- .../implementation/goal/KillAllBossesNewGoal.java | 6 +----- .../challenges/implementation/goal/KillAllMobsGoal.java | 4 ---- .../challenges/implementation/goal/KillAllMonsterGoal.java | 4 ---- .../implementation/goal/KillElderGuardianGoal.java | 4 ---- .../implementation/goal/KillEnderDragonGoal.java | 4 ---- .../challenges/implementation/goal/KillIronGolemGoal.java | 4 ---- .../challenges/implementation/goal/KillSnowGolemGoal.java | 4 ---- .../challenges/implementation/goal/KillWardenGoal.java | 4 ---- .../challenges/implementation/goal/KillWitherGoal.java | 4 ---- .../implementation/goal/LastManStandingGoal.java | 4 ---- .../challenges/implementation/goal/MaxHeightGoal.java | 4 ---- .../challenges/implementation/goal/MinHeightGoal.java | 4 ---- .../challenges/implementation/goal/MineMostBlocksGoal.java | 4 ---- .../challenges/implementation/goal/MostEmeraldsGoal.java | 6 +----- .../challenges/implementation/goal/MostOresGoal.java | 4 ---- .../plugin/challenges/implementation/goal/RaceGoal.java | 4 ---- .../goal/forcebattle/ExtremeForceBattleGoal.java | 4 ---- .../goal/forcebattle/ForceAdvancementBattleGoal.java | 4 ---- .../goal/forcebattle/ForceBiomeBattleGoal.java | 4 ---- .../goal/forcebattle/ForceBlockBattleGoal.java | 4 ---- .../goal/forcebattle/ForceDamageBattleGoal.java | 4 ---- .../goal/forcebattle/ForceHeightBattleGoal.java | 4 ---- .../goal/forcebattle/ForceItemBattleGoal.java | 4 ---- .../goal/forcebattle/ForceMobBattleGoal.java | 4 ---- .../goal/forcebattle/ForcePositionBattleGoal.java | 4 ---- .../goal/forcebattle/targets/AdvancementTarget.java | 4 ---- .../goal/forcebattle/targets/BiomeTarget.java | 4 ---- .../goal/forcebattle/targets/BlockTarget.java | 4 ---- .../goal/forcebattle/targets/DamageTarget.java | 4 ---- .../goal/forcebattle/targets/ForceTarget.java | 6 +----- .../goal/forcebattle/targets/HeightTarget.java | 4 ---- .../goal/forcebattle/targets/ItemTarget.java | 4 ---- .../implementation/goal/forcebattle/targets/MobTarget.java | 4 ---- .../goal/forcebattle/targets/PositionTarget.java | 4 ---- .../implementation/material/BlockMaterialSetting.java | 6 +----- .../challenges/implementation/setting/BackpackSetting.java | 4 ---- .../implementation/setting/BastionSpawnSetting.java | 4 ---- .../challenges/implementation/setting/CutCleanSetting.java | 5 ----- .../implementation/setting/DamageDisplaySetting.java | 4 ---- .../implementation/setting/DamageMultiplierModifier.java | 4 ---- .../implementation/setting/DeathMessageSetting.java | 4 ---- .../implementation/setting/DeathPositionSetting.java | 4 ---- .../implementation/setting/DifficultySetting.java | 5 ----- .../implementation/setting/EnderChestCommandSetting.java | 6 +----- .../implementation/setting/FortressSpawnSetting.java | 4 ---- .../implementation/setting/HealthDisplaySetting.java | 4 ---- .../implementation/setting/ImmediateRespawnSetting.java | 6 +----- .../implementation/setting/KeepInventorySetting.java | 6 +----- .../implementation/setting/MaxHealthSetting.java | 4 ---- .../implementation/setting/NoHitDelaySetting.java | 6 +----- .../challenges/implementation/setting/NoHungerSetting.java | 6 +----- .../implementation/setting/NoItemDamageSetting.java | 6 +----- .../implementation/setting/NoOffhandSetting.java | 6 +----- .../challenges/implementation/setting/OldPvPSetting.java | 4 ---- .../implementation/setting/OneTeamLifeSetting.java | 4 ---- .../implementation/setting/PlayerGlowSetting.java | 4 ---- .../challenges/implementation/setting/PositionSetting.java | 4 ---- .../implementation/setting/PregameMovementSetting.java | 7 +------ .../challenges/implementation/setting/PvPSetting.java | 4 ---- .../implementation/setting/RegenerationSetting.java | 6 +----- .../challenges/implementation/setting/RespawnSetting.java | 4 ---- .../implementation/setting/SlotLimitSetting.java | 6 +----- .../challenges/implementation/setting/SoupSetting.java | 4 ---- .../implementation/setting/SplitHealthSetting.java | 4 ---- .../challenges/implementation/setting/TimberSetting.java | 5 ----- .../implementation/setting/TopCommandSetting.java | 6 +----- .../implementation/setting/TotemSaveDeathSetting.java | 6 +----- .../challenges/plugin/challenges/type/EmptyChallenge.java | 4 ---- .../challenges/plugin/challenges/type/IChallenge.java | 5 ----- .../challenges/plugin/challenges/type/IGoal.java | 5 ----- .../challenges/plugin/challenges/type/IModifier.java | 6 +----- .../challenges/type/abstraction/AbstractChallenge.java | 5 ----- .../type/abstraction/AbstractForceChallenge.java | 4 ---- .../plugin/challenges/type/abstraction/CollectionGoal.java | 4 ---- .../type/abstraction/CompletableForceChallenge.java | 4 ---- .../challenges/type/abstraction/EndingForceChallenge.java | 4 ---- .../plugin/challenges/type/abstraction/FindItemGoal.java | 4 ---- .../type/abstraction/FirstPlayerAtHeightGoal.java | 4 ---- .../type/abstraction/ForceBattleDisplayGoal.java | 4 ---- .../challenges/type/abstraction/ForceBattleGoal.java | 4 ---- .../plugin/challenges/type/abstraction/HydraChallenge.java | 6 +----- .../challenges/type/abstraction/ItemCollectionGoal.java | 4 ---- .../plugin/challenges/type/abstraction/KillEntityGoal.java | 4 ---- .../plugin/challenges/type/abstraction/KillMobsGoal.java | 4 ---- .../plugin/challenges/type/abstraction/MenuGoal.java | 4 ---- .../plugin/challenges/type/abstraction/MenuSetting.java | 4 ---- .../plugin/challenges/type/abstraction/Modifier.java | 4 ---- .../type/abstraction/ModifierCollectionGoal.java | 6 +----- .../type/abstraction/NetherPortalSpawnSetting.java | 7 +------ .../challenges/type/abstraction/OneEnabledSetting.java | 4 ---- .../plugin/challenges/type/abstraction/PointsGoal.java | 4 ---- .../challenges/type/abstraction/RandomizerSetting.java | 4 ---- .../plugin/challenges/type/abstraction/Setting.java | 4 ---- .../plugin/challenges/type/abstraction/SettingGoal.java | 4 ---- .../challenges/type/abstraction/SettingModifier.java | 4 ---- .../type/abstraction/SettingModifierCollectionGoal.java | 6 +----- .../challenges/type/abstraction/SettingModifierGoal.java | 4 ---- .../plugin/challenges/type/abstraction/TimedChallenge.java | 4 ---- .../type/abstraction/WorldDependentChallenge.java | 4 ---- .../challenges/type/helper/ChallengeConfigHelper.java | 6 +----- .../plugin/challenges/type/helper/ChallengeHelper.java | 5 ----- .../plugin/challenges/type/helper/GoalHelper.java | 4 ---- .../plugin/challenges/type/helper/SubSettingsHelper.java | 4 ---- .../challenges/plugin/content/ItemDescription.java | 4 ---- .../net/codingarea/challenges/plugin/content/Message.java | 4 ---- .../net/codingarea/challenges/plugin/content/Prefix.java | 4 ---- .../challenges/plugin/content/impl/MessageImpl.java | 4 ---- .../challenges/plugin/content/impl/MessageManager.java | 4 ---- .../challenges/plugin/content/loader/ContentLoader.java | 4 ---- .../challenges/plugin/content/loader/LanguageLoader.java | 4 ---- .../challenges/plugin/content/loader/LoaderRegistry.java | 4 ---- .../challenges/plugin/content/loader/PrefixLoader.java | 4 ---- .../challenges/plugin/content/loader/UpdateLoader.java | 4 ---- .../plugin/management/blocks/BlockDropManager.java | 4 ---- .../challenges/plugin/management/bstats/MetricsLoader.java | 6 +----- .../plugin/management/challenges/ChallengeLoader.java | 5 ----- .../plugin/management/challenges/ChallengeManager.java | 4 ---- .../management/challenges/CustomChallengesLoader.java | 4 ---- .../management/challenges/ModuleChallengeLoader.java | 4 ---- .../challenges/annotations/CanInstaKillOnEnable.java | 4 ---- .../annotations/ExcludeFromRandomChallenges.java | 4 ---- .../management/challenges/annotations/RequireVersion.java | 4 ---- .../management/challenges/entities/GamestateSaveable.java | 4 ---- .../challenges/plugin/management/cloud/CloudSupport.java | 4 ---- .../plugin/management/cloud/CloudSupportManager.java | 4 ---- .../plugin/management/cloud/support/CloudNet2Support.java | 4 ---- .../plugin/management/cloud/support/CloudNet3Support.java | 4 ---- .../plugin/management/database/DatabaseManager.java | 4 ---- .../challenges/plugin/management/files/ConfigManager.java | 4 ---- .../management/inventory/PlayerInventoryManager.java | 4 ---- .../plugin/management/menu/InventoryTitleManager.java | 4 ---- .../challenges/plugin/management/menu/MenuManager.java | 4 ---- .../challenges/plugin/management/menu/MenuType.java | 5 +---- .../management/menu/generator/ChallengeMenuGenerator.java | 4 ---- .../management/menu/generator/ChooseItemGenerator.java | 4 ---- .../menu/generator/ChooseMultipleItemGenerator.java | 4 ---- .../plugin/management/menu/generator/MenuGenerator.java | 4 ---- .../management/menu/generator/MultiPageMenuGenerator.java | 4 ---- .../management/menu/generator/ValueMenuGenerator.java | 4 ---- .../generator/categorised/CategorisedMenuGenerator.java | 4 ---- .../menu/generator/categorised/SettingCategory.java | 4 ---- .../categorised/SmallCategorisedMenuGenerator.java | 4 ---- .../generator/implementation/SettingsMenuGenerator.java | 4 ---- .../menu/generator/implementation/TimerMenuGenerator.java | 4 ---- .../custom/CustomMainSettingsMenuGenerator.java | 4 ---- .../implementation/custom/IParentCustomGenerator.java | 4 ---- .../generator/implementation/custom/InfoMenuGenerator.java | 4 ---- .../implementation/custom/MainCustomMenuGenerator.java | 4 ---- .../implementation/custom/MaterialMenuGenerator.java | 4 ---- .../custom/SubSettingChooseMenuGenerator.java | 4 ---- .../custom/SubSettingChooseMultipleMenuGenerator.java | 4 ---- .../custom/SubSettingValueMenuGenerator.java | 4 ---- .../management/menu/info/ChallengeMenuClickInfo.java | 4 ---- .../management/menu/position/GeneratorMenuPosition.java | 4 ---- .../plugin/management/scheduler/AbstractTaskConfig.java | 4 ---- .../plugin/management/scheduler/AbstractTaskExecutor.java | 4 ---- .../plugin/management/scheduler/PoliciesContainer.java | 4 ---- .../plugin/management/scheduler/ScheduleManager.java | 4 ---- .../plugin/management/scheduler/ScheduledFunction.java | 4 ---- .../plugin/management/scheduler/ScheduledTaskConfig.java | 4 ---- .../plugin/management/scheduler/ScheduledTaskExecutor.java | 5 ----- .../plugin/management/scheduler/TimerTaskConfig.java | 4 ---- .../plugin/management/scheduler/TimerTaskExecutor.java | 4 ---- .../management/scheduler/policy/ChallengeStatusPolicy.java | 4 ---- .../management/scheduler/policy/ExtraWorldPolicy.java | 4 ---- .../management/scheduler/policy/FreshnessPolicy.java | 4 ---- .../plugin/management/scheduler/policy/IPolicy.java | 4 ---- .../management/scheduler/policy/PlayerCountPolicy.java | 4 ---- .../plugin/management/scheduler/policy/TimerPolicy.java | 4 ---- .../plugin/management/scheduler/task/ScheduledTask.java | 4 ---- .../plugin/management/scheduler/task/TimerTask.java | 4 ---- .../plugin/management/scheduler/timer/ChallengeTimer.java | 4 ---- .../plugin/management/scheduler/timer/TimerFormat.java | 4 ---- .../plugin/management/scheduler/timer/TimerStatus.java | 4 ---- .../plugin/management/server/ChallengeEndCause.java | 4 ---- .../plugin/management/server/GameWorldStorage.java | 4 ---- .../management/server/GeneratorWorldPortalManager.java | 3 --- .../plugin/management/server/ScoreboardManager.java | 4 ---- .../challenges/plugin/management/server/ServerManager.java | 4 ---- .../challenges/plugin/management/server/TitleManager.java | 4 ---- .../challenges/plugin/management/server/WorldManager.java | 4 ---- .../management/server/scoreboard/ChallengeBossBar.java | 4 ---- .../management/server/scoreboard/ChallengeScoreboard.java | 4 ---- .../plugin/management/stats/LeaderboardInfo.java | 4 ---- .../challenges/plugin/management/stats/PlayerStats.java | 6 +----- .../challenges/plugin/management/stats/Statistic.java | 4 ---- .../challenges/plugin/management/stats/StatsManager.java | 5 ----- .../challenges/plugin/spigot/command/BackCommand.java | 4 ---- .../plugin/spigot/command/ChallengesCommand.java | 4 ---- .../challenges/plugin/spigot/command/DatabaseCommand.java | 4 ---- .../challenges/plugin/spigot/command/FeedCommand.java | 4 ---- .../challenges/plugin/spigot/command/FlyCommand.java | 4 ---- .../challenges/plugin/spigot/command/GamemodeCommand.java | 6 +----- .../challenges/plugin/spigot/command/GamestateCommand.java | 4 ---- .../challenges/plugin/spigot/command/GodModeCommand.java | 4 ---- .../challenges/plugin/spigot/command/HealCommand.java | 4 ---- .../challenges/plugin/spigot/command/HelpCommand.java | 4 ---- .../challenges/plugin/spigot/command/InvseeCommand.java | 6 +----- .../challenges/plugin/spigot/command/LanguageCommand.java | 4 ---- .../plugin/spigot/command/LeaderboardCommand.java | 4 ---- .../challenges/plugin/spigot/command/ResetCommand.java | 4 ---- .../challenges/plugin/spigot/command/ResultCommand.java | 4 ---- .../challenges/plugin/spigot/command/SearchCommand.java | 4 ---- .../challenges/plugin/spigot/command/SkipTimerCommand.java | 4 ---- .../challenges/plugin/spigot/command/StatsCommand.java | 5 ----- .../challenges/plugin/spigot/command/TimeCommand.java | 6 +----- .../challenges/plugin/spigot/command/TimerCommand.java | 4 ---- .../challenges/plugin/spigot/command/VillageCommand.java | 6 +----- .../challenges/plugin/spigot/command/WeatherCommand.java | 6 +----- .../challenges/plugin/spigot/command/WorldCommand.java | 4 ---- .../plugin/spigot/events/EntityDamageByPlayerEvent.java | 4 ---- .../plugin/spigot/events/EntityDeathByPlayerEvent.java | 4 ---- .../plugin/spigot/events/InventoryClickEventWrapper.java | 6 +----- .../spigot/events/PlayerIgnoreStatusChangeEvent.java | 4 ---- .../plugin/spigot/events/PlayerInventoryClickEvent.java | 6 +----- .../challenges/plugin/spigot/events/PlayerJumpEvent.java | 4 ---- .../plugin/spigot/events/PlayerPickupItemEvent.java | 6 +----- .../plugin/spigot/generator/VoidMapGenerator.java | 4 ---- .../plugin/spigot/listener/BlockDropListener.java | 4 ---- .../plugin/spigot/listener/ChatInputListener.java | 6 +----- .../challenges/plugin/spigot/listener/CheatListener.java | 4 ---- .../plugin/spigot/listener/CustomEventListener.java | 6 +----- .../spigot/listener/ExtraWorldRestrictionListener.java | 4 ---- .../plugin/spigot/listener/GeneratorWorldsListener.java | 4 ---- .../challenges/plugin/spigot/listener/HelpListener.java | 4 ---- .../plugin/spigot/listener/PlayerConnectionListener.java | 4 ---- .../plugin/spigot/listener/RestrictionListener.java | 5 ----- .../plugin/spigot/listener/ScoreboardUpdateListener.java | 4 ---- .../challenges/plugin/spigot/listener/StatsListener.java | 5 ----- .../challenges/plugin/utils/bukkit/command/Completer.java | 4 ---- .../plugin/utils/bukkit/command/ForwardingCommand.java | 6 +----- .../plugin/utils/bukkit/command/PlayerCommand.java | 4 ---- .../plugin/utils/bukkit/command/SenderCommand.java | 4 ---- .../plugin/utils/bukkit/container/BukkitSerialization.java | 4 ---- .../plugin/utils/bukkit/container/PlayerData.java | 4 ---- .../plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java | 4 ---- .../utils/bukkit/jumpgeneration/RandomJumpGenerator.java | 4 ---- .../plugin/utils/bukkit/misc/BukkitStringUtils.java | 4 ---- .../plugin/utils/bukkit/misc/Version/MinecraftVersion.java | 4 ---- .../challenges/plugin/utils/bukkit/nms/NMSProvider.java | 4 ---- .../challenges/plugin/utils/bukkit/nms/NMSUtils.java | 4 ---- .../challenges/plugin/utils/bukkit/nms/ReflectionUtil.java | 3 +-- .../implementations/v1_13/BorderPacketFactory_1_13.java | 4 ---- .../bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java | 4 ---- .../nms/implementations/v1_13/PacketBorder_1_13.java | 4 ---- .../nms/implementations/v1_13/PlayerConnection_1_13.java | 4 ---- .../bukkit/nms/implementations/v1_13/WorldServer_1_13.java | 4 ---- .../implementations/v1_17/BorderPacketFactory_1_17.java | 4 ---- .../bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java | 4 ---- .../nms/implementations/v1_17/PacketBorder_1_17.java | 6 +----- .../nms/implementations/v1_18/PacketBorder_1_18.java | 4 ---- .../nms/implementations/v1_18/PlayerConnection_1_18.java | 4 ---- .../plugin/utils/bukkit/nms/type/AbstractNMSClass.java | 6 ------ .../plugin/utils/bukkit/nms/type/BorderPacketFactory.java | 4 ---- .../plugin/utils/bukkit/nms/type/BukkitNMSClass.java | 3 --- .../plugin/utils/bukkit/nms/type/CraftPlayer.java | 3 +-- .../plugin/utils/bukkit/nms/type/PacketBorder.java | 2 -- .../plugin/utils/bukkit/nms/type/PlayerConnection.java | 3 +-- .../plugin/utils/bukkit/nms/type/WorldServer.java | 6 +----- .../challenges/plugin/utils/item/DefaultItem.java | 4 ---- .../challenges/plugin/utils/item/ItemBuilder.java | 4 ---- .../codingarea/challenges/plugin/utils/item/ItemUtils.java | 4 ---- .../challenges/plugin/utils/logging/ConsolePrint.java | 4 ---- .../challenges/plugin/utils/misc/ArmorUtils.java | 4 ---- .../challenges/plugin/utils/misc/BlockUtils.java | 5 ----- .../challenges/plugin/utils/misc/ColorConversions.java | 4 ---- .../challenges/plugin/utils/misc/CommandHelper.java | 6 +----- .../challenges/plugin/utils/misc/DatabaseHelper.java | 4 ---- .../challenges/plugin/utils/misc/EntityUtils.java | 4 ---- .../codingarea/challenges/plugin/utils/misc/FontUtils.java | 4 ---- .../challenges/plugin/utils/misc/ImageUtils.java | 4 ---- .../challenges/plugin/utils/misc/InventoryUtils.java | 5 ----- .../challenges/plugin/utils/misc/ListBuilder.java | 6 +----- .../codingarea/challenges/plugin/utils/misc/MapUtils.java | 4 ---- .../challenges/plugin/utils/misc/NameHelper.java | 4 ---- .../challenges/plugin/utils/misc/ParticleUtils.java | 7 ------- .../challenges/plugin/utils/misc/StatsHelper.java | 4 ---- .../challenges/plugin/utils/misc/StructureUtils.java | 4 ---- .../challenges/plugin/utils/misc/TriConsumer.java | 6 +----- .../net/codingarea/challenges/plugin/utils/misc/Utils.java | 5 ----- 469 files changed, 103 insertions(+), 1996 deletions(-) diff --git a/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java b/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java index 0ea5eb464..1277a6e1f 100644 --- a/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java +++ b/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java @@ -4,10 +4,7 @@ import net.codingarea.challenges.plugin.Challenges; import org.bukkit.plugin.java.JavaPlugin; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ + public final class MongoConnector extends JavaPlugin { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java b/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java index fee43728e..309c8efa2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java @@ -16,10 +16,6 @@ import java.util.List; import java.util.function.Supplier; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ChallengeAPI { private ChallengeAPI() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java index 3bc0e9c60..4b0da0fe4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java @@ -25,11 +25,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ @Getter public final class Challenges extends BukkitModule { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index 3c1c775b6..e6035faf9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -24,10 +24,6 @@ import java.util.Map.Entry; import java.util.UUID; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Getter @ToString public class CustomChallenge extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java index f1a4a31fa..133327a32 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java @@ -15,10 +15,6 @@ import java.util.*; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class ChallengeExecutionData { @Getter diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java index f9a6d09b2..f0d9b2657 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java @@ -4,10 +4,6 @@ import java.util.function.Supplier; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class ChallengeSetting implements IChallengeSetting { private final String name; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java index 78b161bb8..d1db4e40f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java @@ -15,10 +15,6 @@ import java.util.LinkedHashMap; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class CustomSettingsLoader { @Getter diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java index 31e878e7b..ab5798085 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java @@ -6,10 +6,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface FallbackNames { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java index 03741e54e..1c91e30be 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java @@ -3,10 +3,6 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import org.bukkit.Material; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public interface IChallengeSetting { SubSettingsBuilder getSubSettingsBuilder(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/SettingType.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/SettingType.java index ba2cdcd26..7946471d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/SettingType.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/SettingType.java @@ -1,9 +1,5 @@ package net.codingarea.challenges.plugin.challenges.custom.settings; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public enum SettingType { CONDITION, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java index 10e2cb0f3..56f9a5b34 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java @@ -11,10 +11,6 @@ import java.util.LinkedHashMap; import java.util.function.Supplier; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class ChallengeAction extends ChallengeSetting implements IChallengeAction { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java index b47bde891..f34860630 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java @@ -4,10 +4,6 @@ import java.util.function.Supplier; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class EntityTargetAction extends ChallengeAction implements IEntityTargetAction { public EntityTargetAction(String name, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java index 7b22dc3ae..fe2536bf4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java @@ -5,10 +5,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public interface IChallengeAction { IRandom random = IRandom.create(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java index 02324016d..6ac64ace4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java @@ -15,10 +15,6 @@ import java.util.List; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public interface IEntityTargetAction extends IChallengeAction { static List getTargets(Entity triggerTarget, Map subActions) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java index 2a7530283..2e9b11cad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java @@ -7,10 +7,6 @@ import java.util.Map; import java.util.function.Supplier; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class PlayerTargetAction extends EntityTargetAction { public PlayerTargetAction(String name, SubSettingsBuilder subSettingsBuilder) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java index bb7029e57..a840f4134 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java @@ -9,10 +9,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class AddPermanentEffectAction extends PlayerTargetAction { PermanentEffectOnDamageChallenge instance = AbstractChallenge diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java index b9f2ebc25..2d27dd98a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java @@ -12,10 +12,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class BoostEntityInAirAction extends EntityTargetAction { public BoostEntityInAirAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java index 1266600d9..717aa170c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java @@ -6,10 +6,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class CancelEventAction extends ChallengeAction { public static boolean inCanceling; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java index efc08ba00..e8a231c5c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java @@ -13,10 +13,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ public class ChangeWorldBorderAction extends ChallengeAction { public ChangeWorldBorderAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java index 2b6fab87c..142e3a0ca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java @@ -7,10 +7,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class ClearInventoryAction extends PlayerTargetAction { public ClearInventoryAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java index 3638cf70e..8120fbc93 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java @@ -10,10 +10,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class DamageEntityAction extends EntityTargetAction { public DamageEntityAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java index 6accab785..6e38e0df8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java @@ -8,10 +8,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class DropRandomItemAction extends PlayerTargetAction { public DropRandomItemAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java index 0ac2d384b..a66818c4f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java @@ -13,10 +13,6 @@ import java.util.List; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public class ExecuteCommandAction extends PlayerTargetAction { // Static because cannot be accessed before super has been called diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java index 2a513836d..8cb0ef400 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java @@ -10,10 +10,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class FreezeAction extends EntityTargetAction { FreezeChallenge instance = AbstractChallenge diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java index 481823ef1..650269296 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java @@ -15,10 +15,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class HealEntityAction extends EntityTargetAction { public HealEntityAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java index 791a0aafd..c7f724f8c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java @@ -9,10 +9,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class HungerPlayerAction extends PlayerTargetAction { public HungerPlayerAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java index 96d8ad6d4..9a77d7833 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java @@ -8,10 +8,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class InvertHealthAction extends PlayerTargetAction { public InvertHealthAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java index 612798911..abc8c20a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java @@ -8,10 +8,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class JumpAndRunAction extends ChallengeAction { public JumpAndRunAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java index 6e34ac4e3..86cb4aef3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java @@ -10,10 +10,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class KillEntityAction extends EntityTargetAction { public KillEntityAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java index 7075c9e34..5d67e6931 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java @@ -13,10 +13,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class ModifyMaxHealthAction extends PlayerTargetAction { public ModifyMaxHealthAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java index 02414dcf5..ed40d21b7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java @@ -15,10 +15,6 @@ import java.util.Map; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.2 - */ @RequireVersion(MinecraftVersion.V1_19) @FallbackNames({"place_random_structure"}) public class PlaceStructureAction extends EntityTargetAction { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java index ece861d40..13d39ea39 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java @@ -11,10 +11,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class PotionEffectAction extends EntityTargetAction { public PotionEffectAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java index d5a8b45fa..5db7eb72f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java @@ -8,10 +8,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ public class RandomHotBarAction extends PlayerTargetAction { public RandomHotBarAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java index de465769b..4898806ff 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java @@ -12,10 +12,6 @@ import javax.annotation.Nonnull; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class RandomItemAction extends ChallengeAction { public RandomItemAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java index 803a4125b..e6f441044 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java @@ -14,10 +14,6 @@ import java.util.Map; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class RandomMobAction extends EntityTargetAction { @Getter diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java index c9569eaec..84c62efe5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java @@ -11,10 +11,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class RandomPotionEffectAction extends EntityTargetAction { public RandomPotionEffectAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java index b64f82cd5..fdfff7d12 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java @@ -8,10 +8,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class RemoveRandomItemAction extends PlayerTargetAction { public RemoveRandomItemAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java index 9b4e274dc..ffae33903 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java @@ -10,10 +10,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ public class SpawnEntityAction extends EntityTargetAction { public SpawnEntityAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java index aa1108649..f11ce7f4b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java @@ -8,10 +8,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class SwapRandomItemAction extends PlayerTargetAction { public SwapRandomItemAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java index d1ced3607..a2b89f1a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java @@ -16,10 +16,6 @@ import java.util.List; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class SwapRandomMobAction extends ChallengeAction { public SwapRandomMobAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java index 389740395..01580348f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java @@ -9,10 +9,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class UncraftInventoryAction extends EntityTargetAction { public UncraftInventoryAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java index 77e938477..e025fb7b9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java @@ -8,10 +8,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class WaterMLGAction extends ChallengeAction { public WaterMLGAction(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java index bb81ba045..9668ca307 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java @@ -12,10 +12,6 @@ import java.util.List; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ public class WinChallengeAction extends PlayerTargetAction { private final List winner = Lists.newLinkedList(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java index 57e40c03b..5f9fed98a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java @@ -15,10 +15,6 @@ import java.util.function.Consumer; import java.util.function.Predicate; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class SubSettingsBuilder { private String key; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java index 0cda0cae3..3e3fcce3c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java @@ -4,10 +4,6 @@ import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class ValueSetting { @Getter diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java index 677844ee0..29c9df582 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java @@ -16,10 +16,6 @@ import java.util.Map.Entry; import java.util.function.Consumer; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Getter public class ChooseItemSubSettingsBuilder extends GeneratorSubSettingsBuilder { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java index ea78e50f7..25b07a132 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java @@ -18,10 +18,6 @@ import java.util.Map.Entry; import java.util.function.Consumer; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Getter public class ChooseMultipleItemSubSettingBuilder extends GeneratorSubSettingsBuilder { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java index 460189c54..a68a92d51 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java @@ -8,10 +8,6 @@ import java.util.List; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class EmptySubSettingsBuilder extends SubSettingsBuilder { public EmptySubSettingsBuilder() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java index c8626503b..9d7775db7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java @@ -6,10 +6,6 @@ import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; import org.bukkit.entity.Player; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public abstract class GeneratorSubSettingsBuilder extends SubSettingsBuilder { public GeneratorSubSettingsBuilder(String key) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java index 85282033a..2a42f29a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java @@ -17,10 +17,6 @@ import java.util.function.Consumer; import java.util.function.Predicate; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public class TextInputSubSettingsBuilder extends SubSettingsBuilder { private final Consumer onOpen; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java index f86fd7cd8..35df97b57 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java @@ -22,10 +22,6 @@ import java.util.function.Consumer; import java.util.function.Function; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Getter public class ValueSubSettingsBuilder extends GeneratorSubSettingsBuilder { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java index db1fa78e4..8296a8fb3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java @@ -5,10 +5,6 @@ import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class BooleanSetting extends ValueSetting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java index b9dcbb68a..ff3e5f2c3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java @@ -10,10 +10,6 @@ import java.util.function.Function; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class ModifierSetting extends ValueSetting implements IModifier { private final int min, max; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java index cec2dd627..4cc577cfb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java @@ -10,10 +10,6 @@ import java.util.LinkedHashMap; import java.util.function.Supplier; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class ChallengeTrigger extends ChallengeSetting implements IChallengeTrigger { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/IChallengeTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/IChallengeTrigger.java index 221be45d7..48f7f468e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/IChallengeTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/IChallengeTrigger.java @@ -3,10 +3,6 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import org.bukkit.event.Listener; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public interface IChallengeTrigger extends Listener { default ChallengeExecutionData createData() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/AdvancementTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/AdvancementTrigger.java index 4964ccce3..cc26df8f2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/AdvancementTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/AdvancementTrigger.java @@ -6,10 +6,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerAdvancementDoneEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class AdvancementTrigger extends ChallengeTrigger { public AdvancementTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/BreakBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/BreakBlockTrigger.java index 21f259a3a..12e06c8a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/BreakBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/BreakBlockTrigger.java @@ -7,10 +7,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.block.BlockBreakEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class BreakBlockTrigger extends ChallengeTrigger { public BreakBlockTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java index b86324d7a..9c2aed119 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java @@ -12,10 +12,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerItemConsumeEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class ConsumeItemTrigger extends ChallengeTrigger { public ConsumeItemTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/CraftItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/CraftItemTrigger.java index add46c5ff..f248ad991 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/CraftItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/CraftItemTrigger.java @@ -7,10 +7,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.inventory.CraftItemEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class CraftItemTrigger extends ChallengeTrigger { public CraftItemTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/DropItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/DropItemTrigger.java index 26d80deaa..815e2d103 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/DropItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/DropItemTrigger.java @@ -6,10 +6,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerDropItemEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class DropItemTrigger extends ChallengeTrigger { public DropItemTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java index 953a7e21e..98e4366cf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java @@ -9,10 +9,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class EntityDamageByPlayerTrigger extends ChallengeTrigger { public EntityDamageByPlayerTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java index a17367b28..84b823770 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java @@ -17,10 +17,6 @@ import javax.annotation.Nonnull; import java.util.*; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class EntityDamageTrigger extends ChallengeTrigger { public EntityDamageTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java index c5735d0af..625c5505e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java @@ -9,10 +9,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class EntityDeathTrigger extends ChallengeTrigger { public EntityDeathTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GainXPTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GainXPTrigger.java index 442e676e8..d453b69ec 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GainXPTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GainXPTrigger.java @@ -6,10 +6,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerExpChangeEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class GainXPTrigger extends ChallengeTrigger { public GainXPTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GetItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GetItemTrigger.java index d15859def..9b087f37b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GetItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GetItemTrigger.java @@ -7,10 +7,6 @@ import org.bukkit.Material; import org.bukkit.event.EventHandler; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ public class GetItemTrigger extends ChallengeTrigger { public GetItemTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java index 05aed6c46..60e32c9a8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java @@ -7,10 +7,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.FoodLevelChangeEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class HungerTrigger extends ChallengeTrigger { public HungerTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java index ef74275e4..cc7020df3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java @@ -15,10 +15,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class InLiquidTrigger extends ChallengeTrigger { public InLiquidTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java index 5d34447b9..b3217aaab 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java @@ -12,10 +12,6 @@ import java.util.LinkedList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class IntervallTrigger extends ChallengeTrigger { public IntervallTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/LevelUpTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/LevelUpTrigger.java index 7e895e6a8..a95ea5de9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/LevelUpTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/LevelUpTrigger.java @@ -6,10 +6,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerLevelChangeEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class LevelUpTrigger extends ChallengeTrigger { public LevelUpTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveBlockTrigger.java index 8fb3639ac..03de99396 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveBlockTrigger.java @@ -7,10 +7,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class MoveBlockTrigger extends ChallengeTrigger { public MoveBlockTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveCameraTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveCameraTrigger.java index 566b96d71..d203be81d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveCameraTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveCameraTrigger.java @@ -6,10 +6,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class MoveCameraTrigger extends ChallengeTrigger { public MoveCameraTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveDownTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveDownTrigger.java index 8623c2f49..e16df9e1b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveDownTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveDownTrigger.java @@ -6,10 +6,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class MoveDownTrigger extends ChallengeTrigger { public MoveDownTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveUpTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveUpTrigger.java index 044e12a06..d2bd8d42f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveUpTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveUpTrigger.java @@ -6,10 +6,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class MoveUpTrigger extends ChallengeTrigger { public MoveUpTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PickupItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PickupItemTrigger.java index 4db6072ce..18192a54e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PickupItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PickupItemTrigger.java @@ -6,10 +6,6 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class PickupItemTrigger extends ChallengeTrigger { public PickupItemTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlaceBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlaceBlockTrigger.java index b17e482d1..9b6de5cdc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlaceBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlaceBlockTrigger.java @@ -7,10 +7,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.block.BlockPlaceEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class PlaceBlockTrigger extends ChallengeTrigger { public PlaceBlockTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java index c5c99d95e..37d5ca5be 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java @@ -8,10 +8,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class PlayerJumpTrigger extends ChallengeTrigger { public PlayerJumpTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java index 198a7f90a..a5b2da478 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java @@ -8,10 +8,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1 - */ public class PlayerSneakTrigger extends ChallengeTrigger { public PlayerSneakTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsNotOnSpecificBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsNotOnSpecificBlockTrigger.java index fd880281e..a53a775ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsNotOnSpecificBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsNotOnSpecificBlockTrigger.java @@ -14,10 +14,6 @@ import java.util.LinkedList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class StandsNotOnSpecificBlockTrigger extends ChallengeTrigger { public StandsNotOnSpecificBlockTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java index 86d4f9069..96b126bd4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java @@ -9,10 +9,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class StandsOnSpecificBlockTrigger extends ChallengeTrigger { public StandsOnSpecificBlockTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java index 59c5999fa..f84d8d37f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java @@ -18,10 +18,6 @@ import javax.annotation.Nonnull; import java.util.concurrent.ThreadLocalRandom; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0.2 - */ @Since("2.0.2") public class DamageTeleportChallenge extends SettingModifier { @@ -85,4 +81,4 @@ public Location getRandomLocation(World world) { return world.getWorldBorder().getCenter().add(randomX, 0, randomY); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index 33b85cbb4..593c12203 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -27,10 +27,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class ZeroHeartsChallenge extends SettingModifier { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java index 36d98cd0f..d3d23f051 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java @@ -14,10 +14,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class AdvancementDamageChallenge extends SettingModifier { public AdvancementDamageChallenge() { @@ -52,4 +48,4 @@ public void onPlayerAdvancementDone(@Nonnull PlayerAdvancementDoneEvent event) { event.getPlayer().damage(getValue()); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java index deea32241..4b9c86806 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java @@ -13,11 +13,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class BlockBreakDamageChallenge extends SettingModifier { public BlockBreakDamageChallenge() { @@ -49,4 +44,4 @@ protected String[] getSettingsDescription() { return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java index 19400f792..f2a10abb6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java @@ -14,11 +14,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class BlockPlaceDamageChallenge extends SettingModifier { @@ -51,4 +46,4 @@ protected String[] getSettingsDescription() { return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java index 75c1cec12..c0ae72c54 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java @@ -17,10 +17,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class DamagePerBlockChallenge extends SettingModifier { public DamagePerBlockChallenge() { @@ -55,4 +51,4 @@ protected String[] getSettingsDescription() { return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java index f459ecbbf..43570f302 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java @@ -15,10 +15,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class DeathOnFallChallenge extends Setting { @@ -44,4 +40,4 @@ public void onEntityDamage(@Nonnull EntityDamageEvent event) { event.setCancelled(false); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java index d8bc6aee1..320d562d6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java @@ -20,11 +20,6 @@ import java.util.HashMap; import java.util.Map; -/** - * @author rollocraft | https://github.com/rollocraft - * @since 2.3.2 - */ - @Since("2.3.2") public class DelayDamageChallenge extends TimedChallenge { @@ -87,4 +82,4 @@ public void onPlayerDamage(@Nonnull EntityDamageEvent event) { damageMap.put(player, damageMap.getOrDefault(player, 0.0) + damage); event.setCancelled(true); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java index 29557fad9..f83e0cd12 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java @@ -19,10 +19,6 @@ import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.potion.PotionEffect; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0.2 - */ @Since("2.0.2") public class FreezeChallenge extends SettingModifier { @@ -77,4 +73,4 @@ public void setFreeze(LivingEntity entity, double damage) { entity.addPotionEffect(new PotionEffect(MinecraftNameWrapper.SLOWNESS, time, 255)); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java index c4b32de44..d7ca9212c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java @@ -19,10 +19,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class JumpDamageChallenge extends SettingModifier { @@ -58,4 +54,4 @@ public void onSneak(@Nonnull PlayerJumpEvent event) { event.getPlayer().setNoDamageTicks(0); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java index 26bbe5c40..7be4a0e9b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java @@ -12,10 +12,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class ReversedDamageChallenge extends Setting { public ReversedDamageChallenge() { @@ -38,4 +34,4 @@ public void onDamageByPlayer(@Nonnull EntityDamageByPlayerEvent event) { event.getDamager().damage(damage); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java index 6b155969a..1ba29b8cf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java @@ -18,10 +18,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class SneakDamageChallenge extends SettingModifier { public SneakDamageChallenge() { @@ -57,4 +53,4 @@ public void onSneak(@Nonnull PlayerToggleSneakEvent event) { event.getPlayer().setNoDamageTicks(0); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java index 4ba093c91..f6b269788 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java @@ -15,10 +15,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class WaterAllergyChallenge extends SettingModifier { @@ -55,4 +51,4 @@ public void playValueChangeTitle() { ChallengeHelper.playChallengeHeartsValueChangeTitle(this); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java index adc63f9af..a9d565725 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java @@ -32,10 +32,6 @@ import java.util.Map; import java.util.UUID; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class BlockEffectChallenge extends Setting { @@ -171,4 +167,4 @@ private PotionEffect getEffect(Material material) { return type.createEffect(Integer.MAX_VALUE, random.nextInt(type.isInstant() ? 1 : 4)); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java index 9778b22ff..7898e893e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java @@ -28,10 +28,6 @@ import java.util.Map; import java.util.UUID; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ @Since("2.1.1") public class ChunkRandomEffectChallenge extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java index 97fa07e7a..8296da817 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java @@ -18,10 +18,6 @@ import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class EntityRandomEffectChallenge extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java index 3df770351..5d088d268 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java @@ -20,10 +20,6 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class InfectionChallenge extends Setting { public InfectionChallenge() { @@ -95,4 +91,4 @@ private List getNearbyTargets(@Nonnull Player player, double range) { && ((Player) entity).getGameMode() != GameMode.SPECTATOR)).collect(Collectors.toList()); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java index b24d137c2..cade26f94 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java @@ -37,10 +37,6 @@ import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class PermanentEffectOnDamageChallenge extends SettingModifier { @@ -281,4 +277,4 @@ public void loadGameState(@Nonnull Document document) { } } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index 460ac6333..8895945de 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -24,10 +24,6 @@ import java.util.Random; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class RandomPotionEffectChallenge extends MenuSetting { @@ -110,4 +106,4 @@ private void applyEffect(@Nonnull Player player, @Nonnull PotionEffectType effec player.addPotionEffect(potionEffect); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java index 89b517a93..6db0b57f0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java @@ -15,10 +15,6 @@ import javax.annotation.Nonnull; import java.util.Collection; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class AllMobsToDeathPoint extends Setting { @@ -54,4 +50,4 @@ public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.SPAWNER, Message.forName("item-all-mobs-to-death-position-challenge")); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java index 9b8c31477..ef714960f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java @@ -23,10 +23,6 @@ import java.util.Collection; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ @Since("2.1.3") public class BlockMobsChallenge extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java index 19e3002f2..9d9934636 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java @@ -13,10 +13,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class DupedSpawningChallenge extends Setting { private boolean inCustomSpawn = false; @@ -50,4 +46,4 @@ public void onSpawn(@Nonnull EntitySpawnEvent event) { inCustomSpawn = false; } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java index 1231cb7e6..3a359fa42 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java @@ -10,10 +10,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class HydraNormalChallenge extends HydraChallenge { public HydraNormalChallenge() { @@ -31,4 +27,4 @@ public ItemBuilder createDisplayItem() { public int getNewMobsCount(@Nonnull EntityType entityType) { return 2; } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java index 98ed37433..835fd5585 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java @@ -11,10 +11,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class HydraPlusChallenge extends HydraChallenge { @@ -43,4 +39,4 @@ public int getNewMobsCount(@Nonnull EntityType entityType) { return currentCount; } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java index 4b1d8b2f5..24e76bf86 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java @@ -23,10 +23,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class InvisibleMobsChallenge extends Setting { @@ -72,4 +68,4 @@ private void addEffect(@Nonnull LivingEntity entity) { entity.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 40, 1, true, false, false)); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java index 8d17dffa7..4d1283419 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java @@ -19,10 +19,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class MobSightDamageChallenge extends SettingModifier { @@ -78,4 +74,4 @@ public void onTick() { } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java index 613b59218..47e444a1e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java @@ -19,10 +19,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class MobTransformationChallenge extends Setting { @@ -78,4 +74,4 @@ private EntityType getType(@Nonnull Player player, @Nullable EntityType defaultT return type; } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java index f49715813..bc34c69b3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java @@ -26,10 +26,6 @@ import java.util.Map; import java.util.concurrent.ThreadLocalRandom; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class MobsRespawnInEndChallenge extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java index a7c6758bd..8ed950886 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java @@ -18,10 +18,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class NewEntityOnJumpChallenge extends Setting { @@ -49,4 +45,4 @@ private void spawnRandomEntity(@Nonnull Location location) { location.getWorld().spawnEntity(location, type); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java index 4c48c5c87..7f85c657e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java @@ -20,10 +20,6 @@ import javax.annotation.Nonnull; import java.util.Random; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class StoneSightChallenge extends Setting { @@ -86,4 +82,4 @@ private Material getRandomStone() { return materials[random.nextInt(materials.length)]; } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java index beeba0d04..d9be4fb72 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java @@ -35,10 +35,6 @@ import java.util.Optional; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class JumpAndRunChallenge extends WorldDependentChallenge { private final List lastPlayers = new ArrayList<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java index 0f66bad4d..17fcfe654 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java @@ -21,10 +21,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class WaterMLGChallenge extends WorldDependentChallenge { public WaterMLGChallenge() { @@ -97,4 +93,4 @@ public void onEntityDamage(@Nonnull EntityDamageEvent event) { } } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java index 9ab4bfea8..e9be24ecc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java @@ -31,10 +31,6 @@ import java.util.Objects; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") @ExcludeFromRandomChallenges public class ForceBiomeChallenge extends CompletableForceChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java index c27761db1..d72b25a1b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java @@ -25,10 +25,6 @@ import java.util.Arrays; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @ExcludeFromRandomChallenges public class ForceBlockChallenge extends EndingForceChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java index 5ebda733f..1de673480 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java @@ -24,10 +24,6 @@ import javax.annotation.Nullable; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @ExcludeFromRandomChallenges public class ForceHeightChallenge extends EndingForceChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java index d34ddfb01..f589ddc4b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java @@ -35,10 +35,6 @@ import java.util.List; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") @ExcludeFromRandomChallenges public class ForceItemChallenge extends CompletableForceChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java index d61d44419..54fbc8b28 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java @@ -30,10 +30,6 @@ import java.util.List; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @ExcludeFromRandomChallenges public class ForceMobChallenge extends CompletableForceChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java index 01f9f84e6..3c9f20982 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java @@ -15,10 +15,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class DamageInventoryClearChallenge extends SettingModifier { public DamageInventoryClearChallenge() { @@ -61,4 +57,4 @@ public void playValueChangeTitle() { ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 0 ? Message.forName("everyone").asString() : Message.forName("player").asString()); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java index b09bda1b3..decb35544 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java @@ -39,10 +39,6 @@ import java.util.function.Consumer; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class MissingItemsChallenge extends TimedChallenge implements PlayerCommand { @@ -241,4 +237,4 @@ private boolean anyRunningGame() { return inventories.keySet().stream().anyMatch(uuid -> Bukkit.getOfflinePlayer(uuid).isOnline()); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java index ac95eb420..7a2504bc3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java @@ -17,10 +17,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class MovementItemRemovingChallenge extends SettingModifier { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java index 51da623b2..54081b17e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java @@ -28,10 +28,6 @@ import java.util.Map; import java.util.Map.Entry; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") @CanInstaKillOnEnable public class NoDupedItemsChallenge extends Setting { @@ -114,4 +110,4 @@ private Triple checkInventory(@Nonnull Player player, return null; } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java index 23db0cc55..37d0671ce 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java @@ -18,10 +18,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class PermanentItemChallenge extends Setting { @@ -61,4 +57,4 @@ public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { event.setCancelled(true); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java index bc6adbf8f..90d325935 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java @@ -18,10 +18,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class PickupItemLaunchChallenge extends SettingModifier { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java index ed181731a..67b61ed2a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java @@ -18,10 +18,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0.2 - */ @Since("2.0.2") public class UncraftItemsChallenge extends TimedChallenge { @@ -141,4 +137,4 @@ protected void onTimeActivation() { } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 7eb4622a2..cc621e5c7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -20,10 +20,6 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class EnderGamesChallenge extends TimedChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java index ed708272d..7c1b57e4d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java @@ -17,10 +17,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0.2 - */ @Since("2.0.2") public class FoodLaunchChallenge extends SettingModifier { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java index b657d8573..354eacae6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java @@ -17,10 +17,6 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class FoodOnceChallenge extends SettingModifier { public FoodOnceChallenge() { @@ -108,4 +104,4 @@ private boolean teamFoodsActivated() { return getValue() == 2; } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java index 99f3f1429..dd9640cfd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java @@ -16,10 +16,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") @ExcludeFromRandomChallenges public class InvertHealthChallenge extends TimedChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java index 9eba3fa27..eaca7adcb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java @@ -16,10 +16,6 @@ import java.util.Arrays; import java.util.Random; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class LowDropRateChallenge extends SettingModifier { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java index b0e4086e0..1383b56fe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java @@ -14,10 +14,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class NoExpChallenge extends Setting { public NoExpChallenge() { @@ -39,4 +35,4 @@ public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-no-exp-challenge")); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java index f85c099b0..19239e2d2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java @@ -19,10 +19,6 @@ import java.util.LinkedList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.2.0 - */ @Since("2.2.0") public class NoSharedAdvancementsChallenge extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java index fe5d0aaa4..f0a09e06d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java @@ -14,10 +14,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class NoTradingChallenge extends Setting { public NoTradingChallenge() { @@ -50,4 +46,4 @@ public void onEntityPickupItem(@Nonnull EntityPickupItemEvent event) { } } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java index 270c344d5..ed2c5fa85 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java @@ -17,10 +17,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class OneDurabilityChallenge extends Setting { public OneDurabilityChallenge() { @@ -69,4 +65,4 @@ private void setDurability(@Nonnull ItemStack item) { } } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java index ec9da640e..21bd6897a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java @@ -14,10 +14,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class AlwaysRunningChallenge extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java index 4e9ab9141..74196fa3f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java @@ -21,10 +21,6 @@ import java.util.HashMap; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0.2 - */ @Since("2.0.2") public class DontStopRunningChallenge extends SettingModifier { @@ -104,4 +100,4 @@ public void onPlayerMove(@Nonnull PlayerMoveEvent event) { playerStandingCount.remove(event.getPlayer()); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java index f4636b09c..6376c38e7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java @@ -34,10 +34,6 @@ import java.util.Map; import java.util.UUID; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Since("2.1.0") public class FiveHundredBlocksChallenge extends SettingModifier { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java index cddb70054..8e69d18e5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java @@ -13,10 +13,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class HigherJumpsChallenge extends Setting { public HigherJumpsChallenge() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java index 7de505ec3..65359282a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java @@ -14,10 +14,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class HungerPerBlockChallenge extends SettingModifier { @@ -41,4 +37,4 @@ public void onPlayerMove(@Nonnull PlayerMoveEvent event) { event.getPlayer().setFoodLevel(Math.max(newFoodLevel, 0)); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java index faba24856..f31e51b72 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java @@ -23,10 +23,6 @@ import java.util.Map.Entry; import java.util.UUID; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class MoveMouseDamage extends SettingModifier { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java index 481e9a674..a642787b5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java @@ -20,10 +20,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ @CanInstaKillOnEnable public class OnlyDirtChallenge extends Setting { @@ -69,4 +65,4 @@ public void onBlockSpread(@Nonnull BlockSpreadEvent event) { } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java index a5128eb07..8cbe2613b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java @@ -15,10 +15,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class OnlyDownChallenge extends Setting { @@ -43,4 +39,4 @@ public void onPlayerMove(@Nonnull PlayerMoveEvent event) { ChallengeHelper.kill(event.getPlayer()); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java index c493342e1..13a0dd130 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java @@ -21,10 +21,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.3 - */ @Since("1.3") public class TrafficLightChallenge extends TimedChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index 214a8e015..8b0e036c3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -46,10 +46,6 @@ import java.util.Map.Entry; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class QuizChallenge extends TimedChallenge implements PlayerCommand, TabCompleter { private static QuizChallenge instance; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java index 390eb21f8..1bdde937a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java @@ -16,10 +16,6 @@ import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import org.bukkit.Material; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class BlockRandomizerChallenge extends RandomizerSetting { public BlockRandomizerChallenge() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java index ab20e5235..829be3904 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java @@ -15,10 +15,6 @@ import javax.annotation.Nonnull; import java.util.*; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class CraftingRandomizerChallenge extends RandomizerSetting { protected final Map randomization = new HashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 3792fbbcb..5def17398 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -30,10 +30,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class HotBarRandomizerChallenge extends TimedChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java index 6259c4eb4..e08dcbe0c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java @@ -34,10 +34,6 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntitySpawnEvent; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class MobRandomizerChallenge extends RandomizerSetting { @@ -229,4 +225,4 @@ private int getSpawnLimit(@Nonnull World world) { } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java index 5b37d22f5..e1904812f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java @@ -20,10 +20,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class RandomChallengeChallenge extends TimedChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java index 596ba187b..c27737b95 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java @@ -24,10 +24,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class RandomEventChallenge extends TimedChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java index cea207c72..8ce471fdc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java @@ -13,10 +13,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class RandomItemChallenge extends TimedChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java index dee55863e..57b92d418 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java @@ -18,10 +18,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class RandomItemDroppingChallenge extends TimedChallenge { @@ -80,4 +76,4 @@ protected void onTimeActivation() { }); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java index aaffe7212..0f6bd79c0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java @@ -15,10 +15,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class RandomItemRemovingChallenge extends TimedChallenge { @@ -63,4 +59,4 @@ protected void onTimeActivation() { } } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java index 76963ee39..9aef3ef61 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java @@ -17,10 +17,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class RandomItemSwappingChallenge extends TimedChallenge { @@ -85,4 +81,4 @@ protected void onTimeActivation() { } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java index b7c22044e..ff3a10448 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java @@ -19,10 +19,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ @Since("2.1.3") public class RandomTeleportOnHitChallenge extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java index 8d6d841ab..ca5546d4f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java @@ -31,10 +31,6 @@ import java.util.Map; import java.util.Random; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class RandomizedHPChallenge extends SettingModifier { private final Random random = new Random(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java index f83daec95..1b6db8258 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java @@ -18,10 +18,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class MaxBiomeTimeChallenge extends SettingModifier { @@ -108,4 +104,4 @@ private Biome getBiome(@Nonnull Player player) { return player.getLocation().getBlock().getBiome(); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java index 6c8564b9f..8d44f4d3f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java @@ -18,10 +18,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class MaxHeightTimeChallenge extends SettingModifier { @@ -103,4 +99,4 @@ private int getCurrentTime(@Nonnull Player player) { return getPlayerData(player).getInt(String.valueOf(player.getLocation().getBlockY()), 0); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java index 743005f34..884d4e679 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java @@ -28,10 +28,6 @@ import javax.annotation.Nullable; import java.util.*; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class AllBlocksDisappearChallenge extends MenuSetting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java index e2fb9e0f6..2a6c0c514 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java @@ -23,10 +23,6 @@ import java.util.List; import java.util.Random; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class AnvilRainChallenge extends MenuSetting { private final Random random = new Random(); @@ -232,4 +228,4 @@ private int getHeight(int currentHeight) { } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java index cf110f0ad..b7cb7d1d6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java @@ -15,11 +15,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class BedrockPathChallenge extends Setting { public BedrockPathChallenge() { @@ -42,4 +37,4 @@ public void onMove(@Nonnull PlayerMoveEvent event) { BlockUtils.createBlockPath(event.getFrom(), event.getTo(), Material.BEDROCK); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java index 8e5e013b6..4e8d42903 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java @@ -17,11 +17,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class BedrockWallChallenge extends SettingModifier { public BedrockWallChallenge() { @@ -71,4 +66,4 @@ protected String[] getSettingsDescription() { return Message.forName("item-time-seconds-description").asArray(getValue()); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java index b304bd2dc..8a4c39d71 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java @@ -17,10 +17,6 @@ import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ @Since("2.1.1") public class BlockFlyInAirChallenge extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java index f1463439c..eaa0fee8b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java @@ -20,10 +20,6 @@ import java.util.HashMap; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class BlocksDisappearAfterTimeChallenge extends SettingModifier { @@ -70,4 +66,4 @@ private BukkitTask runTask(@Nonnull Block block) { return Bukkit.getScheduler().runTaskLater(plugin, () -> block.setType(Material.AIR), getValue() * 20L); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java index 8c766be96..253ff1834 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java @@ -16,10 +16,6 @@ import javax.annotation.Nullable; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class ChunkDeconstructionChallenge extends TimedChallenge { public ChunkDeconstructionChallenge() { @@ -108,4 +104,4 @@ private List getChunksToDeconstruct() { ).build(); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java index 98450318b..1252c24b0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java @@ -16,11 +16,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class FloorIsLavaChallenge extends SettingModifier { public FloorIsLavaChallenge() { @@ -64,4 +59,4 @@ protected String[] getSettingsDescription() { return Message.forName("item-time-seconds-description").asArray(getValue()); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java index ad7e2c3b1..fb0e5b290 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java @@ -24,10 +24,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class IceFloorChallenge extends Setting { @@ -107,4 +103,4 @@ private boolean ignoreIce(@Nonnull Player player) { return ignoredPlayers.contains(player); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java index 065a821b5..921f74194 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java @@ -33,10 +33,6 @@ import java.util.Map; import java.util.UUID; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ @Since("2.2.3") @ExcludeFromRandomChallenges public class LevelBorderChallenge extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index 0982c2576..e3c0ad6f2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -46,10 +46,6 @@ import java.util.*; import java.util.Map.Entry; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0.2 - */ @Since("2.0.2") public class LoopChallenge extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java index fde4a5cc4..ebad2721a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java @@ -34,10 +34,6 @@ import java.util.*; import java.util.Map.Entry; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ @Since("2.1.1") public class RepeatInChunkChallenge extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index 12c9573bb..7e459c445 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -24,10 +24,6 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class SnakeChallenge extends Setting { private final ArrayList blocks = new ArrayList<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java index 3ec66a31a..c07addb57 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java @@ -17,11 +17,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class SurfaceHoleChallenge extends SettingModifier { public SurfaceHoleChallenge() { @@ -73,4 +68,4 @@ protected String[] getSettingsDescription() { return Message.forName("item-time-seconds-description").asArray(getValue()); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java index e70cc0830..90189cadd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java @@ -32,11 +32,6 @@ import java.util.Map; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class TsunamiChallenge extends TimedChallenge { @@ -236,4 +231,4 @@ public void loadGameState(@Nonnull Document document) { lavaHeight = document.getInt("lavaHeight"); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java index 3aeb509e6..b5d281832 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java @@ -16,10 +16,6 @@ import java.util.Arrays; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class DamageRuleSetting extends Setting { private final List causes; @@ -57,4 +53,4 @@ public void onDamage(@Nonnull EntityDamageEvent event) { event.setCancelled(true); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java index fb8893fa1..c02c60823 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java @@ -26,10 +26,6 @@ import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Since("2.1.0") public class AllAdvancementGoal extends PointsGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index a94e89a0e..4044b6b82 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -33,10 +33,6 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class CollectAllItemsGoal extends SettingGoal implements SenderCommand { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java index f1d89a5f2..99b1bec22 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java @@ -13,10 +13,6 @@ import java.util.Arrays; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class CollectHorseAmorGoal extends ItemCollectionGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java index 9b44217ec..42f602a26 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java @@ -8,10 +8,6 @@ import org.bukkit.Material; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class CollectIceBlocksGoal extends ItemCollectionGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java index 17712f8d7..6ced4873d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java @@ -15,10 +15,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class CollectMostDeathsGoal extends CollectionGoal { public CollectMostDeathsGoal() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java index 474a8099d..1131174c3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java @@ -13,10 +13,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class CollectMostExpGoal extends PointsGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java index 6eb21782a..2583fdc7b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java @@ -18,10 +18,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class CollectMostItemsGoal extends CollectionGoal { public CollectMostItemsGoal() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java index a319b6e39..dc326cc51 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java @@ -13,10 +13,6 @@ import java.util.Arrays; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class CollectSwordsGoal extends ItemCollectionGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java index 4ed755a9c..aefe3adc8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java @@ -20,10 +20,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class CollectWoodGoal extends SettingModifierCollectionGoal { private static final boolean newNether = MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_16); @@ -129,4 +125,4 @@ private void handleCollect(@Nonnull Player player, @Nonnull Material material) { }); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java index 4dd1c0a07..e28eb9813 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java @@ -10,10 +10,6 @@ import org.bukkit.Material; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") @RequireVersion(MinecraftVersion.V1_14) public class CollectWorkstationsGoal extends ItemCollectionGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java index 1b2bc328e..8bac031bc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java @@ -18,10 +18,6 @@ import java.util.Collections; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class EatCakeGoal extends SettingGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java index 3d6cc51e6..e61660347 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java @@ -13,10 +13,6 @@ import org.bukkit.event.entity.FoodLevelChangeEvent; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ @Since("2.1.2") public class EatMostGoal extends PointsGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java index c6c48042f..0a3d9b3ca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java @@ -8,10 +8,6 @@ import org.bukkit.Material; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ @Since("2.1.1") public class FindElytraGoal extends FindItemGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java index 09600e547..61e478d00 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java @@ -19,10 +19,6 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") @RequireVersion(MinecraftVersion.V1_16) public class FinishRaidGoal extends SettingGoal { @@ -50,4 +46,4 @@ public void onRaidFinish(@Nonnull RaidFinishEvent event) { ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, event::getWinners); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java index 1f01aa691..622a512d9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java @@ -16,10 +16,6 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class FirstOneToDieGoal extends SettingGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index f0ddfbf14..18e3092f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -24,10 +24,6 @@ import javax.annotation.Nullable; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.2.0 - */ @Since("2.2.0") public class GetFullHealthGoal extends SettingModifierGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java index a8b5157c2..02041d067 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java @@ -11,10 +11,6 @@ import javax.annotation.Nonnull; import java.util.Arrays; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class KillAllBossesGoal extends KillMobsGoal { @@ -34,4 +30,4 @@ public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.DIAMOND_SWORD, Message.forName("item-all-bosses-goal")); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java index 62f39ca4a..0d9206315 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java @@ -13,10 +13,6 @@ import javax.annotation.Nonnull; import java.util.Arrays; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.2.0") @RequireVersion(MinecraftVersion.V1_19) public class KillAllBossesNewGoal extends KillMobsGoal { @@ -37,4 +33,4 @@ public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.NETHERITE_SWORD, Message.forName("item-all-bosses-new-goal")); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java index 1954cbb65..989e47a8d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java @@ -13,10 +13,6 @@ import java.util.LinkedList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ @Since("2.1.3") public class KillAllMobsGoal extends KillMobsGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java index d1f4096b7..049dd1579 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java @@ -15,10 +15,6 @@ import java.util.LinkedList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ @Since("2.1.3") public class KillAllMonsterGoal extends KillMobsGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java index d6ca9b9f8..485f83260 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java @@ -12,10 +12,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class KillElderGuardianGoal extends KillEntityGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java index 382fcc7f4..019320b33 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java @@ -12,10 +12,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class KillEnderDragonGoal extends KillEntityGoal { public KillEnderDragonGoal() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java index cbc79c9c9..377ab6dcd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java @@ -12,10 +12,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class KillIronGolemGoal extends KillEntityGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java index cfe230402..8295a2712 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java @@ -11,10 +11,6 @@ import org.bukkit.Material; import org.bukkit.Sound; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class KillSnowGolemGoal extends KillEntityGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java index ffcd2aae8..68e989ae9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java @@ -14,10 +14,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.2.0") @RequireVersion(MinecraftVersion.V1_19) public class KillWardenGoal extends KillEntityGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java index 11ebc2656..258886f2b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java @@ -11,10 +11,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class KillWitherGoal extends KillEntityGoal { public KillWitherGoal() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java index fe90a8cff..f4b1afab1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java @@ -18,10 +18,6 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class LastManStandingGoal extends SettingGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java index 5416f0951..3abeba17c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java @@ -10,10 +10,6 @@ import org.bukkit.World.Environment; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Since("2.1.0") public class MaxHeightGoal extends FirstPlayerAtHeightGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java index 4b0de86e3..fe2ae7e01 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java @@ -11,10 +11,6 @@ import org.bukkit.World.Environment; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Since("2.1.0") public class MinHeightGoal extends FirstPlayerAtHeightGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java index ec8d2f2f6..df37703b3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java @@ -11,10 +11,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class MineMostBlocksGoal extends PointsGoal { public MineMostBlocksGoal() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java index c5be3df63..8cc7975bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java @@ -18,10 +18,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0.2 - */ @Since("2.0.2") public class MostEmeraldsGoal extends PointsGoal { @@ -84,4 +80,4 @@ public void onUpdate(@Nonnull PlayerDropItemEvent event) { updatePoints(event.getPlayer()); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java index 9852c3409..8d9f1cec1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java @@ -16,10 +16,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ @Since("2.1.1") public class MostOresGoal extends PointsGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java index d8d5a3dcb..c773eb0ad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java @@ -32,10 +32,6 @@ import java.util.Collections; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Since("2.1.0") public class RaceGoal extends SettingModifierGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java index 56259f23e..164737ee5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java @@ -36,10 +36,6 @@ import java.util.UUID; import java.util.function.Function; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class ExtremeForceBattleGoal extends ForceBattleDisplayGoal> { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java index ddb3047f7..ad7364afb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java @@ -21,10 +21,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.0 - */ @Since("2.2.0") public class ForceAdvancementBattleGoal extends ForceBattleGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java index 2bfeca5f5..680cf5fb5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java @@ -17,10 +17,6 @@ import java.util.Objects; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.1.3 - */ public class ForceBiomeBattleGoal extends ForceBattleGoal { public ForceBiomeBattleGoal() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java index 0916d0227..6b72f552d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java @@ -16,10 +16,6 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.0 - */ @Since("2.2.0") public class ForceBlockBattleGoal extends ForceBattleDisplayGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java index c3cb8dd2e..e229b34ea 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java @@ -17,10 +17,6 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class ForceDamageBattleGoal extends ForceBattleGoal { public ForceDamageBattleGoal() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java index 6a85ad51b..f72bdbf81 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java @@ -16,10 +16,6 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class ForceHeightBattleGoal extends ForceBattleGoal { public ForceHeightBattleGoal() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java index b4238e8bd..b74e60a7a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java @@ -18,10 +18,6 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ @Since("2.1.3") public class ForceItemBattleGoal extends ForceBattleDisplayGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java index 573d0dd91..542f64d5d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java @@ -19,10 +19,6 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.0 - */ @Since("2.2.0") public class ForceMobBattleGoal extends ForceBattleDisplayGoal { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java index 6c2a881f2..a800dbff4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java @@ -14,10 +14,6 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class ForcePositionBattleGoal extends ForceBattleGoal { public ForcePositionBattleGoal() { super(Message.forName("menu-force-position-battle-goal-settings")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java index 738269090..62ebf3f97 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java @@ -10,10 +10,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class AdvancementTarget extends ForceTarget { public AdvancementTarget(Advancement target) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java index 181fa0728..11ba3212e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java @@ -10,10 +10,6 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class BiomeTarget extends ForceTarget { public BiomeTarget(Biome target) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java index 585c5acb1..1728cbc6c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java @@ -13,10 +13,6 @@ import java.util.Arrays; import java.util.List; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class BlockTarget extends ForceTarget { public BlockTarget(Material target) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java index 39ab6581c..2cc448a88 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java @@ -4,10 +4,6 @@ import net.codingarea.challenges.plugin.content.Message; import org.bukkit.entity.Player; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class DamageTarget extends ForceTarget { public DamageTarget(Integer target) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java index 8abf1a85b..a04eac918 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java @@ -8,10 +8,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public abstract class ForceTarget { protected final T target; @@ -48,4 +44,4 @@ public Object getTargetSaveObject() { return target.toString(); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java index 9abe837f7..30f913054 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java @@ -4,10 +4,6 @@ import net.codingarea.challenges.plugin.content.Message; import org.bukkit.entity.Player; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class HeightTarget extends ForceTarget { public HeightTarget(Integer target) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java index a407974ec..c8a6c9ca3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java @@ -12,10 +12,6 @@ import java.util.Arrays; import java.util.List; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class ItemTarget extends ForceTarget { public ItemTarget(Material target) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java index d5ce2cc38..cfe4ed8b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java @@ -16,10 +16,6 @@ import java.util.Arrays; import java.util.List; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class MobTarget extends ForceTarget { public MobTarget(EntityType target) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java index 743cf7f16..dae98fc12 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java @@ -8,10 +8,6 @@ import org.bukkit.Location; import org.bukkit.entity.Player; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class PositionTarget extends ForceTarget> { public PositionTarget(double x, double z) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java index 0e0c56653..2305b84e0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java @@ -20,10 +20,6 @@ import javax.annotation.Nonnull; import java.util.Arrays; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class BlockMaterialSetting extends Setting { private final String name; @@ -105,4 +101,4 @@ public String getUniqueName() { return "blockmaterial" + materials[0].name().toLowerCase(); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java index 053947fb2..ffbdb9309 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java @@ -27,10 +27,6 @@ import java.util.Map; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class BackpackSetting extends SettingModifier implements PlayerCommand { public static final int SHARED = 1, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java index 0cd7cb3a7..afdd615d3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java @@ -15,10 +15,6 @@ import java.util.Arrays; import java.util.stream.Collectors; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") @RequireVersion(MinecraftVersion.V1_16) public class BastionSpawnSetting extends NetherPortalSpawnSetting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java index 0ecf32884..ccfd47482 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java @@ -30,11 +30,6 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class CutCleanSetting extends MenuSetting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java index cc0969959..43405e86d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java @@ -23,10 +23,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class DamageDisplaySetting extends Setting { public DamageDisplaySetting() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java index cf6675268..bae4e3b93 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java @@ -14,10 +14,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class DamageMultiplierModifier extends Modifier { public DamageMultiplierModifier() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java index a6f8d4d99..39e646b59 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java @@ -20,10 +20,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class DeathMessageSetting extends Modifier { public static final int ENABLED = 2, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java index 1736b6ba7..19337ecd6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java @@ -14,10 +14,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class DeathPositionSetting extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java index aeb0167f5..0ae530df8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java @@ -30,11 +30,6 @@ import java.util.Arrays; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class DifficultySetting extends Modifier implements SenderCommand, TabCompleter { public DifficultySetting() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java index e097f9b83..80a8c9ef7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java @@ -13,10 +13,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class EnderChestCommandSetting extends Setting implements PlayerCommand { @@ -41,4 +37,4 @@ public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exc Message.forName("command-enderchest-open").send(player, Prefix.CHALLENGES); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java index 13ff7c093..846d5f120 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java @@ -10,10 +10,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class FortressSpawnSetting extends NetherPortalSpawnSetting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java index 8be845fba..dadd0c9e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java @@ -21,10 +21,6 @@ import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.ScoreboardManager; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class HealthDisplaySetting extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java index 2c9a9ab8b..e050cbcb2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java @@ -15,10 +15,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class ImmediateRespawnSetting extends Setting { @@ -69,4 +65,4 @@ public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java index 1f48a805a..3bb1c7b54 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java @@ -11,10 +11,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class KeepInventorySetting extends Setting { public KeepInventorySetting() { @@ -40,4 +36,4 @@ protected void onDisable() { world.setGameRule(GameRule.KEEP_INVENTORY, false); } } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index 1275caf10..4f385dc6e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -19,10 +19,6 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.jetbrains.annotations.NotNull; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class MaxHealthSetting extends Modifier { /** diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java index 627e53494..f74da9f48 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java @@ -14,10 +14,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class NoHitDelaySetting extends Setting { public NoHitDelaySetting() { @@ -39,4 +35,4 @@ public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.FEATHER, Message.forName("item-no-hit-delay-setting")); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java index 077646b53..a3a5ef966 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java @@ -11,10 +11,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class NoHungerSetting extends Setting { public NoHungerSetting() { @@ -45,4 +41,4 @@ private void feedPlayer(@Nonnull Player player) { player.setSaturation(20); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java index 4573cbafd..0a7565208 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java @@ -10,10 +10,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class NoItemDamageSetting extends Setting { public NoItemDamageSetting() { @@ -35,4 +31,4 @@ public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.ANVIL, Message.forName("item-no-item-damage-setting")); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java index f1a3caf24..66e998142 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java @@ -17,10 +17,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class NoOffhandSetting extends Setting { @@ -64,4 +60,4 @@ public void onInventoryClick(InventoryClickEvent event) { event.setCancelled(true); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java index 812befd74..bb6fc9525 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java @@ -20,10 +20,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Since("2.0") public class OldPvPSetting extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java index f306b11a7..8ab6ef1a2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java @@ -15,10 +15,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class OneTeamLifeSetting extends Setting { private boolean isKilling = false; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java index 1dea9c84c..cc8fbad1f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java @@ -16,10 +16,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class PlayerGlowSetting extends Setting { public PlayerGlowSetting() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java index 78a4b5c5b..f9c8b9cd3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java @@ -29,10 +29,6 @@ import java.util.*; import java.util.Map.Entry; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class PositionSetting extends Setting implements PlayerCommand, TabCompleter { private final Map positions = new HashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java index 4e0df21f4..2c6a9e9db 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java @@ -14,11 +14,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class PregameMovementSetting extends Setting { public PregameMovementSetting() { @@ -59,4 +54,4 @@ public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.PISTON, Message.forName("pregame-movement-setting")); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java index c317e1e7b..2a6180473 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java @@ -11,10 +11,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class PvPSetting extends Setting { public PvPSetting() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java index 0625540a5..7402eb235 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java @@ -17,10 +17,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class RegenerationSetting extends Modifier { public RegenerationSetting() { @@ -72,4 +68,4 @@ public void onEntityRegainHealth(EntityRegainHealthEvent event) { } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java index fa4fd7d3f..b2c320340 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java @@ -22,10 +22,6 @@ import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerRespawnEvent; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class RespawnSetting extends Setting { private final Map locationsBeforeRespawn = new ConcurrentHashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java index 88c66b02d..9d60a6687 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java @@ -25,10 +25,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class SlotLimitSetting extends Modifier { @@ -163,4 +159,4 @@ public void onPlayerIgnoreStatusChange(PlayerIgnoreStatusChangeEvent event) { }); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java index ab5ea73de..0ecda9701 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java @@ -15,10 +15,6 @@ import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.potion.PotionEffect; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class SoupSetting extends Setting { public SoupSetting() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index a12386d82..9f9c4669e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -21,10 +21,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class SplitHealthSetting extends Setting { public SplitHealthSetting() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java index 3fa3c49ac..9b0a4e1d4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java @@ -22,11 +22,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class TimberSetting extends SettingModifier { public static final int LOGS_LEAVES = 2; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java index 3f3e08384..9483e70a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java @@ -16,10 +16,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class TopCommandSetting extends Setting implements PlayerCommand { public TopCommandSetting() { @@ -76,4 +72,4 @@ public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.MAGENTA_GLAZED_TERRACOTTA, Message.forName("top-command-setting")); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java index bd0739af2..f441a1429 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java @@ -13,10 +13,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Since("2.0") public class TotemSaveDeathSetting extends Setting { @@ -37,4 +33,4 @@ public void onEntityResurrect(@Nonnull EntityResurrectEvent event) { } } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java index 143f6e1d0..a2ae004e7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java @@ -13,10 +13,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public class EmptyChallenge implements IChallenge { private final MenuType menuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java index 2492c1023..7679a2c08 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java @@ -11,11 +11,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @see ChallengeManager - * @since 2.0 - */ public interface IChallenge extends GamestateSaveable { /** diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java index 455333bd4..66d438d2d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java @@ -10,11 +10,6 @@ import javax.annotation.Nullable; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @see ChallengeManager - * @since 2.0 - */ public interface IGoal extends IChallenge { /** diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java index ee15e6ef5..928f4c13c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java @@ -2,10 +2,6 @@ import javax.annotation.Nonnegative; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public interface IModifier { @Nonnegative @@ -21,4 +17,4 @@ public interface IModifier { void playValueChangeTitle(); -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java index 3fcaeff27..ca222f168 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java @@ -28,11 +28,6 @@ import java.util.UUID; import java.util.function.Consumer; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public abstract class AbstractChallenge implements IChallenge, Listener { protected static final Challenges plugin = Challenges.getInstance(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java index a1e9fbf67..f0c68f3fe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java @@ -10,10 +10,6 @@ import javax.annotation.Nonnull; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class AbstractForceChallenge extends TimedChallenge { public static final int WAITING = 0, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java index 860fa45ec..c43553aa2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java @@ -15,10 +15,6 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class CollectionGoal extends SettingGoal { private final Map> collections = new HashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java index 8e9f186e6..3ed7971dd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java @@ -8,10 +8,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class CompletableForceChallenge extends AbstractForceChallenge { public CompletableForceChallenge(@Nonnull MenuType menu) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java index b9ba6efe5..163fce396 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java @@ -11,10 +11,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class EndingForceChallenge extends AbstractForceChallenge { public EndingForceChallenge(@Nonnull MenuType menu) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java index 33be66503..92e48a424 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java @@ -15,10 +15,6 @@ import java.util.Collections; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class FindItemGoal extends SettingGoal { private final Material searchedItem; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java index 035c06449..463dd0ee2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java @@ -14,10 +14,6 @@ import java.util.Collections; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class FirstPlayerAtHeightGoal extends SettingGoal { private int heightToGetTo; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java index deb6b7486..a2e199a58 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java @@ -18,10 +18,6 @@ import java.util.HashMap; import java.util.Map; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.0 - */ public abstract class ForceBattleDisplayGoal> extends ForceBattleGoal { private Map displayStands; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java index 8583464c3..d12c792b7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java @@ -37,10 +37,6 @@ import java.util.*; import java.util.stream.Collectors; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.0 - */ public abstract class ForceBattleGoal> extends MenuGoal { protected final Map jokerUsed = new HashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java index 80884d628..04b5d1838 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java @@ -13,10 +13,6 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public abstract class HydraChallenge extends Setting { public HydraChallenge(@Nonnull MenuType menu) { @@ -44,4 +40,4 @@ public void onEntityDamageByEntity(@Nonnull EntityDeathByPlayerEvent event) { MinecraftNameWrapper.ENTITY_EFFECT, 2, 17, 1); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java index f2a2a8348..95faee5b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java @@ -16,10 +16,6 @@ import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public abstract class ItemCollectionGoal extends CollectionGoal { public ItemCollectionGoal(@NotNull Material... target) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java index 8c1135858..218a068fe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java @@ -14,10 +14,6 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class KillEntityGoal extends SettingGoal { protected final EntityType entity; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java index 1d58fd1bb..8cd2371a7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java @@ -17,10 +17,6 @@ import java.util.LinkedList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ public abstract class KillMobsGoal extends SettingGoal { protected static List entitiesKilled; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java index 2a4d0e6ed..cf18fb51d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java @@ -10,10 +10,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.1.4 - */ public abstract class MenuGoal extends MenuSetting implements IGoal { public MenuGoal(@NotNull MenuType menu, @NotNull Message title) { super(menu, title); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java index 97b1684fe..4b7427825 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java @@ -29,10 +29,6 @@ import java.util.function.Function; import java.util.function.Supplier; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class MenuSetting extends Setting { private final Map settings = new LinkedHashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java index ccb223b00..a9091053d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java @@ -12,10 +12,6 @@ import javax.annotation.Nonnegative; import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public abstract class Modifier extends AbstractChallenge implements IModifier { private final int max, min; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java index 6d5bd4ffd..0818c892d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java @@ -11,10 +11,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public abstract class ModifierCollectionGoal extends CollectionGoal implements IModifier { private final int max, min; @@ -118,4 +114,4 @@ public void writeSettings(@Nonnull Document document) { document.set("value", value); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java index 79303c354..a10551f4e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java @@ -18,11 +18,6 @@ import java.util.Map; import java.util.Map.Entry; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public abstract class NetherPortalSpawnSetting extends OneEnabledSetting { private static final String id = "netherportal_handle"; @@ -200,4 +195,4 @@ public void writeGameState(@Nonnull Document document) { } } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java index f8a0e3117..ebd7ba918 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java @@ -5,10 +5,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class OneEnabledSetting extends Setting { private final String typeId; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java index b9b21cf94..2ee5d22f0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java @@ -13,10 +13,6 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class PointsGoal extends SettingGoal { private final Map points = new HashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java index 332a9eb59..3c9b8ebb6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java @@ -8,10 +8,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class RandomizerSetting extends Setting { protected IRandom random = IRandom.create(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java index 0662c6c36..0f74a1501 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java @@ -11,10 +11,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public abstract class Setting extends AbstractChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java index 1893f2868..606ddb68d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java @@ -8,10 +8,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class SettingGoal extends Setting implements IGoal { public SettingGoal() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java index 3e9195f2a..644839adc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java @@ -11,10 +11,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class SettingModifier extends Modifier { private boolean enabled; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java index ae202aa1e..69234f1c6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java @@ -9,10 +9,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public abstract class SettingModifierCollectionGoal extends ModifierCollectionGoal { public SettingModifierCollectionGoal(int min, int max, @Nonnull Object... target) { @@ -76,4 +72,4 @@ public void loadSettings(@Nonnull Document document) { setEnabled(document.getBoolean("enabled")); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java index 15e6aa98e..66935584f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java @@ -10,10 +10,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class SettingModifierGoal extends SettingModifier implements IGoal { public SettingModifierGoal(@Nonnull MenuType menu) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java index 7ad17ae2b..7cf353a96 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java @@ -11,10 +11,6 @@ import javax.annotation.Nonnegative; import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class TimedChallenge extends SettingModifier { private final boolean runAsync; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java index 2321efc47..a826eb11f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java @@ -20,10 +20,6 @@ import java.util.List; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class WorldDependentChallenge extends TimedChallenge { private boolean inExtraWorld; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java index 0aa14399a..e17817559 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java @@ -6,10 +6,6 @@ import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public final class ChallengeConfigHelper { private static final Document settingsDocument; @@ -27,4 +23,4 @@ public static Document getSettingsDocument() { return settingsDocument; } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index f25548b8e..eaf6715c9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -34,11 +34,6 @@ import java.util.List; import java.util.stream.Collectors; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public final class ChallengeHelper { @Getter diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java index b2d7105e2..f4253a197 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java @@ -21,10 +21,6 @@ import java.util.function.Supplier; import java.util.function.ToIntBiFunction; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class GoalHelper { public static final int LEADERBOARD_SIZE = 9; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java index f8390f8db..4e10f6821 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java @@ -17,10 +17,6 @@ import org.bukkit.entity.EntityType; import org.bukkit.potion.PotionEffectType; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.1 - */ public class SubSettingsHelper { public static final String diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java index 4e0b2018a..803440ff4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java @@ -10,10 +10,6 @@ import java.util.LinkedList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ItemDescription { private static final Document config = Challenges.getInstance().getConfigDocument().getDocument("design"); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java index 45de793ce..302c0af39 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java @@ -13,10 +13,6 @@ import java.util.ArrayList; import java.util.Collection; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public interface Message { String NULL = "§r§fN/A"; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java index 0995acc77..3ab88d5e1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java @@ -8,10 +8,6 @@ import java.util.HashMap; import java.util.Map; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.2 - */ public class Prefix { private static final Map values = new HashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java index 3056fb22e..c4cdd53e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java @@ -22,10 +22,6 @@ import java.util.function.BiConsumer; import java.util.function.Consumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class MessageImpl implements Message { protected final String name; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java index 95986bfbf..80bf53e2e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java @@ -7,10 +7,6 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class MessageManager { private static final Map cache = new ConcurrentHashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java index 2c7e3f422..97aa23441 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java @@ -5,10 +5,6 @@ import javax.annotation.Nonnull; import java.io.File; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class ContentLoader { @Nonnull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index dbfad9f25..d963b49a5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -19,10 +19,6 @@ import java.io.IOException; import java.util.Map.Entry; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class LanguageLoader extends ContentLoader { public static final String DEFAULT_LANGUAGE = "en"; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java index 4cf96e944..c93ebe49a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java @@ -8,10 +8,6 @@ import java.util.*; import java.util.concurrent.atomic.AtomicInteger; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class LoaderRegistry { private static final AtomicInteger loading = new AtomicInteger(); // Keeps track of how many loaders are still loading diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java index bdd9124f9..012ef9408 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java @@ -7,10 +7,6 @@ import java.io.File; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class PrefixLoader extends ContentLoader { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java index 01b08a662..89efdf0a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java @@ -8,10 +8,6 @@ import java.net.URL; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class UpdateLoader extends ContentLoader { public static final int RESOURCE_ID = 80548; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java index 26baedf27..fcc6ca530 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java @@ -15,10 +15,6 @@ import java.util.function.BooleanSupplier; import java.util.stream.Collectors; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class BlockDropManager { private final Map drops = new HashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java index 4c7223d50..196905805 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java @@ -11,10 +11,6 @@ import java.util.HashMap; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class MetricsLoader { public void start() { @@ -44,4 +40,4 @@ private int getMemory() { return MemoryConverter.getGB(Runtime.getRuntime().maxMemory()); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java index 00c967b31..9d46c150a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java @@ -93,11 +93,6 @@ /** * This class loads all challenges of this plugin. - * In pre2 versions, this class was known as PluginChallengeLoader. - * - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 */ public final class ChallengeLoader extends ModuleChallengeLoader { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java index f9a972891..661d9cfa1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java @@ -22,10 +22,6 @@ import java.util.List; import java.util.function.Predicate; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ChallengeManager { private final List challenges = new LinkedList<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java index 976d2f181..669a3bbe5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java @@ -16,10 +16,6 @@ import javax.annotation.Nonnull; import java.util.*; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1 - */ public class CustomChallengesLoader extends ModuleChallengeLoader { private final Map customChallenges = new LinkedHashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java index d43232af7..d5b098432 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java @@ -19,10 +19,6 @@ import java.lang.reflect.Constructor; import java.util.Optional; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class ModuleChallengeLoader { protected final BukkitModule plugin; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/CanInstaKillOnEnable.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/CanInstaKillOnEnable.java index c3a747521..b6c11153c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/CanInstaKillOnEnable.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/CanInstaKillOnEnable.java @@ -5,10 +5,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface CanInstaKillOnEnable { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/ExcludeFromRandomChallenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/ExcludeFromRandomChallenges.java index 23aae2577..3db378b57 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/ExcludeFromRandomChallenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/ExcludeFromRandomChallenges.java @@ -5,10 +5,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface ExcludeFromRandomChallenges { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java index 4d8666d86..67734ab3e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java @@ -8,10 +8,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface RequireVersion { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java index 4b8744b74..89a79d854 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java @@ -4,10 +4,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public interface GamestateSaveable { String getUniqueGamestateName(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java index cf2806cfc..c77f80de4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java @@ -5,10 +5,6 @@ import javax.annotation.Nonnull; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public interface CloudSupport { @Nonnull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java index 3066c6324..e5fa7d45c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java @@ -21,10 +21,6 @@ import java.util.Map; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class CloudSupportManager implements Listener { private final Map cachedColoredNames = new HashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java index 6c1cfa1a0..2aa437518 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java @@ -11,10 +11,6 @@ import javax.annotation.Nonnull; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class CloudNet2Support implements CloudSupport { @Nonnull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java index 1b96086b8..c3f9e2a0b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java @@ -12,10 +12,6 @@ import javax.annotation.Nonnull; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class CloudNet3Support implements CloudSupport { @Nonnull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java index d061a9da7..356dcc2eb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java @@ -24,10 +24,6 @@ import java.util.HashMap; import java.util.Map; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class DatabaseManager { private final Map> registry = new HashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java index 09b2cccd5..48580b8c6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java @@ -17,10 +17,6 @@ import java.util.LinkedList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public final class ConfigManager { private final List missingConfigSettings; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java index 7ffdeb017..9ded8cf2a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java @@ -29,10 +29,6 @@ import java.util.List; import java.util.function.Consumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class PlayerInventoryManager implements Listener { private final List hotbarItems; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java index 2a5128579..6e12c0c48 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java @@ -4,10 +4,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class InventoryTitleManager { private InventoryTitleManager() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java index 8ba82108f..9ddc48971 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java @@ -19,10 +19,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class MenuManager { public static final String MANAGE_GUI_PERMISSION = "challenges.manage"; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java index 704e544c5..cacd68a2e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java @@ -14,10 +14,7 @@ import javax.annotation.Nonnull; import java.util.function.Consumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ + public enum MenuType { TIMER("timer", Material.CLOCK, new TimerMenuGenerator(), false), diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java index 2faa5a257..764580be4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java @@ -24,10 +24,6 @@ import java.util.List; import java.util.function.Consumer; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class ChallengeMenuGenerator extends MultiPageMenuGenerator { protected final List challenges = new LinkedList<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java index 0f4ad6e67..08222a111 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java @@ -16,10 +16,6 @@ import javax.annotation.Nonnull; import java.util.LinkedHashMap; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class ChooseItemGenerator extends MultiPageMenuGenerator { private final LinkedHashMap items; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java index 99ef204a9..24ae44c25 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java @@ -22,10 +22,6 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class ChooseMultipleItemGenerator extends MultiPageMenuGenerator { public static final int FINISH_SLOT = 40; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java index e112dea0f..fd7122c59 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java @@ -12,10 +12,6 @@ import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class MenuGenerator { private MenuType menuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java index 60898ed8d..971853af9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java @@ -14,10 +14,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public abstract class MultiPageMenuGenerator extends MenuGenerator { protected final List inventories = new ArrayList<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java index 05ccc2f9d..8106fdf87 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java @@ -18,10 +18,6 @@ import javax.annotation.Nonnull; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ @Getter public abstract class ValueMenuGenerator extends MultiPageMenuGenerator { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java index 1541f1070..20291244b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java @@ -20,10 +20,6 @@ import java.util.Map; import java.util.stream.Collectors; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.2.0 - */ public class CategorisedMenuGenerator extends SettingsMenuGenerator { private final Map categories = new LinkedHashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java index 87b064286..da3145a09 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java @@ -7,10 +7,6 @@ import java.util.function.Supplier; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.2.0 - */ public class SettingCategory { //Challenges diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java index b8b9b81bd..4d8f2212f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java @@ -1,9 +1,5 @@ package net.codingarea.challenges.plugin.management.menu.generator.categorised; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.2.0 - */ public class SmallCategorisedMenuGenerator extends CategorisedMenuGenerator { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java index 13404457a..697f88629 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java @@ -7,10 +7,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class SettingsMenuGenerator extends ChallengeMenuGenerator { public static final int[] SLOTS = {10, 11, 12, 13, 14, 15, 16}; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java index 3aeaaca2c..ce6d290fa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java @@ -29,10 +29,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class TimerMenuGenerator extends MenuGenerator { public static final int SIZE = 5 * 9; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java index 1daee6263..a12cccb13 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java @@ -14,10 +14,6 @@ import java.util.Map; import java.util.function.Function; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1 - */ public class CustomMainSettingsMenuGenerator extends ChooseItemGenerator implements IParentCustomGenerator { @Getter diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/IParentCustomGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/IParentCustomGenerator.java index 30b47968b..279db1727 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/IParentCustomGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/IParentCustomGenerator.java @@ -5,10 +5,6 @@ import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public interface IParentCustomGenerator { /** diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java index 44cff4691..7b7bab270 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java @@ -34,10 +34,6 @@ import javax.annotation.Nonnull; import java.util.*; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @ToString public class InfoMenuGenerator extends MenuGenerator implements IParentCustomGenerator { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java index 83da67ff0..73a020dd5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java @@ -17,10 +17,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class MainCustomMenuGenerator extends ChallengeMenuGenerator { public static final int[] SLOTS = {10, 11, 12, 13, 14, 15, 16}; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java index ed35c3120..c142e632f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java @@ -11,10 +11,6 @@ import java.util.LinkedHashMap; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class MaterialMenuGenerator extends ChooseItemGenerator { private final IParentCustomGenerator parent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java index 90d9fa22e..dff2ba522 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java @@ -7,10 +7,6 @@ import java.util.LinkedHashMap; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class SubSettingChooseMenuGenerator extends ChooseItemGenerator { private final IParentCustomGenerator parent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java index 718804f12..8dbf921d4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java @@ -7,10 +7,6 @@ import java.util.LinkedHashMap; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class SubSettingChooseMultipleMenuGenerator extends ChooseMultipleItemGenerator { private final IParentCustomGenerator parent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java index 99620a15a..ea7d84c44 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java @@ -8,10 +8,6 @@ import java.util.Map; import java.util.Map.Entry; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class SubSettingValueMenuGenerator extends ValueMenuGenerator { private final IParentCustomGenerator parent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java index b6ac0ff2d..a37bae7c4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java @@ -8,10 +8,6 @@ import javax.annotation.Nonnegative; import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @ToString public class ChallengeMenuClickInfo extends MenuClickInfo { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java index 28142d975..86acca2c0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java @@ -4,10 +4,6 @@ import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ @Getter public abstract class GeneratorMenuPosition implements MenuPosition { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java index 04d86d139..be1e86430 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java @@ -1,9 +1,5 @@ package net.codingarea.challenges.plugin.management.scheduler; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class AbstractTaskConfig { protected final boolean async; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java index 782750a1b..0ed16c4f0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java @@ -7,10 +7,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public abstract class AbstractTaskExecutor implements Runnable { protected final List functions = new ArrayList<>(1); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java index ce7e033df..e28f4c0f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java @@ -9,10 +9,6 @@ import java.util.Arrays; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class PoliciesContainer { private final List policies = new ArrayList<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java index 4a2d455e2..de7305d1d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java @@ -11,10 +11,6 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ScheduleManager { private final Map scheduledTaskExecutorsByConfig = new ConcurrentHashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java index c8d76f259..5881e556c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java @@ -5,10 +5,6 @@ import javax.annotation.Nonnull; import lombok.EqualsAndHashCode; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @EqualsAndHashCode public final class ScheduledFunction { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java index 1a2b8d454..0af70ab3e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java @@ -6,10 +6,6 @@ import lombok.Getter; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Getter @EqualsAndHashCode(callSuper = false) public final class ScheduledTaskConfig extends AbstractTaskConfig { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java index 296aca5e6..97d295ddb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java @@ -7,11 +7,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @see ScheduleManager - * @since 2.0 - */ final class ScheduledTaskExecutor extends AbstractTaskExecutor { private final ScheduledTaskConfig config; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java index c6b7a2af8..7460bd972 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java @@ -6,10 +6,6 @@ import javax.annotation.Nonnull; import java.util.Arrays; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class TimerTaskConfig extends AbstractTaskConfig { private final TimerStatus[] status; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java index c3e1ffde1..854d8b41d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java @@ -5,10 +5,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ final class TimerTaskExecutor extends AbstractTaskExecutor { private final TimerTaskConfig config; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java index 44a127d36..a39cf8479 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java @@ -5,10 +5,6 @@ import javax.annotation.Nonnull; import java.util.function.Predicate; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public enum ChallengeStatusPolicy implements IPolicy { ALWAYS(challenge -> true), diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java index 164850658..6b62fa74d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java @@ -5,10 +5,6 @@ import javax.annotation.Nonnull; import java.util.function.BooleanSupplier; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public enum ExtraWorldPolicy implements IPolicy { ALWAYS(() -> true), diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java index da57d60d3..22f223d38 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java @@ -5,10 +5,6 @@ import javax.annotation.Nonnull; import java.util.function.BooleanSupplier; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public enum FreshnessPolicy implements IPolicy { ALWAYS(() -> true), diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java index 6c39a8916..300612cbe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java @@ -2,10 +2,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public interface IPolicy { boolean check(@Nonnull Object holder); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java index bcb29fd05..36b206be3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java @@ -5,10 +5,6 @@ import javax.annotation.Nonnull; import java.util.function.BiPredicate; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public enum PlayerCountPolicy implements IPolicy { ALWAYS((online, max) -> true), diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java index b4b578e91..1a31428b9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java @@ -5,10 +5,6 @@ import javax.annotation.Nonnull; import java.util.function.BooleanSupplier; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public enum TimerPolicy implements IPolicy { ALWAYS(() -> true), diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java index eb72dc55e..5b44e293c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java @@ -9,10 +9,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ScheduledTask { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java index bc63d36f3..cf8ba7870 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java @@ -12,10 +12,6 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface TimerTask { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java index b8790babd..b34dcc313 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java @@ -25,10 +25,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public final class ChallengeTimer { @Getter diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java index f2e53215b..3bc78d9e0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java @@ -5,10 +5,6 @@ import javax.annotation.Nonnegative; import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class TimerFormat { private final String seconds, minutes, hours, day, days; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerStatus.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerStatus.java index 25a62ddc7..1e2406fb9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerStatus.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerStatus.java @@ -1,9 +1,5 @@ package net.codingarea.challenges.plugin.management.scheduler.timer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public enum TimerStatus { RUNNING, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java index 1202f3693..4fa74dacf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java @@ -5,10 +5,6 @@ import lombok.Getter; import net.codingarea.challenges.plugin.content.Message; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ @Getter public enum ChallengeEndCause { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java index 398035789..80e0bf35d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java @@ -17,10 +17,6 @@ import java.util.LinkedList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class GameWorldStorage implements GamestateSaveable { private final List worlds = new LinkedList<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java index 08320b295..e274b348d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java @@ -16,9 +16,6 @@ /** * Manages the portal locations of custom worlds - * - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 */ public class GeneratorWorldPortalManager implements GamestateSaveable { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java index 593438834..e2eb84f9e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java @@ -15,10 +15,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ScoreboardManager { private final List bossbars = new ArrayList<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java index 8fff31d40..a876c4ad0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java @@ -23,10 +23,6 @@ import java.util.List; import java.util.function.Supplier; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public final class ServerManager { private final boolean setSpectatorOnWin; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java index 54e8bfc01..db4028ee9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java @@ -7,10 +7,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class TitleManager { private static final int fadein = 5, duration = 20, fadeout = 10; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java index 449e8d750..6f6d3552a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java @@ -24,10 +24,6 @@ import java.util.Map; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class WorldManager { private static final String customSeedWorldPrefix = "pregenerated_"; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java index 701d7da05..90158fe5f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java @@ -19,10 +19,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ChallengeBossBar { private final Map bossbars = new ConcurrentHashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java index 0409e0ceb..d0f6093d6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java @@ -18,10 +18,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ChallengeScoreboard { private final Map objectives = new ConcurrentHashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java index 7054dbfac..923e1ad3f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java @@ -5,10 +5,6 @@ import java.util.EnumMap; import java.util.Map; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class LeaderboardInfo { private final Map values = new EnumMap<>(Statistic.class); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java index 35237f673..fd29c7090 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java @@ -9,10 +9,6 @@ import java.util.Map.Entry; import java.util.UUID; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class PlayerStats { private final Map values = new EnumMap<>(Statistic.class); @@ -66,4 +62,4 @@ public String toString() { return "PlayerStats" + values; } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java index e00959c3c..1fec51752 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java @@ -5,10 +5,6 @@ import javax.annotation.Nonnull; import java.util.function.Function; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public enum Statistic { DRAGON_KILLED(Display.INTEGER), diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java index d620bd304..c7982e92b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java @@ -23,11 +23,6 @@ import java.util.function.Function; import java.util.stream.Collectors; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/KxmischesDomi - * @since 2.0 - */ public final class StatsManager implements Listener { @Getter diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java index 786a7ba4e..7c986528c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java @@ -23,10 +23,6 @@ import java.util.*; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class BackCommand implements PlayerCommand, TabCompleter, Listener { private final Map> lastLocations = new HashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java index cfa0f993a..8b5572568 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java @@ -16,10 +16,6 @@ import java.util.Arrays; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class ChallengesCommand implements PlayerCommand, Completer { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java index fb3a0bdc1..734718d29 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java @@ -20,10 +20,6 @@ import java.util.List; import java.util.Map; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class DatabaseCommand implements PlayerCommand, TabCompleter { private final Map databaseExecutors; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java index d7ad4f38a..6bc0b1e5a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java @@ -13,10 +13,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class FeedCommand implements SenderCommand, Completer { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java index bdf981f42..e176ea9dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java @@ -13,10 +13,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class FlyCommand implements SenderCommand, Completer { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java index 6331305a2..8b042bdc7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java @@ -16,10 +16,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class GamemodeCommand implements SenderCommand, Completer { @Override @@ -96,4 +92,4 @@ public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String return Utils.filterRecommendations(args[0], "0", "1", "2", "3", "survival", "creative", "spectator", "adventure", "s", "c", "sp", "a"); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java index 54460ea86..1d8263af7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java @@ -14,10 +14,6 @@ import java.util.Collections; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class GamestateCommand implements SenderCommand, Completer { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java index d273281f6..53587b632 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java @@ -19,10 +19,6 @@ import java.util.List; import java.util.UUID; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class GodModeCommand implements SenderCommand, Completer, Listener { private final List godModePlayers = new ArrayList<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java index c9c4bc7c2..0a47e3dd3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java @@ -17,10 +17,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class HealCommand implements SenderCommand, Completer { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java index 16edf99c0..75dc5098f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java @@ -5,10 +5,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class HelpCommand implements SenderCommand { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java index 07eb9fed9..d5e8cd095 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java @@ -28,10 +28,6 @@ import java.util.Map; import java.util.Map.Entry; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class InvseeCommand implements PlayerCommand, Listener { private static final int @@ -138,4 +134,4 @@ public void onClose(@Nonnull InventoryCloseEvent event) { }, 1); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java index 186da232c..2dca85891 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java @@ -13,10 +13,6 @@ import java.util.List; -/** - * @author rollocraft | https://github.com/rollocraft - * @since 2.3.2 - */ public class LanguageCommand implements SenderCommand, Completer { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java index 1e9024ae2..8bbfb3e95 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java @@ -24,10 +24,6 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class LeaderboardCommand implements PlayerCommand { protected static final int[] slots = StatsHelper.getSlots(1); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java index 547e55374..b43981339 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java @@ -16,10 +16,6 @@ import java.util.Collections; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class ResetCommand implements SenderCommand, Completer { private final boolean confirmReset, seedResetCommand; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java index a506664db..895769031 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java @@ -11,10 +11,6 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.1.4 - */ public class ResultCommand implements PlayerCommand { @Override public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java index 1908296f7..10ddd47ce 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java @@ -22,10 +22,6 @@ import java.util.Map.Entry; import java.util.stream.Collectors; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class SearchCommand implements SenderCommand, Completer { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java index 955c71e30..93fbafdeb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java @@ -12,10 +12,6 @@ import java.util.Collections; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.2.0 - */ public class SkipTimerCommand implements SenderCommand, Completer { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java index a07af3445..e98dbc4f7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java @@ -26,11 +26,6 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/KxmischesDomi - * @since 2.0 - */ public class StatsCommand implements PlayerCommand { private final Map submitTimeByPlayer = new ConcurrentHashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java index 274cdb835..fd133bf74 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java @@ -15,10 +15,6 @@ import java.util.*; import java.util.Map.Entry; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class TimeCommand implements PlayerCommand, Completer { private final Map names; @@ -141,4 +137,4 @@ public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String return new ArrayList<>(); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java index b775201be..dc9162d1c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java @@ -19,10 +19,6 @@ import java.util.Collections; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class TimerCommand implements SenderCommand, Completer { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java index 2fd574faf..40c3ffe17 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java @@ -12,10 +12,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class VillageCommand implements PlayerCommand { @Override @@ -45,4 +41,4 @@ public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exc } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java index 07726539a..c66a33394 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java @@ -14,10 +14,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class WeatherCommand implements PlayerCommand, Completer { @Override @@ -61,4 +57,4 @@ public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String return Utils.filterRecommendations(args[0], "sun", "clear", "rain", "thunder"); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java index f8f99b2b6..c6ba05aca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java @@ -20,10 +20,6 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class WorldCommand implements PlayerCommand, TabCompleter { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDamageByPlayerEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDamageByPlayerEvent.java index 96c69d567..be99a6abe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDamageByPlayerEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDamageByPlayerEvent.java @@ -8,10 +8,6 @@ import org.bukkit.event.entity.EntityEvent; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public class EntityDamageByPlayerEvent extends EntityEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDeathByPlayerEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDeathByPlayerEvent.java index 5263b12d8..3517e3138 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDeathByPlayerEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDeathByPlayerEvent.java @@ -8,10 +8,6 @@ import org.bukkit.event.entity.EntityEvent; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public class EntityDeathByPlayerEvent extends EntityEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java index ee878c652..018156bf1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java @@ -14,10 +14,6 @@ import javax.annotation.Nullable; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public abstract class InventoryClickEventWrapper extends Event { private final InventoryClickEvent event; @@ -126,4 +122,4 @@ public boolean isShiftClick() { return event.isShiftClick(); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerIgnoreStatusChangeEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerIgnoreStatusChangeEvent.java index 32043c476..b65366107 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerIgnoreStatusChangeEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerIgnoreStatusChangeEvent.java @@ -5,10 +5,6 @@ import org.bukkit.event.player.PlayerEvent; import org.jetbrains.annotations.NotNull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public class PlayerIgnoreStatusChangeEvent extends PlayerEvent { private static final HandlerList handlers = new HandlerList(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java index 9f8bf56ed..098ead5c2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java @@ -7,10 +7,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class PlayerInventoryClickEvent extends InventoryClickEventWrapper { private static final HandlerList handlers = new HandlerList(); @@ -34,4 +30,4 @@ public HandlerList getHandlers() { return getHandlerList(); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java index d3531fcdb..975740144 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java @@ -8,10 +8,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class PlayerJumpEvent extends PlayerEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java index 7287968b0..9a52cf53a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java @@ -9,10 +9,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ @Getter public class PlayerPickupItemEvent extends PlayerEvent implements Cancellable { @@ -48,4 +44,4 @@ public void setCancelled(boolean cancel) { public HandlerList getHandlers() { return handlers; } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java index c2d29a2ba..bc3609180 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java @@ -11,10 +11,6 @@ import javax.annotation.Nonnull; import java.util.Random; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class VoidMapGenerator extends ChunkGenerator { private static final boolean generateEndPortal = MinecraftVersion.current().getMinor() == 18; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java index e80518a57..d93e5c6cd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java @@ -19,10 +19,6 @@ import javax.annotation.Nonnull; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class BlockDropListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java index 38ca8e8ad..32aef252e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java @@ -12,10 +12,6 @@ import java.util.UUID; import java.util.function.Consumer; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1 - */ public class ChatInputListener implements Listener { private static Map> inputActions = new HashMap<>(); @@ -44,4 +40,4 @@ public void onQuit(PlayerQuitEvent event) { inputActions.remove(event.getPlayer().getUniqueId()); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java index 77e1f9086..c17bda8ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java @@ -17,10 +17,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class CheatListener implements Listener { public CheatListener() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java index 411e1fde7..5d12811ae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java @@ -20,10 +20,6 @@ import javax.annotation.Nonnull; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class CustomEventListener implements Listener { /** @@ -94,4 +90,4 @@ public void onGameModeChange(PlayerGameModeChangeEvent event) { } } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java index 9a2cb4a66..a3348e7e1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java @@ -13,10 +13,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class ExtraWorldRestrictionListener implements Listener { @EventHandler(priority = EventPriority.LOW) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/GeneratorWorldsListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/GeneratorWorldsListener.java index 1d3481cb1..885f17067 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/GeneratorWorldsListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/GeneratorWorldsListener.java @@ -12,10 +12,6 @@ import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.0 - */ public class GeneratorWorldsListener implements Listener { @EventHandler(priority = EventPriority.LOW) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java index bd818993c..73acb3143 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java @@ -16,10 +16,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class HelpListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index 103d4577e..720988271 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -20,10 +20,6 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class PlayerConnectionListener implements Listener { private final boolean messages; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java index b73b68131..523b9331c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java @@ -23,11 +23,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class RestrictionListener implements Listener { @EventHandler(priority = EventPriority.LOW) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java index 3e4ea849b..71f3d03b3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java @@ -7,10 +7,6 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.2 - */ public class ScoreboardUpdateListener implements Listener { @EventHandler diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java index 1e23c0883..57c560066 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java @@ -33,11 +33,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @see net.codingarea.challenges.plugin.management.stats.StatsManager - * @since 2.0 - */ public class StatsListener implements Listener { private final List dragonDamager = new ArrayList<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java index 623717492..c81a982d1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java @@ -8,10 +8,6 @@ import javax.annotation.Nullable; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public interface Completer extends TabCompleter { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java index 8b4fe018f..9ccfbb7fb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java @@ -10,10 +10,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public class ForwardingCommand implements SenderCommand, TabCompleter { private final String forwardCommand; @@ -39,4 +35,4 @@ public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Comman return overrideTab ? new ArrayList<>() : null; } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java index 5ef0b43dd..385740ae8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java @@ -10,10 +10,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public interface PlayerCommand extends CommandExecutor { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java index 1fc276e71..41aca835e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java @@ -8,10 +8,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public interface SenderCommand extends CommandExecutor { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java index b3396201c..e94d0de28 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java @@ -11,10 +11,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.1.3 - */ public class BukkitSerialization { /** diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java index d67dc877d..3a64320c8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java @@ -9,10 +9,6 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @Data public final class PlayerData { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java index 458297fc4..8f2c6bb10 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java @@ -6,10 +6,6 @@ import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ @FunctionalInterface public interface IJumpGenerator { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java index 4bf485b51..18bf7befa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java @@ -7,10 +7,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public class RandomJumpGenerator implements IJumpGenerator { @Nonnull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java index dbb121a81..8b03d4c7d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java @@ -18,10 +18,6 @@ import java.util.concurrent.Callable; import java.util.function.Supplier; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.2.0 - */ public class BukkitStringUtils { @Nonnull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java index bc7e1afcd..fe0353359 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java @@ -5,10 +5,6 @@ import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public enum MinecraftVersion implements Version { V1_0, // 1.0 diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java index 9358640a4..f899d1aaa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java @@ -12,10 +12,6 @@ import org.bukkit.World; import org.bukkit.entity.Player; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class NMSProvider { private final static int majorVersion; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java index f051f5944..ca81f2938 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java @@ -6,10 +6,6 @@ import org.bukkit.boss.BossBar; import org.bukkit.entity.Entity; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.0 - */ public final class NMSUtils { public static void setEntityName(Entity entity, BaseComponent baseComponent) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java index b8e2705c0..3dd617ac6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java @@ -14,7 +14,6 @@ /** * @author TobiasDeBruijn | https://github.com/TobiasDeBruijn * @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil - * @since 2.2.0 */ public class ReflectionUtil { @@ -497,4 +496,4 @@ private static String getModifiers(int modifiers) { return modifiersStr.toString().trim(); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java index a9f99d719..d2f329402 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java @@ -6,10 +6,6 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.type.BorderPacketFactory; import net.codingarea.challenges.plugin.utils.bukkit.nms.type.PacketBorder; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class BorderPacketFactory_1_13 extends BorderPacketFactory { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java index f744646f1..97968be4f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java @@ -5,10 +5,6 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.type.CraftPlayer; import org.bukkit.entity.Player; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class CraftPlayer_1_13 extends CraftPlayer { /** * @param player The player to create the CraftPlayer for diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java index d38986f12..a5c65b210 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java @@ -9,10 +9,6 @@ import org.bukkit.World; import org.bukkit.entity.Player; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class PacketBorder_1_13 extends PacketBorder { /** * Creates a new packet border. diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java index 6cf52e01c..4720ffea6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java @@ -5,10 +5,6 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; import net.codingarea.challenges.plugin.utils.bukkit.nms.type.PlayerConnection; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class PlayerConnection_1_13 extends PlayerConnection { public PlayerConnection_1_13(Object connection) throws ClassNotFoundException { super(NMSUtils.getClass("network.protocol.Packet"), connection); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java index 101b6e094..62e7037e4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java @@ -5,10 +5,6 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.type.WorldServer; import org.bukkit.World; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class WorldServer_1_13 extends WorldServer { /** diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java index e4eb93d55..678a0bfe7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java @@ -6,10 +6,6 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.type.BorderPacketFactory; import net.codingarea.challenges.plugin.utils.bukkit.nms.type.PacketBorder; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class BorderPacketFactory_1_17 extends BorderPacketFactory { @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java index 59b650c0b..2798bf7c4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java @@ -5,10 +5,6 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; import org.bukkit.entity.Player; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class CraftPlayer_1_17 extends CraftPlayer { /** diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java index c251270f5..8e991c636 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java @@ -6,10 +6,6 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_13.PacketBorder_1_13; import org.bukkit.World; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class PacketBorder_1_17 extends PacketBorder_1_13 { public PacketBorder_1_17(World world) { @@ -30,4 +26,4 @@ protected Object createWorldBorder() { } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java index 56345b44a..f1a3c832a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java @@ -5,10 +5,6 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_17.PacketBorder_1_17; import org.bukkit.World; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class PacketBorder_1_18 extends PacketBorder_1_17 { public PacketBorder_1_18(World world) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java index fadc1c6a7..c466e679c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java @@ -4,10 +4,6 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_13.PlayerConnection_1_13; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class PlayerConnection_1_18 extends PlayerConnection_1_13 { public PlayerConnection_1_18(Object connection) throws ClassNotFoundException { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/AbstractNMSClass.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/AbstractNMSClass.java index 889900976..79cf77cd9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/AbstractNMSClass.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/AbstractNMSClass.java @@ -1,11 +1,5 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms.type; -/** - * An abstract class for other classes that represent NMS classes - - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public abstract class AbstractNMSClass { protected final Class nmsClass; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BorderPacketFactory.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BorderPacketFactory.java index 4d7a4b239..04d514842 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BorderPacketFactory.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BorderPacketFactory.java @@ -1,9 +1,5 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms.type; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public abstract class BorderPacketFactory { public abstract Object center(PacketBorder packetBorder); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BukkitNMSClass.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BukkitNMSClass.java index 998e1774a..2b3afb1eb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BukkitNMSClass.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BukkitNMSClass.java @@ -2,9 +2,6 @@ /** * Used for nms classes that are represented by a bukkit class - * @param The bukkit type that represents the NMS class - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 */ public abstract class BukkitNMSClass extends AbstractNMSClass { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java index 2f2999bf6..48e101f32 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java @@ -6,7 +6,6 @@ /** * @author TobiasDeBruijn | https://github.com/TobiasDeBruijn * @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil - * @since 2.2.0 */ public abstract class CraftPlayer extends BukkitNMSClass { @@ -31,4 +30,4 @@ public CraftPlayer(Class nmsClass, Player player) { public PlayerConnection getConnection() { return NMSProvider.createPlayerConnection(this); } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PacketBorder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PacketBorder.java index 6d35b748b..0a5d1ac8f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PacketBorder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PacketBorder.java @@ -11,8 +11,6 @@ /** * Provides a WorldBorder that can be sent to the client via packets - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 */ public abstract class PacketBorder extends AbstractNMSClass { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java index fbc1526e4..1625cb2c2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java @@ -3,7 +3,6 @@ /** * @author TobiasDeBruijn | https://github.com/TobiasDeBruijn * @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil - * @since 2.2.0 */ public abstract class PlayerConnection extends AbstractNMSClass { @@ -22,4 +21,4 @@ public PlayerConnection(Class nmsClass, Object connection) { * @param packet The packet to send */ public abstract void sendPacket(Object packet); -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/WorldServer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/WorldServer.java index 7737f65ed..48a91c78b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/WorldServer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/WorldServer.java @@ -2,10 +2,6 @@ import org.bukkit.World; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public abstract class WorldServer extends BukkitNMSClass { /** * @param object The instance of the specified bukkit type @@ -18,4 +14,4 @@ protected WorldServer(World object, Class nmsClass) { public Object getWorldServerObject() { return nmsObject; } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java index b7fb9d587..7857104ad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java @@ -10,10 +10,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class DefaultItem { private static final String ARROW_LEFT = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjAwNmVjMWVjYTJmMjY4NWY3MGU2NTQxMWNmZTg4MDhhMDg4ZjdjZjA4MDg3YWQ4ZWVjZTk2MTgzNjEwNzBlMyJ9fX0=", diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index 24ca1b091..24f8ed898 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -29,10 +29,6 @@ import java.nio.charset.StandardCharsets; import java.util.*; -/** - * @author anweisen | https://github.com/anweisen - * @since 1.0 - */ public class ItemBuilder extends net.anweisen.utilities.bukkit.utils.item.ItemBuilder { public static final ItemStack BLOCKED_ITEM = new ItemBuilder(Material.BARRIER, "§cBlocked").build(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java index b7afc6b48..716d88602 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java @@ -9,10 +9,6 @@ import javax.annotation.Nonnull; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class ItemUtils { @Nonnull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java index 66c2eeeca..43eaa118e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java @@ -6,10 +6,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ConsolePrint { private ConsolePrint() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java index fa142bc00..e80deebf8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java @@ -2,10 +2,6 @@ import org.bukkit.Material; -/** - * @author KxmischesDomi | https://github.com/KxmischesDomi - * @since 2.0 - */ public final class ArmorUtils { private ArmorUtils() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java index dfbf273fd..edee046dd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java @@ -11,11 +11,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public final class BlockUtils { private static final BlockFace[] faces = { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java index 2078261ed..7ac2e0cd9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java @@ -10,10 +10,6 @@ import java.util.Map; import java.util.Optional; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ColorConversions { private static final Map colorsByChatColor = new HashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java index 6bbe268ee..34cdc714d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java @@ -14,10 +14,6 @@ import java.util.List; import java.util.concurrent.ThreadLocalRandom; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public final class CommandHelper { private CommandHelper() { @@ -95,4 +91,4 @@ public static Player getNearestPlayer(@Nonnull Location location) { return currentPlayer; } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java index a19871374..d4f1bb209 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java @@ -13,10 +13,6 @@ import javax.annotation.Nullable; import java.util.*; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class DatabaseHelper { private static final Map cachedTextures = new HashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java index 80ea08eaf..8c1dd221e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java @@ -8,10 +8,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public final class EntityUtils { private EntityUtils() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FontUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FontUtils.java index 72a417e32..760fc54d4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FontUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FontUtils.java @@ -4,10 +4,6 @@ import java.util.LinkedList; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class FontUtils { private static final char[] SMALL_CAPS_ALPHABET = "ᴀʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ".toCharArray(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java index b0d52e334..f64928ea6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java @@ -11,10 +11,6 @@ import java.net.HttpURLConnection; import java.net.URL; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ImageUtils { public static final char IMAGE_CHAR = '█'; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java index e055de09c..b0e6af5f5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java @@ -23,11 +23,6 @@ import java.util.List; import java.util.concurrent.ThreadLocalRandom; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public final class InventoryUtils { private static final IRandom random; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java index 95eb84774..3b4ddbff2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java @@ -7,10 +7,6 @@ import java.util.function.Consumer; import java.util.function.Predicate; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 2.0 - */ public final class ListBuilder { private final List list = new ArrayList<>(); @@ -76,4 +72,4 @@ public List build() { return list; } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java index fc334406b..650d72cf1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java @@ -6,10 +6,6 @@ import java.util.*; import java.util.Map.Entry; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public class MapUtils { public static Map createStringMap(String... data) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java index 2534de3eb..4d2650c64 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java @@ -6,10 +6,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class NameHelper { private NameHelper() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java index 46efced22..a72079576 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java @@ -18,13 +18,6 @@ import org.bukkit.util.Vector; import org.jetbrains.annotations.Nullable; -/** - * This class contains util methods to create fancy particles. - * Most of these methods were found in {@link Utils} previously (pre 2.0). - * - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class ParticleUtils { private static final IRandom iRandom = IRandom.create(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java index 7c1e91f32..33ae0e17b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java @@ -8,10 +8,6 @@ import javax.annotation.Nonnull; -/** - * @author anweisen | https://github.com/anweisen - * @since 2.0 - */ public final class StatsHelper { private StatsHelper() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StructureUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StructureUtils.java index 831820d5c..a163910ab 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StructureUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StructureUtils.java @@ -3,10 +3,6 @@ import org.bukkit.Material; import org.bukkit.StructureType; -/** - * @author sehrschlechtYT | https://github.com/sehrschlechtYT - * @since 2.2.3 - */ public class StructureUtils { public static Material getStructureIcon(StructureType structureType) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriConsumer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriConsumer.java index 278dbc026..e5951b662 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriConsumer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriConsumer.java @@ -1,11 +1,7 @@ package net.codingarea.challenges.plugin.utils.misc; -/** - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public interface TriConsumer { void accept(A a, B b, C c); -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java index ea856217c..8ba0c86d2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java @@ -14,11 +14,6 @@ import java.util.*; import java.util.regex.Pattern; -/** - * @author anweisen | https://github.com/anweisen - * @author KxmischesDomi | https://github.com/kxmischesdomi - * @since 1.0 - */ public final class Utils { private Utils() { From cd786bc2d8f37aa9ed2b17be30cbc42daa0b9dd7 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 18 Apr 2025 10:21:04 +0200 Subject: [PATCH 045/119] feat: move language setting to properties file --- .../setting/LanguageSetting.java | 4 +- .../plugin/content/loader/LanguageLoader.java | 63 +++++++++++++++++-- .../spigot/command/LanguageCommand.java | 4 +- 3 files changed, 61 insertions(+), 10 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java index 16003a6db..b912bccc3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java @@ -42,11 +42,11 @@ public ItemBuilder createSettingsItem() { public void playValueChangeTitle() { switch (getValue()) { case GERMAN: - Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).reload("de"); + Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).changeLanguage("de"); ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName(getSettingName())); break; case ENGLISH: - Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).reload("en"); + Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).changeLanguage("en"); ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName(getSettingName())); break; default: diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index dbfad9f25..ee54cdd9f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -8,6 +8,7 @@ import net.anweisen.utilities.bukkit.utils.logging.Logger; import net.anweisen.utilities.common.collection.IOUtils; import net.anweisen.utilities.common.config.Document; +import net.anweisen.utilities.common.config.FileDocument; import net.anweisen.utilities.common.misc.FileUtils; import net.anweisen.utilities.common.misc.GsonUtils; import net.codingarea.challenges.plugin.Challenges; @@ -15,6 +16,7 @@ import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; import javax.annotation.Nonnull; +import javax.print.Doc; import java.io.File; import java.io.IOException; import java.util.Map.Entry; @@ -26,7 +28,8 @@ public final class LanguageLoader extends ContentLoader { public static final String DEFAULT_LANGUAGE = "en"; - public static final String DIRECT_FILE_PATH = "direct-language-file"; + + public static final String KEY_LANGUAGE = "language", KEY_SMALL_CAPS = "smallcaps", KEY_DIRECT_LANGUAGE_FILE = "manualfile"; @Getter private static volatile boolean loaded = false; @@ -35,16 +38,46 @@ public final class LanguageLoader extends ContentLoader { @Getter private boolean smallCapsFont; + public File getLanguagePropertiesFile() { + return getMessageFile("language", "properties"); + } + + public Document getLanguageProperties() { + try { + FileUtils.createFilesIfNecessary(getLanguagePropertiesFile()); + + FileDocument document = FileDocument.readPropertiesFile(getLanguagePropertiesFile()); + } catch (Exception e) { + Logger.error("Could not read language properties", e); + } + return Document.empty(); + } + + public void migrateLanguageConfig() { + Document configDocument = Challenges.getInstance().getConfigDocument(); + String oldLanguage = configDocument.getString("language"); + String oldDirectFilePath = configDocument.getString("direct-language-file"); + boolean oldSmallCapsFont = configDocument.getBoolean("small-caps"); + + Document languageProperties = getLanguageProperties(); + languageProperties.set(KEY_LANGUAGE, oldLanguage); + languageProperties.set(KEY_SMALL_CAPS, oldSmallCapsFont); + + if (configDocument.contains("direct-language-file")) { + languageProperties.set(KEY_DIRECT_LANGUAGE_FILE, oldDirectFilePath); + } + } + @Override protected void load() { - Document config = Challenges.getInstance().getConfigDocument(); + Document config = getLanguageProperties(); - smallCapsFont = config.getBoolean("small-caps", false); + smallCapsFont = config.getBoolean(KEY_SMALL_CAPS, false); - if (config.contains(DIRECT_FILE_PATH)) { - language = Challenges.getInstance().getConfigDocument().getString("language", DEFAULT_LANGUAGE); - String path = config.getString(DIRECT_FILE_PATH); + if (config.contains(KEY_DIRECT_LANGUAGE_FILE)) { + language = config.getString(KEY_LANGUAGE, DEFAULT_LANGUAGE); + String path = config.getString(KEY_DIRECT_LANGUAGE_FILE); if (path == null) return; Logger.info("Using direct language file '{}'", path); readLanguage(new File(path)); @@ -54,6 +87,24 @@ protected void load() { loadDefault(); } + public void changeLanguage(@Nonnull String language) { + if (language.equalsIgnoreCase(this.language)) { + Logger.info("Language '{}' is already selected", language); + return; + } + + this.language = language; + Document properties = getLanguageProperties(); + properties.set(KEY_LANGUAGE, language); + try { + properties.saveToFile(getLanguagePropertiesFile()); + } catch (IOException e) { + Logger.error("Could not save language properties", e); + } + reload(language); + Logger.info("Language changed to '{}'", language); + } + public void reload(String language) { this.language = language; read(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java index 186da232c..f73bd3504 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java @@ -29,12 +29,12 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr case "german": case "deutsch": case "de": - Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).reload("de"); + Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).changeLanguage("de"); break; case "english": case "englisch": case "en": - Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).reload("en"); + Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).changeLanguage("en"); break; default: Message.forName("unsuported-language").send(sender, Prefix.CHALLENGES, args[0]); From 5d7ff5909eea799528fc12fed1eaeaf4ef26a045 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 18 Apr 2025 10:21:33 +0200 Subject: [PATCH 046/119] fix: call migration --- .../challenges/plugin/content/loader/LanguageLoader.java | 1 + 1 file changed, 1 insertion(+) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index ee54cdd9f..770cef6fb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -70,6 +70,7 @@ public void migrateLanguageConfig() { @Override protected void load() { + migrateLanguageConfig(); Document config = getLanguageProperties(); From 51097ae746c7a648d5cebf7c545070d6d6e2eadb Mon Sep 17 00:00:00 2001 From: qodana-bot Date: Fri, 18 Apr 2025 08:24:43 +0000 Subject: [PATCH 047/119] =?UTF-8?q?=F0=9F=A4=96=20Apply=20quick-fixes=20by?= =?UTF-8?q?=20Qodana?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../action/impl/HealEntityAction.java | 2 - .../settings/sub/SubSettingsBuilder.java | 18 ++--- .../settings/trigger/impl/HungerTrigger.java | 2 +- .../impl/StandsOnSpecificBlockTrigger.java | 4 +- .../challenge/ZeroHeartsChallenge.java | 2 - .../entities/BlockMobsChallenge.java | 6 +- .../inventory/UncraftItemsChallenge.java | 5 +- .../NoSharedAdvancementsChallenge.java | 3 +- .../challenge/quiz/QuizChallenge.java | 6 +- .../randomizer/RandomEventChallenge.java | 8 +-- .../RandomItemDroppingChallenge.java | 2 +- .../RandomItemRemovingChallenge.java | 2 +- .../RandomItemSwappingChallenge.java | 2 +- .../randomizer/RandomizedHPChallenge.java | 2 - .../challenge/world/LoopChallenge.java | 9 +-- .../challenge/world/SnakeChallenge.java | 7 +- .../goal/CollectAllItemsGoal.java | 31 +++----- .../goal/GetFullHealthGoal.java | 2 - .../goal/KillAllMonsterGoal.java | 5 +- .../forcebattle/ExtremeForceBattleGoal.java | 7 +- .../ForceAdvancementBattleGoal.java | 9 ++- .../goal/forcebattle/targets/ForceTarget.java | 12 ++-- .../goal/forcebattle/targets/MobTarget.java | 5 +- .../setting/HealthDisplaySetting.java | 3 +- .../setting/LanguageSetting.java | 7 +- .../setting/MaxHealthSetting.java | 1 - .../implementation/setting/OldPvPSetting.java | 2 - .../implementation/setting/TimberSetting.java | 3 +- .../abstraction/AbstractForceChallenge.java | 6 +- .../abstraction/EndingForceChallenge.java | 7 +- .../abstraction/FirstPlayerAtHeightGoal.java | 8 +-- .../abstraction/ForceBattleDisplayGoal.java | 3 +- .../abstraction/ModifierCollectionGoal.java | 14 +--- .../challenges/type/helper/GoalHelper.java | 2 +- .../plugin/content/loader/LanguageLoader.java | 1 - .../plugin/content/loader/UpdateLoader.java | 31 +++----- .../challenges/CustomChallengesLoader.java | 10 +-- .../menu/InventoryTitleManager.java | 8 +-- .../generator/ChallengeMenuGenerator.java | 2 +- .../menu/generator/MenuGenerator.java | 17 ++--- .../categorised/SettingCategory.java | 16 +---- .../CustomMainSettingsMenuGenerator.java | 7 +- .../custom/InfoMenuGenerator.java | 10 +-- .../custom/MainCustomMenuGenerator.java | 2 +- .../scheduler/AbstractTaskConfig.java | 7 +- .../scheduler/timer/ChallengeTimer.java | 1 - .../management/server/ServerManager.java | 2 +- .../management/server/TitleManager.java | 12 +--- .../scoreboard/ChallengeScoreboard.java | 6 +- .../plugin/management/stats/StatsManager.java | 4 +- .../spigot/command/DatabaseCommand.java | 2 +- .../spigot/command/GamemodeCommand.java | 2 +- .../plugin/spigot/command/HealCommand.java | 2 - .../spigot/command/LanguageCommand.java | 5 +- .../plugin/spigot/command/StatsCommand.java | 1 - .../plugin/spigot/command/TimeCommand.java | 8 +-- .../plugin/spigot/command/TimerCommand.java | 10 +-- .../events/PlayerInventoryClickEvent.java | 2 +- .../spigot/generator/VoidMapGenerator.java | 46 +----------- .../plugin/spigot/listener/CheatListener.java | 12 +--- .../spigot/listener/CustomEventListener.java | 3 +- .../bukkit/container/BukkitSerialization.java | 17 ++--- .../utils/bukkit/misc/BukkitStringUtils.java | 3 +- .../bukkit/misc/Version/MinecraftVersion.java | 2 +- .../utils/bukkit/misc/Version/Version.java | 4 +- .../misc/Version/VersionComparator.java | 2 +- .../bukkit/misc/Version/VersionInfo.java | 23 ++---- .../plugin/utils/bukkit/nms/NMSProvider.java | 16 ++--- .../utils/bukkit/nms/ReflectionUtil.java | 71 ++++--------------- .../v1_13/BorderPacketFactory_1_13.java | 1 + .../v1_17/PacketBorder_1_17.java | 10 --- .../utils/bukkit/nms/type/CraftPlayer.java | 4 +- .../bukkit/nms/type/PlayerConnection.java | 4 +- .../plugin/utils/item/DefaultItem.java | 3 - .../plugin/utils/item/ItemBuilder.java | 5 -- .../plugin/utils/item/ItemUtils.java | 4 +- .../plugin/utils/misc/BlockUtils.java | 6 +- .../plugin/utils/misc/ListBuilder.java | 4 +- 78 files changed, 194 insertions(+), 421 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java index 650269296..b0c3740b9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java @@ -2,13 +2,11 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Material; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java index 5f9fed98a..56dab8b5a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub; +import lombok.Getter; import net.anweisen.utilities.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.*; import net.codingarea.challenges.plugin.content.Message; @@ -15,6 +16,7 @@ import java.util.function.Consumer; import java.util.function.Predicate; +@Getter public abstract class SubSettingsBuilder { private String key; @@ -59,11 +61,7 @@ public static EmptySubSettingsBuilder createEmpty() { public abstract boolean hasSettings(); - public SubSettingsBuilder getParent() { - return parent; - } - - public SubSettingsBuilder setParent(SubSettingsBuilder parent) { + public SubSettingsBuilder setParent(SubSettingsBuilder parent) { SubSettingsBuilder parentBuilder = getParent(); if (parentBuilder != null) { @@ -75,15 +73,7 @@ public SubSettingsBuilder setParent(SubSettingsBuilder parent) { } - public SubSettingsBuilder getChild() { - return child; - } - - public String getKey() { - return key; - } - - public SubSettingsBuilder setKey(String key) { + public SubSettingsBuilder setKey(String key) { this.key = key; return this; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java index 60e32c9a8..06e772fbd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java @@ -21,7 +21,7 @@ public Material getMaterial() { @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPickup(FoodLevelChangeEvent event) { if (!(event.getEntity() instanceof Player)) return; - if (event.getFoodLevel() < ((Player) event.getEntity()).getFoodLevel()) { + if (event.getFoodLevel() < event.getEntity().getFoodLevel()) { createData() .entity(event.getEntity()) .event(event) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java index 96b126bd4..3836f8921 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java @@ -9,6 +9,8 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; +import java.util.Objects; + public class StandsOnSpecificBlockTrigger extends ChallengeTrigger { public StandsOnSpecificBlockTrigger(String name) { @@ -24,7 +26,7 @@ public Material getMaterial() { public void onMove(PlayerMoveEvent event) { if (BlockUtils.isSameBlockLocation(event.getTo(), event.getFrom())) return; Block blockBelow = BlockUtils.getBlockBelow( - event.getTo()); + Objects.requireNonNull(event.getTo())); if (blockBelow == null) return; createData() diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index 593c12203..baca7505e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -8,13 +8,11 @@ import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Bukkit; import org.bukkit.Material; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java index ef714960f..36225f70a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java @@ -22,6 +22,7 @@ import org.jetbrains.annotations.NotNull; import java.util.Collection; +import java.util.Objects; @Since("2.1.3") public class BlockMobsChallenge extends Setting { @@ -45,7 +46,7 @@ public void onBlockBreak(BlockBreakEvent event) { LivingEntity entity = (LivingEntity) event.getBlock().getWorld() .spawnEntity(event.getBlock().getLocation().add(0.5, 0, 0.5), type); - Collection drops = event.getBlock().getDrops(event.getPlayer().getEquipment().getItemInMainHand()); + Collection drops = event.getBlock().getDrops(Objects.requireNonNull(event.getPlayer().getEquipment()).getItemInMainHand()); int i = 0; // Put every stack in a different slot to make sure everything drops properly @@ -56,7 +57,8 @@ public void onBlockBreak(BlockBreakEvent event) { switch (i) { case 0: - equipment.setHelmetDropChance(1); + assert equipment != null; + equipment.setHelmetDropChance(1); break; case 1: slot = EquipmentSlot.CHEST; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java index 67b61ed2a..2f87be910 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java @@ -17,6 +17,7 @@ import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; +import java.util.Objects; @Since("2.0.2") public class UncraftItemsChallenge extends TimedChallenge { @@ -105,8 +106,8 @@ private static List getIngredientsOfRecipe(@Nonnull Recipe recipe) { ingredients.add(furnace.getInput()); } else if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14) && recipe instanceof SmithingRecipe) { SmithingRecipe smithing = (SmithingRecipe) recipe; - ingredients.add(smithing.getBase().getItemStack()); - ingredients.add(smithing.getAddition().getItemStack()); + ingredients.add(Objects.requireNonNull(smithing.getBase()).getItemStack()); + ingredients.add(Objects.requireNonNull(smithing.getAddition()).getItemStack()); } return ingredients; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java index 19239e2d2..23feeba3e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java @@ -18,6 +18,7 @@ import java.util.LinkedList; import java.util.List; +import java.util.Objects; @Since("2.2.0") public class NoSharedAdvancementsChallenge extends Setting { @@ -51,7 +52,7 @@ public void loadGameState(@NotNull Document document) { List advancementKeys = document.getStringList("advancements"); for (String advancementKey : advancementKeys) { try { - advancementsDone.add(Bukkit.getAdvancement(BukkitReflectionUtils.fromString(advancementKey))); + advancementsDone.add(Bukkit.getAdvancement(Objects.requireNonNull(BukkitReflectionUtils.fromString(advancementKey)))); } catch (Exception exception) { // DON'T EXIST } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index 8b0e036c3..f49b6e2af 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -15,14 +15,12 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; -import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.TriFunction; import org.bukkit.Material; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.boss.BarColor; import org.bukkit.command.Command; @@ -565,8 +563,8 @@ public void onMove(@Nonnull PlayerDropItemEvent event) { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onMove(@Nonnull EntityDamageEvent event) { if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return;; - Player player = (Player) event.getEntity(); + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); if (ignorePlayer(player)) return; SavedStatistic.DAMAGE_TAKEN.increaseStatistic(player, event.getCause().name(), ChallengeHelper.getFinalDamage(event)); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java index c27737b95..d39094ba3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java @@ -34,10 +34,10 @@ public RandomEventChallenge() { setCategory(SettingCategory.RANDOMIZER); events = new Event[]{ new SpeedEvent(), - new SpawnEntitiesEvent(), + new SpawnEntitiesEvent(), new HoleEvent(), new FlyEvent(), - new CobWebEvent(), + new CobWebEvent(), new ReplaceOresEvent(), new SicknessEvent() }; @@ -186,7 +186,7 @@ public void run(@Nonnull Player player) { } } - public class SpawnEntitiesEvent implements Event { + public static class SpawnEntitiesEvent implements Event { @Nonnull @Override @@ -210,7 +210,7 @@ public void run(@Nonnull Player player) { } - public class CobWebEvent implements Event { + public static class CobWebEvent implements Event { @Nonnull @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java index 57b92d418..fd613961d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java @@ -27,7 +27,7 @@ public RandomItemDroppingChallenge() { } public static void dropRandomItem(Player player) { - if (player.getInventory().getContents().length <= 0) return; + if (player.getInventory().getContents().length == 0) return; dropRandomItem(player.getLocation(), player.getInventory()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java index 0f6bd79c0..ae705f94f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java @@ -51,7 +51,7 @@ protected void onTimeActivation() { for (Player player : Bukkit.getOnlinePlayers()) { if (ignorePlayer(player)) continue; - if (player.getInventory().getContents().length <= 0) continue; + if (player.getInventory().getContents().length == 0) continue; Bukkit.getScheduler().runTask(plugin, () -> { InventoryUtils.removeRandomItem(player.getInventory()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java index 9aef3ef61..9e21a2a80 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java @@ -26,7 +26,7 @@ public RandomItemSwappingChallenge() { } public static void swapRandomItems(Player player) { - if (player.getInventory().getContents().length <= 0) return; + if (player.getInventory().getContents().length == 0) return; int slot = InventoryUtils.getRandomFullSlot(player.getInventory()); if (slot == -1) return; swapItemToRandomSlot( diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java index ca5546d4f..1bb679ef7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java @@ -6,7 +6,6 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; @@ -15,7 +14,6 @@ import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index e3c0ad6f2..11352c5de 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -13,7 +13,6 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; -import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; @@ -186,13 +185,11 @@ public void execute() { private static class EntityDamageLoop implements Loop { private final LivingEntity entity; - private final DamageCause damageCause; - private final double damage; + private final double damage; public EntityDamageLoop(LivingEntity entity, DamageCause cause, double damage) { this.entity = entity; - this.damageCause = cause; - this.damage = damage; + this.damage = damage; } @Override @@ -301,7 +298,7 @@ private boolean decreaseDurability() { org.bukkit.inventory.meta.Damageable damageable = (org.bukkit.inventory.meta.Damageable) itemStack.getItemMeta(); if (damageable == null) return false; damageable.setDamage(damageable.getDamage() + 1); - itemStack.setItemMeta((ItemMeta) damageable); + itemStack.setItemMeta(damageable); for (int slot = 0; slot < player.getInventory().getSize(); slot++) { ItemStack item = player.getInventory().getItem(slot); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index 7e459c445..f494c35dd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -39,12 +39,7 @@ public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.BLUE_TERRACOTTA, Message.forName("item-snake-challenge")); } - @Override - protected void onEnable() { - - } - - @Override + @Override protected void onDisable() { blocks.clear(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index 4044b6b82..8ddbb8b79 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; +import lombok.Getter; import net.anweisen.utilities.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.anweisen.utilities.common.annotations.Since; @@ -36,11 +37,15 @@ @Since("2.0") public class CollectAllItemsGoal extends SettingGoal implements SenderCommand { - private final int totalItemsCount; + @Getter + private final int totalItemsCount; private SeededRandomWrapper random; - private List allItemsToFind; - private List itemsToFind; - private Material currentItem; + @Getter + private List allItemsToFind; + @Getter + private List itemsToFind; + @Getter + private Material currentItem; public CollectAllItemsGoal() { random = new SeededRandomWrapper(); @@ -168,23 +173,7 @@ public void writeGameState(@Nonnull Document document) { document.set("found", totalItemsCount - itemsToFind.size()); } - public Material getCurrentItem() { - return currentItem; - } - - public List getItemsToFind() { - return itemsToFind; - } - - public List getAllItemsToFind() { - return allItemsToFind; - } - - public int getTotalItemsCount() { - return totalItemsCount; - } - - private String getItemDisplayName(@Nullable Material material) { + private String getItemDisplayName(@Nullable Material material) { if (material == null) return "Unbekannt"; String name = material.name(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index 18e3092f6..1cff0e3ff 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -8,12 +8,10 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java index 049dd1579..8e846d715 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java @@ -26,7 +26,10 @@ public KillAllMonsterGoal() { static List getAllMobsToKill() { LinkedList list = new LinkedList<>(Arrays.asList(EntityType.values())); list.removeIf(type -> !type.isAlive()); - list.removeIf(type -> !Monster.class.isAssignableFrom(type.getEntityClass())); + list.removeIf(type -> { + assert type.getEntityClass() != null; + return !Monster.class.isAssignableFrom(type.getEntityClass()); + }); list.add(EntityType.PHANTOM); list.add(EntityType.ENDER_DRAGON); list.add(EntityType.SHULKER); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java index 164737ee5..3eab72397 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java @@ -30,10 +30,7 @@ import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.UUID; +import java.util.*; import java.util.function.Function; public class ExtremeForceBattleGoal extends ForceBattleDisplayGoal> { @@ -220,7 +217,7 @@ public enum TargetType { return new DamageTarget(globalRandom.range(1, 19)); }), ADVANCEMENT(object -> { - return new AdvancementTarget(Bukkit.getAdvancement(NamespacedKey.fromString((String) object))); + return new AdvancementTarget(Bukkit.getAdvancement(Objects.requireNonNull(NamespacedKey.fromString((String) object)))); }, player -> { return new AdvancementTarget(globalRandom.choose(AdvancementTarget.getPossibleAdvancements())); }), diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java index ad7364afb..2a637edd4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; @Since("2.2.0") public class ForceAdvancementBattleGoal extends ForceBattleGoal { @@ -50,8 +51,10 @@ protected AdvancementTarget[] getTargetsPossibleToFind() { public AdvancementTarget getTargetFromDocument(Document document, String path) { String advancementKey = document.getString(path); try { - NamespacedKey namespacedKey = BukkitReflectionUtils.fromString(advancementKey); - return new AdvancementTarget(Bukkit.getAdvancement(namespacedKey)); + assert advancementKey != null; + NamespacedKey namespacedKey = BukkitReflectionUtils.fromString(advancementKey); + assert namespacedKey != null; + return new AdvancementTarget(Bukkit.getAdvancement(namespacedKey)); } catch (Exception exception) { // DON'T EXIST } @@ -64,7 +67,7 @@ public List getListFromDocument(Document document, String pat List advancementTargets = new ArrayList<>(); for (String advancementKey : advancementKeys) { try { - advancementTargets.add(new AdvancementTarget(Bukkit.getAdvancement(BukkitReflectionUtils.fromString(advancementKey)))); + advancementTargets.add(new AdvancementTarget(Bukkit.getAdvancement(Objects.requireNonNull(BukkitReflectionUtils.fromString(advancementKey))))); } catch (Exception exception) { // DON'T EXIST } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java index a04eac918..167bfbd0a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; +import lombok.Getter; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import org.bukkit.Material; @@ -8,6 +9,9 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import java.util.Objects; + +@Getter public abstract class ForceTarget { protected final T target; @@ -28,15 +32,11 @@ public String toString() { return target.toString(); } - public T getTarget() { - return target; - } - public void updateDisplayStand(@NotNull ArmorStand armorStand) { if (target instanceof Material) { - armorStand.getEquipment().setHelmet(new ItemStack((Material) target)); + Objects.requireNonNull(armorStand.getEquipment()).setHelmet(new ItemStack((Material) target)); } else { - armorStand.getEquipment().setHelmet(null); + Objects.requireNonNull(armorStand.getEquipment()).setHelmet(null); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java index cfe4ed8b8..c333e8307 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java @@ -15,6 +15,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Objects; public class MobTarget extends ForceTarget { @@ -70,9 +71,9 @@ public Message getScoreboardDisplayMessage() { public void updateDisplayStand(@NotNull ArmorStand armorStand) { Material spawnEgg = EntityUtils.getSpawnEgg(target); if (spawnEgg == null) { - armorStand.getEquipment().setHelmet(null); + Objects.requireNonNull(armorStand.getEquipment()).setHelmet(null); } else { - armorStand.getEquipment().setHelmet(new ItemStack(spawnEgg)); + Objects.requireNonNull(armorStand.getEquipment()).setHelmet(new ItemStack(spawnEgg)); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java index dadd0c9e9..3349bcb63 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import javax.annotation.Nonnull; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; + import net.anweisen.utilities.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; @@ -14,7 +14,6 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.scoreboard.Criteria; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.RenderType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java index b912bccc3..ea526cc68 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java @@ -10,8 +10,7 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import javax.annotation.Nonnull; -import java.net.MalformedURLException; -import java.net.URL; +import java.util.Objects; public class LanguageSetting extends Modifier { @@ -42,11 +41,11 @@ public ItemBuilder createSettingsItem() { public void playValueChangeTitle() { switch (getValue()) { case GERMAN: - Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).changeLanguage("de"); + Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("de"); ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName(getSettingName())); break; case ENGLISH: - Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).changeLanguage("en"); + Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("en"); ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName(getSettingName())); break; default: diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index 4f385dc6e..0b380bb82 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -12,7 +12,6 @@ import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java index bb6fc9525..0b756d43d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java @@ -4,11 +4,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java index 9b0a4e1d4..0d2235a39 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java @@ -21,6 +21,7 @@ import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; +import java.util.Objects; public class TimberSetting extends SettingModifier { @@ -60,7 +61,7 @@ public void onBreak(@Nonnull BlockBreakEvent event) { final int[] index = {0}; - boolean damageItem = !item.getItemMeta().isUnbreakable() && !AbstractChallenge.getFirstInstance(NoItemDamageSetting.class).isEnabled(); + boolean damageItem = !Objects.requireNonNull(item.getItemMeta()).isUnbreakable() && !AbstractChallenge.getFirstInstance(NoItemDamageSetting.class).isEnabled(); Bukkit.getScheduler().runTaskTimer(plugin, timer -> { for (int i = 0; i < 2 && !treeBlocks.isEmpty(); i++) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java index f0c68f3fe..e35e8bab3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; +import lombok.Setter; import net.anweisen.utilities.bukkit.utils.animation.SoundSample; import net.anweisen.utilities.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -10,6 +11,7 @@ import javax.annotation.Nonnull; import java.util.function.BiConsumer; +@Setter public abstract class AbstractForceChallenge extends TimedChallenge { public static final int WAITING = 0, @@ -95,8 +97,4 @@ public final int getState() { return state; } - public void setState(int state) { - this.state = state; - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java index 163fce396..7a8b496b4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java @@ -56,12 +56,7 @@ private void killFailedPlayers(@Nonnull Iterable failed) { failed.forEach(ChallengeHelper::kill); } - @Override - protected void handleCountdown() { - bossbar.update(); - } - - protected abstract boolean isFailing(@Nonnull Player player); + protected abstract boolean isFailing(@Nonnull Player player); protected abstract void broadcastFailedMessage(@Nonnull Player player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java index 463dd0ee2..153913c7b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; +import lombok.Getter; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -14,6 +15,7 @@ import java.util.Collections; import java.util.List; +@Getter public abstract class FirstPlayerAtHeightGoal extends SettingGoal { private int heightToGetTo; @@ -47,11 +49,7 @@ public void onMove(PlayerMoveEvent event) { } } - public int getHeightToGetTo() { - return heightToGetTo; - } - - protected void setHeightToGetTo(int heightToGetTo) { + protected void setHeightToGetTo(int heightToGetTo) { this.heightToGetTo = heightToGetTo; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java index a2e199a58..aeb3455cb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java @@ -17,6 +17,7 @@ import java.util.HashMap; import java.util.Map; +import java.util.Objects; public abstract class ForceBattleDisplayGoal> extends ForceBattleGoal { @@ -62,7 +63,7 @@ public void updateDisplayStand(Player player) { public void handleDisplayStandUpdate(@NotNull Player player, @NotNull ArmorStand armorStand) { if (currentTarget.containsKey(player.getUniqueId())) { currentTarget.get(player.getUniqueId()).updateDisplayStand(armorStand); - } else if (armorStand.getEquipment().getHelmet() != null) { + } else if (Objects.requireNonNull(armorStand.getEquipment()).getHelmet() != null) { armorStand.getEquipment().setHelmet(null); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java index 0818c892d..b9a9e3276 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java @@ -38,19 +38,7 @@ public void restoreDefaults() { setValue(defaultValue); } - @Nonnull - @Override - public SoundSample getStartSound() { - return SoundSample.DRAGON_BREATH; - } - - @Nullable - @Override - public SoundSample getWinSound() { - return SoundSample.WIN; - } - - @Override + @Override public void handleClick(@Nonnull ChallengeMenuClickInfo info) { ChallengeHelper.handleModifierClick(info, this); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java index f4253a197..b46770766 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java @@ -102,7 +102,7 @@ public static BiConsumer createScoreboard(@Nonnull S if (displayed >= LEADERBOARD_SIZE) break; scoreboard.addLine(Message.forName("scoreboard-leaderboard").asString(place, NameHelper.getName(current), NumberFormatter.MIDDLE_NUMBER.format(entry.getKey()))); } - if (displayed >= LEADERBOARD_SIZE) break; + if (displayed == LEADERBOARD_SIZE) break; place++; } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index 5d65bb35e..9390c78ca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -16,7 +16,6 @@ import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; import javax.annotation.Nonnull; -import javax.print.Doc; import java.io.File; import java.io.IOException; import java.util.Map.Entry; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java index 89efdf0a1..85de7893c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.content.loader; +import lombok.Getter; import net.anweisen.utilities.bukkit.utils.logging.Logger; import net.anweisen.utilities.common.collection.IOUtils; import net.anweisen.utilities.common.version.Version; @@ -12,28 +13,16 @@ public final class UpdateLoader extends ContentLoader { public static final int RESOURCE_ID = 80548; - private static boolean newestPluginVersion = true; - private static boolean newestConfigVersion = true; - private static Version defaultConfigVersion; - private static Version currentConfigVersion; + @Getter + private static boolean newestPluginVersion = true; + @Getter + private static boolean newestConfigVersion = true; + @Getter + private static Version defaultConfigVersion; + @Getter + private static Version currentConfigVersion; - public static Version getDefaultConfigVersion() { - return defaultConfigVersion; - } - - public static Version getCurrentConfigVersion() { - return currentConfigVersion; - } - - public static boolean isNewestConfigVersion() { - return newestConfigVersion; - } - - public static boolean isNewestPluginVersion() { - return newestPluginVersion; - } - - @Override + @Override protected void load() { try { URL url = new URL("https://api.spigotmc.org/legacy/update.php?resource=" + RESOURCE_ID); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java index 669a3bbe5..993a08dc5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.management.challenges; +import lombok.Getter; import net.anweisen.utilities.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; @@ -16,6 +17,7 @@ import javax.annotation.Nonnull; import java.util.*; +@Getter public class CustomChallengesLoader extends ModuleChallengeLoader { private final Map customChallenges = new LinkedHashMap<>(); @@ -120,12 +122,4 @@ public void executeTrigger(@Nonnull ChallengeExecutionData challengeExecutionDat .onTriggerFulfilled(challengeExecutionData)); } - public int getMaxNameLength() { - return maxNameLength; - } - - public Map getCustomChallenges() { - return customChallenges; - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java index 6e12c0c48..6bcebc258 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java @@ -31,11 +31,11 @@ public static String getTitle(@Nonnull MenuType menu, String... sub) { @Nonnull public static String getTitle(@Nonnull String menu, String... sub) { - String name = menu; + StringBuilder name = new StringBuilder(menu); for (String s : sub) { - name += getTitleSplitter() + s; + name.append(getTitleSplitter()).append(s); } - return getTitle(name); + return getTitle(name.toString()); } @Nonnull @@ -45,7 +45,7 @@ public static String getTitleSplitter() { @Nonnull public static String getMenuSettingTitle(@Nonnull MenuType menu, @Nonnull String name, int page, boolean showPages) { - return getTitle(menu.getName() + getTitleSplitter() + name + (showPages && false ? " §8• " + Message.forName("inventory-color") + (page + 1) : "")); + return getTitle(menu.getName() + getTitleSplitter() + name + (false ? " §8• " + Message.forName("inventory-color") + (page + 1) : "")); } @Nonnull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java index 764580be4..3a27bfcee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java @@ -220,7 +220,7 @@ public void handleClick(@Nonnull MenuClickInfo info) { index++; } - if (itemIndex >= 2) { + if (itemIndex == 2) { SoundSample.CLICK.play(info.getPlayer()); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java index fd7122c59..9a114acda 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java @@ -3,6 +3,9 @@ import java.util.List; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; + +import lombok.Getter; +import lombok.Setter; import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; import net.anweisen.utilities.bukkit.utils.misc.CompatibilityUtils; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -12,9 +15,12 @@ import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; +@Getter +@Setter public abstract class MenuGenerator { - private MenuType menuType; + // ONLY MODIFY IF YOU KNOW WHAT YOU ARE DOING + private MenuType menuType; public abstract void generateInventories(); @@ -54,13 +60,4 @@ public void open(@Nonnull Player player, @Nonnegative int page) { player.openInventory(inventory); } - public MenuType getMenuType() { - return menuType; - } - - // ONLY MODIFY IF YOU KNOW WHAT YOU ARE DOING - public void setMenuType(MenuType menuType) { - this.menuType = menuType; - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java index da3145a09..2059f5128 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator.categorised; +import lombok.Getter; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; @@ -7,6 +8,7 @@ import java.util.function.Supplier; +@Getter public class SettingCategory { //Challenges @@ -40,20 +42,8 @@ public SettingCategory(int priority, Material material, Supplier messag this.messageSupplier = messageSupplier; } - public int getPriority() { - return priority; - } - - public ItemBuilder getDisplayItem() { + public ItemBuilder getDisplayItem() { return new ItemBuilder(material, messageSupplier.get()); } - public Material getMaterial() { - return material; - } - - public Supplier getMessageSupplier() { - return messageSupplier; - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java index a12cccb13..e0d5fa869 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java @@ -41,12 +41,7 @@ public String[] getSubTitles(int page) { return new String[]{title}; } - @Override - public int[] getNavigationSlots(int page) { - return MainCustomMenuGenerator.NAVIGATION_SLOTS; - } - - @Override + @Override public void accept(Player player, SettingType type, Map data) { subSettings.putAll(data); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java index 7b7bab270..d0465a925 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java @@ -228,10 +228,7 @@ public void handleClick(@Nonnull MenuClickInfo info) { Player player = info.getPlayer(); switch (info.getSlot()) { - default: - SoundSample.CLICK.play(player); - break; - case DELETE_SLOT: + case DELETE_SLOT: if (!Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().containsKey(uuid)) { Message.forName("custom-not-deleted").send(player, Prefix.CUSTOM); SoundSample.BASS_OFF.play(player); @@ -301,7 +298,10 @@ public void handleClick(@Nonnull MenuClickInfo info) { materialMenuGenerator.open(player, 0); SoundSample.CLICK.play(player); break; - } + default: + SoundSample.CLICK.play(player); + break; + } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java index 73a020dd5..4c7da170a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java @@ -64,7 +64,7 @@ public void generatePage(@Nonnull Inventory inventory, int page) { @Override public void onPreChallengePageClicking(@Nonnull MenuClickInfo info, int page) { if (info.getSlot() == VIEW_SLOT) { - if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() == 0) { + if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().isEmpty()) { Message.forName("custom-not-loaded").send(info.getPlayer(), Prefix.CUSTOM); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java index be1e86430..5f0484895 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java @@ -1,5 +1,8 @@ package net.codingarea.challenges.plugin.management.scheduler; +import lombok.Getter; + +@Getter public abstract class AbstractTaskConfig { protected final boolean async; @@ -8,8 +11,4 @@ public AbstractTaskConfig(boolean async) { this.async = async; } - public boolean isAsync() { - return async; - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java index b34dcc313..2c1873c2d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java @@ -17,7 +17,6 @@ import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.challenges.plugin.utils.misc.FontUtils; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.*; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java index a876c4ad0..07bc2790a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java @@ -30,7 +30,7 @@ public final class ServerManager { private final boolean winSounds; private boolean isFresh; // This indicated if the timer was never started before - private boolean hasCheated = false; + private boolean hasCheated; public ServerManager() { Document sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java index db4028ee9..ff503aca6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.management.server; +import lombok.Getter; import net.anweisen.utilities.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -7,6 +8,7 @@ import javax.annotation.Nonnull; +@Getter public final class TitleManager { private static final int fadein = 5, duration = 20, fadeout = 10; @@ -30,15 +32,7 @@ public void sendChallengeStatusTitle(@Nonnull Message message, @Nonnull Object.. message.broadcastTitle(args); } - public boolean isChallengeStatusEnabled() { - return challengeStatusEnabled; - } - - public boolean isTimerStatusEnabled() { - return timerStatusEnabled; - } - - public void sendTitle(@Nonnull Player player, @Nonnull String title, @Nonnull String subtitle) { + public void sendTitle(@Nonnull Player player, @Nonnull String title, @Nonnull String subtitle) { player.sendTitle(title, subtitle, fadein, duration, fadeout); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java index d0f6093d6..78f5e5b2b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java @@ -88,16 +88,16 @@ public void update(@Nonnull Player player) { } } - public final void show() { + public void show() { Challenges.getInstance().getScoreboardManager().setCurrentScoreboard(this); } - public final void hide() { + public void hide() { if (Challenges.getInstance().getScoreboardManager().getCurrentScoreboard() != this) return; Challenges.getInstance().getScoreboardManager().setCurrentScoreboard(null); } - public final boolean isShown() { + public boolean isShown() { return Challenges.getInstance().getScoreboardManager().isShown(this); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java index c7982e92b..b4f4d9c6b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java @@ -113,7 +113,7 @@ private PlayerStats getStatsFromDatabase(@Nonnull UUID uuid, @Nonnull String nam .select("stats", "name") .where("uuid", uuid) .execute().first() - .map(result -> new PlayerStats(uuid, result.getString("name"), result.getDocument("stats"))) + .map(result -> new PlayerStats(uuid, Objects.requireNonNull(result.getString("name")), result.getDocument("stats"))) .orElse(new PlayerStats(uuid, name)); } @@ -134,7 +134,7 @@ private List getAllStats0() throws DatabaseException { .select("uuid", "stats", "name") .execute().all() .filter(result -> result.getUUID("uuid") != null) - .map(result -> new PlayerStats(result.getUUID("uuid"), result.getString("name"), result.getDocument("stats"))) + .map(result -> new PlayerStats(Objects.requireNonNull(result.getUUID("uuid")), Objects.requireNonNull(result.getString("name")), result.getDocument("stats"))) .collect(Collectors.toList()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java index 734718d29..2b8de1c9b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java @@ -144,7 +144,7 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman if (args.length <= 1) { return Utils.filterRecommendations(args[0], "save", "load", "reset"); - } else if (args.length <= 2) { + } else if (args.length == 2) { return Utils.filterRecommendations(args[1], databaseExecutors.keySet().toArray(new String[0])); } return Lists.newLinkedList(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java index 8b042bdc7..e295cd168 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java @@ -22,7 +22,7 @@ public class GamemodeCommand implements SenderCommand, Completer { public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { List targets = new ArrayList<>(); - if (args.length <= 0) { + if (args.length == 0) { Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java index 0a47e3dd3..16b5397fb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java @@ -4,10 +4,8 @@ import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; -import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; -import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java index 4ee7ff32d..87759746f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java @@ -12,6 +12,7 @@ import org.jetbrains.annotations.Nullable; import java.util.List; +import java.util.Objects; public class LanguageCommand implements SenderCommand, Completer { @@ -25,12 +26,12 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr case "german": case "deutsch": case "de": - Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).changeLanguage("de"); + Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("de"); break; case "english": case "englisch": case "en": - Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).changeLanguage("en"); + Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("en"); break; default: Message.forName("unsuported-language").send(sender, Prefix.CHALLENGES, args[0]); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java index e98dbc4f7..861d1fb02 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java @@ -17,7 +17,6 @@ import net.codingarea.challenges.plugin.utils.misc.StatsHelper; import net.codingarea.challenges.plugin.utils.misc.Utils; import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java index fd133bf74..4d8bb05fe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java @@ -30,7 +30,7 @@ public TimeCommand() { @Override public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - if (args.length <= 0) { + if (args.length == 0) { Message.forName("syntax").send(player, Prefix.CHALLENGES, "time "); return; } @@ -50,7 +50,7 @@ public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exc player.performCommand("time set midnight"); break; case "set": { - if (args.length <= 1) { + if (args.length == 1) { Message.forName("syntax").send(player, Prefix.CHALLENGES, "time set "); break; } @@ -70,7 +70,7 @@ public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exc break; } case "add": { - if (args.length <= 1) { + if (args.length == 1) { Message.forName("syntax").send(player, Prefix.CHALLENGES, "time add "); break; } @@ -83,7 +83,7 @@ public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exc break; } case "subtract": { - if (args.length <= 1) { + if (args.length == 1) { Message.forName("syntax").send(player, Prefix.CHALLENGES, "time subtract "); break; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java index dc9162d1c..234662988 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java @@ -78,10 +78,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { break; } switch (args[1].toLowerCase()) { - default: - Message.forName("syntax").send(sender, Prefix.TIMER, "timer mode "); - break; - case "up": + case "up": case "forward": Challenges.getInstance().getChallengeTimer().setCountingUp(true); break; @@ -90,7 +87,10 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { case "backwards": Challenges.getInstance().getChallengeTimer().setCountingUp(false); break; - } + default: + Message.forName("syntax").send(sender, Prefix.TIMER, "timer mode "); + break; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java index 098ead5c2..7c5078c7e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java @@ -7,11 +7,11 @@ import javax.annotation.Nonnull; +@Getter public class PlayerInventoryClickEvent extends InventoryClickEventWrapper { private static final HandlerList handlers = new HandlerList(); - @Getter private final Player player; public PlayerInventoryClickEvent(@Nonnull InventoryClickEvent event) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java index bc3609180..60e77344b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java @@ -15,53 +15,11 @@ public class VoidMapGenerator extends ChunkGenerator { private static final boolean generateEndPortal = MinecraftVersion.current().getMinor() == 18; -// private static class PortalInfo { -// -// private final int chunkX; -// private final int y; -// private final int chunkZ; -// -// public PortalInfo(int chunkX, int y, int chunkZ) { -// this.chunkX = chunkX; -// this.y = y; -// this.chunkZ = chunkZ; -// } -// -// } - -// private List portalChunks; -// -// public void loadStrongholds(World world) { -// -// for (int i = 0; i < 3; i++) { -// Bukkit.getScheduler().runTaskLater(Challenges.getInstance().getPlugin(), () -> { -// Location portal = world -// .locateNearestStructure(new Location(world, 0, 0, 0), StructureType.STRONGHOLD, 180, -// true); -// if (portal != null) { -// Chunk chunk = portal.getChunk(); -// chunk.load(true); -// portalChunks.add(new PortalInfo(chunk.getX(), portal.getBlockY(), chunk.getZ())); -// } -// }, i*5); -// -// } -// -// -// } - - @Override + @Override @Nonnull public ChunkData generateChunkData(@Nonnull World world, @Nonnull Random random, int x, int z, @Nonnull BiomeGrid biome) { -// if (portalChunks == null) { -// portalChunks = Lists.newLinkedList(); -// Bukkit.getScheduler().runTask(Challenges.getInstance().getPlugin(), () -> { -// loadStrongholds(world); -// }); -// } - - ChunkData chunkData = createChunkData(world); + ChunkData chunkData = createChunkData(world); if (x == 0 && z == 0) { chunkData.setBlock(0, 59, 0, Material.BEDROCK); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java index c17bda8ed..453464bac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java @@ -33,17 +33,11 @@ public void onGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { @EventHandler(priority = EventPriority.MONITOR) public void onSneak(PlayerToggleSneakEvent event) { - if (!event.isSneaking()) return; -// -// StructureManager manager = Bukkit.getStructureManager(); -// Map structures = manager.getStructures(); -// // Entry entry = IRandom.threadLocal().choose(entries); + if (!event.isSneaking()) { + } //// Structure structure = entry.getValue(); -// Structure structure = manager.getStructure(new NamespacedKey("minecraft", "shipwreck/rightsideup_backhalf")); -// structure.place(event.getPlayer().getLocation(), true, StructureRotation.NONE, Mirror.NONE, -1, 0, -// ThreadLocalRandom.current()); - } + } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCommand(@Nonnull PlayerCommandPreprocessEvent event) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java index 5d12811ae..0b6729a3b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java @@ -81,8 +81,7 @@ public void onGameModeChange(PlayerGameModeChangeEvent event) { isIgnored = true; } else if (!AbstractChallenge.ignoreGameMode(event.getNewGameMode()) && AbstractChallenge.ignoreGameMode(event.getPlayer().getGameMode())) { execute = true; - isIgnored = false; - } + } if (execute) { PlayerIgnoreStatusChangeEvent statusEvent = new PlayerIgnoreStatusChangeEvent(event.getPlayer(), isIgnored); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java index e94d0de28..6711694e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java @@ -18,8 +18,7 @@ public class BukkitSerialization { * * @param playerInventory to turn into an array of strings. * @return Array of strings: [ main content, armor content ] - * @throws IllegalStateException - */ + */ public static String[] playerInventoryToBase64(PlayerInventory playerInventory) throws IllegalStateException { //get the main content part, this doesn't return the armor String content = toBase64(playerInventory); @@ -37,8 +36,7 @@ public static String[] playerInventoryToBase64(PlayerInventory playerInventory) * * @param items to turn into a Base64 String. * @return Base64 string of the items. - * @throws IllegalStateException - */ + */ public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); @@ -72,8 +70,7 @@ public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalSta * * @param inventory to serialize * @return Base64 string of the provided inventory - * @throws IllegalStateException - */ + */ public static String toBase64(Inventory inventory) throws IllegalStateException { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); @@ -104,8 +101,7 @@ public static String toBase64(Inventory inventory) throws IllegalStateException * * @param data Base64 string of data containing an inventory. * @return Inventory created from the Base64 string. - * @throws IOException - */ + */ public static Inventory fromBase64(Inventory inventory, String data) throws IOException { try { ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); @@ -128,12 +124,11 @@ public static Inventory fromBase64(Inventory inventory, String data) throws IOEx *

*

*

- * Base off of {@link #fromBase64(String)}. + * Base off of . * * @param data Base64 string to convert to ItemStack array. * @return ItemStack array created from the Base64 string. - * @throws IOException - */ + */ public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException { try { ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java index 8b03d4c7d..6c0f43430 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java @@ -63,7 +63,8 @@ public static List format(@Nonnull String sequence, @Nonnull Obje } else { if (lastWasParagraph) { ChatColor newColor = ChatColor.getByChar(c); - if (!newColor.isColor()) { + assert newColor != null; + if (!newColor.isColor()) { if (newColor == ChatColor.RESET) { currentFormatting.clear(); currentColor = null; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java index fe0353359..c40302d9d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.version; +package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java index 3b2d48418..b7918391b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.version; +package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; import java.util.ArrayList; import java.util.Arrays; @@ -82,7 +82,7 @@ static Version parseExceptionally(@Nullable String input) { @Nonnull @CheckReturnValue static Version getAnnotatedSince(@Nonnull Object object) { - return (Version)(!object.getClass().isAnnotationPresent(Since.class) ? new VersionInfo(1, 0, 0) : parse(((Since)object.getClass().getAnnotation(Since.class)).value())); + return (Version)(!object.getClass().isAnnotationPresent(Since.class) ? new VersionInfo(1, 0, 0) : parse(object.getClass().getAnnotation(Since.class).value())); } @Nonnull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java index 205a5cbfe..4c856af7a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.version; +package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; import java.util.Comparator; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java index 17b50e494..1564993bd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java @@ -1,9 +1,12 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.version; +package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; import java.util.Objects; import javax.annotation.Nullable; + +import lombok.Getter; import net.anweisen.utilities.common.logging.ILogger; +@Getter public class VersionInfo implements Version { protected static final ILogger logger = ILogger.forThisClass(); private final int major; @@ -20,28 +23,16 @@ public VersionInfo(int major, int minor, int revision) { this.revision = revision; } - public int getMajor() { - return this.major; - } - - public int getMinor() { - return this.minor; - } - - public int getRevision() { - return this.revision; - } - public boolean equals(Object other) { if (this == other) { return true; } else { - return !(other instanceof Version) ? false : this.equals((Version)other); + return other instanceof Version && this.equals(other); } } public int hashCode() { - return Objects.hash(new Object[]{this.major, this.minor, this.revision}); + return Objects.hash(this.major, this.minor, this.revision); } public String toString() { @@ -72,7 +63,7 @@ public static Version parse(@Nullable String input, Version def) { try { return parseExceptionally(input); } catch (Exception ex) { - logger.error("Could not parse version for input {}", new Object[]{ex.getMessage()}); + logger.error("Could not parse version for input {}", ex.getMessage()); return def; } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java index f899d1aaa..07bc07991 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms; +import lombok.Getter; import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_13.*; @@ -15,6 +16,13 @@ public class NMSProvider { private final static int majorVersion; + /** + * -- GETTER -- + * + * @return A border packet factory + * + */ + @Getter private static final BorderPacketFactory borderPacketFactory; static { @@ -100,14 +108,6 @@ public static PacketBorder createPacketBorder(World world) { throw new IllegalStateException("Could not find a PacketBorder implementation for version " + getFormattedVersion()); } - /** - * @return A border packet factory - * @throws IllegalStateException If no implementation was found for the current version - */ - public static BorderPacketFactory getBorderPacketFactory() { - return borderPacketFactory; - } - private static boolean versionIsAtLeast(int majorVersion) { return NMSProvider.majorVersion >= majorVersion; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java index 3dd617ac6..d0415f66a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java @@ -12,8 +12,8 @@ import org.bukkit.Bukkit; /** - * @author TobiasDeBruijn | https://github.com/TobiasDeBruijn - * @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil + * @author TobiasDeBruijn | .* @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil */ public class ReflectionUtil { @@ -27,7 +27,6 @@ public class ReflectionUtil { * (<=1.16) or * (>=1.17). * - * @return Returns true if it is, false if it is now */ @Getter private static boolean useNewSpigotPackaging; @@ -38,7 +37,6 @@ public class ReflectionUtil { *

* E.g for Minecraft 1.18 this is 18. * - * @return The current major Minecraft version */ @Getter private static int majorVersion; @@ -48,7 +46,6 @@ public class ReflectionUtil { *

* E.g. for Minecraft 1.18.2 this is 2. * - * @return The current minor Minecraft version */ @Getter private static int minorVersion; @@ -193,9 +190,7 @@ public static Field getField(Class clazz, String fieldName) throws NoSuchFiel * @param instance The instance of the class in which the field is defined * @param fieldName The name of the field * @param value The value the field should be set to - * @throws NoSuchFieldException - * @throws IllegalAccessException - */ + */ public static void setFieldValue(Object instance, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { Field field = instance.getClass().getDeclaredField(fieldName); field.setAccessible(true); @@ -209,8 +204,7 @@ public static void setFieldValue(Object instance, String fieldName, Object value * @param methodName The name of the method * @param args The argument types the method takes * @return Returns the Method - * @throws NoSuchMethodException - */ + */ public static Method getMethod(Class clazz, String methodName, Class... args) throws NoSuchMethodException { Method m = clazz.getDeclaredMethod(methodName, args); m.setAccessible(true); @@ -223,11 +217,7 @@ public static Method getMethod(Class clazz, String methodName, Class... ar * @param obj The object to invoke the method on * @param methodName The name of the Method * @return Returns the result of the method, can be null if the method returns void - * @throws NoSuchMethodException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ + */ public static Object invokeMethod(Object obj, String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { return invokeMethod(obj.getClass(), obj, methodName); } @@ -239,11 +229,7 @@ public static Object invokeMethod(Object obj, String methodName) throws NoSuchMe * @param methodName The name of the Method * @param args The arguments to pass to the Method * @return Returns the result of the method, can be null if the method returns void - * @throws NoSuchMethodException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ + */ public static Object invokeMethod(Object obj, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { return invokeMethod(obj.getClass(), obj, methodName, args); } @@ -256,11 +242,7 @@ public static Object invokeMethod(Object obj, String methodName, Object[] args) * @param argTypes The types of arguments as a Class array * @param args The arguments as an object array * @return Returns the result of the method, can be null if the method returns void - * @throws NoSuchMethodException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ + */ public static Object invokeMethod(Object obj, String methodName, Class[] argTypes, Object[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { return invokeMethod(obj.getClass(), obj, methodName, argTypes, args); } @@ -273,11 +255,7 @@ public static Object invokeMethod(Object obj, String methodName, Class[] argT * @param methodName The name of the method * @param args The arguments to be passed to the method * @return Returns the result of the method, can be null if the method returns void - * @throws NoSuchMethodException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ + */ public static Object invokeMethod(Class clazz, Object obj, String methodName, Object... args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class[] argTypes = new Class[args.length]; for (int i = 0; i < args.length; i++) { @@ -296,11 +274,7 @@ public static Object invokeMethod(Class clazz, Object obj, String methodName, * @param argTypes Argument types * @param args Arguments to pass to the method * @return Returns the result of the method, can be null if the method returns void - * @throws NoSuchMethodException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ + */ public static Object invokeMethod(Class clazz, Object obj, String methodName, Class[] argTypes, Object[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Method m = getMethod(clazz, methodName, argTypes); return m.invoke(obj, args); @@ -312,10 +286,7 @@ public static Object invokeMethod(Class clazz, Object obj, String methodName, * @param obj The object in which the field is located, and from which to get the value * @param name The name of the Field to get the value from * @return Returns the value of the Field - * @throws NoSuchFieldException - * @throws IllegalArgumentException - * @throws IllegalAccessException - */ + */ public static Object getObject(Object obj, String name) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { return getObject(obj.getClass(), obj, name); } @@ -327,9 +298,6 @@ public static Object getObject(Object obj, String name) throws NoSuchFieldExcept * @param clazz The Class in which the Field is defined * @param name The name of the Field * @return Returns the value of the Field - * @throws NoSuchFieldException - * @throws IllegalArgumentException - * @throws IllegalAccessException * @deprecated Use {@link #getObject(Class, Object, String)} instead */ @Deprecated @@ -344,10 +312,7 @@ public static Object getObject(Object obj, Class clazz, String name) throws N * @param obj The Object to get the value from * @param name The name of the Field * @return Returns the value of the Field - * @throws NoSuchFieldException - * @throws IllegalArgumentException - * @throws IllegalAccessException - */ + */ public static Object getObject(Class clazz, Object obj, String name) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field f = getField(clazz, name); f.setAccessible(true); @@ -360,12 +325,7 @@ public static Object getObject(Class clazz, Object obj, String name) throws N * @param clazz The Class in which the Constructor is defined * @param args The arguments to pass to the Constructor * @return Returns an instance of the provided Class in which the Constructor is located - * @throws NoSuchMethodException - * @throws InstantiationException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ + */ public static Object invokeConstructor(Class clazz, Object... args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class[] argTypes = new Class[args.length]; for (int i = 0; i < args.length; i++) { @@ -382,12 +342,7 @@ public static Object invokeConstructor(Class clazz, Object... args) throws No * @param argTypes The argument types * @param args The arguments to pass to the constructor * @return Returns an instance of the provided Class in which the Constructor is located - * @throws NoSuchMethodException - * @throws InstantiationException - * @throws IllegalAccessException - * @throws IllegalArgumentException - * @throws InvocationTargetException - */ + */ public static Object invokeConstructor(Class clazz, Class[] argTypes, Object[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Constructor con = getConstructor(clazz, argTypes); return con.newInstance(args); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java index d2f329402..c104b2598 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java @@ -32,6 +32,7 @@ private Object createPacket(PacketBorder packetBorder, String worldBorderAction) try { Class clazz = NMSUtils.getClass("PacketPlayOutWorldBorder"); Class actionClazz = NMSUtils.getClass("PacketPlayOutWorldBorder$EnumWorldBorderAction"); + assert actionClazz != null; for (Object enumConstant : actionClazz.getEnumConstants()) { if (enumConstant.toString().equalsIgnoreCase(worldBorderAction)) { return ReflectionUtil.invokeConstructor(clazz, new Class[]{packetBorder.getNMSClass(), actionClazz}, new Object[]{packetBorder.getWorldBorderObject(), enumConstant}); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java index 8e991c636..9ec5f716b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java @@ -15,15 +15,5 @@ public PacketBorder_1_17(World world) { ); } - @Override - protected Object createWorldBorder() { - try { - return ReflectionUtil.invokeConstructor(nmsClass); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create world border:", exception); - return null; - } - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java index 48e101f32..afff1f330 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java @@ -4,8 +4,8 @@ import org.bukkit.entity.Player; /** - * @author TobiasDeBruijn | https://github.com/TobiasDeBruijn - * @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil + * @author TobiasDeBruijn | .* @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil */ public abstract class CraftPlayer extends BukkitNMSClass { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java index 1625cb2c2..96fcd5a26 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms.type; /** - * @author TobiasDeBruijn | https://github.com/TobiasDeBruijn - * @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil + * @author TobiasDeBruijn | .* @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil */ public abstract class PlayerConnection extends AbstractNMSClass { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java index 7857104ad..415637d7a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.utils.item; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.UUID; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.SkullBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index 24f8ed898..dead068e2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -3,13 +3,8 @@ import com.google.gson.JsonParser; import lombok.NonNull; import net.anweisen.utilities.bukkit.utils.item.BannerPattern; -import net.anweisen.utilities.bukkit.utils.misc.GameProfileUtils; -import net.anweisen.utilities.common.annotations.DeprecatedSince; -import net.anweisen.utilities.common.annotations.ReplaceWith; -import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.ItemDescription; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.utils.misc.DatabaseHelper; import org.bukkit.*; import org.bukkit.block.banner.Pattern; import org.bukkit.block.banner.PatternType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java index 716d88602..42a6efc52 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java @@ -65,9 +65,7 @@ public static boolean isObtainableInSurvival(@Nonnull Material material) { } if (MinecraftVersion.current().isOlderThan(MinecraftVersion.V1_19)) { - if (name.equals("SCULK_SENSOR")) { - return false; - } + return !name.equals("SCULK_SENSOR"); } return true; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java index edee046dd..071ef4ffc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java @@ -144,11 +144,9 @@ public static void setBlockNatural(@Nullable Block block, @Nonnull Material type if (!upperBlock.getType().isSolid()) { upperBlock.breakNaturally(); - if (playSound) { - // TODO: PLAY THE RIGHT BREAKING SOUND FOR THE BLOCK - } + // TODO: PLAY THE RIGHT BREAKING SOUND FOR THE BLOCK - } + } block.setType(type, blockUpdate); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java index 3b4ddbff2..f2a5bda15 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java @@ -26,7 +26,7 @@ public final ListBuilder addAll(T... t) { return addAll(Arrays.asList(t)); } - public final ListBuilder addAll(Collection collection) { + public ListBuilder addAll(Collection collection) { list.addAll(collection); return this; } @@ -36,7 +36,7 @@ public final ListBuilder addAllIfNotContains(T... t) { return addAllIfNotContains(Arrays.asList(t)); } - public final ListBuilder addAllIfNotContains(Collection collection) { + public ListBuilder addAllIfNotContains(Collection collection) { for (T t : collection) { if (!list.contains(t)) list.add(t); } From b61db47633e19f4c309e7b0e280a331d48146f4d Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 18 Apr 2025 10:25:39 +0200 Subject: [PATCH 048/119] fix: remove default config options for language --- plugin/src/main/resources/config.yml | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/plugin/src/main/resources/config.yml b/plugin/src/main/resources/config.yml index 1d4c0c2f3..cc8c942c5 100644 --- a/plugin/src/main/resources/config.yml +++ b/plugin/src/main/resources/config.yml @@ -24,15 +24,6 @@ # We recommend regenerating the config to get access to new features / settings. config-version: "2.2.1" -# Currently supported by default -# - en (English) -# - de (German / Deutsch) -language: "de" - -# Makes text from the plugin appear in the 'small caps' font -# Example: ᴛʜɪs ɪs sᴍᴀʟʟ ᴄᴀᴘs -small-caps: false - timer: format: seconds: "{mm}:{ss}" @@ -159,10 +150,6 @@ no-stats-after-cheating: false # - Will download languages from github development branch (https://github.com/anweisen/Challenges/tree/development). dev-mode: false -# Set a path to a json language file on your computer to use the translations out of this file. -# Useful when developing with the plugin -# direct-language-file: C:\PathToWorkDic\Challenges\language\files\de.json - database: # Available database types: # - mysql From 75fc929aac6a76a3ec7937a742b29959bf3c640f Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 18 Apr 2025 10:26:16 +0200 Subject: [PATCH 049/119] chore: bump version to 2.4 --- mongo-connector/pom.xml | 2 +- plugin/pom.xml | 2 +- plugin/src/main/resources/config.yml | 2 +- pom.xml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/mongo-connector/pom.xml b/mongo-connector/pom.xml index cc17f0e40..7dfe556eb 100644 --- a/mongo-connector/pom.xml +++ b/mongo-connector/pom.xml @@ -7,7 +7,7 @@ net.codingarea.challenges root - 2.3.2 + 2.4 mongo-connector diff --git a/plugin/pom.xml b/plugin/pom.xml index 49a44ba2d..76c5becdd 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -7,7 +7,7 @@ net.codingarea.challenges root - 2.3.2 + 2.4 plugin diff --git a/plugin/src/main/resources/config.yml b/plugin/src/main/resources/config.yml index cc8c942c5..02be209b6 100644 --- a/plugin/src/main/resources/config.yml +++ b/plugin/src/main/resources/config.yml @@ -22,7 +22,7 @@ # The config-version is even with the version of the default config. # You will be notified, when this version is older than the of the default in the plugin jar. # We recommend regenerating the config to get access to new features / settings. -config-version: "2.2.1" +config-version: "2.4" timer: format: diff --git a/pom.xml b/pom.xml index a2d103724..43f00b0da 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ net.codingarea.challenges root - 2.3.2 + 2.4 pom root https://github.com/anweisen/Challenges From 73c134b7f4a5147bb875c2d0e27cda6fa12410aa Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 18 Apr 2025 10:29:03 +0200 Subject: [PATCH 050/119] style: reindent with 2 spaces --- .../challenges/plugin/Challenges.java | 377 +++--- .../challenges/custom/CustomChallenge.java | 326 ++--- .../settings/ChallengeExecutionData.java | 146 +-- .../custom/settings/ChallengeSetting.java | 58 +- .../custom/settings/CustomSettingsLoader.java | 276 ++-- .../custom/settings/FallbackNames.java | 4 +- .../custom/settings/IChallengeSetting.java | 8 +- .../custom/settings/SettingType.java | 6 +- .../settings/action/ChallengeAction.java | 46 +- .../settings/action/EntityTargetAction.java | 20 +- .../settings/action/IChallengeAction.java | 4 +- .../settings/action/IEntityTargetAction.java | 108 +- .../settings/action/PlayerTargetAction.java | 44 +- .../action/impl/AddPermanentEffectAction.java | 34 +- .../action/impl/BoostEntityInAirAction.java | 60 +- .../action/impl/CancelEventAction.java | 54 +- .../action/impl/ChangeWorldBorderAction.java | 64 +- .../action/impl/ClearInventoryAction.java | 22 +- .../action/impl/DamageEntityAction.java | 44 +- .../action/impl/DropRandomItemAction.java | 22 +- .../action/impl/ExecuteCommandAction.java | 84 +- .../settings/action/impl/FreezeAction.java | 32 +- .../action/impl/HealEntityAction.java | 58 +- .../action/impl/HungerPlayerAction.java | 46 +- .../action/impl/InvertHealthAction.java | 22 +- .../action/impl/JumpAndRunAction.java | 26 +- .../action/impl/KillEntityAction.java | 30 +- .../action/impl/ModifyMaxHealthAction.java | 68 +- .../action/impl/PlaceStructureAction.java | 122 +- .../action/impl/PotionEffectAction.java | 56 +- .../action/impl/RandomHotBarAction.java | 22 +- .../action/impl/RandomItemAction.java | 52 +- .../settings/action/impl/RandomMobAction.java | 56 +- .../action/impl/RandomPotionEffectAction.java | 48 +- .../action/impl/RemoveRandomItemAction.java | 22 +- .../action/impl/SpawnEntityAction.java | 42 +- .../action/impl/SwapRandomItemAction.java | 22 +- .../action/impl/SwapRandomMobAction.java | 68 +- .../action/impl/UncraftInventoryAction.java | 28 +- .../settings/action/impl/WaterMLGAction.java | 26 +- .../action/impl/WinChallengeAction.java | 44 +- .../settings/sub/SubSettingsBuilder.java | 250 ++-- .../custom/settings/sub/ValueSetting.java | 30 +- .../builder/ChooseItemSubSettingsBuilder.java | 84 +- .../ChooseMultipleItemSubSettingBuilder.java | 138 +- .../sub/builder/EmptySubSettingsBuilder.java | 36 +- .../builder/GeneratorSubSettingsBuilder.java | 32 +- .../builder/TextInputSubSettingsBuilder.java | 136 +- .../sub/builder/ValueSubSettingsBuilder.java | 124 +- .../settings/sub/impl/BooleanSetting.java | 24 +- .../settings/sub/impl/ModifierSetting.java | 162 +-- .../settings/trigger/ChallengeTrigger.java | 44 +- .../settings/trigger/IChallengeTrigger.java | 6 +- .../trigger/impl/AdvancementTrigger.java | 24 +- .../trigger/impl/BreakBlockTrigger.java | 30 +- .../trigger/impl/ConsumeItemTrigger.java | 42 +- .../trigger/impl/CraftItemTrigger.java | 32 +- .../trigger/impl/DropItemTrigger.java | 28 +- .../impl/EntityDamageByPlayerTrigger.java | 30 +- .../trigger/impl/EntityDamageTrigger.java | 78 +- .../trigger/impl/EntityDeathTrigger.java | 28 +- .../settings/trigger/impl/GainXPTrigger.java | 32 +- .../settings/trigger/impl/GetItemTrigger.java | 48 +- .../settings/trigger/impl/HungerTrigger.java | 34 +- .../trigger/impl/InLiquidTrigger.java | 80 +- .../trigger/impl/IntervallTrigger.java | 122 +- .../settings/trigger/impl/LevelUpTrigger.java | 30 +- .../trigger/impl/MoveBlockTrigger.java | 30 +- .../trigger/impl/MoveCameraTrigger.java | 32 +- .../trigger/impl/MoveDownTrigger.java | 34 +- .../settings/trigger/impl/MoveUpTrigger.java | 34 +- .../trigger/impl/PickupItemTrigger.java | 28 +- .../trigger/impl/PlaceBlockTrigger.java | 30 +- .../trigger/impl/PlayerJumpTrigger.java | 22 +- .../trigger/impl/PlayerSneakTrigger.java | 26 +- .../impl/StandsNotOnSpecificBlockTrigger.java | 66 +- .../impl/StandsOnSpecificBlockTrigger.java | 44 +- .../challenge/DamageTeleportChallenge.java | 118 +- .../challenge/ZeroHeartsChallenge.java | 142 +- .../damage/AdvancementDamageChallenge.java | 62 +- .../damage/BlockBreakDamageChallenge.java | 56 +- .../damage/BlockPlaceDamageChallenge.java | 56 +- .../damage/DamagePerBlockChallenge.java | 62 +- .../damage/DamagePerItemChallenge.java | 68 +- .../damage/DeathOnFallChallenge.java | 38 +- .../challenge/damage/FreezeChallenge.java | 89 +- .../challenge/damage/JumpDamageChallenge.java | 62 +- .../damage/ReversedDamageChallenge.java | 38 +- .../damage/SneakDamageChallenge.java | 64 +- .../damage/WaterAllergyChallenge.java | 64 +- .../effect/BlockEffectChallenge.java | 262 ++-- .../effect/ChunkRandomEffectChallenge.java | 216 ++-- .../effect/EntityRandomEffectChallenge.java | 80 +- .../challenge/effect/InfectionChallenge.java | 116 +- .../PermanentEffectOnDamageChallenge.java | 483 ++++--- .../effect/RandomPotionEffectChallenge.java | 156 +-- .../entities/AllMobsToDeathPoint.java | 62 +- .../entities/BlockMobsChallenge.java | 134 +- .../entities/DupedSpawningChallenge.java | 60 +- .../entities/HydraNormalChallenge.java | 26 +- .../entities/HydraPlusChallenge.java | 48 +- .../entities/InvisibleMobsChallenge.java | 70 +- .../entities/MobSightDamageChallenge.java | 102 +- .../entities/MobTransformationChallenge.java | 86 +- .../entities/MobsRespawnInEndChallenge.java | 184 +-- .../entities/NewEntityOnJumpChallenge.java | 46 +- .../entities/StoneSightChallenge.java | 116 +- .../extraworld/JumpAndRunChallenge.java | 387 +++--- .../extraworld/WaterMLGChallenge.java | 138 +- .../challenge/force/ForceBiomeChallenge.java | 226 ++-- .../challenge/force/ForceBlockChallenge.java | 196 +-- .../challenge/force/ForceHeightChallenge.java | 168 +-- .../challenge/force/ForceItemChallenge.java | 218 ++-- .../challenge/force/ForceMobChallenge.java | 184 +-- .../DamageInventoryClearChallenge.java | 78 +- .../inventory/MissingItemsChallenge.java | 378 +++--- .../MovementItemRemovingChallenge.java | 73 +- .../inventory/NoDupedItemsChallenge.java | 154 +-- .../inventory/PermanentItemChallenge.java | 70 +- .../inventory/PickupItemLaunchChallenge.java | 62 +- .../inventory/UncraftItemsChallenge.java | 188 +-- .../miscellaneous/EnderGamesChallenge.java | 82 +- .../miscellaneous/FoodLaunchChallenge.java | 60 +- .../miscellaneous/FoodOnceChallenge.java | 168 +-- .../miscellaneous/InvertHealthChallenge.java | 78 +- .../miscellaneous/LowDropRateChallenge.java | 70 +- .../miscellaneous/NoExpChallenge.java | 32 +- .../NoSharedAdvancementsChallenge.java | 78 +- .../miscellaneous/NoTradingChallenge.java | 58 +- .../miscellaneous/OneDurabilityChallenge.java | 80 +- .../movement/AlwaysRunningChallenge.java | 78 +- .../movement/DontStopRunningChallenge.java | 150 +-- .../movement/FiveHundredBlocksChallenge.java | 300 ++--- .../movement/HigherJumpsChallenge.java | 44 +- .../movement/HungerPerBlockChallenge.java | 34 +- .../challenge/movement/MoveMouseDamage.java | 92 +- .../challenge/movement/OnlyDirtChallenge.java | 66 +- .../challenge/movement/OnlyDownChallenge.java | 36 +- .../movement/TrafficLightChallenge.java | 194 +-- .../challenge/quiz/QuizChallenge.java | 970 +++++++------- .../randomizer/BlockRandomizerChallenge.java | 89 +- .../CraftingRandomizerChallenge.java | 74 +- .../EntityLootRandomizerChallenge.java | 292 ++--- .../randomizer/HotBarRandomizerChallenge.java | 232 ++-- .../randomizer/MobRandomizerChallenge.java | 396 +++--- .../randomizer/RandomChallengeChallenge.java | 206 +-- .../randomizer/RandomEventChallenge.java | 408 +++--- .../randomizer/RandomItemChallenge.java | 64 +- .../RandomItemDroppingChallenge.java | 90 +- .../RandomItemRemovingChallenge.java | 80 +- .../RandomItemSwappingChallenge.java | 120 +- .../RandomTeleportOnHitChallenge.java | 66 +- .../randomizer/RandomizedHPChallenge.java | 204 +-- .../challenge/time/MaxBiomeTimeChallenge.java | 164 +-- .../time/MaxHeightTimeChallenge.java | 154 +-- .../world/AllBlocksDisappearChallenge.java | 220 ++-- .../challenge/world/AnvilRainChallenge.java | 402 +++--- .../challenge/world/BedrockPathChallenge.java | 38 +- .../challenge/world/BedrockWallChallenge.java | 74 +- .../world/BlockFlyInAirChallenge.java | 74 +- .../BlocksDisappearAfterTimeChallenge.java | 66 +- .../world/ChunkDeconstructionChallenge.java | 170 +-- .../world/ChunkDeletionChallenge.java | 9 +- .../challenge/world/FloorIsLavaChallenge.java | 80 +- .../challenge/world/IceFloorChallenge.java | 150 +-- .../challenge/world/LevelBorderChallenge.java | 572 ++++---- .../challenge/world/LoopChallenge.java | 631 +++++---- .../world/RepeatInChunkChallenge.java | 468 +++---- .../challenge/world/SnakeChallenge.java | 150 +-- .../challenge/world/SurfaceHoleChallenge.java | 76 +- .../challenge/world/TsunamiChallenge.java | 390 +++--- .../damage/DamageRuleSetting.java | 68 +- .../goal/AllAdvancementGoal.java | 184 +-- .../goal/CollectAllItemsGoal.java | 328 ++--- .../goal/CollectHorseAmorGoal.java | 42 +- .../goal/CollectIceBlocksGoal.java | 18 +- .../goal/CollectMostDeathsGoal.java | 52 +- .../goal/CollectMostExpGoal.java | 44 +- .../goal/CollectMostItemsGoal.java | 68 +- .../goal/CollectSwordsGoal.java | 40 +- .../implementation/goal/CollectWoodGoal.java | 204 +-- .../goal/CollectWorkstationsGoal.java | 28 +- .../implementation/goal/EatCakeGoal.java | 56 +- .../implementation/goal/EatMostGoal.java | 40 +- .../implementation/goal/FindElytraGoal.java | 18 +- .../implementation/goal/FinishRaidGoal.java | 44 +- .../goal/FirstOneToDieGoal.java | 60 +- .../goal/GetFullHealthGoal.java | 108 +- .../goal/KillAllBossesGoal.java | 26 +- .../goal/KillAllBossesNewGoal.java | 26 +- .../implementation/goal/KillAllMobsGoal.java | 50 +- .../goal/KillAllMonsterGoal.java | 72 +- .../goal/KillElderGuardianGoal.java | 28 +- .../goal/KillEnderDragonGoal.java | 30 +- .../goal/KillIronGolemGoal.java | 30 +- .../goal/KillSnowGolemGoal.java | 33 +- .../implementation/goal/KillWardenGoal.java | 28 +- .../implementation/goal/KillWitherGoal.java | 28 +- .../goal/LastManStandingGoal.java | 74 +- .../implementation/goal/MaxHeightGoal.java | 18 +- .../implementation/goal/MinHeightGoal.java | 18 +- .../goal/MineMostBlocksGoal.java | 30 +- .../implementation/goal/MostEmeraldsGoal.java | 102 +- .../implementation/goal/MostOresGoal.java | 114 +- .../implementation/goal/RaceGoal.java | 269 ++-- .../forcebattle/ExtremeForceBattleGoal.java | 444 +++---- .../ForceAdvancementBattleGoal.java | 136 +- .../forcebattle/ForceBiomeBattleGoal.java | 78 +- .../forcebattle/ForceBlockBattleGoal.java | 96 +- .../forcebattle/ForceDamageBattleGoal.java | 88 +- .../forcebattle/ForceHeightBattleGoal.java | 86 +- .../goal/forcebattle/ForceItemBattleGoal.java | 122 +- .../goal/forcebattle/ForceMobBattleGoal.java | 74 +- .../forcebattle/ForcePositionBattleGoal.java | 112 +- .../targets/AdvancementTarget.java | 90 +- .../goal/forcebattle/targets/BiomeTarget.java | 90 +- .../goal/forcebattle/targets/BlockTarget.java | 82 +- .../forcebattle/targets/DamageTarget.java | 76 +- .../goal/forcebattle/targets/ForceTarget.java | 56 +- .../forcebattle/targets/HeightTarget.java | 76 +- .../goal/forcebattle/targets/ItemTarget.java | 84 +- .../goal/forcebattle/targets/MobTarget.java | 92 +- .../forcebattle/targets/PositionTarget.java | 94 +- .../material/BlockMaterialSetting.java | 156 +-- .../setting/BackpackSetting.java | 264 ++-- .../setting/BastionSpawnSetting.java | 18 +- .../setting/CutCleanSetting.java | 382 +++--- .../setting/DamageDisplaySetting.java | 100 +- .../setting/DamageMultiplierModifier.java | 52 +- .../setting/DeathMessageSetting.java | 120 +- .../setting/DeathPositionSetting.java | 36 +- .../setting/DifficultySetting.java | 266 ++-- .../setting/EnderChestCommandSetting.java | 40 +- .../setting/FortressSpawnSetting.java | 16 +- .../setting/HealthDisplaySetting.java | 144 +-- .../setting/ImmediateRespawnSetting.java | 80 +- .../setting/KeepInventorySetting.java | 40 +- .../setting/LanguageSetting.java | 1 + .../setting/MaxHealthSetting.java | 193 +-- .../setting/MobGriefingSetting.java | 38 +- .../setting/NoHitDelaySetting.java | 32 +- .../setting/NoHungerSetting.java | 54 +- .../setting/NoItemDamageSetting.java | 36 +- .../setting/NoOffhandSetting.java | 78 +- .../implementation/setting/OldPvPSetting.java | 84 +- .../setting/OneTeamLifeSetting.java | 60 +- .../setting/PlayerGlowSetting.java | 70 +- .../setting/PositionSetting.java | 554 ++++---- .../setting/PregameMovementSetting.java | 74 +- .../implementation/setting/PvPSetting.java | 28 +- .../setting/RegenerationSetting.java | 82 +- .../setting/RespawnSetting.java | 85 +- .../setting/SlotLimitSetting.java | 260 ++-- .../implementation/setting/SoupSetting.java | 59 +- .../setting/SplitHealthSetting.java | 158 +-- .../implementation/setting/TimberSetting.java | 232 ++-- .../setting/TopCommandSetting.java | 90 +- .../setting/TotemSaveDeathSetting.java | 28 +- .../challenges/type/EmptyChallenge.java | 120 +- .../plugin/challenges/type/IChallenge.java | 102 +- .../plugin/challenges/type/IGoal.java | 68 +- .../plugin/challenges/type/IModifier.java | 16 +- .../type/abstraction/AbstractChallenge.java | 350 ++--- .../abstraction/AbstractForceChallenge.java | 164 +-- .../type/abstraction/CollectionGoal.java | 214 +-- .../CompletableForceChallenge.java | 66 +- .../abstraction/EndingForceChallenge.java | 76 +- .../type/abstraction/FindItemGoal.java | 64 +- .../abstraction/FirstPlayerAtHeightGoal.java | 68 +- .../abstraction/ForceBattleDisplayGoal.java | 182 +-- .../type/abstraction/ForceBattleGoal.java | 814 ++++++------ .../type/abstraction/HydraChallenge.java | 41 +- .../type/abstraction/ItemCollectionGoal.java | 82 +- .../type/abstraction/KillEntityGoal.java | 76 +- .../type/abstraction/KillMobsGoal.java | 156 +-- .../challenges/type/abstraction/MenuGoal.java | 38 +- .../type/abstraction/MenuSetting.java | 1150 ++++++++--------- .../challenges/type/abstraction/Modifier.java | 198 +-- .../abstraction/ModifierCollectionGoal.java | 178 ++- .../abstraction/NetherPortalSpawnSetting.java | 348 ++--- .../type/abstraction/OneEnabledSetting.java | 54 +- .../type/abstraction/PointsGoal.java | 174 +-- .../type/abstraction/RandomizerSetting.java | 94 +- .../challenges/type/abstraction/Setting.java | 154 +-- .../type/abstraction/SettingGoal.java | 50 +- .../type/abstraction/SettingModifier.java | 178 +-- .../SettingModifierCollectionGoal.java | 100 +- .../type/abstraction/SettingModifierGoal.java | 90 +- .../type/abstraction/TimedChallenge.java | 296 ++--- .../abstraction/WorldDependentChallenge.java | 258 ++-- .../type/helper/ChallengeConfigHelper.java | 22 +- .../type/helper/ChallengeHelper.java | 338 ++--- .../challenges/type/helper/GoalHelper.java | 232 ++-- .../type/helper/SubSettingsHelper.java | 270 ++-- .../plugin/content/ItemDescription.java | 244 ++-- .../challenges/plugin/content/Message.java | 84 +- .../challenges/plugin/content/Prefix.java | 92 +- .../plugin/content/impl/MessageImpl.java | 394 +++--- .../plugin/content/impl/MessageManager.java | 30 +- .../plugin/content/loader/ContentLoader.java | 32 +- .../plugin/content/loader/LanguageLoader.java | 328 ++--- .../plugin/content/loader/LoaderRegistry.java | 193 +-- .../plugin/content/loader/PrefixLoader.java | 42 +- .../plugin/content/loader/UpdateLoader.java | 70 +- .../management/bstats/MetricsLoader.java | 52 +- .../challenges/ChallengeManager.java | 448 +++---- .../challenges/ModuleChallengeLoader.java | 158 +-- .../cloud/support/CloudNet3Support.java | 76 +- .../plugin/management/menu/MenuManager.java | 232 ++-- .../menu/generator/ChooseItemGenerator.java | 152 +-- .../ChooseMultipleItemGenerator.java | 263 ++-- .../SmallCategorisedMenuGenerator.java | 24 +- .../implementation/SettingsMenuGenerator.java | 52 +- .../custom/IParentCustomGenerator.java | 14 +- .../custom/MaterialMenuGenerator.java | 66 +- .../custom/SubSettingChooseMenuGenerator.java | 50 +- ...SubSettingChooseMultipleMenuGenerator.java | 50 +- .../menu/info/ChallengeMenuClickInfo.java | 56 +- .../menu/position/GeneratorMenuPosition.java | 12 +- .../scheduler/AbstractTaskExecutor.java | 46 +- .../scheduler/PoliciesContainer.java | 66 +- .../scheduler/ScheduledTaskConfig.java | 21 +- .../scheduler/policy/TimerPolicy.java | 22 +- .../management/server/TitleManager.java | 56 +- .../management/stats/LeaderboardInfo.java | 14 +- .../plugin/management/stats/PlayerStats.java | 84 +- .../plugin/spigot/command/BackCommand.java | 164 +-- .../spigot/command/ChallengesCommand.java | 64 +- .../spigot/command/DatabaseCommand.java | 272 ++-- .../plugin/spigot/command/FeedCommand.java | 54 +- .../plugin/spigot/command/FlyCommand.java | 62 +- .../spigot/command/GamemodeCommand.java | 146 +-- .../spigot/command/GamestateCommand.java | 64 +- .../plugin/spigot/command/GodModeCommand.java | 98 +- .../plugin/spigot/command/HealCommand.java | 74 +- .../plugin/spigot/command/HelpCommand.java | 6 +- .../plugin/spigot/command/InvseeCommand.java | 206 +-- .../spigot/command/LanguageCommand.java | 48 +- .../spigot/command/LeaderboardCommand.java | 198 +-- .../plugin/spigot/command/ResetCommand.java | 146 +-- .../plugin/spigot/command/ResultCommand.java | 30 +- .../plugin/spigot/command/SearchCommand.java | 80 +- .../spigot/command/SkipTimerCommand.java | 30 +- .../plugin/spigot/command/StatsCommand.java | 176 +-- .../plugin/spigot/command/TimeCommand.java | 218 ++-- .../plugin/spigot/command/TimerCommand.java | 166 +-- .../plugin/spigot/command/VillageCommand.java | 40 +- .../plugin/spigot/command/WeatherCommand.java | 80 +- .../plugin/spigot/command/WorldCommand.java | 98 +- .../events/EntityDamageByPlayerEvent.java | 56 +- .../events/EntityDeathByPlayerEvent.java | 64 +- .../events/InventoryClickEventWrapper.java | 210 +-- .../events/PlayerIgnoreStatusChangeEvent.java | 42 +- .../events/PlayerInventoryClickEvent.java | 30 +- .../plugin/spigot/events/PlayerJumpEvent.java | 58 +- .../spigot/events/PlayerPickupItemEvent.java | 64 +- .../spigot/generator/VoidMapGenerator.java | 92 +- .../spigot/listener/BlockDropListener.java | 78 +- .../spigot/listener/ChatInputListener.java | 38 +- .../plugin/spigot/listener/CheatListener.java | 126 +- .../spigot/listener/CustomEventListener.java | 116 +- .../ExtraWorldRestrictionListener.java | 82 +- .../listener/GeneratorWorldsListener.java | 56 +- .../plugin/spigot/listener/HelpListener.java | 58 +- .../listener/PlayerConnectionListener.java | 253 ++-- .../spigot/listener/RestrictionListener.java | 274 ++-- .../listener/ScoreboardUpdateListener.java | 18 +- .../plugin/spigot/listener/StatsListener.java | 214 +-- .../utils/bukkit/command/Completer.java | 14 +- .../bukkit/command/ForwardingCommand.java | 44 +- .../utils/bukkit/command/PlayerCommand.java | 30 +- .../utils/bukkit/command/SenderCommand.java | 22 +- .../bukkit/container/BukkitSerialization.java | 266 ++-- .../utils/bukkit/container/PlayerData.java | 139 +- .../bukkit/jumpgeneration/IJumpGenerator.java | 6 +- .../jumpgeneration/RandomJumpGenerator.java | 90 +- .../utils/bukkit/misc/BukkitStringUtils.java | 533 ++++---- .../bukkit/misc/Version/MinecraftVersion.java | 206 +-- .../utils/bukkit/misc/Version/Version.java | 187 ++- .../misc/Version/VersionComparator.java | 12 +- .../bukkit/misc/Version/VersionInfo.java | 102 +- .../plugin/utils/bukkit/nms/NMSProvider.java | 180 +-- .../plugin/utils/bukkit/nms/NMSUtils.java | 100 +- .../utils/bukkit/nms/ReflectionUtil.java | 828 ++++++------ .../v1_13/BorderPacketFactory_1_13.java | 58 +- .../v1_13/CraftPlayer_1_13.java | 66 +- .../v1_13/PacketBorder_1_13.java | 174 +-- .../v1_13/PlayerConnection_1_13.java | 20 +- .../v1_13/WorldServer_1_13.java | 44 +- .../v1_17/BorderPacketFactory_1_17.java | 48 +- .../v1_17/CraftPlayer_1_17.java | 54 +- .../v1_17/PacketBorder_1_17.java | 14 +- .../v1_18/PacketBorder_1_18.java | 86 +- .../v1_18/PlayerConnection_1_18.java | 20 +- .../bukkit/nms/type/AbstractNMSClass.java | 20 +- .../bukkit/nms/type/BorderPacketFactory.java | 11 +- .../utils/bukkit/nms/type/BukkitNMSClass.java | 29 +- .../utils/bukkit/nms/type/CraftPlayer.java | 40 +- .../utils/bukkit/nms/type/PacketBorder.java | 266 ++-- .../bukkit/nms/type/PlayerConnection.java | 28 +- .../utils/bukkit/nms/type/WorldServer.java | 20 +- .../plugin/utils/item/DefaultItem.java | 146 +-- .../plugin/utils/item/ItemBuilder.java | 815 ++++++------ .../plugin/utils/item/ItemUtils.java | 186 +-- .../plugin/utils/logging/ConsolePrint.java | 120 +- .../plugin/utils/misc/ArmorUtils.java | 28 +- .../plugin/utils/misc/BlockUtils.java | 414 +++--- .../plugin/utils/misc/ColorConversions.java | 286 ++-- .../plugin/utils/misc/CommandHelper.java | 130 +- .../plugin/utils/misc/DatabaseHelper.java | 132 +- .../plugin/utils/misc/EntityUtils.java | 64 +- .../plugin/utils/misc/ExperimentalUtils.java | 11 +- .../plugin/utils/misc/FontUtils.java | 66 +- .../plugin/utils/misc/ImageUtils.java | 58 +- .../plugin/utils/misc/InventoryUtils.java | 392 +++--- .../plugin/utils/misc/ListBuilder.java | 124 +- .../plugin/utils/misc/MapUtils.java | 68 +- .../plugin/utils/misc/MemoryConverter.java | 10 +- .../utils/misc/MinecraftNameWrapper.java | 7 +- .../plugin/utils/misc/NameHelper.java | 40 +- .../plugin/utils/misc/ParticleUtils.java | 196 ++- .../plugin/utils/misc/StatsHelper.java | 100 +- .../plugin/utils/misc/StructureUtils.java | 82 +- .../plugin/utils/misc/TriConsumer.java | 2 +- .../plugin/utils/misc/TriFunction.java | 12 +- .../challenges/plugin/utils/misc/Utils.java | 78 +- 426 files changed, 24945 insertions(+), 24908 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java index 4b0da0fe4..3b8a554d1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java @@ -4,7 +4,10 @@ import net.anweisen.utilities.bukkit.core.BukkitModule; import net.anweisen.utilities.common.version.Version; import net.codingarea.challenges.plugin.challenges.custom.settings.CustomSettingsLoader; -import net.codingarea.challenges.plugin.content.loader.*; +import net.codingarea.challenges.plugin.content.loader.LanguageLoader; +import net.codingarea.challenges.plugin.content.loader.LoaderRegistry; +import net.codingarea.challenges.plugin.content.loader.PrefixLoader; +import net.codingarea.challenges.plugin.content.loader.UpdateLoader; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager; import net.codingarea.challenges.plugin.management.bstats.MetricsLoader; import net.codingarea.challenges.plugin.management.challenges.ChallengeLoader; @@ -28,191 +31,191 @@ @Getter public final class Challenges extends BukkitModule { - private static Challenges instance; - private PlayerInventoryManager playerInventoryManager; - private ScoreboardManager scoreboardManager; - private ChallengeManager challengeManager; - private BlockDropManager blockDropManager; - private ChallengeLoader challengeLoader; - private CustomChallengesLoader customChallengesLoader; - private CustomSettingsLoader customSettingsLoader; - private DatabaseManager databaseManager; - private CloudSupportManager cloudSupportManager; - private ServerManager serverManager; - private ConfigManager configManager; - private ScheduleManager scheduler; - private StatsManager statsManager; - private WorldManager worldManager; - private TitleManager titleManager; - private MenuManager menuManager; - private ChallengeTimer challengeTimer; - private LoaderRegistry loaderRegistry; - private MetricsLoader metricsLoader; - private GameWorldStorage gameWorldStorage; - private GeneratorWorldPortalManager generatorWorldPortalManager; - - @Nonnull - public static Challenges getInstance() { - return instance; - } - - @Override - protected void handleLoad() { - checkConfig(); - createManagers(); - loadManagers(); - } - - private void checkConfig() { - saveResource("hotbar-items.yml", false); - if (getConfigDocument().getVersion("config-version", Version.parse("1.0")).isOlderThan(Version.parse("2.0"))) { - saveResource("config.yml", true); - reloadConfig(); - getLogger().info("A deprecated config was found and replaced with a new one"); - } - } - - @Override - protected void handleEnable() { - enableManagers(); - - registerCommands(); - registerListeners(); - } - - private void createManagers() { - - configManager = new ConfigManager(); - configManager.loadConfigs(); - - loaderRegistry = new LoaderRegistry( - new LanguageLoader(), - new PrefixLoader(), - new UpdateLoader() - ); - - databaseManager = new DatabaseManager(); - worldManager = new WorldManager(); - serverManager = new ServerManager(); - scheduler = new ScheduleManager(); - scoreboardManager = new ScoreboardManager(); - cloudSupportManager = new CloudSupportManager(); - titleManager = new TitleManager(); - challengeTimer = new ChallengeTimer(); - blockDropManager = new BlockDropManager(); - challengeManager = new ChallengeManager(); - challengeLoader = new ChallengeLoader(); - customChallengesLoader = new CustomChallengesLoader(); - customSettingsLoader = new CustomSettingsLoader(); - menuManager = new MenuManager(); - playerInventoryManager = new PlayerInventoryManager(); - statsManager = new StatsManager(); - metricsLoader = new MetricsLoader(); - gameWorldStorage = new GameWorldStorage(); - generatorWorldPortalManager = new GeneratorWorldPortalManager(); - - } - - private void loadManagers() { - loaderRegistry.load(); - worldManager.load(); - } - - private void enableManagers() { - gameWorldStorage.enable(); - challengeLoader.enable(); - customSettingsLoader.enable(); - databaseManager.enable(); - worldManager.enable(); - challengeTimer.loadSession(); - challengeTimer.enable(); - challengeManager.enable(); - statsManager.register(); - scheduler.start(); - metricsLoader.start(); - - loaderRegistry.enable(); - } - - private void registerCommands() { - registerCommand(new HelpCommand(), "help"); - registerCommand(new ChallengesCommand(), "challenges"); - registerCommand(new TimerCommand(), "timer"); - registerCommand(new ForwardingCommand("timer start"), "start"); - registerCommand(new ForwardingCommand("timer pause"), "pause"); - registerCommand(new ResetCommand(), "reset"); - registerCommand(new StatsCommand(), "stats"); - registerCommand(new LeaderboardCommand(), "leaderboard"); - registerCommand(new DatabaseCommand(), "database"); - registerCommand(new GamestateCommand(), "gamestate"); - registerCommand(new VillageCommand(), "village"); - registerCommand(new HealCommand(), "heal"); - registerCommand(new FeedCommand(), "feed"); - registerCommand(new SearchCommand(), "search"); - registerListenerCommand(new InvseeCommand(), "invsee"); - registerCommand(new FlyCommand(), "fly"); - registerCommand(new WorldCommand(), "world"); - registerListenerCommand(new BackCommand(), "back"); - registerCommand(new GamemodeCommand(), "gamemode"); - registerCommand(new ForwardingCommand("gamemode 0", false), "gms"); - registerCommand(new ForwardingCommand("gamemode 1", false), "gmc"); - registerCommand(new ForwardingCommand("gamemode 2", false), "gma"); - registerCommand(new ForwardingCommand("gamemode 3", false), "gmsp"); - registerCommand(new WeatherCommand(), "weather"); - registerCommand(new ForwardingCommand("weather sun"), "sun"); - registerCommand(new ForwardingCommand("weather rain"), "rain"); - registerCommand(new ForwardingCommand("weather thunder"), "thunder"); - registerCommand(new TimeCommand(), "time"); - registerCommand(new ForwardingCommand("time set day"), "day"); - registerCommand(new ForwardingCommand("time set night"), "night"); - registerCommand(new ForwardingCommand("time set noon"), "noon"); - registerCommand(new ForwardingCommand("time set midnight"), "midnight"); - registerCommand(new ResultCommand(), "result"); - registerCommand(new SkipTimerCommand(), "skiptimer"); - registerCommand(new LanguageCommand(), "setlanguage"); - registerListenerCommand(new GodModeCommand(), "godmode"); - } - - private void registerListeners() { - registerListener( - new PlayerConnectionListener(), - new RestrictionListener(), - new ExtraWorldRestrictionListener(), - new CheatListener(), - new BlockDropListener(), - new CustomEventListener(), - new HelpListener(), - new ChatInputListener(), - new GeneratorWorldsListener(), - new ScoreboardUpdateListener() - ); - } - - @Override - protected void handleDisable() { - boolean shutdownBecauseOfReset = worldManager != null && worldManager.isShutdownBecauseOfReset(); - boolean restoreDefaultsOnReset = getConfigDocument().getBoolean("restore-defaults-on-reset"); - - if (playerInventoryManager != null) playerInventoryManager.handleDisable(); - if (challengeTimer != null && !shutdownBecauseOfReset) challengeTimer.saveSession(false); - if (scheduler != null) scheduler.stop(); - if (loaderRegistry != null) loaderRegistry.disable(); - if (databaseManager != null) databaseManager.disconnectIfConnected(); - if (scoreboardManager != null) scoreboardManager.disable(); - - if (challengeManager != null) { - challengeManager.shutdownChallenges(); - if (shutdownBecauseOfReset && restoreDefaultsOnReset) { - challengeManager.restoreDefaults(); - } - challengeManager.saveLocalSettings(false); - challengeManager.saveLocalCustomChallenges(false); - - if (!shutdownBecauseOfReset) { - challengeManager.saveGamestate(false); - } - challengeManager.clearChallengeCache(); - } - } + private static Challenges instance; + private PlayerInventoryManager playerInventoryManager; + private ScoreboardManager scoreboardManager; + private ChallengeManager challengeManager; + private BlockDropManager blockDropManager; + private ChallengeLoader challengeLoader; + private CustomChallengesLoader customChallengesLoader; + private CustomSettingsLoader customSettingsLoader; + private DatabaseManager databaseManager; + private CloudSupportManager cloudSupportManager; + private ServerManager serverManager; + private ConfigManager configManager; + private ScheduleManager scheduler; + private StatsManager statsManager; + private WorldManager worldManager; + private TitleManager titleManager; + private MenuManager menuManager; + private ChallengeTimer challengeTimer; + private LoaderRegistry loaderRegistry; + private MetricsLoader metricsLoader; + private GameWorldStorage gameWorldStorage; + private GeneratorWorldPortalManager generatorWorldPortalManager; + + @Nonnull + public static Challenges getInstance() { + return instance; + } + + @Override + protected void handleLoad() { + checkConfig(); + createManagers(); + loadManagers(); + } + + private void checkConfig() { + saveResource("hotbar-items.yml", false); + if (getConfigDocument().getVersion("config-version", Version.parse("1.0")).isOlderThan(Version.parse("2.0"))) { + saveResource("config.yml", true); + reloadConfig(); + getLogger().info("A deprecated config was found and replaced with a new one"); + } + } + + @Override + protected void handleEnable() { + enableManagers(); + + registerCommands(); + registerListeners(); + } + + private void createManagers() { + + configManager = new ConfigManager(); + configManager.loadConfigs(); + + loaderRegistry = new LoaderRegistry( + new LanguageLoader(), + new PrefixLoader(), + new UpdateLoader() + ); + + databaseManager = new DatabaseManager(); + worldManager = new WorldManager(); + serverManager = new ServerManager(); + scheduler = new ScheduleManager(); + scoreboardManager = new ScoreboardManager(); + cloudSupportManager = new CloudSupportManager(); + titleManager = new TitleManager(); + challengeTimer = new ChallengeTimer(); + blockDropManager = new BlockDropManager(); + challengeManager = new ChallengeManager(); + challengeLoader = new ChallengeLoader(); + customChallengesLoader = new CustomChallengesLoader(); + customSettingsLoader = new CustomSettingsLoader(); + menuManager = new MenuManager(); + playerInventoryManager = new PlayerInventoryManager(); + statsManager = new StatsManager(); + metricsLoader = new MetricsLoader(); + gameWorldStorage = new GameWorldStorage(); + generatorWorldPortalManager = new GeneratorWorldPortalManager(); + + } + + private void loadManagers() { + loaderRegistry.load(); + worldManager.load(); + } + + private void enableManagers() { + gameWorldStorage.enable(); + challengeLoader.enable(); + customSettingsLoader.enable(); + databaseManager.enable(); + worldManager.enable(); + challengeTimer.loadSession(); + challengeTimer.enable(); + challengeManager.enable(); + statsManager.register(); + scheduler.start(); + metricsLoader.start(); + + loaderRegistry.enable(); + } + + private void registerCommands() { + registerCommand(new HelpCommand(), "help"); + registerCommand(new ChallengesCommand(), "challenges"); + registerCommand(new TimerCommand(), "timer"); + registerCommand(new ForwardingCommand("timer start"), "start"); + registerCommand(new ForwardingCommand("timer pause"), "pause"); + registerCommand(new ResetCommand(), "reset"); + registerCommand(new StatsCommand(), "stats"); + registerCommand(new LeaderboardCommand(), "leaderboard"); + registerCommand(new DatabaseCommand(), "database"); + registerCommand(new GamestateCommand(), "gamestate"); + registerCommand(new VillageCommand(), "village"); + registerCommand(new HealCommand(), "heal"); + registerCommand(new FeedCommand(), "feed"); + registerCommand(new SearchCommand(), "search"); + registerListenerCommand(new InvseeCommand(), "invsee"); + registerCommand(new FlyCommand(), "fly"); + registerCommand(new WorldCommand(), "world"); + registerListenerCommand(new BackCommand(), "back"); + registerCommand(new GamemodeCommand(), "gamemode"); + registerCommand(new ForwardingCommand("gamemode 0", false), "gms"); + registerCommand(new ForwardingCommand("gamemode 1", false), "gmc"); + registerCommand(new ForwardingCommand("gamemode 2", false), "gma"); + registerCommand(new ForwardingCommand("gamemode 3", false), "gmsp"); + registerCommand(new WeatherCommand(), "weather"); + registerCommand(new ForwardingCommand("weather sun"), "sun"); + registerCommand(new ForwardingCommand("weather rain"), "rain"); + registerCommand(new ForwardingCommand("weather thunder"), "thunder"); + registerCommand(new TimeCommand(), "time"); + registerCommand(new ForwardingCommand("time set day"), "day"); + registerCommand(new ForwardingCommand("time set night"), "night"); + registerCommand(new ForwardingCommand("time set noon"), "noon"); + registerCommand(new ForwardingCommand("time set midnight"), "midnight"); + registerCommand(new ResultCommand(), "result"); + registerCommand(new SkipTimerCommand(), "skiptimer"); + registerCommand(new LanguageCommand(), "setlanguage"); + registerListenerCommand(new GodModeCommand(), "godmode"); + } + + private void registerListeners() { + registerListener( + new PlayerConnectionListener(), + new RestrictionListener(), + new ExtraWorldRestrictionListener(), + new CheatListener(), + new BlockDropListener(), + new CustomEventListener(), + new HelpListener(), + new ChatInputListener(), + new GeneratorWorldsListener(), + new ScoreboardUpdateListener() + ); + } + + @Override + protected void handleDisable() { + boolean shutdownBecauseOfReset = worldManager != null && worldManager.isShutdownBecauseOfReset(); + boolean restoreDefaultsOnReset = getConfigDocument().getBoolean("restore-defaults-on-reset"); + + if (playerInventoryManager != null) playerInventoryManager.handleDisable(); + if (challengeTimer != null && !shutdownBecauseOfReset) challengeTimer.saveSession(false); + if (scheduler != null) scheduler.stop(); + if (loaderRegistry != null) loaderRegistry.disable(); + if (databaseManager != null) databaseManager.disconnectIfConnected(); + if (scoreboardManager != null) scoreboardManager.disable(); + + if (challengeManager != null) { + challengeManager.shutdownChallenges(); + if (shutdownBecauseOfReset && restoreDefaultsOnReset) { + challengeManager.restoreDefaults(); + } + challengeManager.saveLocalSettings(false); + challengeManager.saveLocalCustomChallenges(false); + + if (!shutdownBecauseOfReset) { + challengeManager.saveGamestate(false); + } + challengeManager.clearChallengeCache(); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index e6035faf9..e0f17ae5a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -28,168 +28,168 @@ @ToString public class CustomChallenge extends Setting { - private final UUID uuid; - private Material material; - private String name; - private ChallengeTrigger trigger; - private Map subTriggers; - private ChallengeAction action; - private Map subActions; - - public CustomChallenge(MenuType menuType, UUID uuid, Material displayItem, String displayName, ChallengeTrigger trigger, - Map subTriggers, ChallengeAction action, Map subActions) { - super(menuType); - this.uuid = uuid; - this.material = displayItem; - this.name = displayName; - this.trigger = trigger; - this.subTriggers = subTriggers; - this.action = action; - this.subActions = subActions; - } - - @NotNull - @Override - public ItemStack getDisplayItem() { - String name = this.name; - if (name == null) { - name = "NULL"; - - } - Material material = this.material; - if (material == null) { - material = Material.BARRIER; - } - - ItemBuilder builder = new ItemBuilder(material, Message.forName("item-prefix").asString() + "§7" + name); - - // ADDING CONDITION INFO - if (getTrigger() != null) { - builder.appendLore(" "); - List triggerDisplay = InfoMenuGenerator - .getSubSettingsDisplay(getTrigger().getSubSettingsBuilder(), getSubTriggers()); - - String triggerName = Message.forName(getTrigger().getMessage()).asItemDescription().getName(); - builder.appendLore(Message.forName("custom-info-trigger").asString() + " " + triggerName); - builder.appendLore(triggerDisplay); - } - - // ADDING ACTION INFO - if (getAction() != null) { - builder.appendLore(" "); - List actionDisplay = InfoMenuGenerator - .getSubSettingsDisplay(getAction().getSubSettingsBuilder(), getSubActions()); - - String actionName = Message.forName(getAction().getMessage()).asItemDescription().getName(); - builder.appendLore(Message.forName("custom-info-action").asString() + " " + actionName); - builder.appendLore(actionDisplay); - } - - return builder.build(); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BARRIER); - } - - @Override - public void playStatusUpdateTitle() { - Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(enabled ? Message.forName("title-challenge-enabled") : Message.forName("title-challenge-disabled"), getDisplayName()); - } - - @Override - public void writeSettings(@Nonnull Document document) { - super.writeSettings(document); - - document.set("material", material == null ? null : material.name()); - document.set("name", name); - document.set("trigger", trigger == null ? null : trigger.getName()); - document.set("subTrigger", subTriggers); - document.set("action", action == null ? null : action.getName()); - document.set("subActions", subActions); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return super.getSettingsDescription(); - } - - public final void onTriggerFulfilled(ChallengeExecutionData challengeExecutionData) { - if (isEnabled()) { - - boolean triggerMet = isTriggerMet(challengeExecutionData.getTriggerData()); - if (triggerMet) { - executeAction(challengeExecutionData); - } - - } - } - - /** - * @return if the trigger is met. - * That is when every key in the subTriggers is contained by the data map and one or more value - * of the lists are equal to one another. - */ - public boolean isTriggerMet(Map> data) { - if (!subTriggers.isEmpty()) { - for (Entry entry : subTriggers.entrySet()) { - if (!data.containsKey(entry.getKey())) { - return false; - } - List list = data.get(entry.getKey()); - - boolean match = false; - for (String value : entry.getValue()) { - if (list.contains(value)) { - match = true; - break; - } - } - - if (!match) { - return false; - } - } - } - return true; - } - - public void executeAction(ChallengeExecutionData challengeExecutionData) { - if (!Bukkit.isPrimaryThread()) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - action.execute(challengeExecutionData, subActions); - }); - return; - } - action.execute(challengeExecutionData, subActions); - } - - public void applySettings(@Nonnull Material material, @Nonnull String name, @Nonnull ChallengeTrigger trigger, - Map subTriggers, ChallengeAction action, Map subActions) { - this.material = material; - this.name = name; - this.trigger = trigger; - this.subTriggers = subTriggers; - this.action = action; - this.subActions = subActions; - } - - public UUID getUniqueId() { - return uuid; - } - - @Nonnull - public String getDisplayName() { - return name; - } - - @NotNull - @Override - public String getUniqueName() { - return uuid.toString(); - } + private final UUID uuid; + private Material material; + private String name; + private ChallengeTrigger trigger; + private Map subTriggers; + private ChallengeAction action; + private Map subActions; + + public CustomChallenge(MenuType menuType, UUID uuid, Material displayItem, String displayName, ChallengeTrigger trigger, + Map subTriggers, ChallengeAction action, Map subActions) { + super(menuType); + this.uuid = uuid; + this.material = displayItem; + this.name = displayName; + this.trigger = trigger; + this.subTriggers = subTriggers; + this.action = action; + this.subActions = subActions; + } + + @NotNull + @Override + public ItemStack getDisplayItem() { + String name = this.name; + if (name == null) { + name = "NULL"; + + } + Material material = this.material; + if (material == null) { + material = Material.BARRIER; + } + + ItemBuilder builder = new ItemBuilder(material, Message.forName("item-prefix").asString() + "§7" + name); + + // ADDING CONDITION INFO + if (getTrigger() != null) { + builder.appendLore(" "); + List triggerDisplay = InfoMenuGenerator + .getSubSettingsDisplay(getTrigger().getSubSettingsBuilder(), getSubTriggers()); + + String triggerName = Message.forName(getTrigger().getMessage()).asItemDescription().getName(); + builder.appendLore(Message.forName("custom-info-trigger").asString() + " " + triggerName); + builder.appendLore(triggerDisplay); + } + + // ADDING ACTION INFO + if (getAction() != null) { + builder.appendLore(" "); + List actionDisplay = InfoMenuGenerator + .getSubSettingsDisplay(getAction().getSubSettingsBuilder(), getSubActions()); + + String actionName = Message.forName(getAction().getMessage()).asItemDescription().getName(); + builder.appendLore(Message.forName("custom-info-action").asString() + " " + actionName); + builder.appendLore(actionDisplay); + } + + return builder.build(); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BARRIER); + } + + @Override + public void playStatusUpdateTitle() { + Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(enabled ? Message.forName("title-challenge-enabled") : Message.forName("title-challenge-disabled"), getDisplayName()); + } + + @Override + public void writeSettings(@Nonnull Document document) { + super.writeSettings(document); + + document.set("material", material == null ? null : material.name()); + document.set("name", name); + document.set("trigger", trigger == null ? null : trigger.getName()); + document.set("subTrigger", subTriggers); + document.set("action", action == null ? null : action.getName()); + document.set("subActions", subActions); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return super.getSettingsDescription(); + } + + public final void onTriggerFulfilled(ChallengeExecutionData challengeExecutionData) { + if (isEnabled()) { + + boolean triggerMet = isTriggerMet(challengeExecutionData.getTriggerData()); + if (triggerMet) { + executeAction(challengeExecutionData); + } + + } + } + + /** + * @return if the trigger is met. + * That is when every key in the subTriggers is contained by the data map and one or more value + * of the lists are equal to one another. + */ + public boolean isTriggerMet(Map> data) { + if (!subTriggers.isEmpty()) { + for (Entry entry : subTriggers.entrySet()) { + if (!data.containsKey(entry.getKey())) { + return false; + } + List list = data.get(entry.getKey()); + + boolean match = false; + for (String value : entry.getValue()) { + if (list.contains(value)) { + match = true; + break; + } + } + + if (!match) { + return false; + } + } + } + return true; + } + + public void executeAction(ChallengeExecutionData challengeExecutionData) { + if (!Bukkit.isPrimaryThread()) { + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + action.execute(challengeExecutionData, subActions); + }); + return; + } + action.execute(challengeExecutionData, subActions); + } + + public void applySettings(@Nonnull Material material, @Nonnull String name, @Nonnull ChallengeTrigger trigger, + Map subTriggers, ChallengeAction action, Map subActions) { + this.material = material; + this.name = name; + this.trigger = trigger; + this.subTriggers = subTriggers; + this.action = action; + this.subActions = subActions; + } + + public UUID getUniqueId() { + return uuid; + } + + @Nonnull + public String getDisplayName() { + return name; + } + + @NotNull + @Override + public String getUniqueName() { + return uuid.toString(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java index 133327a32..0cde7dbe5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java @@ -17,78 +17,78 @@ public class ChallengeExecutionData { - @Getter - private final IChallengeTrigger trigger; - @Getter - private final Map> triggerData; - @Getter - private Entity entity; - private Runnable cancelAction; - @Getter - private int timesExecuting; - - public ChallengeExecutionData( - IChallengeTrigger trigger) { - this.trigger = trigger; - this.triggerData = new HashMap<>(); - } - - public ChallengeExecutionData data(String key, String data) { - triggerData.put(key, Collections.singletonList(data)); - return this; - } - - public ChallengeExecutionData data(String key, List data) { - triggerData.put(key, data); - return this; - } - - public ChallengeExecutionData data(String key, String... data) { - triggerData.put(key, Arrays.asList(data)); - return this; - } - - public ChallengeExecutionData block(Material material) { - return data(SubSettingsHelper.BLOCK, SubSettingsHelper.ANY, material.name()); - } - - public ChallengeExecutionData entityType(EntityType type) { - return data(SubSettingsHelper.ENTITY_TYPE, SubSettingsHelper.ANY, type.name()); - } - - public ChallengeExecutionData entity(Entity entity) { - this.entity = entity; - return this; - } - - public ChallengeExecutionData cancelAction(Runnable cancelAction) { - this.cancelAction = cancelAction; - return this; - } - - public ChallengeExecutionData event(Cancellable event) { - this.cancelAction = () -> event.setCancelled(true); - return this; - } - - public ChallengeExecutionData times(int timesExecuting) { - this.timesExecuting = timesExecuting; - return this; - } - - public void execute() { - if (ChallengeAPI.isStarted() && !ChallengeAPI.isWorldInUse()) { - if (entity instanceof Player && AbstractChallenge.ignorePlayer(((Player) entity))) { - return; - } - if (cancelAction != null) { - CancelEventAction.onPreTrigger(); - } - Challenges.getInstance().getCustomChallengesLoader().executeTrigger(this); - if (cancelAction != null && CancelEventAction.shouldCancel()) { - cancelAction.run(); - } - } - } + @Getter + private final IChallengeTrigger trigger; + @Getter + private final Map> triggerData; + @Getter + private Entity entity; + private Runnable cancelAction; + @Getter + private int timesExecuting; + + public ChallengeExecutionData( + IChallengeTrigger trigger) { + this.trigger = trigger; + this.triggerData = new HashMap<>(); + } + + public ChallengeExecutionData data(String key, String data) { + triggerData.put(key, Collections.singletonList(data)); + return this; + } + + public ChallengeExecutionData data(String key, List data) { + triggerData.put(key, data); + return this; + } + + public ChallengeExecutionData data(String key, String... data) { + triggerData.put(key, Arrays.asList(data)); + return this; + } + + public ChallengeExecutionData block(Material material) { + return data(SubSettingsHelper.BLOCK, SubSettingsHelper.ANY, material.name()); + } + + public ChallengeExecutionData entityType(EntityType type) { + return data(SubSettingsHelper.ENTITY_TYPE, SubSettingsHelper.ANY, type.name()); + } + + public ChallengeExecutionData entity(Entity entity) { + this.entity = entity; + return this; + } + + public ChallengeExecutionData cancelAction(Runnable cancelAction) { + this.cancelAction = cancelAction; + return this; + } + + public ChallengeExecutionData event(Cancellable event) { + this.cancelAction = () -> event.setCancelled(true); + return this; + } + + public ChallengeExecutionData times(int timesExecuting) { + this.timesExecuting = timesExecuting; + return this; + } + + public void execute() { + if (ChallengeAPI.isStarted() && !ChallengeAPI.isWorldInUse()) { + if (entity instanceof Player && AbstractChallenge.ignorePlayer(((Player) entity))) { + return; + } + if (cancelAction != null) { + CancelEventAction.onPreTrigger(); + } + Challenges.getInstance().getCustomChallengesLoader().executeTrigger(this); + if (cancelAction != null && CancelEventAction.shouldCancel()) { + cancelAction.run(); + } + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java index f0d9b2657..6ba0be71f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java @@ -6,34 +6,34 @@ public abstract class ChallengeSetting implements IChallengeSetting { - private final String name; - private final SubSettingsBuilder subSettingsBuilder; - - public ChallengeSetting(String name, SubSettingsBuilder subSettingsBuilder) { - this.name = name; - this.subSettingsBuilder = subSettingsBuilder.build(); - } - - public ChallengeSetting(String name) { - this(name, SubSettingsBuilder.createEmpty()); - } - - public ChallengeSetting(String name, Supplier builderSupplier) { - this(name, builderSupplier.get()); - } - - public String getMessageSuffix() { - return name.toLowerCase(); - } - - @Override - public SubSettingsBuilder getSubSettingsBuilder() { - return subSettingsBuilder; - } - - @Override - public String getName() { - return name; - } + private final String name; + private final SubSettingsBuilder subSettingsBuilder; + + public ChallengeSetting(String name, SubSettingsBuilder subSettingsBuilder) { + this.name = name; + this.subSettingsBuilder = subSettingsBuilder.build(); + } + + public ChallengeSetting(String name) { + this(name, SubSettingsBuilder.createEmpty()); + } + + public ChallengeSetting(String name, Supplier builderSupplier) { + this(name, builderSupplier.get()); + } + + public String getMessageSuffix() { + return name.toLowerCase(); + } + + @Override + public SubSettingsBuilder getSubSettingsBuilder() { + return subSettingsBuilder; + } + + @Override + public String getName() { + return name; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java index d1db4e40f..117bead96 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java @@ -17,143 +17,143 @@ public class CustomSettingsLoader { - @Getter - private final Map triggers; - private final Map fallbackTriggers; - - @Getter - private final Map actions; - private final Map fallbackActions; - - public CustomSettingsLoader() { - actions = new LinkedHashMap<>(); - fallbackActions = new LinkedHashMap<>(); - triggers = new LinkedHashMap<>(); - fallbackTriggers = new LinkedHashMap<>(); - } - - public void enable() { - loadTrigger(); - loadActions(); - } - - private void loadTrigger() { - registerTriggers( - new IntervallTrigger("intervall"), - new PlayerJumpTrigger("jump"), - new PlayerSneakTrigger("sneak"), - new MoveBlockTrigger("move_block"), - new BreakBlockTrigger("block_break"), - new PlaceBlockTrigger("block_place"), - new EntityDeathTrigger("death"), - new EntityDamageTrigger("damage"), - new EntityDamageByPlayerTrigger("damage_by_player"), - new ConsumeItemTrigger("consume_item"), - new PickupItemTrigger("pickup_item"), - new DropItemTrigger("drop_item"), - new AdvancementTrigger("advancement"), - new HungerTrigger("hunger"), - new MoveUpTrigger("move_up"), - new MoveDownTrigger("move_down"), - new MoveCameraTrigger("move_camera"), - new StandsOnSpecificBlockTrigger("stands_on_specific_block"), - new StandsNotOnSpecificBlockTrigger("stands_not_on_specific_block"), - new GainXPTrigger("gain_xp"), - new LevelUpTrigger("level_up"), - new CraftItemTrigger("item_craft"), - new InLiquidTrigger("in_liquid"), - new GetItemTrigger("get_item") - ); - } - - private void loadActions() { - registerActions( - new CancelEventAction("cancel"), - new WinChallengeAction("win"), - new ExecuteCommandAction("command"), - new KillEntityAction("kill"), - new DamageEntityAction("damage"), - new HealEntityAction("heal"), - new ModifyMaxHealthAction("max_health"), - new HungerPlayerAction("hunger"), - new SpawnEntityAction("spawn_entity"), - new RandomMobAction("random_mob"), - new RandomItemAction("random_item"), - new UncraftInventoryAction("uncraft_inventory"), - new BoostEntityInAirAction("boost_in_air"), - new PotionEffectAction("potion_effect"), - new AddPermanentEffectAction("permanent_effect"), - new RandomPotionEffectAction("random_effect"), - new ClearInventoryAction("clear_inventory"), - new DropRandomItemAction("drop_random_item"), - new RemoveRandomItemAction("remove_random_item"), - new SwapRandomItemAction("swap_random_item"), - new FreezeAction("freeze"), - new InvertHealthAction("invert_health"), - new WaterMLGAction("water_mlg"), - new JumpAndRunAction("jnr"), - new RandomHotBarAction("random_hotbar"), - new ChangeWorldBorderAction("modify_border"), - new SwapRandomMobAction("swap_mobs"), - new PlaceStructureAction("place_structure") - ); - } - - public void registerTriggers(ChallengeTrigger... trigger) { - for (ChallengeTrigger trigger1 : trigger) { - if (trigger1.getClass().isAnnotationPresent(RequireVersion.class)) { - RequireVersion requireVersion = trigger1.getClass().getAnnotation(RequireVersion.class); - MinecraftVersion minVersion = requireVersion.value(); - - if (!MinecraftVersion.current().isNewerOrEqualThan(minVersion)) { - Logger.debug("Did not register trigger {}, requires version {}, server running on {}", trigger1.getClass().getSimpleName(), minVersion, MinecraftVersion.current()); - continue; - } - } - if (trigger1.getClass().isAnnotationPresent(FallbackNames.class)) { - FallbackNames fallbackName = trigger1.getClass().getAnnotation(FallbackNames.class); - String[] fallbackNames = fallbackName.value(); - - for (String name : fallbackNames) { - fallbackTriggers.put(name, trigger1); - } - } - triggers.put(trigger1.getName(), trigger1); - Bukkit.getPluginManager().registerEvents(trigger1, Challenges.getInstance()); - } - } - - public void registerActions(ChallengeAction... action) { - for (ChallengeAction action1 : action) { - if (action1.getClass().isAnnotationPresent(RequireVersion.class)) { - RequireVersion requireVersion = action1.getClass().getAnnotation(RequireVersion.class); - MinecraftVersion minVersion = requireVersion.value(); - - if (!MinecraftVersion.current().isNewerOrEqualThan(minVersion)) { - Logger.debug("Did not register action {}, requires version {}, server running on {}", action1.getClass().getSimpleName(), minVersion, MinecraftVersion.current()); - continue; - } - } - if (action1.getClass().isAnnotationPresent(FallbackNames.class)) { - FallbackNames fallbackName = action1.getClass().getAnnotation(FallbackNames.class); - String[] fallbackNames = fallbackName.value(); - - for (String name : fallbackNames) { - fallbackActions.put(name, action1); - } - } - actions.put(action1.getName(), action1); - } - } - - @Nullable - public ChallengeAction getActionByName(String name) { - return actions.getOrDefault(name, fallbackActions.get(name)); - } - - @Nullable - public ChallengeTrigger getTriggerByName(String name) { - return triggers.getOrDefault(name, fallbackTriggers.get(name)); - } + @Getter + private final Map triggers; + private final Map fallbackTriggers; + + @Getter + private final Map actions; + private final Map fallbackActions; + + public CustomSettingsLoader() { + actions = new LinkedHashMap<>(); + fallbackActions = new LinkedHashMap<>(); + triggers = new LinkedHashMap<>(); + fallbackTriggers = new LinkedHashMap<>(); + } + + public void enable() { + loadTrigger(); + loadActions(); + } + + private void loadTrigger() { + registerTriggers( + new IntervallTrigger("intervall"), + new PlayerJumpTrigger("jump"), + new PlayerSneakTrigger("sneak"), + new MoveBlockTrigger("move_block"), + new BreakBlockTrigger("block_break"), + new PlaceBlockTrigger("block_place"), + new EntityDeathTrigger("death"), + new EntityDamageTrigger("damage"), + new EntityDamageByPlayerTrigger("damage_by_player"), + new ConsumeItemTrigger("consume_item"), + new PickupItemTrigger("pickup_item"), + new DropItemTrigger("drop_item"), + new AdvancementTrigger("advancement"), + new HungerTrigger("hunger"), + new MoveUpTrigger("move_up"), + new MoveDownTrigger("move_down"), + new MoveCameraTrigger("move_camera"), + new StandsOnSpecificBlockTrigger("stands_on_specific_block"), + new StandsNotOnSpecificBlockTrigger("stands_not_on_specific_block"), + new GainXPTrigger("gain_xp"), + new LevelUpTrigger("level_up"), + new CraftItemTrigger("item_craft"), + new InLiquidTrigger("in_liquid"), + new GetItemTrigger("get_item") + ); + } + + private void loadActions() { + registerActions( + new CancelEventAction("cancel"), + new WinChallengeAction("win"), + new ExecuteCommandAction("command"), + new KillEntityAction("kill"), + new DamageEntityAction("damage"), + new HealEntityAction("heal"), + new ModifyMaxHealthAction("max_health"), + new HungerPlayerAction("hunger"), + new SpawnEntityAction("spawn_entity"), + new RandomMobAction("random_mob"), + new RandomItemAction("random_item"), + new UncraftInventoryAction("uncraft_inventory"), + new BoostEntityInAirAction("boost_in_air"), + new PotionEffectAction("potion_effect"), + new AddPermanentEffectAction("permanent_effect"), + new RandomPotionEffectAction("random_effect"), + new ClearInventoryAction("clear_inventory"), + new DropRandomItemAction("drop_random_item"), + new RemoveRandomItemAction("remove_random_item"), + new SwapRandomItemAction("swap_random_item"), + new FreezeAction("freeze"), + new InvertHealthAction("invert_health"), + new WaterMLGAction("water_mlg"), + new JumpAndRunAction("jnr"), + new RandomHotBarAction("random_hotbar"), + new ChangeWorldBorderAction("modify_border"), + new SwapRandomMobAction("swap_mobs"), + new PlaceStructureAction("place_structure") + ); + } + + public void registerTriggers(ChallengeTrigger... trigger) { + for (ChallengeTrigger trigger1 : trigger) { + if (trigger1.getClass().isAnnotationPresent(RequireVersion.class)) { + RequireVersion requireVersion = trigger1.getClass().getAnnotation(RequireVersion.class); + MinecraftVersion minVersion = requireVersion.value(); + + if (!MinecraftVersion.current().isNewerOrEqualThan(minVersion)) { + Logger.debug("Did not register trigger {}, requires version {}, server running on {}", trigger1.getClass().getSimpleName(), minVersion, MinecraftVersion.current()); + continue; + } + } + if (trigger1.getClass().isAnnotationPresent(FallbackNames.class)) { + FallbackNames fallbackName = trigger1.getClass().getAnnotation(FallbackNames.class); + String[] fallbackNames = fallbackName.value(); + + for (String name : fallbackNames) { + fallbackTriggers.put(name, trigger1); + } + } + triggers.put(trigger1.getName(), trigger1); + Bukkit.getPluginManager().registerEvents(trigger1, Challenges.getInstance()); + } + } + + public void registerActions(ChallengeAction... action) { + for (ChallengeAction action1 : action) { + if (action1.getClass().isAnnotationPresent(RequireVersion.class)) { + RequireVersion requireVersion = action1.getClass().getAnnotation(RequireVersion.class); + MinecraftVersion minVersion = requireVersion.value(); + + if (!MinecraftVersion.current().isNewerOrEqualThan(minVersion)) { + Logger.debug("Did not register action {}, requires version {}, server running on {}", action1.getClass().getSimpleName(), minVersion, MinecraftVersion.current()); + continue; + } + } + if (action1.getClass().isAnnotationPresent(FallbackNames.class)) { + FallbackNames fallbackName = action1.getClass().getAnnotation(FallbackNames.class); + String[] fallbackNames = fallbackName.value(); + + for (String name : fallbackNames) { + fallbackActions.put(name, action1); + } + } + actions.put(action1.getName(), action1); + } + } + + @Nullable + public ChallengeAction getActionByName(String name) { + return actions.getOrDefault(name, fallbackActions.get(name)); + } + + @Nullable + public ChallengeTrigger getTriggerByName(String name) { + return triggers.getOrDefault(name, fallbackTriggers.get(name)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java index ab5798085..dc64e015f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java @@ -10,7 +10,7 @@ @Retention(RetentionPolicy.RUNTIME) public @interface FallbackNames { - @Nonnull - String[] value(); + @Nonnull + String[] value(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java index 1c91e30be..087837cca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java @@ -5,12 +5,12 @@ public interface IChallengeSetting { - SubSettingsBuilder getSubSettingsBuilder(); + SubSettingsBuilder getSubSettingsBuilder(); - String getName(); + String getName(); - Material getMaterial(); + Material getMaterial(); - String getMessage(); + String getMessage(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/SettingType.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/SettingType.java index 7946471d7..b8c06e97c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/SettingType.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/SettingType.java @@ -2,8 +2,8 @@ public enum SettingType { - CONDITION, - MATERIAL, - ACTION + CONDITION, + MATERIAL, + ACTION } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java index 56f9a5b34..586ff2b89 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java @@ -12,36 +12,36 @@ import java.util.function.Supplier; public abstract class ChallengeAction extends ChallengeSetting implements - IChallengeAction { + IChallengeAction { - protected static final IRandom random = IRandom.create(); + protected static final IRandom random = IRandom.create(); - public ChallengeAction(String name, - SubSettingsBuilder subSettingsBuilder) { - super(name, subSettingsBuilder); - } + public ChallengeAction(String name, + SubSettingsBuilder subSettingsBuilder) { + super(name, subSettingsBuilder); + } - public ChallengeAction(String name) { - super(name); - } + public ChallengeAction(String name) { + super(name); + } - public ChallengeAction(String name, Supplier builderSupplier) { - super(name, builderSupplier); - } + public ChallengeAction(String name, Supplier builderSupplier) { + super(name, builderSupplier); + } - public static LinkedHashMap getMenuItems() { - LinkedHashMap map = new LinkedHashMap<>(); + public static LinkedHashMap getMenuItems() { + LinkedHashMap map = new LinkedHashMap<>(); - for (ChallengeAction value : Challenges.getInstance().getCustomSettingsLoader().getActions().values()) { - map.put(value.getName(), new ItemBuilder(value.getMaterial(), Message.forName(value.getMessage())).hideAttributes().build()); - } + for (ChallengeAction value : Challenges.getInstance().getCustomSettingsLoader().getActions().values()) { + map.put(value.getName(), new ItemBuilder(value.getMaterial(), Message.forName(value.getMessage())).hideAttributes().build()); + } - return map; - } + return map; + } - @Override - public final String getMessage() { - return "item-custom-action-" + getMessageSuffix(); - } + @Override + public final String getMessage() { + return "item-custom-action-" + getMessageSuffix(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java index f34860630..f57c55daf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java @@ -6,17 +6,17 @@ public abstract class EntityTargetAction extends ChallengeAction implements IEntityTargetAction { - public EntityTargetAction(String name, - SubSettingsBuilder subSettingsBuilder) { - super(name, subSettingsBuilder); - } + public EntityTargetAction(String name, + SubSettingsBuilder subSettingsBuilder) { + super(name, subSettingsBuilder); + } - public EntityTargetAction(String name) { - super(name); - } + public EntityTargetAction(String name) { + super(name); + } - public EntityTargetAction(String name, Supplier builderSupplier) { - super(name, builderSupplier); - } + public EntityTargetAction(String name, Supplier builderSupplier) { + super(name, builderSupplier); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java index fe2536bf4..a452f268a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java @@ -7,8 +7,8 @@ public interface IChallengeAction { - IRandom random = IRandom.create(); + IRandom random = IRandom.create(); - void execute(ChallengeExecutionData executionData, Map subActions); + void execute(ChallengeExecutionData executionData, Map subActions); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java index 6ac64ace4..d03ef8cf7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IEntityTargetAction.java @@ -17,64 +17,64 @@ public interface IEntityTargetAction extends IChallengeAction { - static List getTargets(Entity triggerTarget, Map subActions) { - return getTargets(triggerTarget, subActions, SubSettingsHelper.TARGET_ENTITY); - } + static List getTargets(Entity triggerTarget, Map subActions) { + return getTargets(triggerTarget, subActions, SubSettingsHelper.TARGET_ENTITY); + } - static List getTargets(Entity triggerTarget, Map subActions, String key) { - if (!subActions.containsKey(key)) { - return Lists.newLinkedList(); - } - String targetEntity = subActions.get(key)[0]; + static List getTargets(Entity triggerTarget, Map subActions, String key) { + if (!subActions.containsKey(key)) { + return Lists.newLinkedList(); + } + String targetEntity = subActions.get(key)[0]; - switch (targetEntity) { - case "random_player": - List players = ChallengeAPI.getIngamePlayers(); - if (players.isEmpty()) return new LinkedList<>(); - return Collections.singletonList(players.get(random.nextInt(players.size()))); - case "every_player": - return Lists.newLinkedList(ChallengeAPI.getIngamePlayers()); - case "current_player": - return triggerTarget instanceof Player ? Lists.newArrayList(triggerTarget) : Lists.newLinkedList(); - case "every_mob": - List everyList = Lists.newLinkedList(); - for (World world : ChallengeAPI.getGameWorlds()) { - everyList.addAll(world.getLivingEntities()); - } - return everyList; - case "every_mob_except_current": - List exceptList = Lists.newLinkedList(); - for (World world : ChallengeAPI.getGameWorlds()) { - exceptList.addAll(world.getLivingEntities()); - } - exceptList.remove(triggerTarget); - return exceptList; - case "every_mob_except_players": - List noPlayers = Lists.newLinkedList(); - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - if (entity.getType() == EntityType.PLAYER) continue; - noPlayers.add(entity); - } - } + switch (targetEntity) { + case "random_player": + List players = ChallengeAPI.getIngamePlayers(); + if (players.isEmpty()) return new LinkedList<>(); + return Collections.singletonList(players.get(random.nextInt(players.size()))); + case "every_player": + return Lists.newLinkedList(ChallengeAPI.getIngamePlayers()); + case "current_player": + return triggerTarget instanceof Player ? Lists.newArrayList(triggerTarget) : Lists.newLinkedList(); + case "every_mob": + List everyList = Lists.newLinkedList(); + for (World world : ChallengeAPI.getGameWorlds()) { + everyList.addAll(world.getLivingEntities()); + } + return everyList; + case "every_mob_except_current": + List exceptList = Lists.newLinkedList(); + for (World world : ChallengeAPI.getGameWorlds()) { + exceptList.addAll(world.getLivingEntities()); + } + exceptList.remove(triggerTarget); + return exceptList; + case "every_mob_except_players": + List noPlayers = Lists.newLinkedList(); + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + if (entity.getType() == EntityType.PLAYER) continue; + noPlayers.add(entity); + } + } - return noPlayers; - case "console": - return Collections.singletonList(null); - } - if (triggerTarget == null) { - return Lists.newLinkedList(); - } - return Lists.newArrayList(triggerTarget); - } + return noPlayers; + case "console": + return Collections.singletonList(null); + } + if (triggerTarget == null) { + return Lists.newLinkedList(); + } + return Lists.newArrayList(triggerTarget); + } - @Override - default void execute(ChallengeExecutionData executionData, Map subActions) { - for (Entity target : getTargets(executionData.getEntity(), subActions)) { - executeFor(target, subActions); - } - } + @Override + default void execute(ChallengeExecutionData executionData, Map subActions) { + for (Entity target : getTargets(executionData.getEntity(), subActions)) { + executeFor(target, subActions); + } + } - void executeFor(Entity entity, Map subActions); + void executeFor(Entity entity, Map subActions); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java index 2e9b11cad..32fb6d6fd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java @@ -9,27 +9,27 @@ public abstract class PlayerTargetAction extends EntityTargetAction { - public PlayerTargetAction(String name, SubSettingsBuilder subSettingsBuilder) { - super(name, subSettingsBuilder); - } - - public PlayerTargetAction(String name) { - super(name); - } - - public PlayerTargetAction(String name, - Supplier builderSupplier) { - super(name, builderSupplier); - } - - @Override - public void executeFor(Entity entity, Map subActions) { - // Entity is null if the target entity is the console - if (entity instanceof Player || entity == null) { - executeForPlayer(((Player) entity), subActions); - } - } - - public abstract void executeForPlayer(Player player, Map subActions); + public PlayerTargetAction(String name, SubSettingsBuilder subSettingsBuilder) { + super(name, subSettingsBuilder); + } + + public PlayerTargetAction(String name) { + super(name); + } + + public PlayerTargetAction(String name, + Supplier builderSupplier) { + super(name, builderSupplier); + } + + @Override + public void executeFor(Entity entity, Map subActions) { + // Entity is null if the target entity is the console + if (entity instanceof Player || entity == null) { + executeForPlayer(((Player) entity), subActions); + } + } + + public abstract void executeForPlayer(Player player, Map subActions); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java index a840f4134..a3d5d0dfc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java @@ -11,22 +11,22 @@ public class AddPermanentEffectAction extends PlayerTargetAction { - PermanentEffectOnDamageChallenge instance = AbstractChallenge - .getFirstInstance(PermanentEffectOnDamageChallenge.class); - - public AddPermanentEffectAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } - - @Override - public Material getMaterial() { - return Material.MAGMA_CREAM; - } - - @Override - public void executeForPlayer(Player player, Map subActions) { - instance.addRandomEffect(player); - instance.updateEffects(); - } + PermanentEffectOnDamageChallenge instance = AbstractChallenge + .getFirstInstance(PermanentEffectOnDamageChallenge.class); + + public AddPermanentEffectAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } + + @Override + public Material getMaterial() { + return Material.MAGMA_CREAM; + } + + @Override + public void executeForPlayer(Player player, Map subActions) { + instance.addRandomEffect(player); + instance.updateEffects(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java index 2d27dd98a..fc56b49a4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java @@ -14,35 +14,35 @@ public class BoostEntityInAirAction extends EntityTargetAction { - public BoostEntityInAirAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createValueChild().fill(builder -> { - builder.addModifierSetting("strength", - new ItemBuilder(Material.FEATHER, Message.forName("item-custom-action-boost_in_air-strength")), - 1, 1, 10, - value -> Message.forName("amplifier").asString(), - integer -> "" - ); - })); - } - - @Override - public Material getMaterial() { - return Material.FEATHER; - } - - @Override - public void executeFor(Entity entity, Map subActions) { - - int strength = 1; - try { - strength = Integer.parseInt(subActions.get("strength")[0]); - } catch (NumberFormatException exception) { - Logger.error("", exception); - } - - Vector velocityToAdd = new Vector(0, 1, 0).multiply(strength); - Vector newVelocity = EntityUtils.getSucceedingVelocity(entity.getVelocity()).add(velocityToAdd); - entity.setVelocity(newVelocity); - } + public BoostEntityInAirAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createValueChild().fill(builder -> { + builder.addModifierSetting("strength", + new ItemBuilder(Material.FEATHER, Message.forName("item-custom-action-boost_in_air-strength")), + 1, 1, 10, + value -> Message.forName("amplifier").asString(), + integer -> "" + ); + })); + } + + @Override + public Material getMaterial() { + return Material.FEATHER; + } + + @Override + public void executeFor(Entity entity, Map subActions) { + + int strength = 1; + try { + strength = Integer.parseInt(subActions.get("strength")[0]); + } catch (NumberFormatException exception) { + Logger.error("", exception); + } + + Vector velocityToAdd = new Vector(0, 1, 0).multiply(strength); + Vector newVelocity = EntityUtils.getSucceedingVelocity(entity.getVelocity()).add(velocityToAdd); + entity.setVelocity(newVelocity); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java index 717aa170c..2fb034f66 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java @@ -8,32 +8,32 @@ public class CancelEventAction extends ChallengeAction { - public static boolean inCanceling; - - public CancelEventAction(String name) { - super(name); - } - - public static void onPreTrigger() { - inCanceling = false; - } - - public static boolean shouldCancel() { - if (inCanceling) { - inCanceling = false; - return true; - } - return false; - } - - @Override - public Material getMaterial() { - return Material.BARRIER; - } - - @Override - public void execute(ChallengeExecutionData executionData, Map subActions) { - inCanceling = true; - } + public static boolean inCanceling; + + public CancelEventAction(String name) { + super(name); + } + + public static void onPreTrigger() { + inCanceling = false; + } + + public static boolean shouldCancel() { + if (inCanceling) { + inCanceling = false; + return true; + } + return false; + } + + @Override + public Material getMaterial() { + return Material.BARRIER; + } + + @Override + public void execute(ChallengeExecutionData executionData, Map subActions) { + inCanceling = true; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java index e8a231c5c..2180fcc5e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java @@ -15,37 +15,37 @@ public class ChangeWorldBorderAction extends ChallengeAction { - public ChangeWorldBorderAction(String name) { - super(name, SubSettingsBuilder.createValueItem() - .addModifierSetting( - "change", - new ItemBuilder(Material.MAGENTA_GLAZED_TERRACOTTA, Message.forName("item-custom-action-modify_border-change")), - 1, -10, 10 - )); - } - - @Override - public Material getMaterial() { - return Material.STRUCTURE_VOID; - } - - @Override - public void execute(ChallengeExecutionData executionData, Map subActions) { - - try { - int change = Integer.parseInt(subActions.get("change")[0]); - - for (World world : ChallengeAPI.getGameWorlds()) { - WorldBorder border = world.getWorldBorder(); - if (border.getSize() + change >= 1) { // Don't change if it gets under 1 - border.setSize(border.getSize() + change); - } - } - - } catch (NumberFormatException | IndexOutOfBoundsException ex) { - Logger.error("Error while accessing change border action values", ex); - } - - } + public ChangeWorldBorderAction(String name) { + super(name, SubSettingsBuilder.createValueItem() + .addModifierSetting( + "change", + new ItemBuilder(Material.MAGENTA_GLAZED_TERRACOTTA, Message.forName("item-custom-action-modify_border-change")), + 1, -10, 10 + )); + } + + @Override + public Material getMaterial() { + return Material.STRUCTURE_VOID; + } + + @Override + public void execute(ChallengeExecutionData executionData, Map subActions) { + + try { + int change = Integer.parseInt(subActions.get("change")[0]); + + for (World world : ChallengeAPI.getGameWorlds()) { + WorldBorder border = world.getWorldBorder(); + if (border.getSize() + change >= 1) { // Don't change if it gets under 1 + border.setSize(border.getSize() + change); + } + } + + } catch (NumberFormatException | IndexOutOfBoundsException ex) { + Logger.error("Error while accessing change border action values", ex); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java index 142e3a0ca..d5408346f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java @@ -9,18 +9,18 @@ public class ClearInventoryAction extends PlayerTargetAction { - public ClearInventoryAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } + public ClearInventoryAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } - @Override - public Material getMaterial() { - return Material.TRAPPED_CHEST; - } + @Override + public Material getMaterial() { + return Material.TRAPPED_CHEST; + } - @Override - public void executeForPlayer(Player player, Map subActions) { - player.getInventory().clear(); - } + @Override + public void executeForPlayer(Player player, Map subActions) { + player.getInventory().clear(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java index 8120fbc93..290f11e2b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java @@ -12,29 +12,29 @@ public class DamageEntityAction extends EntityTargetAction { - public DamageEntityAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createChooseItemChild("amount").fill(builder -> { - String prefix = DefaultItem.getItemPrefix(); - for (int i = 1; i < 21; i++) { - builder.addSetting( - String.valueOf(i), new ItemBuilder(Material.FERMENTED_SPIDER_EYE, prefix + "§7" + (i / 2f) + " §c❤").setAmount(i).build()); - } - })); - } + public DamageEntityAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createChooseItemChild("amount").fill(builder -> { + String prefix = DefaultItem.getItemPrefix(); + for (int i = 1; i < 21; i++) { + builder.addSetting( + String.valueOf(i), new ItemBuilder(Material.FERMENTED_SPIDER_EYE, prefix + "§7" + (i / 2f) + " §c❤").setAmount(i).build()); + } + })); + } - @Override - public void executeFor(Entity entity, Map subActions) { - int amount = Integer.parseInt(subActions.get("amount")[0]); - if (entity instanceof LivingEntity) { - ((LivingEntity) entity).setNoDamageTicks(0); - ((LivingEntity) entity).damage(amount); - ((LivingEntity) entity).setNoDamageTicks(0); - } - } + @Override + public void executeFor(Entity entity, Map subActions) { + int amount = Integer.parseInt(subActions.get("amount")[0]); + if (entity instanceof LivingEntity) { + ((LivingEntity) entity).setNoDamageTicks(0); + ((LivingEntity) entity).damage(amount); + ((LivingEntity) entity).setNoDamageTicks(0); + } + } - @Override - public Material getMaterial() { - return Material.FERMENTED_SPIDER_EYE; - } + @Override + public Material getMaterial() { + return Material.FERMENTED_SPIDER_EYE; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java index 6e38e0df8..c8d0d74b6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java @@ -10,18 +10,18 @@ public class DropRandomItemAction extends PlayerTargetAction { - public DropRandomItemAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } + public DropRandomItemAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } - @Override - public Material getMaterial() { - return Material.DISPENSER; - } + @Override + public Material getMaterial() { + return Material.DISPENSER; + } - @Override - public void executeForPlayer(Player player, Map subActions) { - RandomItemDroppingChallenge.dropRandomItem(player); - } + @Override + public void executeForPlayer(Player player, Map subActions) { + RandomItemDroppingChallenge.dropRandomItem(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java index a66818c4f..8a2066b96 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java @@ -15,46 +15,46 @@ public class ExecuteCommandAction extends PlayerTargetAction { - // Static because cannot be accessed before super has been called - public static int maxCommandLength = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-command-length"); - private static List commandsThatCanBeExecuted = Challenges.getInstance().getConfigDocument().getStringList("custom-challenge-settings.allowed-commands-to-execute"); - - public ExecuteCommandAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true, true, true).createTextInputChild("command", player -> { - Message.forName("custom-command-info").send(player, Prefix.CUSTOM, "/" + String.join(" /", commandsThatCanBeExecuted)); - }, event -> { - String cmd = event.getMessage().split(" ")[0].toLowerCase(); - - if (!commandsThatCanBeExecuted.contains(cmd)) { - Message.forName("custom-command-not-allowed").send(event.getPlayer(), Prefix.CUSTOM, cmd); - return false; - } - - if (event.getMessage().length() > maxCommandLength) { - Message.forName("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxCommandLength); - return false; - } - return true; - })); - // Reload from config on reload - maxCommandLength = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-command-length"); - commandsThatCanBeExecuted = Challenges.getInstance().getConfigDocument().getStringList("custom-challenge-settings.allowed-commands-to-execute"); - } - - @Override - public void executeForPlayer(Player player, Map subActions) { - String fullCommand = subActions.get("command")[0]; - - CommandSender sender = Bukkit.getConsoleSender(); - if (player != null) { - fullCommand = "execute as " + player.getName() + " at " + player.getName() + " run " + fullCommand; - } - - Bukkit.getServer().dispatchCommand(sender, fullCommand); - } - - @Override - public Material getMaterial() { - return Material.COMMAND_BLOCK; - } + // Static because cannot be accessed before super has been called + public static int maxCommandLength = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-command-length"); + private static List commandsThatCanBeExecuted = Challenges.getInstance().getConfigDocument().getStringList("custom-challenge-settings.allowed-commands-to-execute"); + + public ExecuteCommandAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true, true, true).createTextInputChild("command", player -> { + Message.forName("custom-command-info").send(player, Prefix.CUSTOM, "/" + String.join(" /", commandsThatCanBeExecuted)); + }, event -> { + String cmd = event.getMessage().split(" ")[0].toLowerCase(); + + if (!commandsThatCanBeExecuted.contains(cmd)) { + Message.forName("custom-command-not-allowed").send(event.getPlayer(), Prefix.CUSTOM, cmd); + return false; + } + + if (event.getMessage().length() > maxCommandLength) { + Message.forName("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxCommandLength); + return false; + } + return true; + })); + // Reload from config on reload + maxCommandLength = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-command-length"); + commandsThatCanBeExecuted = Challenges.getInstance().getConfigDocument().getStringList("custom-challenge-settings.allowed-commands-to-execute"); + } + + @Override + public void executeForPlayer(Player player, Map subActions) { + String fullCommand = subActions.get("command")[0]; + + CommandSender sender = Bukkit.getConsoleSender(); + if (player != null) { + fullCommand = "execute as " + player.getName() + " at " + player.getName() + " run " + fullCommand; + } + + Bukkit.getServer().dispatchCommand(sender, fullCommand); + } + + @Override + public Material getMaterial() { + return Material.COMMAND_BLOCK; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java index 8cb0ef400..4123e255f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java @@ -12,27 +12,27 @@ public class FreezeAction extends EntityTargetAction { - FreezeChallenge instance = AbstractChallenge - .getFirstInstance(FreezeChallenge.class); + FreezeChallenge instance = AbstractChallenge + .getFirstInstance(FreezeChallenge.class); - public FreezeAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true)); - } + public FreezeAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true)); + } - @Override - public Material getMaterial() { - return Material.ICE; - } + @Override + public Material getMaterial() { + return Material.ICE; + } - @Override - public void executeFor(Entity entity, Map subActions) { + @Override + public void executeFor(Entity entity, Map subActions) { - if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; - instance.setFreeze(livingEntity, 2); - } + if (entity instanceof LivingEntity) { + LivingEntity livingEntity = (LivingEntity) entity; + instance.setFreeze(livingEntity, 2); + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java index b0c3740b9..8044df01f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java @@ -15,34 +15,34 @@ public class HealEntityAction extends EntityTargetAction { - public HealEntityAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createChooseItemChild("amount").fill(builder -> { - String prefix = DefaultItem.getItemPrefix(); - for (int i = 1; i < 21; i++) { - builder.addSetting( - String.valueOf(i), new ItemBuilder( - MinecraftNameWrapper.RED_DYE, prefix + "§7" + (i / 2f) + " §c❤").setAmount(i).build()); - } - })); - } - - @Override - public void executeFor(Entity entity, Map subActions) { - int amount = Integer.parseInt(subActions.get("amount")[0]); - if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; - AttributeInstance attribute = livingEntity.getAttribute(AttributeWrapper.MAX_HEALTH); - - if (attribute == null) return; - double newHealth = Math.min(livingEntity.getHealth() + amount, - attribute.getBaseValue()); - livingEntity.setHealth(newHealth); - } - } - - @Override - public Material getMaterial() { - return Material.GOLDEN_APPLE; - } + public HealEntityAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createChooseItemChild("amount").fill(builder -> { + String prefix = DefaultItem.getItemPrefix(); + for (int i = 1; i < 21; i++) { + builder.addSetting( + String.valueOf(i), new ItemBuilder( + MinecraftNameWrapper.RED_DYE, prefix + "§7" + (i / 2f) + " §c❤").setAmount(i).build()); + } + })); + } + + @Override + public void executeFor(Entity entity, Map subActions) { + int amount = Integer.parseInt(subActions.get("amount")[0]); + if (entity instanceof LivingEntity) { + LivingEntity livingEntity = (LivingEntity) entity; + AttributeInstance attribute = livingEntity.getAttribute(AttributeWrapper.MAX_HEALTH); + + if (attribute == null) return; + double newHealth = Math.min(livingEntity.getHealth() + amount, + attribute.getBaseValue()); + livingEntity.setHealth(newHealth); + } + } + + @Override + public Material getMaterial() { + return Material.GOLDEN_APPLE; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java index c7f724f8c..3458c69f3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java @@ -11,28 +11,28 @@ public class HungerPlayerAction extends PlayerTargetAction { - public HungerPlayerAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true) - .createChooseItemChild("amount").fill(builder -> { - String prefix = DefaultItem.getItemPrefix(); - - for (int i = 1; i < 21; i++) { - builder.addSetting( - String.valueOf(i), new ItemBuilder(Material.ROTTEN_FLESH, prefix + "§7" + i).setAmount(i).build()); - } - - })); - } - - @Override - public Material getMaterial() { - return Material.ROTTEN_FLESH; - } - - @Override - public void executeForPlayer(Player player, Map subActions) { - int newFoodLevel = player.getFoodLevel() - Integer.parseInt(subActions.get("amount")[0]); - player.setFoodLevel(Math.max(newFoodLevel, 0)); - } + public HungerPlayerAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true) + .createChooseItemChild("amount").fill(builder -> { + String prefix = DefaultItem.getItemPrefix(); + + for (int i = 1; i < 21; i++) { + builder.addSetting( + String.valueOf(i), new ItemBuilder(Material.ROTTEN_FLESH, prefix + "§7" + i).setAmount(i).build()); + } + + })); + } + + @Override + public Material getMaterial() { + return Material.ROTTEN_FLESH; + } + + @Override + public void executeForPlayer(Player player, Map subActions) { + int newFoodLevel = player.getFoodLevel() - Integer.parseInt(subActions.get("amount")[0]); + player.setFoodLevel(Math.max(newFoodLevel, 0)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java index 9a77d7833..38ed19e6b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java @@ -10,19 +10,19 @@ public class InvertHealthAction extends PlayerTargetAction { - public InvertHealthAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } + public InvertHealthAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } - @Override - public Material getMaterial() { - return Material.REDSTONE; - } + @Override + public Material getMaterial() { + return Material.REDSTONE; + } - @Override - public void executeForPlayer(Player player, Map subActions) { - InvertHealthChallenge.invertHealth(player); - } + @Override + public void executeForPlayer(Player player, Map subActions) { + InvertHealthChallenge.invertHealth(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java index abc8c20a0..a2d6f33fe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java @@ -10,20 +10,20 @@ public class JumpAndRunAction extends ChallengeAction { - public JumpAndRunAction(String name) { - super(name); - } + public JumpAndRunAction(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.ACACIA_STAIRS; - } + @Override + public Material getMaterial() { + return Material.ACACIA_STAIRS; + } - @Override - public void execute( - ChallengeExecutionData executionData, - Map subActions) { - AbstractChallenge.getFirstInstance(JumpAndRunChallenge.class).startWorldChallenge(); - } + @Override + public void execute( + ChallengeExecutionData executionData, + Map subActions) { + AbstractChallenge.getFirstInstance(JumpAndRunChallenge.class).startWorldChallenge(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java index 86cb4aef3..74b1ad670 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java @@ -12,22 +12,22 @@ public class KillEntityAction extends EntityTargetAction { - public KillEntityAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true)); - } + public KillEntityAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true)); + } - @Override - public void executeFor(Entity entity, Map subActions) { - if (entity instanceof Player) { - ChallengeHelper.kill(((Player) entity)); - } else if (entity instanceof LivingEntity) { - ((LivingEntity) entity).damage(((LivingEntity) entity).getHealth()); - } - } + @Override + public void executeFor(Entity entity, Map subActions) { + if (entity instanceof Player) { + ChallengeHelper.kill(((Player) entity)); + } else if (entity instanceof LivingEntity) { + ((LivingEntity) entity).damage(((LivingEntity) entity).getHealth()); + } + } - @Override - public Material getMaterial() { - return Material.DIAMOND_SWORD; - } + @Override + public Material getMaterial() { + return Material.DIAMOND_SWORD; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java index 5d67e6931..829701896 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java @@ -15,39 +15,39 @@ public class ModifyMaxHealthAction extends PlayerTargetAction { - public ModifyMaxHealthAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true) - .createValueChild().fill(builder -> { - builder.addModifierSetting("health_offset", - new ItemBuilder(MinecraftNameWrapper.RED_DYE, - Message.forName("item-custom-action-max_health-offset")), - 0, -20, 20, - integer -> "", integer -> "HP §8(§e" + (integer / 2f) + " §c❤§8)"); - })); - } - - @Override - public Material getMaterial() { - return MinecraftNameWrapper.RED_DYE; - } - - @Override - public void executeForPlayer(Player player, Map subActions) { - int healthOffset = Integer.parseInt(subActions.get("health_offset")[0]); - MaxHealthSetting instance = AbstractChallenge.getFirstInstance(MaxHealthSetting.class); - - int oldMaxHealth = instance.getMaxHealth(player); - if (oldMaxHealth <= 0) { - ChallengeHelper.kill(player); - return; - } - - instance.addHealth(player, healthOffset); - - int newMaxHealth = instance.getMaxHealth(player); - if (newMaxHealth <= 0) { - ChallengeHelper.kill(player); - } - } + public ModifyMaxHealthAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true) + .createValueChild().fill(builder -> { + builder.addModifierSetting("health_offset", + new ItemBuilder(MinecraftNameWrapper.RED_DYE, + Message.forName("item-custom-action-max_health-offset")), + 0, -20, 20, + integer -> "", integer -> "HP §8(§e" + (integer / 2f) + " §c❤§8)"); + })); + } + + @Override + public Material getMaterial() { + return MinecraftNameWrapper.RED_DYE; + } + + @Override + public void executeForPlayer(Player player, Map subActions) { + int healthOffset = Integer.parseInt(subActions.get("health_offset")[0]); + MaxHealthSetting instance = AbstractChallenge.getFirstInstance(MaxHealthSetting.class); + + int oldMaxHealth = instance.getMaxHealth(player); + if (oldMaxHealth <= 0) { + ChallengeHelper.kill(player); + return; + } + + instance.addHealth(player, healthOffset); + + int newMaxHealth = instance.getMaxHealth(player); + if (newMaxHealth <= 0) { + ChallengeHelper.kill(player); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java index ed40d21b7..71165a4c1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java @@ -19,71 +19,71 @@ @FallbackNames({"place_random_structure"}) public class PlaceStructureAction extends EntityTargetAction { - private List structureKeys; - private List villageKeys; - - public PlaceStructureAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true).addChild(SubSettingsHelper.createStructureSettingsBuilder())); - } - - @Override - public Material getMaterial() { - return Material.STRUCTURE_BLOCK; + private List structureKeys; + private List villageKeys; + + public PlaceStructureAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true).addChild(SubSettingsHelper.createStructureSettingsBuilder())); + } + + @Override + public Material getMaterial() { + return Material.STRUCTURE_BLOCK; + } + + @Override + public void executeFor(Entity entity, Map subActions) { + String structureString = subActions.get(SubSettingsHelper.STRUCTURE)[0]; + + NamespacedKey structureKey; + + if (structureString.equals("random_structure")) { + if (structureKeys == null) { + reloadStructureKeys(); + } + + structureKey = structureKeys.get(IRandom.singleton().nextInt(structureKeys.size())); + if (structureKey == StructureType.VILLAGE.getKey()) { + structureKey = villageKeys.get(IRandom.singleton().nextInt(villageKeys.size())); + } + } else { + StructureType structureType = StructureType.getStructureTypes().get(structureString); + structureKey = getStructureKey(structureType); } - @Override - public void executeFor(Entity entity, Map subActions) { - String structureString = subActions.get(SubSettingsHelper.STRUCTURE)[0]; - - NamespacedKey structureKey; - - if (structureString.equals("random_structure")) { - if (structureKeys == null) { - reloadStructureKeys(); - } - structureKey = structureKeys.get(IRandom.singleton().nextInt(structureKeys.size())); - if (structureKey == StructureType.VILLAGE.getKey()) { - structureKey = villageKeys.get(IRandom.singleton().nextInt(villageKeys.size())); - } - } else { - StructureType structureType = StructureType.getStructureTypes().get(structureString); - structureKey = getStructureKey(structureType); - } - - - Location location = entity.getLocation(); - String locationString = (int) location.getX() + " " + (int) location.getY() + " " + (int) location.getZ(); - String command = String.format("minecraft:place structure %s %s", structureKey, locationString); - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); + Location location = entity.getLocation(); + String locationString = (int) location.getX() + " " + (int) location.getY() + " " + (int) location.getZ(); + String command = String.format("minecraft:place structure %s %s", structureKey, locationString); + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); + } + + private void reloadStructureKeys() { + structureKeys = StructureType.getStructureTypes().values().stream() + .map(StructureType::getKey) + .collect(Collectors.toList()); + + structureKeys.remove(StructureType.OCEAN_RUIN.getKey()); + structureKeys.add(NamespacedKey.minecraft("ocean_ruin_cold")); + structureKeys.add(NamespacedKey.minecraft("ocean_ruin_warm")); + + villageKeys = new ArrayList<>(); + villageKeys.add(NamespacedKey.minecraft("village_desert")); + villageKeys.add(NamespacedKey.minecraft("village_plains")); + villageKeys.add(NamespacedKey.minecraft("village_savanna")); + villageKeys.add(NamespacedKey.minecraft("village_snowy")); + villageKeys.add(NamespacedKey.minecraft("village_taiga")); + } + + private NamespacedKey getStructureKey(StructureType structureType) { + if (structureType == StructureType.OCEAN_RUIN) { + List oceanRuins = Arrays.asList(NamespacedKey.minecraft("ocean_ruin_cold"), NamespacedKey.minecraft("ocean_ruin_warm")); + return oceanRuins.get(IRandom.singleton().nextInt(oceanRuins.size())); } - - private void reloadStructureKeys() { - structureKeys = StructureType.getStructureTypes().values().stream() - .map(StructureType::getKey) - .collect(Collectors.toList()); - - structureKeys.remove(StructureType.OCEAN_RUIN.getKey()); - structureKeys.add(NamespacedKey.minecraft("ocean_ruin_cold")); - structureKeys.add(NamespacedKey.minecraft("ocean_ruin_warm")); - - villageKeys = new ArrayList<>(); - villageKeys.add(NamespacedKey.minecraft("village_desert")); - villageKeys.add(NamespacedKey.minecraft("village_plains")); - villageKeys.add(NamespacedKey.minecraft("village_savanna")); - villageKeys.add(NamespacedKey.minecraft("village_snowy")); - villageKeys.add(NamespacedKey.minecraft("village_taiga")); - } - - private NamespacedKey getStructureKey(StructureType structureType) { - if (structureType == StructureType.OCEAN_RUIN) { - List oceanRuins = Arrays.asList(NamespacedKey.minecraft("ocean_ruin_cold"), NamespacedKey.minecraft("ocean_ruin_warm")); - return oceanRuins.get(IRandom.singleton().nextInt(oceanRuins.size())); - } - if (structureType == StructureType.VILLAGE) { - return villageKeys.get(IRandom.singleton().nextInt(villageKeys.size())); - } - return structureType.getKey(); + if (structureType == StructureType.VILLAGE) { + return villageKeys.get(IRandom.singleton().nextInt(villageKeys.size())); } + return structureType.getKey(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java index 13d39ea39..6e835fdcc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java @@ -13,33 +13,33 @@ public class PotionEffectAction extends EntityTargetAction { - public PotionEffectAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).addChild( - SubSettingsHelper.createPotionSettingsBuilder(true, true))); - } - - @Override - public void executeFor(Entity entity, Map subActions) { - if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; - try { - - PotionEffectType effectType = PotionEffectType.getByName(subActions.get("potion_type")[0]); - if (effectType == null) return; - PotionEffect effect = effectType.createEffect(Integer.parseInt(subActions.get("length")[0]) * 20 + 1, - Integer.parseInt(subActions.get("amplifier")[0])); - - livingEntity.addPotionEffect(effect); - } catch (Exception exception) { - Challenges.getInstance().getLogger().severe("Error while adding potion effect to player"); - Challenges.getInstance().getLogger().error("", exception); - } - } - } - - @Override - public Material getMaterial() { - return Material.POTION; - } + public PotionEffectAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).addChild( + SubSettingsHelper.createPotionSettingsBuilder(true, true))); + } + + @Override + public void executeFor(Entity entity, Map subActions) { + if (entity instanceof LivingEntity) { + LivingEntity livingEntity = (LivingEntity) entity; + try { + + PotionEffectType effectType = PotionEffectType.getByName(subActions.get("potion_type")[0]); + if (effectType == null) return; + PotionEffect effect = effectType.createEffect(Integer.parseInt(subActions.get("length")[0]) * 20 + 1, + Integer.parseInt(subActions.get("amplifier")[0])); + + livingEntity.addPotionEffect(effect); + } catch (Exception exception) { + Challenges.getInstance().getLogger().severe("Error while adding potion effect to player"); + Challenges.getInstance().getLogger().error("", exception); + } + } + } + + @Override + public Material getMaterial() { + return Material.POTION; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java index 5db7eb72f..0755dda5e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java @@ -10,18 +10,18 @@ public class RandomHotBarAction extends PlayerTargetAction { - public RandomHotBarAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true, true)); - } + public RandomHotBarAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true, true)); + } - @Override - public Material getMaterial() { - return Material.ARMOR_STAND; - } + @Override + public Material getMaterial() { + return Material.ARMOR_STAND; + } - @Override - public void executeForPlayer(Player player, Map subActions) { - HotBarRandomizerChallenge.addItems(player, true); - } + @Override + public void executeForPlayer(Player player, Map subActions) { + HotBarRandomizerChallenge.addItems(player, true); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java index 4898806ff..17b682f2b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java @@ -14,31 +14,31 @@ public class RandomItemAction extends ChallengeAction { - public RandomItemAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } - - public static void giveRandomItemToPlayer(@Nonnull Player player) { - InventoryUtils.giveItem(player.getInventory(), - player.getLocation(), InventoryUtils.getRandomItem(true, false)); - } - - @Override - public void execute( - ChallengeExecutionData executionData, - Map subActions) { - - for (Entity target : IEntityTargetAction.getTargets(executionData.getEntity(), subActions)) { - if (target instanceof Player) { - Player player = (Player) target; - giveRandomItemToPlayer(player); - } - } - } - - @Override - public Material getMaterial() { - return Material.BEACON; - } + public RandomItemAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } + + public static void giveRandomItemToPlayer(@Nonnull Player player) { + InventoryUtils.giveItem(player.getInventory(), + player.getLocation(), InventoryUtils.getRandomItem(true, false)); + } + + @Override + public void execute( + ChallengeExecutionData executionData, + Map subActions) { + + for (Entity target : IEntityTargetAction.getTargets(executionData.getEntity(), subActions)) { + if (target instanceof Player) { + Player player = (Player) target; + giveRandomItemToPlayer(player); + } + } + } + + @Override + public Material getMaterial() { + return Material.BEACON; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java index e6f441044..181089413 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java @@ -16,33 +16,33 @@ public class RandomMobAction extends EntityTargetAction { - @Getter - private static final EntityType[] spawnableMobs; - @Getter - private static final EntityType[] livingMobs; - - static { - List list = new LinkedList<>(Arrays.asList(EntityType.values())); - list = list.stream().filter(EntityType::isSpawnable).collect(Collectors.toList()); - spawnableMobs = list.toArray(new EntityType[0]); - list = list.stream().filter(EntityType::isAlive).collect(Collectors.toList()); - livingMobs = list.toArray(new EntityType[0]); - } - - public RandomMobAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false)); - } - - @Override - public void executeFor(Entity entity, Map subActions) { - if (entity.getLocation().getWorld() == null) return; - EntityType value = ChallengeAction.random.choose(spawnableMobs); - entity.getLocation().getWorld().spawnEntity(entity.getLocation(), value); - } - - @Override - public Material getMaterial() { - return Material.BLAZE_SPAWN_EGG; - } + @Getter + private static final EntityType[] spawnableMobs; + @Getter + private static final EntityType[] livingMobs; + + static { + List list = new LinkedList<>(Arrays.asList(EntityType.values())); + list = list.stream().filter(EntityType::isSpawnable).collect(Collectors.toList()); + spawnableMobs = list.toArray(new EntityType[0]); + list = list.stream().filter(EntityType::isAlive).collect(Collectors.toList()); + livingMobs = list.toArray(new EntityType[0]); + } + + public RandomMobAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false)); + } + + @Override + public void executeFor(Entity entity, Map subActions) { + if (entity.getLocation().getWorld() == null) return; + EntityType value = ChallengeAction.random.choose(spawnableMobs); + entity.getLocation().getWorld().spawnEntity(entity.getLocation(), value); + } + + @Override + public Material getMaterial() { + return Material.BLAZE_SPAWN_EGG; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java index 84c62efe5..1cefa0e5a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java @@ -13,29 +13,29 @@ public class RandomPotionEffectAction extends EntityTargetAction { - public RandomPotionEffectAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).addChild( - SubSettingsHelper.createPotionSettingsBuilder(false, true))); - } - - @Override - public void executeFor(Entity entity, Map subActions) { - if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; - PotionEffectType randomEffect = RandomPotionEffectChallenge - .getNewRandomEffect(livingEntity); - - if (randomEffect == null) return; - PotionEffect effect = randomEffect.createEffect(Integer.parseInt(subActions.get("length")[0]) * 20 + 1, - Integer.parseInt(subActions.get("amplifier")[0])); - - livingEntity.addPotionEffect(effect); - } - } - - @Override - public Material getMaterial() { - return Material.BREWING_STAND; - } + public RandomPotionEffectAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).addChild( + SubSettingsHelper.createPotionSettingsBuilder(false, true))); + } + + @Override + public void executeFor(Entity entity, Map subActions) { + if (entity instanceof LivingEntity) { + LivingEntity livingEntity = (LivingEntity) entity; + PotionEffectType randomEffect = RandomPotionEffectChallenge + .getNewRandomEffect(livingEntity); + + if (randomEffect == null) return; + PotionEffect effect = randomEffect.createEffect(Integer.parseInt(subActions.get("length")[0]) * 20 + 1, + Integer.parseInt(subActions.get("amplifier")[0])); + + livingEntity.addPotionEffect(effect); + } + } + + @Override + public Material getMaterial() { + return Material.BREWING_STAND; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java index fdfff7d12..a1fa56280 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java @@ -10,18 +10,18 @@ public class RemoveRandomItemAction extends PlayerTargetAction { - public RemoveRandomItemAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } + public RemoveRandomItemAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } - @Override - public Material getMaterial() { - return Material.DROPPER; - } + @Override + public Material getMaterial() { + return Material.DROPPER; + } - @Override - public void executeForPlayer(Player player, Map subActions) { - InventoryUtils.removeRandomItem(player.getInventory()); - } + @Override + public void executeForPlayer(Player player, Map subActions) { + InventoryUtils.removeRandomItem(player.getInventory()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java index ffae33903..036b63421 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java @@ -12,35 +12,35 @@ public class SpawnEntityAction extends EntityTargetAction { - public SpawnEntityAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false).addChild(SubSettingsHelper.createEntityTypeSettingsBuilder(false, false))); - } + public SpawnEntityAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false).addChild(SubSettingsHelper.createEntityTypeSettingsBuilder(false, false))); + } - @Override - public Material getMaterial() { - return Material.ZOMBIE_SPAWN_EGG; - } + @Override + public Material getMaterial() { + return Material.ZOMBIE_SPAWN_EGG; + } - @Override - public void executeFor(Entity entity, Map subActions) { - if (entity.getLocation().getWorld() == null) return; + @Override + public void executeFor(Entity entity, Map subActions) { + if (entity.getLocation().getWorld() == null) return; - String[] args = subActions.get(SubSettingsHelper.ENTITY_TYPE); + String[] args = subActions.get(SubSettingsHelper.ENTITY_TYPE); - for (String arg : args) { + for (String arg : args) { - try { - EntityType type = EntityType.valueOf(arg); - World world = entity.getLocation().getWorld(); - world.spawnEntity(entity.getLocation(), type); + try { + EntityType type = EntityType.valueOf(arg); + World world = entity.getLocation().getWorld(); + world.spawnEntity(entity.getLocation(), type); - } catch (Exception exception) { - Logger.error("", exception); - } + } catch (Exception exception) { + Logger.error("", exception); + } - } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java index f11ce7f4b..c71c793b1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java @@ -10,18 +10,18 @@ public class SwapRandomItemAction extends PlayerTargetAction { - public SwapRandomItemAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } + public SwapRandomItemAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } - @Override - public Material getMaterial() { - return Material.HOPPER; - } + @Override + public Material getMaterial() { + return Material.HOPPER; + } - @Override - public void executeForPlayer(Player player, Map subActions) { - RandomItemSwappingChallenge.swapRandomItems(player); - } + @Override + public void executeForPlayer(Player player, Map subActions) { + RandomItemSwappingChallenge.swapRandomItems(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java index a2b89f1a0..f84400c0a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java @@ -18,38 +18,38 @@ public class SwapRandomMobAction extends ChallengeAction { - public SwapRandomMobAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true) - .addChild(SubSettingsHelper.createEntityTargetSettingsBuilder(true).setKey("swap_targets"))); - } - - @Override - public Material getMaterial() { - return Material.ENDER_PEARL; - } - - @Override - public void execute(ChallengeExecutionData executionData, Map subActions) { - - List targets = IEntityTargetAction.getTargets(executionData.getEntity(), subActions); - List swapTargets = IEntityTargetAction.getTargets(executionData.getEntity(), subActions, "swap_targets"); - swapTargets.removeIf(entity -> !(entity instanceof LivingEntity)); - long seed = random.nextLong(); - Collections.shuffle(swapTargets, IRandom.create(seed).asRandom()); - Collections.shuffle(swapTargets, IRandom.create(seed).asRandom()); - for (World world : ChallengeAPI.getGameWorlds()) { - for (Entity target : targets) { - if (swapTargets.isEmpty()) break; - if (!(target instanceof LivingEntity)) continue; - if (target.getWorld() == world) { - int i = targets.indexOf(target); - int targetIndex = i + 1; - if (targetIndex >= swapTargets.size()) targetIndex = 0; - LivingEntity teleportTarget = (LivingEntity) swapTargets.remove(targetIndex); - RandomTeleportOnHitChallenge.switchEntityLocations(teleportTarget, (LivingEntity) target); - } - } - } - - } + public SwapRandomMobAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true) + .addChild(SubSettingsHelper.createEntityTargetSettingsBuilder(true).setKey("swap_targets"))); + } + + @Override + public Material getMaterial() { + return Material.ENDER_PEARL; + } + + @Override + public void execute(ChallengeExecutionData executionData, Map subActions) { + + List targets = IEntityTargetAction.getTargets(executionData.getEntity(), subActions); + List swapTargets = IEntityTargetAction.getTargets(executionData.getEntity(), subActions, "swap_targets"); + swapTargets.removeIf(entity -> !(entity instanceof LivingEntity)); + long seed = random.nextLong(); + Collections.shuffle(swapTargets, IRandom.create(seed).asRandom()); + Collections.shuffle(swapTargets, IRandom.create(seed).asRandom()); + for (World world : ChallengeAPI.getGameWorlds()) { + for (Entity target : targets) { + if (swapTargets.isEmpty()) break; + if (!(target instanceof LivingEntity)) continue; + if (target.getWorld() == world) { + int i = targets.indexOf(target); + int targetIndex = i + 1; + if (targetIndex >= swapTargets.size()) targetIndex = 0; + LivingEntity teleportTarget = (LivingEntity) swapTargets.remove(targetIndex); + RandomTeleportOnHitChallenge.switchEntityLocations(teleportTarget, (LivingEntity) target); + } + } + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java index 01580348f..3bd858bae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java @@ -11,21 +11,21 @@ public class UncraftInventoryAction extends EntityTargetAction { - public UncraftInventoryAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false)); - } + public UncraftInventoryAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false)); + } - @Override - public void executeFor(Entity entity, Map subActions) { - if (entity instanceof Player) { - Player player = (Player) entity; - UncraftItemsChallenge.uncraftInventory(player); - } - } + @Override + public void executeFor(Entity entity, Map subActions) { + if (entity instanceof Player) { + Player player = (Player) entity; + UncraftItemsChallenge.uncraftInventory(player); + } + } - @Override - public Material getMaterial() { - return Material.CRAFTING_TABLE; - } + @Override + public Material getMaterial() { + return Material.CRAFTING_TABLE; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java index e025fb7b9..d7348fcfb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java @@ -10,20 +10,20 @@ public class WaterMLGAction extends ChallengeAction { - public WaterMLGAction(String name) { - super(name); - } + public WaterMLGAction(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.WATER_BUCKET; - } + @Override + public Material getMaterial() { + return Material.WATER_BUCKET; + } - @Override - public void execute( - ChallengeExecutionData executionData, - Map subActions) { - AbstractChallenge.getFirstInstance(WaterMLGChallenge.class).startWorldChallenge(); - } + @Override + public void execute( + ChallengeExecutionData executionData, + Map subActions) { + AbstractChallenge.getFirstInstance(WaterMLGChallenge.class).startWorldChallenge(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java index 9668ca307..8a064c9ef 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java @@ -14,27 +14,27 @@ public class WinChallengeAction extends PlayerTargetAction { - private final List winner = Lists.newLinkedList(); - - public WinChallengeAction(String name) { - super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); - } - - @Override - public Material getMaterial() { - return Material.GOLDEN_HELMET; - } - - @Override - public void execute(ChallengeExecutionData executionData, Map subActions) { - super.execute(executionData, subActions); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> winner); - winner.clear(); - } - - @Override - public void executeForPlayer(Player player, Map subActions) { - winner.add(player); - } + private final List winner = Lists.newLinkedList(); + + public WinChallengeAction(String name) { + super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); + } + + @Override + public Material getMaterial() { + return Material.GOLDEN_HELMET; + } + + @Override + public void execute(ChallengeExecutionData executionData, Map subActions) { + super.execute(executionData, subActions); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> winner); + winner.clear(); + } + + @Override + public void executeForPlayer(Player player, Map subActions) { + winner.add(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java index 56dab8b5a..9e549f65d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java @@ -19,130 +19,130 @@ @Getter public abstract class SubSettingsBuilder { - private String key; - private SubSettingsBuilder parent; - private SubSettingsBuilder child; - - protected SubSettingsBuilder(String key) { - this.key = key; - parent = null; - } - - protected SubSettingsBuilder(String key, SubSettingsBuilder parent) { - this.key = key; - this.parent = parent; - } - - public static ChooseItemSubSettingsBuilder createChooseItem(String key) { - return new ChooseItemSubSettingsBuilder(key); - } - - public static ValueSubSettingsBuilder createValueItem() { - return new ValueSubSettingsBuilder(); - } - - public static ChooseMultipleItemSubSettingBuilder createChooseMultipleItem(String key) { - return new ChooseMultipleItemSubSettingBuilder(key); - } - - public static TextInputSubSettingsBuilder createTextInput(String key, - Consumer onOpen, - Predicate isValid) { - return new TextInputSubSettingsBuilder(key, onOpen, isValid); - } - - public static EmptySubSettingsBuilder createEmpty() { - return new EmptySubSettingsBuilder(); - } - - public abstract boolean open(Player player, IParentCustomGenerator parentGenerator, String title); - - public abstract List getDisplay(Map activated); - - public abstract boolean hasSettings(); - - public SubSettingsBuilder setParent(SubSettingsBuilder parent) { - - SubSettingsBuilder parentBuilder = getParent(); - if (parentBuilder != null) { - return parentBuilder.setParent(parent); - } else { - this.parent = parent; - return this; - } - - } - - public SubSettingsBuilder setKey(String key) { - this.key = key; - return this; - } - - public String getKeyTranslation() { - String messageName = "custom-subsetting-" + key; - return MessageManager.hasMessageInCache(messageName) - ? Message.forName(messageName).asString() : StringUtils.getEnumName(key); - } - - public List getAllChildren() { - LinkedList children = new LinkedList<>(Collections.singleton(this)); - - SubSettingsBuilder last = this; - - while (last != null) { - if (last.getChild() != null) { - children.add(last.getChild()); - } - last = last.getChild(); - } - - return children; - } - - /** - * @return the first parent that was created. - * Only required if first builder has one ore more children. - */ - public SubSettingsBuilder build() { - return parent == null ? this : parent.build(); - } - - /** - * Sets the highest parent of a child as the child of this builder. - * - * @param child one of the child builders that are added. - * @return the highest parent of that child - */ - public SubSettingsBuilder addChild(SubSettingsBuilder child) { - this.child = child.setParent(this); - return child; - } - - public ChooseItemSubSettingsBuilder createChooseItemChild(String key) { - ChooseItemSubSettingsBuilder builder = new ChooseItemSubSettingsBuilder(key, this); - this.child = builder; - return builder; - } - - public ValueSubSettingsBuilder createValueChild() { - ValueSubSettingsBuilder builder = new ValueSubSettingsBuilder(this); - this.child = builder; - return builder; - } - - public ChooseMultipleItemSubSettingBuilder createChooseMultipleChild(String key) { - ChooseMultipleItemSubSettingBuilder builder = new ChooseMultipleItemSubSettingBuilder(key, this); - this.child = builder; - return builder; - } - - public TextInputSubSettingsBuilder createTextInputChild(String key, - Consumer onOpen, - Predicate isValid) { - TextInputSubSettingsBuilder builder = new TextInputSubSettingsBuilder(key, - this, onOpen, isValid); - this.child = builder; - return builder; - } + private String key; + private SubSettingsBuilder parent; + private SubSettingsBuilder child; + + protected SubSettingsBuilder(String key) { + this.key = key; + parent = null; + } + + protected SubSettingsBuilder(String key, SubSettingsBuilder parent) { + this.key = key; + this.parent = parent; + } + + public static ChooseItemSubSettingsBuilder createChooseItem(String key) { + return new ChooseItemSubSettingsBuilder(key); + } + + public static ValueSubSettingsBuilder createValueItem() { + return new ValueSubSettingsBuilder(); + } + + public static ChooseMultipleItemSubSettingBuilder createChooseMultipleItem(String key) { + return new ChooseMultipleItemSubSettingBuilder(key); + } + + public static TextInputSubSettingsBuilder createTextInput(String key, + Consumer onOpen, + Predicate isValid) { + return new TextInputSubSettingsBuilder(key, onOpen, isValid); + } + + public static EmptySubSettingsBuilder createEmpty() { + return new EmptySubSettingsBuilder(); + } + + public abstract boolean open(Player player, IParentCustomGenerator parentGenerator, String title); + + public abstract List getDisplay(Map activated); + + public abstract boolean hasSettings(); + + public SubSettingsBuilder setParent(SubSettingsBuilder parent) { + + SubSettingsBuilder parentBuilder = getParent(); + if (parentBuilder != null) { + return parentBuilder.setParent(parent); + } else { + this.parent = parent; + return this; + } + + } + + public SubSettingsBuilder setKey(String key) { + this.key = key; + return this; + } + + public String getKeyTranslation() { + String messageName = "custom-subsetting-" + key; + return MessageManager.hasMessageInCache(messageName) + ? Message.forName(messageName).asString() : StringUtils.getEnumName(key); + } + + public List getAllChildren() { + LinkedList children = new LinkedList<>(Collections.singleton(this)); + + SubSettingsBuilder last = this; + + while (last != null) { + if (last.getChild() != null) { + children.add(last.getChild()); + } + last = last.getChild(); + } + + return children; + } + + /** + * @return the first parent that was created. + * Only required if first builder has one ore more children. + */ + public SubSettingsBuilder build() { + return parent == null ? this : parent.build(); + } + + /** + * Sets the highest parent of a child as the child of this builder. + * + * @param child one of the child builders that are added. + * @return the highest parent of that child + */ + public SubSettingsBuilder addChild(SubSettingsBuilder child) { + this.child = child.setParent(this); + return child; + } + + public ChooseItemSubSettingsBuilder createChooseItemChild(String key) { + ChooseItemSubSettingsBuilder builder = new ChooseItemSubSettingsBuilder(key, this); + this.child = builder; + return builder; + } + + public ValueSubSettingsBuilder createValueChild() { + ValueSubSettingsBuilder builder = new ValueSubSettingsBuilder(this); + this.child = builder; + return builder; + } + + public ChooseMultipleItemSubSettingBuilder createChooseMultipleChild(String key) { + ChooseMultipleItemSubSettingBuilder builder = new ChooseMultipleItemSubSettingBuilder(key, this); + this.child = builder; + return builder; + } + + public TextInputSubSettingsBuilder createTextInputChild(String key, + Consumer onOpen, + Predicate isValid) { + TextInputSubSettingsBuilder builder = new TextInputSubSettingsBuilder(key, + this, onOpen, isValid); + this.child = builder; + return builder; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java index 3e3fcce3c..99db78f06 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java @@ -6,25 +6,25 @@ public abstract class ValueSetting { - @Getter - private final String key; - private final ItemBuilder itemBuilder; + @Getter + private final String key; + private final ItemBuilder itemBuilder; - public ValueSetting(String key, ItemBuilder itemBuilder) { - this.key = key; - this.itemBuilder = itemBuilder; - } + public ValueSetting(String key, ItemBuilder itemBuilder) { + this.key = key; + this.itemBuilder = itemBuilder; + } - public ItemBuilder createDisplayItem() { - return itemBuilder; - } + public ItemBuilder createDisplayItem() { + return itemBuilder; + } - public abstract String onClick(MenuClickInfo info, String value, int slotIndex); + public abstract String onClick(MenuClickInfo info, String value, int slotIndex); - public ItemBuilder getDisplayItem(String value) { - return createDisplayItem().hideAttributes(); - } + public ItemBuilder getDisplayItem(String value) { + return createDisplayItem().hideAttributes(); + } - public abstract ItemBuilder getSettingsItem(String value); + public abstract ItemBuilder getSettingsItem(String value); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java index 29c9df582..3ddf864c1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java @@ -19,57 +19,57 @@ @Getter public class ChooseItemSubSettingsBuilder extends GeneratorSubSettingsBuilder { - protected final LinkedHashMap settings = new LinkedHashMap<>(); + protected final LinkedHashMap settings = new LinkedHashMap<>(); - public ChooseItemSubSettingsBuilder(String key) { - super(key); - } + public ChooseItemSubSettingsBuilder(String key) { + super(key); + } - public ChooseItemSubSettingsBuilder(String key, SubSettingsBuilder parent) { - super(key, parent); - } + public ChooseItemSubSettingsBuilder(String key, SubSettingsBuilder parent) { + super(key, parent); + } - @Override - public MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title) { - return new SubSettingChooseMenuGenerator(getKey(), parentGenerator, getSettings(), title); - } + @Override + public MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title) { + return new SubSettingChooseMenuGenerator(getKey(), parentGenerator, getSettings(), title); + } - @Override - public List getDisplay(Map activated) { - List display = Lists.newLinkedList(); + @Override + public List getDisplay(Map activated) { + List display = Lists.newLinkedList(); - for (Entry entry : activated.entrySet()) { - if (entry.getKey().equals(getKey())) { - for (String value : entry.getValue()) { - ItemStack itemStack = getSettings().get(value); - if (itemStack != null) { - if (itemStack.getItemMeta() == null) continue; - display.add("§7" + getKeyTranslation() + " " + itemStack.getItemMeta().getDisplayName()); - } - } - } - } + for (Entry entry : activated.entrySet()) { + if (entry.getKey().equals(getKey())) { + for (String value : entry.getValue()) { + ItemStack itemStack = getSettings().get(value); + if (itemStack != null) { + if (itemStack.getItemMeta() == null) continue; + display.add("§7" + getKeyTranslation() + " " + itemStack.getItemMeta().getDisplayName()); + } + } + } + } - return display; - } + return display; + } - public ChooseItemSubSettingsBuilder addSetting(String key, ItemStack value) { - settings.put(key, value); - return this; - } + public ChooseItemSubSettingsBuilder addSetting(String key, ItemStack value) { + settings.put(key, value); + return this; + } - public ChooseItemSubSettingsBuilder addSetting(String key, ItemBuilder value) { - settings.put(key, value.hideAttributes().build()); - return this; - } + public ChooseItemSubSettingsBuilder addSetting(String key, ItemBuilder value) { + settings.put(key, value.hideAttributes().build()); + return this; + } - public ChooseItemSubSettingsBuilder fill(Consumer actions) { - actions.accept(this); - return this; - } + public ChooseItemSubSettingsBuilder fill(Consumer actions) { + actions.accept(this); + return this; + } - public boolean hasSettings() { - return !settings.isEmpty(); - } + public boolean hasSettings() { + return !settings.isEmpty(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java index 25b07a132..83ef09deb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java @@ -21,74 +21,74 @@ @Getter public class ChooseMultipleItemSubSettingBuilder extends GeneratorSubSettingsBuilder { - protected final LinkedHashMap settings = new LinkedHashMap<>(); - - public ChooseMultipleItemSubSettingBuilder(String key) { - super(key); - } - - public ChooseMultipleItemSubSettingBuilder(String key, SubSettingsBuilder parent) { - super(key, parent); - } - - @Override - public MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title) { - return new SubSettingChooseMultipleMenuGenerator(getKey(), parentGenerator, getSettings(), title); - } - - @Override - public List getDisplay(Map activated) { - List display = Lists.newLinkedList(); - - for (Entry entry : activated.entrySet()) { - if (entry.getKey().equals(getKey())) { - - int count = 0; - String firstDisplay = null; - - for (String value : entry.getValue()) { - ItemStack itemStack = getSettings().get(value); - if (itemStack != null) { - if (firstDisplay == null) { - if (itemStack.getItemMeta() == null) continue; - firstDisplay = "§7" + getKeyTranslation() + " " + itemStack.getItemMeta().getDisplayName(); - } else { - count++; - } - - } - } - - if (firstDisplay != null) { - String suffix = count == 0 ? "" : " §7+" + count; - display.add(firstDisplay + suffix); - } else { - display.add("§7" + getKeyTranslation() + " " + DefaultItem.getItemPrefix() + Message.forName("none").asString()); - } - - } - } - - return display; - } - - public ChooseMultipleItemSubSettingBuilder addSetting(String key, ItemStack value) { - settings.put(key, value); - return this; - } - - public ChooseMultipleItemSubSettingBuilder addSetting(String key, ItemBuilder value) { - settings.put(key, value.hideAttributes().build()); - return this; - } - - public ChooseMultipleItemSubSettingBuilder fill(Consumer actions) { - actions.accept(this); - return this; - } - - public boolean hasSettings() { - return !settings.isEmpty(); - } + protected final LinkedHashMap settings = new LinkedHashMap<>(); + + public ChooseMultipleItemSubSettingBuilder(String key) { + super(key); + } + + public ChooseMultipleItemSubSettingBuilder(String key, SubSettingsBuilder parent) { + super(key, parent); + } + + @Override + public MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title) { + return new SubSettingChooseMultipleMenuGenerator(getKey(), parentGenerator, getSettings(), title); + } + + @Override + public List getDisplay(Map activated) { + List display = Lists.newLinkedList(); + + for (Entry entry : activated.entrySet()) { + if (entry.getKey().equals(getKey())) { + + int count = 0; + String firstDisplay = null; + + for (String value : entry.getValue()) { + ItemStack itemStack = getSettings().get(value); + if (itemStack != null) { + if (firstDisplay == null) { + if (itemStack.getItemMeta() == null) continue; + firstDisplay = "§7" + getKeyTranslation() + " " + itemStack.getItemMeta().getDisplayName(); + } else { + count++; + } + + } + } + + if (firstDisplay != null) { + String suffix = count == 0 ? "" : " §7+" + count; + display.add(firstDisplay + suffix); + } else { + display.add("§7" + getKeyTranslation() + " " + DefaultItem.getItemPrefix() + Message.forName("none").asString()); + } + + } + } + + return display; + } + + public ChooseMultipleItemSubSettingBuilder addSetting(String key, ItemStack value) { + settings.put(key, value); + return this; + } + + public ChooseMultipleItemSubSettingBuilder addSetting(String key, ItemBuilder value) { + settings.put(key, value.hideAttributes().build()); + return this; + } + + public ChooseMultipleItemSubSettingBuilder fill(Consumer actions) { + actions.accept(this); + return this; + } + + public boolean hasSettings() { + return !settings.isEmpty(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java index a68a92d51..4cd85ec7c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java @@ -10,23 +10,23 @@ public class EmptySubSettingsBuilder extends SubSettingsBuilder { - public EmptySubSettingsBuilder() { - super("none"); - } - - @Override - public List getDisplay(Map activated) { - return Lists.newLinkedList(); - } - - @Override - public boolean hasSettings() { - return false; - } - - @Override - public boolean open(Player player, IParentCustomGenerator parentGenerator, String title) { - return false; - } + public EmptySubSettingsBuilder() { + super("none"); + } + + @Override + public List getDisplay(Map activated) { + return Lists.newLinkedList(); + } + + @Override + public boolean hasSettings() { + return false; + } + + @Override + public boolean open(Player player, IParentCustomGenerator parentGenerator, String title) { + return false; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java index 9d7775db7..27b413afc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java @@ -8,26 +8,26 @@ public abstract class GeneratorSubSettingsBuilder extends SubSettingsBuilder { - public GeneratorSubSettingsBuilder(String key) { - super(key); - } + public GeneratorSubSettingsBuilder(String key) { + super(key); + } - public GeneratorSubSettingsBuilder(String key, SubSettingsBuilder parent) { - super(key, parent); - } + public GeneratorSubSettingsBuilder(String key, SubSettingsBuilder parent) { + super(key, parent); + } - public boolean open(Player player, IParentCustomGenerator parentGenerator, String title) { + public boolean open(Player player, IParentCustomGenerator parentGenerator, String title) { - if (hasSettings()) { - MenuGenerator generator = getGenerator(player, parentGenerator, title + InventoryTitleManager.getTitleSplitter() + getKeyTranslation()); - if (generator == null) return false; - generator.open(player, 0); - return true; - } + if (hasSettings()) { + MenuGenerator generator = getGenerator(player, parentGenerator, title + InventoryTitleManager.getTitleSplitter() + getKeyTranslation()); + if (generator == null) return false; + generator.open(player, 0); + return true; + } - return false; - } + return false; + } - public abstract MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title); + public abstract MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java index 2a42f29a0..d9dc98472 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java @@ -19,73 +19,73 @@ public class TextInputSubSettingsBuilder extends SubSettingsBuilder { - private final Consumer onOpen; - private final Predicate isValid; - - public TextInputSubSettingsBuilder(String key) { - this(key, null); - } - - public TextInputSubSettingsBuilder(String key, SubSettingsBuilder parent) { - this(key, parent, event -> { - }, event -> true); - } - - public TextInputSubSettingsBuilder(String key, - Consumer onOpen, - Predicate isValid) { - super(key); - this.onOpen = onOpen; - this.isValid = isValid; - } - - public TextInputSubSettingsBuilder(String key, - SubSettingsBuilder parent, - Consumer onOpen, - Predicate isValid) { - super(key, parent); - this.onOpen = onOpen; - this.isValid = isValid; - } - - @Override - public boolean open(Player player, IParentCustomGenerator parentGenerator, String title) { - player.closeInventory(); - onOpen.accept(player); - - ChatInputListener.setInputAction(player, event -> { - if (!isValid.test(event)) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - parentGenerator.decline(player); - }); - return; - } - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - parentGenerator.accept(player, null, MapUtils.createStringArrayMap(getKey(), event.getMessage())); - }); - }); - - return true; - } - - @Override - public List getDisplay(Map activated) { - List display = Lists.newLinkedList(); - - for (Entry entry : activated.entrySet()) { - if (entry.getKey().equals(getKey())) { - for (String value : entry.getValue()) { - display.add("§7" + getKeyTranslation() + " " + DefaultItem.getItemPrefix() + value); - } - } - } - - return display; - } - - @Override - public boolean hasSettings() { - return true; - } + private final Consumer onOpen; + private final Predicate isValid; + + public TextInputSubSettingsBuilder(String key) { + this(key, null); + } + + public TextInputSubSettingsBuilder(String key, SubSettingsBuilder parent) { + this(key, parent, event -> { + }, event -> true); + } + + public TextInputSubSettingsBuilder(String key, + Consumer onOpen, + Predicate isValid) { + super(key); + this.onOpen = onOpen; + this.isValid = isValid; + } + + public TextInputSubSettingsBuilder(String key, + SubSettingsBuilder parent, + Consumer onOpen, + Predicate isValid) { + super(key, parent); + this.onOpen = onOpen; + this.isValid = isValid; + } + + @Override + public boolean open(Player player, IParentCustomGenerator parentGenerator, String title) { + player.closeInventory(); + onOpen.accept(player); + + ChatInputListener.setInputAction(player, event -> { + if (!isValid.test(event)) { + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + parentGenerator.decline(player); + }); + return; + } + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + parentGenerator.accept(player, null, MapUtils.createStringArrayMap(getKey(), event.getMessage())); + }); + }); + + return true; + } + + @Override + public List getDisplay(Map activated) { + List display = Lists.newLinkedList(); + + for (Entry entry : activated.entrySet()) { + if (entry.getKey().equals(getKey())) { + for (String value : entry.getValue()) { + display.add("§7" + getKeyTranslation() + " " + DefaultItem.getItemPrefix() + value); + } + } + } + + return display; + } + + @Override + public boolean hasSettings() { + return true; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java index 35df97b57..6e28dfb55 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java @@ -25,88 +25,88 @@ @Getter public class ValueSubSettingsBuilder extends GeneratorSubSettingsBuilder { - private final LinkedHashMap defaultSettings = new LinkedHashMap<>(); + private final LinkedHashMap defaultSettings = new LinkedHashMap<>(); - public ValueSubSettingsBuilder() { - super("value"); - } + public ValueSubSettingsBuilder() { + super("value"); + } - public ValueSubSettingsBuilder(SubSettingsBuilder parent) { - super("value", parent); - } + public ValueSubSettingsBuilder(SubSettingsBuilder parent) { + super("value", parent); + } - @Override - public MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title) { - return new SubSettingValueMenuGenerator(parentGenerator, new LinkedHashMap<>(getDefaultSettings()), title); - } + @Override + public MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title) { + return new SubSettingValueMenuGenerator(parentGenerator, new LinkedHashMap<>(getDefaultSettings()), title); + } - @Override - public List getDisplay(Map activated) { - List display = Lists.newLinkedList(); + @Override + public List getDisplay(Map activated) { + List display = Lists.newLinkedList(); - for (Entry entry : activated.entrySet()) { + for (Entry entry : activated.entrySet()) { - for (ValueSetting setting : defaultSettings.keySet()) { + for (ValueSetting setting : defaultSettings.keySet()) { - if (entry.getKey().equals(setting.getKey())) { + if (entry.getKey().equals(setting.getKey())) { - ItemBuilder builder = setting.getSettingsItem(entry.getValue()[0]); - if (builder != null) { - display.add("§7" + getKeyTranslation(entry.getKey()) + " " + builder.getName()); + ItemBuilder builder = setting.getSettingsItem(entry.getValue()[0]); + if (builder != null) { + display.add("§7" + getKeyTranslation(entry.getKey()) + " " + builder.getName()); - } + } - } + } - } + } - } + } - return display; - } + return display; + } - public String getKeyTranslation(String key) { - String messageName = "custom-subsetting-" + key; - return MessageManager.hasMessageInCache(messageName) - ? Message.forName(messageName).asString() : StringUtils.getEnumName(key); - } + public String getKeyTranslation(String key) { + String messageName = "custom-subsetting-" + key; + return MessageManager.hasMessageInCache(messageName) + ? Message.forName(messageName).asString() : StringUtils.getEnumName(key); + } - public ValueSubSettingsBuilder addBooleanSetting(String key, ItemBuilder displayItem, - boolean defaultValue) { - defaultSettings.put(new BooleanSetting(key, displayItem), - defaultValue ? "enabled" : "disabled"); - return this; - } + public ValueSubSettingsBuilder addBooleanSetting(String key, ItemBuilder displayItem, + boolean defaultValue) { + defaultSettings.put(new BooleanSetting(key, displayItem), + defaultValue ? "enabled" : "disabled"); + return this; + } - public ValueSubSettingsBuilder addModifierSetting(String key, ItemBuilder displayItem, - int defaultValue, int min, int max) { - defaultSettings.put(new ModifierSetting(key, min, max, displayItem), - String.valueOf(defaultValue)); - return this; - } + public ValueSubSettingsBuilder addModifierSetting(String key, ItemBuilder displayItem, + int defaultValue, int min, int max) { + defaultSettings.put(new ModifierSetting(key, min, max, displayItem), + String.valueOf(defaultValue)); + return this; + } - public ValueSubSettingsBuilder addModifierSetting(String key, ItemBuilder displayItem, - int defaultValue, int min, int max, Function prefixGetter, Function suffixGetter) { - defaultSettings.put(new ModifierSetting(key, min, max, displayItem, prefixGetter, suffixGetter), - String.valueOf(defaultValue)); - return this; - } + public ValueSubSettingsBuilder addModifierSetting(String key, ItemBuilder displayItem, + int defaultValue, int min, int max, Function prefixGetter, Function suffixGetter) { + defaultSettings.put(new ModifierSetting(key, min, max, displayItem, prefixGetter, suffixGetter), + String.valueOf(defaultValue)); + return this; + } - public ValueSubSettingsBuilder addModifierSetting(String key, ItemBuilder displayItem, - int defaultValue, int min, int max, Function settingsItemGetter) { - defaultSettings.put(new ModifierSetting(key, min, max, displayItem, settingsItemGetter), - String.valueOf(defaultValue)); - return this; - } + public ValueSubSettingsBuilder addModifierSetting(String key, ItemBuilder displayItem, + int defaultValue, int min, int max, Function settingsItemGetter) { + defaultSettings.put(new ModifierSetting(key, min, max, displayItem, settingsItemGetter), + String.valueOf(defaultValue)); + return this; + } - public ValueSubSettingsBuilder fill(Consumer actions) { - actions.accept(this); - return this; - } + public ValueSubSettingsBuilder fill(Consumer actions) { + actions.accept(this); + return this; + } - public boolean hasSettings() { - return !defaultSettings.isEmpty(); - } + public boolean hasSettings() { + return !defaultSettings.isEmpty(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java index 8296a8fb3..f8702057c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java @@ -8,19 +8,19 @@ public class BooleanSetting extends ValueSetting { - public BooleanSetting(String key, ItemBuilder itemBuilder) { - super(key, itemBuilder); - } + public BooleanSetting(String key, ItemBuilder itemBuilder) { + super(key, itemBuilder); + } - @Override - public String onClick(MenuClickInfo info, String value, - int slotIndex) { - return value.equals("enabled") ? "disabled" : "enabled"; - } + @Override + public String onClick(MenuClickInfo info, String value, + int slotIndex) { + return value.equals("enabled") ? "disabled" : "enabled"; + } - @Override - public ItemBuilder getSettingsItem(String value) { - return value.equals("enabled") ? DefaultItem.enabled() : DefaultItem.disabled(); - } + @Override + public ItemBuilder getSettingsItem(String value) { + return value.equals("enabled") ? DefaultItem.enabled() : DefaultItem.disabled(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java index ff3e5f2c3..8b68286e1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java @@ -12,86 +12,86 @@ public class ModifierSetting extends ValueSetting implements IModifier { - private final int min, max; - private final Function settingsItemGetter; - - private int tempValue; - - public ModifierSetting(String key, int min, int max, ItemBuilder displayItem) { - this(key, min, max, displayItem, integer -> "", integer -> ""); - } - - public ModifierSetting(String key, int min, int max, ItemBuilder itemBuilder, Function prefixGetter, Function suffixGetter) { - this(key, min, max, itemBuilder, value -> - { - String prefix = prefixGetter.apply(value); - String suffix = suffixGetter.apply(value); - return DefaultItem.value(value, (prefix.isEmpty() ? "" : "§7" + prefix + " ") + "§e") - .appendName(suffix.isEmpty() ? "" : " " + "§7" + suffix); - }); - } - - public ModifierSetting(String key, int min, int max, ItemBuilder itemBuilder, Function settingsItemGetter) { - super(key, itemBuilder); - this.min = min; - this.max = max; - this.settingsItemGetter = settingsItemGetter; - } - - @Override - public String onClick(MenuClickInfo info, String value, int slotIndex) { - - int intValue = getIntValue(value); - tempValue = intValue; - - ChallengeHelper.handleModifierClick(info, this); - - intValue = tempValue; - tempValue = 0; - return String.valueOf(intValue); - } - - @Override - public int getValue() { - return tempValue; - } - - @Override - public void setValue(int value) { - tempValue = value; - } - - @Override - public int getMinValue() { - return min; - } - - @Override - public int getMaxValue() { - return max; - } - - @Override - public void playValueChangeTitle() { - } - - @Override - public ItemBuilder getSettingsItem(String value) { - int intValue = getIntValue(value); - return settingsItemGetter.apply(intValue); - } - - public int getIntValue(String value) { - - try { - return Integer.parseInt(value); - } catch (Exception exception) { - Challenges.getInstance().getLogger().severe("Something went wrong while parsing the " - + "value of subsetting " + getKey() + " with value " + value); - Challenges.getInstance().getLogger().error("", exception); - } - - return 0; - } + private final int min, max; + private final Function settingsItemGetter; + + private int tempValue; + + public ModifierSetting(String key, int min, int max, ItemBuilder displayItem) { + this(key, min, max, displayItem, integer -> "", integer -> ""); + } + + public ModifierSetting(String key, int min, int max, ItemBuilder itemBuilder, Function prefixGetter, Function suffixGetter) { + this(key, min, max, itemBuilder, value -> + { + String prefix = prefixGetter.apply(value); + String suffix = suffixGetter.apply(value); + return DefaultItem.value(value, (prefix.isEmpty() ? "" : "§7" + prefix + " ") + "§e") + .appendName(suffix.isEmpty() ? "" : " " + "§7" + suffix); + }); + } + + public ModifierSetting(String key, int min, int max, ItemBuilder itemBuilder, Function settingsItemGetter) { + super(key, itemBuilder); + this.min = min; + this.max = max; + this.settingsItemGetter = settingsItemGetter; + } + + @Override + public String onClick(MenuClickInfo info, String value, int slotIndex) { + + int intValue = getIntValue(value); + tempValue = intValue; + + ChallengeHelper.handleModifierClick(info, this); + + intValue = tempValue; + tempValue = 0; + return String.valueOf(intValue); + } + + @Override + public int getValue() { + return tempValue; + } + + @Override + public void setValue(int value) { + tempValue = value; + } + + @Override + public int getMinValue() { + return min; + } + + @Override + public int getMaxValue() { + return max; + } + + @Override + public void playValueChangeTitle() { + } + + @Override + public ItemBuilder getSettingsItem(String value) { + int intValue = getIntValue(value); + return settingsItemGetter.apply(intValue); + } + + public int getIntValue(String value) { + + try { + return Integer.parseInt(value); + } catch (Exception exception) { + Challenges.getInstance().getLogger().severe("Something went wrong while parsing the " + + "value of subsetting " + getKey() + " with value " + value); + Challenges.getInstance().getLogger().error("", exception); + } + + return 0; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java index 4cc577cfb..26888233f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java @@ -11,34 +11,34 @@ import java.util.function.Supplier; public abstract class ChallengeTrigger extends ChallengeSetting implements - IChallengeTrigger { + IChallengeTrigger { - public ChallengeTrigger(String name, - SubSettingsBuilder subSettingsBuilder) { - super(name, subSettingsBuilder); - } + public ChallengeTrigger(String name, + SubSettingsBuilder subSettingsBuilder) { + super(name, subSettingsBuilder); + } - public ChallengeTrigger(String name) { - super(name); - } + public ChallengeTrigger(String name) { + super(name); + } - public ChallengeTrigger(String name, Supplier builderSupplier) { - super(name, builderSupplier); - } + public ChallengeTrigger(String name, Supplier builderSupplier) { + super(name, builderSupplier); + } - public static LinkedHashMap getMenuItems() { - LinkedHashMap map = new LinkedHashMap<>(); + public static LinkedHashMap getMenuItems() { + LinkedHashMap map = new LinkedHashMap<>(); - for (ChallengeTrigger value : Challenges.getInstance().getCustomSettingsLoader().getTriggers().values()) { - map.put(value.getName(), new ItemBuilder(value.getMaterial(), Message.forName(value.getMessage())).hideAttributes().build()); - } + for (ChallengeTrigger value : Challenges.getInstance().getCustomSettingsLoader().getTriggers().values()) { + map.put(value.getName(), new ItemBuilder(value.getMaterial(), Message.forName(value.getMessage())).hideAttributes().build()); + } - return map; - } + return map; + } - @Override - public final String getMessage() { - return "item-custom-trigger-" + getMessageSuffix(); - } + @Override + public final String getMessage() { + return "item-custom-trigger-" + getMessageSuffix(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/IChallengeTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/IChallengeTrigger.java index 48f7f468e..f31a8fbb0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/IChallengeTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/IChallengeTrigger.java @@ -5,8 +5,8 @@ public interface IChallengeTrigger extends Listener { - default ChallengeExecutionData createData() { - return new ChallengeExecutionData(this); - } + default ChallengeExecutionData createData() { + return new ChallengeExecutionData(this); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/AdvancementTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/AdvancementTrigger.java index cc26df8f2..2fb962d42 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/AdvancementTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/AdvancementTrigger.java @@ -8,19 +8,19 @@ public class AdvancementTrigger extends ChallengeTrigger { - public AdvancementTrigger(String name) { - super(name); - } + public AdvancementTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.KNOWLEDGE_BOOK; - } + @Override + public Material getMaterial() { + return Material.KNOWLEDGE_BOOK; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPickup(PlayerAdvancementDoneEvent event) { - if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; - createData().entity(event.getPlayer()).execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPickup(PlayerAdvancementDoneEvent event) { + if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; + createData().entity(event.getPlayer()).execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/BreakBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/BreakBlockTrigger.java index 12e06c8a1..959e9a8ab 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/BreakBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/BreakBlockTrigger.java @@ -9,22 +9,22 @@ public class BreakBlockTrigger extends ChallengeTrigger { - public BreakBlockTrigger(String name) { - super(name, SubSettingsHelper.createBlockSettingsBuilder()); - } + public BreakBlockTrigger(String name) { + super(name, SubSettingsHelper.createBlockSettingsBuilder()); + } - @Override - public Material getMaterial() { - return Material.GOLDEN_PICKAXE; - } + @Override + public Material getMaterial() { + return Material.GOLDEN_PICKAXE; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - createData() - .entity(event.getPlayer()) - .event(event) - .block(event.getBlock().getType()) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + createData() + .entity(event.getPlayer()) + .event(event) + .block(event.getBlock().getType()) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java index 9c2aed119..b13f0e5d3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java @@ -14,28 +14,28 @@ public class ConsumeItemTrigger extends ChallengeTrigger { - public ConsumeItemTrigger(String name) { - super(name, SubSettingsBuilder.createChooseMultipleItem(SubSettingsHelper.ITEM).fill(builder -> { - for (Material material : ExperimentalUtils.getMaterials()) { - if (material.isEdible()) { - builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); - } - } - })); - } + public ConsumeItemTrigger(String name) { + super(name, SubSettingsBuilder.createChooseMultipleItem(SubSettingsHelper.ITEM).fill(builder -> { + for (Material material : ExperimentalUtils.getMaterials()) { + if (material.isEdible()) { + builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); + } + } + })); + } - @Override - public Material getMaterial() { - return Material.COOKED_BEEF; - } + @Override + public Material getMaterial() { + return Material.COOKED_BEEF; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onConsumeItem(PlayerItemConsumeEvent event) { - createData() - .entity(event.getPlayer()) - .event(event) - .data(SubSettingsHelper.ITEM, SubSettingsHelper.ANY, event.getItem().getType().name()) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onConsumeItem(PlayerItemConsumeEvent event) { + createData() + .entity(event.getPlayer()) + .event(event) + .data(SubSettingsHelper.ITEM, SubSettingsHelper.ANY, event.getItem().getType().name()) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/CraftItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/CraftItemTrigger.java index f248ad991..a90c7850a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/CraftItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/CraftItemTrigger.java @@ -9,23 +9,23 @@ public class CraftItemTrigger extends ChallengeTrigger { - public CraftItemTrigger(String name) { - super(name); - } + public CraftItemTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.CRAFTING_TABLE; - } + @Override + public Material getMaterial() { + return Material.CRAFTING_TABLE; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onCraft(CraftItemEvent event) { - if (!(event.getWhoClicked() instanceof Player)) return; - Player player = (Player) event.getWhoClicked(); - createData() - .entity(player) - .event(event) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onCraft(CraftItemEvent event) { + if (!(event.getWhoClicked() instanceof Player)) return; + Player player = (Player) event.getWhoClicked(); + createData() + .entity(player) + .event(event) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/DropItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/DropItemTrigger.java index 815e2d103..3a87e15ac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/DropItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/DropItemTrigger.java @@ -8,21 +8,21 @@ public class DropItemTrigger extends ChallengeTrigger { - public DropItemTrigger(String name) { - super(name); - } + public DropItemTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.DROPPER; - } + @Override + public Material getMaterial() { + return Material.DROPPER; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onItemDrop(PlayerDropItemEvent event) { - createData() - .entity(event.getPlayer()) - .event(event) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onItemDrop(PlayerDropItemEvent event) { + createData() + .entity(event.getPlayer()) + .event(event) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java index 98e4366cf..37f1ccab3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java @@ -11,24 +11,24 @@ public class EntityDamageByPlayerTrigger extends ChallengeTrigger { - public EntityDamageByPlayerTrigger(String name) { - super(name, SubSettingsHelper.createEntityTypeSettingsBuilder(true, true)); - } + public EntityDamageByPlayerTrigger(String name) { + super(name, SubSettingsHelper.createEntityTypeSettingsBuilder(true, true)); + } - @Override - public Material getMaterial() { - return Material.WOODEN_SWORD; - } + @Override + public Material getMaterial() { + return Material.WOODEN_SWORD; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDeath(@Nonnull EntityDamageByPlayerEvent event) { + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDeath(@Nonnull EntityDamageByPlayerEvent event) { - createData() - .entity(event.getDamager()) - .event(event) - .entityType(event.getEntityType()) - .execute(); + createData() + .entity(event.getDamager()) + .event(event) + .entityType(event.getEntityType()) + .execute(); - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java index 84b823770..fb20cdc25 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java @@ -19,44 +19,44 @@ public class EntityDamageTrigger extends ChallengeTrigger { - public EntityDamageTrigger(String name) { - super(name, SubSettingsHelper.createEntityTypeSettingsBuilder(true, true).createChooseMultipleChild("damage_cause").fill(builder -> { - - List types = new ArrayList<>( - Arrays.asList(PotionEffectType.values())); - Collections.shuffle(types, new Random(1)); - - builder.addSetting(SubSettingsHelper.ANY, new ItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-trigger-damage-any"))); - - DamageCause[] values = DamageCause.values(); - for (int i = 0; i < values.length; i++) { - DamageCause cause = values[i]; - PotionEffectType effectType = types.get(i); - - builder.addSetting(cause.name(), - new PotionBuilder(Material.TIPPED_ARROW, - DefaultItem.getItemPrefix() + StringUtils.getEnumName(cause)) - .color(effectType.getColor()) - .build()); - - } - - })); - } - - @Override - public Material getMaterial() { - return Material.FLINT_AND_STEEL; - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDeath(@Nonnull EntityDamageEvent event) { - createData() - .entity(event.getEntity()) - .event(event) - .entityType(event.getEntityType()) - .data("damage_cause", SubSettingsHelper.ANY, event.getCause().name()) - .execute(); - } + public EntityDamageTrigger(String name) { + super(name, SubSettingsHelper.createEntityTypeSettingsBuilder(true, true).createChooseMultipleChild("damage_cause").fill(builder -> { + + List types = new ArrayList<>( + Arrays.asList(PotionEffectType.values())); + Collections.shuffle(types, new Random(1)); + + builder.addSetting(SubSettingsHelper.ANY, new ItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-trigger-damage-any"))); + + DamageCause[] values = DamageCause.values(); + for (int i = 0; i < values.length; i++) { + DamageCause cause = values[i]; + PotionEffectType effectType = types.get(i); + + builder.addSetting(cause.name(), + new PotionBuilder(Material.TIPPED_ARROW, + DefaultItem.getItemPrefix() + StringUtils.getEnumName(cause)) + .color(effectType.getColor()) + .build()); + + } + + })); + } + + @Override + public Material getMaterial() { + return Material.FLINT_AND_STEEL; + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDeath(@Nonnull EntityDamageEvent event) { + createData() + .entity(event.getEntity()) + .event(event) + .entityType(event.getEntityType()) + .data("damage_cause", SubSettingsHelper.ANY, event.getCause().name()) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java index 625c5505e..7cdb06121 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java @@ -11,21 +11,21 @@ public class EntityDeathTrigger extends ChallengeTrigger { - public EntityDeathTrigger(String name) { - super(name, SubSettingsHelper.createEntityTypeSettingsBuilder(true, true)); - } + public EntityDeathTrigger(String name) { + super(name, SubSettingsHelper.createEntityTypeSettingsBuilder(true, true)); + } - @Override - public Material getMaterial() { - return Material.BONE; - } + @Override + public Material getMaterial() { + return Material.BONE; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDeath(@Nonnull EntityDeathEvent event) { - createData() - .entity(event.getEntity()) - .entityType(event.getEntityType()) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDeath(@Nonnull EntityDeathEvent event) { + createData() + .entity(event.getEntity()) + .entityType(event.getEntityType()) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GainXPTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GainXPTrigger.java index d453b69ec..dd7421c52 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GainXPTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GainXPTrigger.java @@ -8,23 +8,23 @@ public class GainXPTrigger extends ChallengeTrigger { - public GainXPTrigger(String name) { - super(name); - } + public GainXPTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.EXPERIENCE_BOTTLE; - } + @Override + public Material getMaterial() { + return Material.EXPERIENCE_BOTTLE; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onXPGain(PlayerExpChangeEvent event) { - if (event.getAmount() > 0) { - createData() - .entity(event.getPlayer()) - .cancelAction(() -> event.setAmount(0)) - .execute(); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onXPGain(PlayerExpChangeEvent event) { + if (event.getAmount() > 0) { + createData() + .entity(event.getPlayer()) + .cancelAction(() -> event.setAmount(0)) + .execute(); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GetItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GetItemTrigger.java index 9b087f37b..31d624648 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GetItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/GetItemTrigger.java @@ -9,32 +9,32 @@ public class GetItemTrigger extends ChallengeTrigger { - public GetItemTrigger(String name) { - super(name, SubSettingsHelper.createItemSettingsBuilder()); - } + public GetItemTrigger(String name) { + super(name, SubSettingsHelper.createItemSettingsBuilder()); + } - @Override - public Material getMaterial() { - return Material.HOPPER; - } + @Override + public Material getMaterial() { + return Material.HOPPER; + } - @EventHandler - public void onPickupItem(PlayerPickupItemEvent event) { - createData() - .entity(event.getPlayer()) - .data("item", event.getItem().getItemStack().getType().name()) - .execute(); - } + @EventHandler + public void onPickupItem(PlayerPickupItemEvent event) { + createData() + .entity(event.getPlayer()) + .data("item", event.getItem().getItemStack().getType().name()) + .execute(); + } - @EventHandler - public void onPlayerInventoryClick(PlayerInventoryClickEvent event) { - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getHolder() != event.getPlayer()) return; - if (event.getCurrentItem() == null) return; - createData() - .entity(event.getPlayer()) - .data("item", event.getCurrentItem().getType().name()) - .execute(); - } + @EventHandler + public void onPlayerInventoryClick(PlayerInventoryClickEvent event) { + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getHolder() != event.getPlayer()) return; + if (event.getCurrentItem() == null) return; + createData() + .entity(event.getPlayer()) + .data("item", event.getCurrentItem().getType().name()) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java index 06e772fbd..7f04b2497 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/HungerTrigger.java @@ -9,24 +9,24 @@ public class HungerTrigger extends ChallengeTrigger { - public HungerTrigger(String name) { - super(name); - } + public HungerTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.ROTTEN_FLESH; - } + @Override + public Material getMaterial() { + return Material.ROTTEN_FLESH; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPickup(FoodLevelChangeEvent event) { - if (!(event.getEntity() instanceof Player)) return; - if (event.getFoodLevel() < event.getEntity().getFoodLevel()) { - createData() - .entity(event.getEntity()) - .event(event) - .execute(); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPickup(FoodLevelChangeEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (event.getFoodLevel() < event.getEntity().getFoodLevel()) { + createData() + .entity(event.getEntity()) + .event(event) + .execute(); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java index cc7020df3..cf6208b42 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java @@ -17,51 +17,51 @@ public class InLiquidTrigger extends ChallengeTrigger { - public InLiquidTrigger(String name) { - super(name, SubSettingsBuilder.createChooseMultipleItem(SubSettingsHelper.LIQUID).fill(builder -> { - builder.addSetting("LAVA", new ItemBuilder(Material.LAVA_BUCKET, DefaultItem.getItemPrefix() + "§cLava")); - builder.addSetting("WATER", new ItemBuilder(Material.WATER_BUCKET, DefaultItem.getItemPrefix() + "§9Water")); - })); - Challenges.getInstance().getScheduler().register(this); - } + public InLiquidTrigger(String name) { + super(name, SubSettingsBuilder.createChooseMultipleItem(SubSettingsHelper.LIQUID).fill(builder -> { + builder.addSetting("LAVA", new ItemBuilder(Material.LAVA_BUCKET, DefaultItem.getItemPrefix() + "§cLava")); + builder.addSetting("WATER", new ItemBuilder(Material.WATER_BUCKET, DefaultItem.getItemPrefix() + "§9Water")); + })); + Challenges.getInstance().getScheduler().register(this); + } - @Override - public Material getMaterial() { - return Material.BUCKET; - } + @Override + public Material getMaterial() { + return Material.BUCKET; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (BlockUtils.isSameBlockLocation(event.getTo(), event.getFrom())) return; - if (event.getTo() == null) return; + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (BlockUtils.isSameBlockLocation(event.getTo(), event.getFrom())) return; + if (event.getTo() == null) return; - Material type = event.getTo().getBlock().getType(); - Material oldType = event.getFrom().getBlock().getType(); - if ((type == Material.WATER || - type == Material.LAVA) && - oldType != Material.WATER && - oldType != Material.LAVA) { - createData() - .entity(event.getPlayer()) - .data(SubSettingsHelper.LIQUID, type.name()) - .execute(); - } + Material type = event.getTo().getBlock().getType(); + Material oldType = event.getFrom().getBlock().getType(); + if ((type == Material.WATER || + type == Material.LAVA) && + oldType != Material.WATER && + oldType != Material.LAVA) { + createData() + .entity(event.getPlayer()) + .data(SubSettingsHelper.LIQUID, type.name()) + .execute(); + } - } + } - @ScheduledTask(ticks = 5, async = false) - public void onFifthTick() { - for (Player player : Bukkit.getOnlinePlayers()) { - Material type = player.getLocation().getBlock().getType(); - if (type == Material.WATER || - type == Material.LAVA) { - createData() - .entity(player) - .data("liquid", type.name()) - .execute(); - } - } + @ScheduledTask(ticks = 5, async = false) + public void onFifthTick() { + for (Player player : Bukkit.getOnlinePlayers()) { + Material type = player.getLocation().getBlock().getType(); + if (type == Material.WATER || + type == Material.LAVA) { + createData() + .entity(player) + .data("liquid", type.name()) + .execute(); + } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java index b3217aaab..87f91462a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java @@ -14,72 +14,72 @@ public class IntervallTrigger extends ChallengeTrigger { - public IntervallTrigger(String name) { - super(name, SubSettingsBuilder.createChooseItem("time").fill(builder -> { - builder.addSetting("1", new ItemBuilder(Material.MUSIC_DISC_13, Message.forName("item-custom-trigger-intervall-second"), "1").build()); - String seconds = "item-custom-trigger-intervall-seconds"; - builder.addSetting("2", new ItemBuilder(Material.MUSIC_DISC_CAT, Message.forName(seconds), "2")); - builder.addSetting("5", new ItemBuilder(Material.MUSIC_DISC_BLOCKS, Message.forName(seconds), "5")); - builder.addSetting("10", new ItemBuilder(Material.MUSIC_DISC_CHIRP, Message.forName(seconds), "10")); - builder.addSetting("20", new ItemBuilder(Material.MUSIC_DISC_FAR, Message.forName(seconds), "20")); - builder.addSetting("30", new ItemBuilder(Material.MUSIC_DISC_MALL, Message.forName(seconds), "30")); - builder.addSetting("60", new ItemBuilder(Material.MUSIC_DISC_MELLOHI, Message.forName(seconds), "60")); - String minutes = "item-custom-trigger-intervall-minutes"; - builder.addSetting("120", new ItemBuilder(Material.MUSIC_DISC_STAL, Message.forName(minutes), "2")); - builder.addSetting("180", new ItemBuilder(Material.MUSIC_DISC_STRAD, Message.forName(minutes), "3")); - builder.addSetting("240", new ItemBuilder(Material.MUSIC_DISC_WARD, Message.forName(minutes), "4")); - builder.addSetting("300", new ItemBuilder(Material.MUSIC_DISC_11, Message.forName(minutes), "5")); - })); - Challenges.getInstance().getScheduler().register(this); - } + public IntervallTrigger(String name) { + super(name, SubSettingsBuilder.createChooseItem("time").fill(builder -> { + builder.addSetting("1", new ItemBuilder(Material.MUSIC_DISC_13, Message.forName("item-custom-trigger-intervall-second"), "1").build()); + String seconds = "item-custom-trigger-intervall-seconds"; + builder.addSetting("2", new ItemBuilder(Material.MUSIC_DISC_CAT, Message.forName(seconds), "2")); + builder.addSetting("5", new ItemBuilder(Material.MUSIC_DISC_BLOCKS, Message.forName(seconds), "5")); + builder.addSetting("10", new ItemBuilder(Material.MUSIC_DISC_CHIRP, Message.forName(seconds), "10")); + builder.addSetting("20", new ItemBuilder(Material.MUSIC_DISC_FAR, Message.forName(seconds), "20")); + builder.addSetting("30", new ItemBuilder(Material.MUSIC_DISC_MALL, Message.forName(seconds), "30")); + builder.addSetting("60", new ItemBuilder(Material.MUSIC_DISC_MELLOHI, Message.forName(seconds), "60")); + String minutes = "item-custom-trigger-intervall-minutes"; + builder.addSetting("120", new ItemBuilder(Material.MUSIC_DISC_STAL, Message.forName(minutes), "2")); + builder.addSetting("180", new ItemBuilder(Material.MUSIC_DISC_STRAD, Message.forName(minutes), "3")); + builder.addSetting("240", new ItemBuilder(Material.MUSIC_DISC_WARD, Message.forName(minutes), "4")); + builder.addSetting("300", new ItemBuilder(Material.MUSIC_DISC_11, Message.forName(minutes), "5")); + })); + Challenges.getInstance().getScheduler().register(this); + } - @Override - public Material getMaterial() { - return Material.CLOCK; - } + @Override + public Material getMaterial() { + return Material.CLOCK; + } - @ScheduledTask(ticks = 20, playerPolicy = PlayerCountPolicy.ALWAYS) - public void onSecond() { - long currentTime = Challenges.getInstance().getChallengeTimer().getTime(); + @ScheduledTask(ticks = 20, playerPolicy = PlayerCountPolicy.ALWAYS) + public void onSecond() { + long currentTime = Challenges.getInstance().getChallengeTimer().getTime(); - List list = new LinkedList<>(); - list.add("1"); + List list = new LinkedList<>(); + list.add("1"); - if (currentTime % 2 == 0) { - list.add("2"); - } - if (currentTime % 5 == 0) { - list.add("5"); - } - if (currentTime % 10 == 0) { - list.add("10"); - } - if (currentTime % 20 == 0) { - list.add("20"); - } - if (currentTime % 30 == 0) { - list.add("30"); - } - if (currentTime % 60 == 0) { - list.add("60"); - } - if (currentTime % 120 == 0) { - list.add("120"); - } - if (currentTime % 180 == 0) { - list.add("180"); - } - if (currentTime % 180 == 0) { - list.add("180"); - } - if (currentTime % 300 == 0) { - list.add("300"); - } + if (currentTime % 2 == 0) { + list.add("2"); + } + if (currentTime % 5 == 0) { + list.add("5"); + } + if (currentTime % 10 == 0) { + list.add("10"); + } + if (currentTime % 20 == 0) { + list.add("20"); + } + if (currentTime % 30 == 0) { + list.add("30"); + } + if (currentTime % 60 == 0) { + list.add("60"); + } + if (currentTime % 120 == 0) { + list.add("120"); + } + if (currentTime % 180 == 0) { + list.add("180"); + } + if (currentTime % 180 == 0) { + list.add("180"); + } + if (currentTime % 300 == 0) { + list.add("300"); + } - createData() - .data("time", list) - .execute(); - } + createData() + .data("time", list) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/LevelUpTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/LevelUpTrigger.java index a95ea5de9..784ddb0d5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/LevelUpTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/LevelUpTrigger.java @@ -8,22 +8,22 @@ public class LevelUpTrigger extends ChallengeTrigger { - public LevelUpTrigger(String name) { - super(name); - } + public LevelUpTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.ENCHANTING_TABLE; - } + @Override + public Material getMaterial() { + return Material.ENCHANTING_TABLE; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onLevelUp(PlayerLevelChangeEvent event) { - if (event.getNewLevel() > event.getOldLevel()) { - createData() - .entity(event.getPlayer()) - .execute(); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onLevelUp(PlayerLevelChangeEvent event) { + if (event.getNewLevel() > event.getOldLevel()) { + createData() + .entity(event.getPlayer()) + .execute(); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveBlockTrigger.java index 03de99396..c20e0fc76 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveBlockTrigger.java @@ -9,22 +9,22 @@ public class MoveBlockTrigger extends ChallengeTrigger { - public MoveBlockTrigger(String name) { - super(name); - } + public MoveBlockTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.LEATHER_BOOTS; - } + @Override + public Material getMaterial() { + return Material.LEATHER_BOOTS; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), event.getFrom())) return; - createData() - .entity(event.getPlayer()) - .event(event) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), event.getFrom())) return; + createData() + .entity(event.getPlayer()) + .event(event) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveCameraTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveCameraTrigger.java index d203be81d..47d79e92c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveCameraTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveCameraTrigger.java @@ -8,23 +8,23 @@ public class MoveCameraTrigger extends ChallengeTrigger { - public MoveCameraTrigger(String name) { - super(name); - } + public MoveCameraTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.COMPASS; - } + @Override + public Material getMaterial() { + return Material.COMPASS; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getTo() == null) return; - if (event.getFrom().getDirection().equals(event.getTo().getDirection())) return; - createData() - .entity(event.getPlayer()) - .event(event) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (event.getTo() == null) return; + if (event.getFrom().getDirection().equals(event.getTo().getDirection())) return; + createData() + .entity(event.getPlayer()) + .event(event) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveDownTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveDownTrigger.java index e16df9e1b..73fd6a60c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveDownTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveDownTrigger.java @@ -8,25 +8,25 @@ public class MoveDownTrigger extends ChallengeTrigger { - public MoveDownTrigger(String name) { - super(name); - } + public MoveDownTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.NETHER_BRICK_STAIRS; - } + @Override + public Material getMaterial() { + return Material.NETHER_BRICK_STAIRS; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getTo() == null) return; - if (event.getTo().getBlockY() < event.getFrom().getBlockY()) { - createData() - .entity(event.getPlayer()) - .event(event) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (event.getTo() == null) return; + if (event.getTo().getBlockY() < event.getFrom().getBlockY()) { + createData() + .entity(event.getPlayer()) + .event(event) + .execute(); + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveUpTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveUpTrigger.java index d2bd8d42f..0ee50a4aa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveUpTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/MoveUpTrigger.java @@ -8,25 +8,25 @@ public class MoveUpTrigger extends ChallengeTrigger { - public MoveUpTrigger(String name) { - super(name); - } + public MoveUpTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.PURPUR_STAIRS; - } + @Override + public Material getMaterial() { + return Material.PURPUR_STAIRS; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getTo() == null) return; - if (event.getTo().getBlockY() > event.getFrom().getBlockY()) { - createData() - .entity(event.getPlayer()) - .event(event) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (event.getTo() == null) return; + if (event.getTo().getBlockY() > event.getFrom().getBlockY()) { + createData() + .entity(event.getPlayer()) + .event(event) + .execute(); + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PickupItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PickupItemTrigger.java index 18192a54e..0de86a1f2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PickupItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PickupItemTrigger.java @@ -8,21 +8,21 @@ public class PickupItemTrigger extends ChallengeTrigger { - public PickupItemTrigger(String name) { - super(name); - } + public PickupItemTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.STICK; - } + @Override + public Material getMaterial() { + return Material.STICK; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPickup(PlayerPickupItemEvent event) { - createData() - .entity(event.getPlayer()) - .event(event) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPickup(PlayerPickupItemEvent event) { + createData() + .entity(event.getPlayer()) + .event(event) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlaceBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlaceBlockTrigger.java index 9b6de5cdc..21674f27f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlaceBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlaceBlockTrigger.java @@ -9,22 +9,22 @@ public class PlaceBlockTrigger extends ChallengeTrigger { - public PlaceBlockTrigger(String name) { - super(name, SubSettingsHelper.createBlockSettingsBuilder()); - } + public PlaceBlockTrigger(String name) { + super(name, SubSettingsHelper.createBlockSettingsBuilder()); + } - @Override - public Material getMaterial() { - return Material.BRICKS; - } + @Override + public Material getMaterial() { + return Material.BRICKS; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) { - createData() - .entity(event.getPlayer()) - .event(event) - .block(event.getBlock().getType()) - .execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockPlace(BlockPlaceEvent event) { + createData() + .entity(event.getPlayer()) + .event(event) + .block(event.getBlock().getType()) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java index 37d5ca5be..440a0bcb1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java @@ -10,18 +10,18 @@ public class PlayerJumpTrigger extends ChallengeTrigger { - public PlayerJumpTrigger(String name) { - super(name); - } + public PlayerJumpTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.RABBIT_FOOT; - } + @Override + public Material getMaterial() { + return Material.RABBIT_FOOT; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onJump(@Nonnull PlayerJumpEvent event) { - createData().entity(event.getPlayer()).execute(); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onJump(@Nonnull PlayerJumpEvent event) { + createData().entity(event.getPlayer()).execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java index a5b2da478..75b19ba32 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java @@ -10,20 +10,20 @@ public class PlayerSneakTrigger extends ChallengeTrigger { - public PlayerSneakTrigger(String name) { - super(name); - } + public PlayerSneakTrigger(String name) { + super(name); + } - @Override - public Material getMaterial() { - return Material.SANDSTONE_SLAB; - } + @Override + public Material getMaterial() { + return Material.SANDSTONE_SLAB; + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onJump(@Nonnull PlayerToggleSneakEvent event) { - if (event.isSneaking()) { - createData().entity(event.getPlayer()).execute(); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onJump(@Nonnull PlayerToggleSneakEvent event) { + if (event.isSneaking()) { + createData().entity(event.getPlayer()).execute(); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsNotOnSpecificBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsNotOnSpecificBlockTrigger.java index a53a775ed..ab3afe49c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsNotOnSpecificBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsNotOnSpecificBlockTrigger.java @@ -16,38 +16,38 @@ public class StandsNotOnSpecificBlockTrigger extends ChallengeTrigger { - public StandsNotOnSpecificBlockTrigger(String name) { - super(name, SubSettingsHelper.createBlockSettingsBuilder()); - } - - @Override - public Material getMaterial() { - return Material.MAGMA_BLOCK; - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (BlockUtils.isSameBlockLocation(event.getTo(), event.getFrom())) return; - if (event.getTo() == null) return; - Block blockBelow = BlockUtils.getBlockBelow(event.getTo()); - if (blockBelow == null) return; - - Material type = blockBelow.getType(); - - List materials = new LinkedList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - materials.remove(type); - materials.removeIf(material -> !material.isBlock() || !material.isItem()); - - List names = new LinkedList<>(); - for (Material material : materials) { - names.add(material.name()); - } - - createData() - .entity(event.getPlayer()) - .event(event) - .data("block", names) - .execute(); - } + public StandsNotOnSpecificBlockTrigger(String name) { + super(name, SubSettingsHelper.createBlockSettingsBuilder()); + } + + @Override + public Material getMaterial() { + return Material.MAGMA_BLOCK; + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (BlockUtils.isSameBlockLocation(event.getTo(), event.getFrom())) return; + if (event.getTo() == null) return; + Block blockBelow = BlockUtils.getBlockBelow(event.getTo()); + if (blockBelow == null) return; + + Material type = blockBelow.getType(); + + List materials = new LinkedList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + materials.remove(type); + materials.removeIf(material -> !material.isBlock() || !material.isItem()); + + List names = new LinkedList<>(); + for (Material material : materials) { + names.add(material.name()); + } + + createData() + .entity(event.getPlayer()) + .event(event) + .data("block", names) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java index 3836f8921..38606ffcd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java @@ -13,27 +13,27 @@ public class StandsOnSpecificBlockTrigger extends ChallengeTrigger { - public StandsOnSpecificBlockTrigger(String name) { - super(name, SubSettingsHelper.createBlockSettingsBuilder()); - } - - @Override - public Material getMaterial() { - return Material.PACKED_ICE; - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (BlockUtils.isSameBlockLocation(event.getTo(), event.getFrom())) return; - Block blockBelow = BlockUtils.getBlockBelow( - Objects.requireNonNull(event.getTo())); - if (blockBelow == null) return; - - createData() - .entity(event.getPlayer()) - .event(event) - .block(blockBelow.getType()) - .execute(); - } + public StandsOnSpecificBlockTrigger(String name) { + super(name, SubSettingsHelper.createBlockSettingsBuilder()); + } + + @Override + public Material getMaterial() { + return Material.PACKED_ICE; + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (BlockUtils.isSameBlockLocation(event.getTo(), event.getFrom())) return; + Block blockBelow = BlockUtils.getBlockBelow( + Objects.requireNonNull(event.getTo())); + if (blockBelow == null) return; + + createData() + .entity(event.getPlayer()) + .event(event) + .block(blockBelow.getType()) + .execute(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java index f84d8d37f..1ed8be435 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java @@ -21,64 +21,64 @@ @Since("2.0.2") public class DamageTeleportChallenge extends SettingModifier { - private static final int PLAYER = 1, EVERYONE = 2; - - public DamageTeleportChallenge() { - super(MenuType.CHALLENGES, 1, 2); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SHULKER_SHELL, Message.forName("item-damage-teleport-challenge")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (getValue() == 1) { - return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone")); - } else { - return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("player")); - } - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 0 ? Message.forName("everyone").asString() : Message.forName("player").asString()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (!(event.getEntity() instanceof Player)) return; - if (!shouldExecuteEffect()) return; - if (ChallengeHelper.finalDamageIsNull(event)) return; - - handleDamage(((Player) event.getEntity())); - } - - private void handleDamage(@Nonnull Player player) { - - Location location = player.getWorld().getHighestBlockAt(getRandomLocation(player.getWorld())).getLocation(); - location.setY(location.getY() + 1); - location.getChunk().load(true); - - if (getValue() == PLAYER) { - player.teleport(location); - } else { - broadcastFiltered(player1 -> player1.teleport(location)); - } - - } - - public Location getRandomLocation(World world) { - double size = world.getWorldBorder().getSize() / 2; - size--; - - final double randomX = ThreadLocalRandom.current().nextDouble(-size, size); - final double randomY = ThreadLocalRandom.current().nextDouble(-size, size); - - return world.getWorldBorder().getCenter().add(randomX, 0, randomY); - } + private static final int PLAYER = 1, EVERYONE = 2; + + public DamageTeleportChallenge() { + super(MenuType.CHALLENGES, 1, 2); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SHULKER_SHELL, Message.forName("item-damage-teleport-challenge")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (getValue() == 1) { + return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone")); + } else { + return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("player")); + } + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 0 ? Message.forName("everyone").asString() : Message.forName("player").asString()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!shouldExecuteEffect()) return; + if (ChallengeHelper.finalDamageIsNull(event)) return; + + handleDamage(((Player) event.getEntity())); + } + + private void handleDamage(@Nonnull Player player) { + + Location location = player.getWorld().getHighestBlockAt(getRandomLocation(player.getWorld())).getLocation(); + location.setY(location.getY() + 1); + location.getChunk().load(true); + + if (getValue() == PLAYER) { + player.teleport(location); + } else { + broadcastFiltered(player1 -> player1.teleport(location)); + } + + } + + public Location getRandomLocation(World world) { + double size = world.getWorldBorder().getSize() / 2; + size--; + + final double randomX = ThreadLocalRandom.current().nextDouble(-size, size); + final double randomY = ThreadLocalRandom.current().nextDouble(-size, size); + + return world.getWorldBorder().getCenter().add(randomX, 0, randomY); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index baca7505e..cdffe4629 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -28,85 +28,85 @@ @Since("2.0") public class ZeroHeartsChallenge extends SettingModifier { - public ZeroHeartsChallenge() { - super(MenuType.CHALLENGES, 5, 30, 10); - } + public ZeroHeartsChallenge() { + super(MenuType.CHALLENGES, 5, 30, 10); + } - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - int currentTime = getCurrentTime(); - int maxTime = getValue() * 60; - bossbar.setTitle(Message.forName("bossbar-zero-hearts").asString(maxTime - currentTime)); - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(1 - ((float) currentTime / maxTime)); - }); - bossbar.show(); - Bukkit.getOnlinePlayers().forEach(player -> { - AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); - if (attribute == null) return; - attribute.setBaseValue(0); - }); - } + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + int currentTime = getCurrentTime(); + int maxTime = getValue() * 60; + bossbar.setTitle(Message.forName("bossbar-zero-hearts").asString(maxTime - currentTime)); + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(1 - ((float) currentTime / maxTime)); + }); + bossbar.show(); + Bukkit.getOnlinePlayers().forEach(player -> { + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return; + attribute.setBaseValue(0); + }); + } - @Override - protected void onDisable() { - bossbar.hide(); - AbstractChallenge.getFirstInstance(MaxHealthSetting.class).onValueChange(); - } + @Override + protected void onDisable() { + bossbar.hide(); + AbstractChallenge.getFirstInstance(MaxHealthSetting.class).onValueChange(); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENCHANTED_GOLDEN_APPLE, Message.forName("item-zero-hearts-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ENCHANTED_GOLDEN_APPLE, Message.forName("item-zero-hearts-challenge")); + } - @Override - protected void onValueChange() { - bossbar.update(); - } + @Override + protected void onValueChange() { + bossbar.update(); + } - @ScheduledTask(ticks = 20, async = false) - public void onSecond() { - broadcast(player -> { - AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); - if (attribute == null) return; - attribute.setBaseValue(0); - }); - int absorptionTime = getCurrentTime(); - if (absorptionTime >= getValue() * 60) { - bossbar.hide(); - if (absorptionTime == getValue() * 60) { - removeAbsorptionEffect(); - } - return; - } - getGameStateData().set("absorption-time", absorptionTime + 1); - applyAbsorptionEffect(); - bossbar.update(); - } + @ScheduledTask(ticks = 20, async = false) + public void onSecond() { + broadcast(player -> { + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return; + attribute.setBaseValue(0); + }); + int absorptionTime = getCurrentTime(); + if (absorptionTime >= getValue() * 60) { + bossbar.hide(); + if (absorptionTime == getValue() * 60) { + removeAbsorptionEffect(); + } + return; + } + getGameStateData().set("absorption-time", absorptionTime + 1); + applyAbsorptionEffect(); + bossbar.update(); + } - private int getCurrentTime() { - return getGameStateData().getInt("absorption-time"); - } + private int getCurrentTime() { + return getGameStateData().getInt("absorption-time"); + } - private void applyAbsorptionEffect() { - broadcastFiltered(player -> player.addPotionEffect(new PotionEffect(PotionEffectType.ABSORPTION, (getValue() - getCurrentTime()) * 20 * 60, 1, true, false, false))); - } + private void applyAbsorptionEffect() { + broadcastFiltered(player -> player.addPotionEffect(new PotionEffect(PotionEffectType.ABSORPTION, (getValue() - getCurrentTime()) * 20 * 60, 1, true, false, false))); + } - private void removeAbsorptionEffect() { - broadcastFiltered(player -> player.removePotionEffect(PotionEffectType.ABSORPTION)); - } + private void removeAbsorptionEffect() { + broadcastFiltered(player -> player.removePotionEffect(PotionEffectType.ABSORPTION)); + } - @EventHandler(priority = EventPriority.HIGH) - public void onEntityPotionEffect(@Nonnull EntityPotionEffectEvent event) { - if (event.getAction() != Action.REMOVED) return; - if (!(event.getEntity() instanceof Player)) return; - if (!shouldExecuteEffect()) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - kill(player); - Message.forName("zero-hearts-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); - } + @EventHandler(priority = EventPriority.HIGH) + public void onEntityPotionEffect(@Nonnull EntityPotionEffectEvent event) { + if (event.getAction() != Action.REMOVED) return; + if (!(event.getEntity() instanceof Player)) return; + if (!shouldExecuteEffect()) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + kill(player); + Message.forName("zero-hearts-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java index d3d23f051..827616b35 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java @@ -16,36 +16,36 @@ public class AdvancementDamageChallenge extends SettingModifier { - public AdvancementDamageChallenge() { - super(MenuType.CHALLENGES, 1, 40); - setCategory(SettingCategory.DAMAGE); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOOK, Message.forName("item-advancement-damage-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerAdvancementDone(@Nonnull PlayerAdvancementDoneEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; - - event.getPlayer().setNoDamageTicks(0); - event.getPlayer().damage(getValue()); - } + public AdvancementDamageChallenge() { + super(MenuType.CHALLENGES, 1, 40); + setCategory(SettingCategory.DAMAGE); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BOOK, Message.forName("item-advancement-damage-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerAdvancementDone(@Nonnull PlayerAdvancementDoneEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; + + event.getPlayer().setNoDamageTicks(0); + event.getPlayer().damage(getValue()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java index 4b9c86806..aa70429fa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java @@ -15,33 +15,33 @@ public class BlockBreakDamageChallenge extends SettingModifier { - public BlockBreakDamageChallenge() { - super(MenuType.CHALLENGES, 1, 60); - setCategory(SettingCategory.DAMAGE); - } - - @EventHandler - public void onBreak(BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - event.getPlayer().setNoDamageTicks(0); - event.getPlayer().damage(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-block-break-damage-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } + public BlockBreakDamageChallenge() { + super(MenuType.CHALLENGES, 1, 60); + setCategory(SettingCategory.DAMAGE); + } + + @EventHandler + public void onBreak(BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + event.getPlayer().setNoDamageTicks(0); + event.getPlayer().damage(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-block-break-damage-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java index f2a10abb6..53f3059fa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java @@ -17,33 +17,33 @@ @Since("2.0") public class BlockPlaceDamageChallenge extends SettingModifier { - public BlockPlaceDamageChallenge() { - super(MenuType.CHALLENGES, 1, 60); - setCategory(SettingCategory.DAMAGE); - } - - @EventHandler - public void onBreak(BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - event.getPlayer().setNoDamageTicks(0); - event.getPlayer().damage(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLD_BLOCK, Message.forName("item-block-place-damage-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } + public BlockPlaceDamageChallenge() { + super(MenuType.CHALLENGES, 1, 60); + setCategory(SettingCategory.DAMAGE); + } + + @EventHandler + public void onBreak(BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + event.getPlayer().setNoDamageTicks(0); + event.getPlayer().damage(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GOLD_BLOCK, Message.forName("item-block-place-damage-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java index c0ae72c54..ca487586a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java @@ -19,36 +19,36 @@ public class DamagePerBlockChallenge extends SettingModifier { - public DamagePerBlockChallenge() { - super(MenuType.CHALLENGES, 1, 40); - setCategory(SettingCategory.DAMAGE); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), event.getFrom())) return; - - event.getPlayer().setNoDamageTicks(0); - event.getPlayer().damage(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-damage-block-challenge")).setColor(Color.RED); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } + public DamagePerBlockChallenge() { + super(MenuType.CHALLENGES, 1, 40); + setCategory(SettingCategory.DAMAGE); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), event.getFrom())) return; + + event.getPlayer().setNoDamageTicks(0); + event.getPlayer().damage(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-damage-block-challenge")).setColor(Color.RED); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java index bd3ece7ea..196888b2a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java @@ -17,37 +17,37 @@ public class DamagePerItemChallenge extends Setting { - public DamagePerItemChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.DAMAGE); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPickup(@Nonnull PlayerPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - applyDamage(event.getPlayer(), event.getItem().getItemStack().getAmount()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onClick(@Nonnull PlayerInventoryClickEvent event) { - if (event.isCancelled()) return; // ignoreCancelled not working on own event - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getAction() == InventoryAction.NOTHING) return; - if (event.getCurrentItem() == null) return; - applyDamage(event.getPlayer(), event.getCurrentItem().getAmount()); - } - - private void applyDamage(@Nonnull Player player, int amount) { - player.setNoDamageTicks(0); - player.damage(amount); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SHEARS, Message.forName("item-damage-item-challenge")); - } - -} \ No newline at end of file + public DamagePerItemChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.DAMAGE); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPickup(@Nonnull PlayerPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + applyDamage(event.getPlayer(), event.getItem().getItemStack().getAmount()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onClick(@Nonnull PlayerInventoryClickEvent event) { + if (event.isCancelled()) return; // ignoreCancelled not working on own event + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getAction() == InventoryAction.NOTHING) return; + if (event.getCurrentItem() == null) return; + applyDamage(event.getPlayer(), event.getCurrentItem().getAmount()); + } + + private void applyDamage(@Nonnull Player player, int amount) { + player.setNoDamageTicks(0); + player.damage(amount); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SHEARS, Message.forName("item-damage-item-challenge")); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java index 43570f302..7b1642b87 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java @@ -18,26 +18,26 @@ @Since("2.0") public class DeathOnFallChallenge extends Setting { - public DeathOnFallChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.DAMAGE); - } + public DeathOnFallChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.DAMAGE); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FEATHER, Message.forName("item-death-on-fall-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FEATHER, Message.forName("item-death-on-fall-challenge")); + } - @EventHandler(priority = EventPriority.HIGH) - public void onEntityDamage(@Nonnull EntityDamageEvent event) { - if (!(event.getEntity() instanceof Player)) return; - if (!shouldExecuteEffect()) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - if (event.getCause() != DamageCause.FALL) return; - event.setDamage(player.getHealth()); - event.setCancelled(false); - } + @EventHandler(priority = EventPriority.HIGH) + public void onEntityDamage(@Nonnull EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!shouldExecuteEffect()) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + if (event.getCause() != DamageCause.FALL) return; + event.setDamage(player.getHealth()); + event.setCancelled(false); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java index f83e0cd12..5c9ce881f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import net.anweisen.utilities.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -19,58 +17,61 @@ import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.potion.PotionEffect; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + @Since("2.0.2") public class FreezeChallenge extends SettingModifier { - public FreezeChallenge() { - super(MenuType.CHALLENGES, 5, 60, 20); - setCategory(SettingCategory.DAMAGE); - } + public FreezeChallenge() { + super(MenuType.CHALLENGES, 5, 60, 20); + setCategory(SettingCategory.DAMAGE); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BLUE_ICE, Message.forName("item-freeze-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BLUE_ICE, Message.forName("item-freeze-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - if (ChallengeHelper.finalDamageIsNull(event)) return; - double damage = ChallengeHelper.getFinalDamage(event); + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + if (ChallengeHelper.finalDamageIsNull(event)) return; + double damage = ChallengeHelper.getFinalDamage(event); - setFreeze(player, damage); - } + setFreeze(player, damage); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - if (event.getTo().getY() == event.getFrom().getY() && event.getTo().getX() == event.getFrom().getX() && event.getTo().getZ() == event.getFrom().getZ()) - return; - PotionEffect effect = event.getPlayer().getPotionEffect(MinecraftNameWrapper.SLOWNESS); - if (effect == null || effect.getAmplifier() != 255) return; - event.setCancelled(true); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + if (event.getTo().getY() == event.getFrom().getY() && event.getTo().getX() == event.getFrom().getX() && event.getTo().getZ() == event.getFrom().getZ()) + return; + PotionEffect effect = event.getPlayer().getPotionEffect(MinecraftNameWrapper.SLOWNESS); + if (effect == null || effect.getAmplifier() != 255) return; + event.setCancelled(true); + } - public void setFreeze(LivingEntity entity, double damage) { - int time = (int) (damage * getValue() * 20 / 2); - PotionEffect effect = entity.getPotionEffect(MinecraftNameWrapper.SLOWNESS); - entity.removePotionEffect(MinecraftNameWrapper.SLOWNESS); + public void setFreeze(LivingEntity entity, double damage) { + int time = (int) (damage * getValue() * 20 / 2); + PotionEffect effect = entity.getPotionEffect(MinecraftNameWrapper.SLOWNESS); + entity.removePotionEffect(MinecraftNameWrapper.SLOWNESS); - if (effect != null && effect.getAmplifier() == 255) time += effect.getDuration(); + if (effect != null && effect.getAmplifier() == 255) time += effect.getDuration(); - entity.addPotionEffect(new PotionEffect(MinecraftNameWrapper.SLOWNESS, time, 255)); - } + entity.addPotionEffect(new PotionEffect(MinecraftNameWrapper.SLOWNESS, time, 255)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java index d7ca9212c..677f1af99 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java @@ -22,36 +22,36 @@ @Since("2.0") public class JumpDamageChallenge extends SettingModifier { - public JumpDamageChallenge() { - super(MenuType.CHALLENGES, 1, 60); - setCategory(SettingCategory.DAMAGE); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-jump-damage-challenge")).setColor(Color.ORANGE); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() / 2); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSneak(@Nonnull PlayerJumpEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - Message.forName("jump-damage-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - event.getPlayer().setNoDamageTicks(0); - event.getPlayer().damage(getValue()); - event.getPlayer().setNoDamageTicks(0); - } + public JumpDamageChallenge() { + super(MenuType.CHALLENGES, 1, 60); + setCategory(SettingCategory.DAMAGE); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-jump-damage-challenge")).setColor(Color.ORANGE); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() / 2); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSneak(@Nonnull PlayerJumpEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + Message.forName("jump-damage-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + event.getPlayer().setNoDamageTicks(0); + event.getPlayer().damage(getValue()); + event.getPlayer().setNoDamageTicks(0); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java index 7be4a0e9b..babb068e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java @@ -14,24 +14,24 @@ public class ReversedDamageChallenge extends Setting { - public ReversedDamageChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.DAMAGE); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_SWORD, Message.forName("item-reversed-damage-challenge")); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDamageByPlayer(@Nonnull EntityDamageByPlayerEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getDamager())) return; - - double damage = event.getFinalDamage(); - event.getDamager().damage(damage); - } + public ReversedDamageChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.DAMAGE); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GOLDEN_SWORD, Message.forName("item-reversed-damage-challenge")); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDamageByPlayer(@Nonnull EntityDamageByPlayerEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getDamager())) return; + + double damage = event.getFinalDamage(); + event.getDamager().damage(damage); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java index 1ba29b8cf..86f1b627d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java @@ -20,37 +20,37 @@ public class SneakDamageChallenge extends SettingModifier { - public SneakDamageChallenge() { - super(MenuType.CHALLENGES, 1, 60); - setCategory(SettingCategory.DAMAGE); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-sneak-damage-challenge")).setColor(Color.YELLOW); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() / 2); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSneak(@Nonnull PlayerToggleSneakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (!event.isSneaking()) return; - Message.forName("sneak-damage-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - event.getPlayer().setNoDamageTicks(0); - event.getPlayer().damage(getValue()); - event.getPlayer().setNoDamageTicks(0); - } + public SneakDamageChallenge() { + super(MenuType.CHALLENGES, 1, 60); + setCategory(SettingCategory.DAMAGE); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-sneak-damage-challenge")).setColor(Color.YELLOW); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() / 2); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSneak(@Nonnull PlayerToggleSneakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (!event.isSneaking()) return; + Message.forName("sneak-damage-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + event.getPlayer().setNoDamageTicks(0); + event.getPlayer().damage(getValue()); + event.getPlayer().setNoDamageTicks(0); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java index f6b269788..47e5c80fa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java @@ -18,37 +18,37 @@ @Since("2.0") public class WaterAllergyChallenge extends SettingModifier { - public WaterAllergyChallenge() { - super(MenuType.CHALLENGES, 1, 40); - setCategory(SettingCategory.DAMAGE); - } - - @ScheduledTask(ticks = 5, async = false) - public void onFifthTick() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) return; - if (player.getLocation().getBlock().getType() == Material.WATER) { - player.damage(getValue()); - } - } - - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CYAN_GLAZED_TERRACOTTA, Message.forName("item-water-allergy-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } + public WaterAllergyChallenge() { + super(MenuType.CHALLENGES, 1, 40); + setCategory(SettingCategory.DAMAGE); + } + + @ScheduledTask(ticks = 5, async = false) + public void onFifthTick() { + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) return; + if (player.getLocation().getBlock().getType() == Material.WATER) { + player.damage(getValue()); + } + } + + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CYAN_GLAZED_TERRACOTTA, Message.forName("item-water-allergy-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java index a9d565725..91e7dc361 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java @@ -35,136 +35,136 @@ @Since("2.1.2") public class BlockEffectChallenge extends Setting { - /* - * Saving potion effect to prevent the possibility that an effect remove was somehow skipped - */ - private Map currentPotionEffects = new HashMap<>(); - - public BlockEffectChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.EFFECT); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CARVED_PUMPKIN, Message.forName("item-block-effect-challenge")); - } - - @Override - protected void onEnable() { - currentPotionEffects = new HashMap<>(); - if (!shouldExecuteEffect()) return; - broadcastFiltered(player -> { - addEffect(player, player.getLocation(), null); - }); - } - - @TimerTask(status = TimerStatus.RUNNING) - public void onStart() { - broadcastFiltered(player -> { - addEffect(player, player.getLocation(), null); - }); - } - - @Override - protected void onDisable() { - broadcastFiltered(player -> { - removeEffect(player, player.getLocation(), null); - }); - currentPotionEffects = null; - } - - @EventHandler(priority = EventPriority.LOW) - public void onLeave(PlayerQuitEvent event) { - if (!shouldExecuteEffect()) return; - currentPotionEffects.remove(event.getPlayer().getUniqueId()); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onGameModeChange(PlayerIgnoreStatusChangeEvent event) { - if (!shouldExecuteEffect()) return; - if (event.isIgnored()) { - removeEffect(event.getPlayer(), event.getPlayer().getLocation(), null); - } else { - addEffect(event.getPlayer(), event.getPlayer().getLocation(), null); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - Block fromBlock = BlockUtils.getBlockBelow(event.getFrom()); - Block toBlock = BlockUtils.getBlockBelow(event.getTo()); - if (toBlock != null && fromBlock != null) { - if (toBlock.getType() == fromBlock.getType()) return; - } - removeEffect(event.getPlayer(), event.getFrom(), fromBlock); - addEffect(event.getPlayer(), event.getTo(), toBlock); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onTeleport(PlayerTeleportEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - Block fromBlock = BlockUtils.getBlockBelow(event.getFrom()); - Block toBlock = BlockUtils.getBlockBelow(event.getTo()); - if (toBlock != null && fromBlock != null) { - if (toBlock.getType() == fromBlock.getType()) return; - } - removeEffect(event.getPlayer(), event.getFrom(), fromBlock); - addEffect(event.getPlayer(), event.getTo(), toBlock); - } - - @ScheduledTask(ticks = 20, async = false) - public void onSecond() { - broadcastFiltered(player -> { - addEffect(player, player.getLocation(), null); - }); - } - - public void removeEffect(Player player, Location location, Block blockBelow) { - if (blockBelow == null) { - blockBelow = BlockUtils.getBlockBelow(location, -1); - } - if (blockBelow == null) return; - PotionEffectType type = getEffect(blockBelow.getType()).getType(); - player.removePotionEffect(type); - - removeEffectInCache(player); - } - - - public void addEffect(Player player, Location location, Block blockBelow) { - if (blockBelow == null) { - blockBelow = BlockUtils.getBlockBelow(location, -1); - } - if (blockBelow == null) return; - PotionEffect effect = getEffect(blockBelow.getType()); - PotionEffect currentEffect = currentPotionEffects.get(player.getUniqueId()); - if (currentEffect != null && !currentEffect.equals(effect)) { - player.removePotionEffect(currentEffect.getType()); - } else if (player.hasPotionEffect(effect.getType())) return; - player.addPotionEffect(effect); - currentPotionEffects.put(player.getUniqueId(), effect); - } - - public void removeEffectInCache(Player player) { - PotionEffect currentEffect = currentPotionEffects.get(player.getUniqueId()); - if (currentEffect != null) { - player.removePotionEffect(currentEffect.getType()); - } - } - - private PotionEffect getEffect(Material material) { - long seed = ChallengeAPI.getGameWorld(World.Environment.NORMAL).getSeed(); - IRandom random = new SeededRandomWrapper(seed / material.ordinal()); - PotionEffectType[] types = PotionEffectType.values(); - PotionEffectType type = types[random.nextInt(types.length)]; - return type.createEffect(Integer.MAX_VALUE, random.nextInt(type.isInstant() ? 1 : 4)); - } + /* + * Saving potion effect to prevent the possibility that an effect remove was somehow skipped + */ + private Map currentPotionEffects = new HashMap<>(); + + public BlockEffectChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.EFFECT); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CARVED_PUMPKIN, Message.forName("item-block-effect-challenge")); + } + + @Override + protected void onEnable() { + currentPotionEffects = new HashMap<>(); + if (!shouldExecuteEffect()) return; + broadcastFiltered(player -> { + addEffect(player, player.getLocation(), null); + }); + } + + @TimerTask(status = TimerStatus.RUNNING) + public void onStart() { + broadcastFiltered(player -> { + addEffect(player, player.getLocation(), null); + }); + } + + @Override + protected void onDisable() { + broadcastFiltered(player -> { + removeEffect(player, player.getLocation(), null); + }); + currentPotionEffects = null; + } + + @EventHandler(priority = EventPriority.LOW) + public void onLeave(PlayerQuitEvent event) { + if (!shouldExecuteEffect()) return; + currentPotionEffects.remove(event.getPlayer().getUniqueId()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onGameModeChange(PlayerIgnoreStatusChangeEvent event) { + if (!shouldExecuteEffect()) return; + if (event.isIgnored()) { + removeEffect(event.getPlayer(), event.getPlayer().getLocation(), null); + } else { + addEffect(event.getPlayer(), event.getPlayer().getLocation(), null); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + Block fromBlock = BlockUtils.getBlockBelow(event.getFrom()); + Block toBlock = BlockUtils.getBlockBelow(event.getTo()); + if (toBlock != null && fromBlock != null) { + if (toBlock.getType() == fromBlock.getType()) return; + } + removeEffect(event.getPlayer(), event.getFrom(), fromBlock); + addEffect(event.getPlayer(), event.getTo(), toBlock); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + Block fromBlock = BlockUtils.getBlockBelow(event.getFrom()); + Block toBlock = BlockUtils.getBlockBelow(event.getTo()); + if (toBlock != null && fromBlock != null) { + if (toBlock.getType() == fromBlock.getType()) return; + } + removeEffect(event.getPlayer(), event.getFrom(), fromBlock); + addEffect(event.getPlayer(), event.getTo(), toBlock); + } + + @ScheduledTask(ticks = 20, async = false) + public void onSecond() { + broadcastFiltered(player -> { + addEffect(player, player.getLocation(), null); + }); + } + + public void removeEffect(Player player, Location location, Block blockBelow) { + if (blockBelow == null) { + blockBelow = BlockUtils.getBlockBelow(location, -1); + } + if (blockBelow == null) return; + PotionEffectType type = getEffect(blockBelow.getType()).getType(); + player.removePotionEffect(type); + + removeEffectInCache(player); + } + + + public void addEffect(Player player, Location location, Block blockBelow) { + if (blockBelow == null) { + blockBelow = BlockUtils.getBlockBelow(location, -1); + } + if (blockBelow == null) return; + PotionEffect effect = getEffect(blockBelow.getType()); + PotionEffect currentEffect = currentPotionEffects.get(player.getUniqueId()); + if (currentEffect != null && !currentEffect.equals(effect)) { + player.removePotionEffect(currentEffect.getType()); + } else if (player.hasPotionEffect(effect.getType())) return; + player.addPotionEffect(effect); + currentPotionEffects.put(player.getUniqueId(), effect); + } + + public void removeEffectInCache(Player player) { + PotionEffect currentEffect = currentPotionEffects.get(player.getUniqueId()); + if (currentEffect != null) { + player.removePotionEffect(currentEffect.getType()); + } + } + + private PotionEffect getEffect(Material material) { + long seed = ChallengeAPI.getGameWorld(World.Environment.NORMAL).getSeed(); + IRandom random = new SeededRandomWrapper(seed / material.ordinal()); + PotionEffectType[] types = PotionEffectType.values(); + PotionEffectType type = types[random.nextInt(types.length)]; + return type.createEffect(Integer.MAX_VALUE, random.nextInt(type.isInstant() ? 1 : 4)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java index 7898e893e..fc4ca4027 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java @@ -31,113 +31,113 @@ @Since("2.1.1") public class ChunkRandomEffectChallenge extends Setting { - /* - * Saving potion effect to prevent the possibility that an effect remove was somehow skipped - */ - private Map currentPotionEffects = new HashMap<>(); - - private long worldSeed; - - public ChunkRandomEffectChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.EFFECT); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CAULDRON, Message.forName("item-chunk-effect-challenge")); - } - - @Override - protected void onEnable() { - currentPotionEffects = new HashMap<>(); - worldSeed = ChallengeAPI.getGameWorld(Environment.NORMAL).getSeed(); - broadcastFiltered(player -> { - addEffect(player, player.getLocation()); - }); - } - - @Override - protected void onDisable() { - broadcastFiltered(player -> { - removeEffect(player, player.getLocation()); - }); - worldSeed = 0; - currentPotionEffects = null; - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onGameModeChange(PlayerIgnoreStatusChangeEvent event) { - if (!shouldExecuteEffect()) return; - if (event.isIgnored()) { - removeEffect(event.getPlayer(), event.getPlayer().getLocation()); - } else { - addEffect(event.getPlayer(), event.getPlayer().getLocation()); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getTo() == null) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo().getChunk() == event.getFrom().getChunk()) return; - removeEffect(event.getPlayer(), event.getFrom()); - addEffect(event.getPlayer(), event.getTo()); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onTeleport(PlayerTeleportEvent event) { - if (event.getTo() == null) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo().getChunk() == event.getFrom().getChunk()) return; - removeEffect(event.getPlayer(), event.getFrom()); - addEffect(event.getPlayer(), event.getTo()); - } - - @ScheduledTask(ticks = 20, async = false) - public void onSecond() { - broadcastFiltered(player -> { - addEffect(player, player.getLocation()); - }); - } - - public void removeEffect(Player player, Location location) { - PotionEffectType type = getEffect(location.getChunk()).getType(); - player.removePotionEffect(type); - - removeEffectInCache(player); - } - - public void addEffect(Player player, Location location) { - Chunk chunk = location.getChunk(); - PotionEffect effect = getEffect(chunk); - - removeEffectInCache(player); - - if (player.hasPotionEffect(effect.getType())) return; - player.addPotionEffect(effect); - currentPotionEffects.put(player.getUniqueId(), effect); - } - - public void removeEffectInCache(Player player) { - PotionEffect currentEffect = currentPotionEffects.remove(player.getUniqueId()); - if (currentEffect != null) { - player.removePotionEffect(currentEffect.getType()); - } - } - - public PotionEffect getEffect(Chunk chunk) { - - IRandom random = new SeededRandomWrapper(worldSeed * ( - (long) (chunk.getX() == 0 ? Integer.MAX_VALUE : chunk.getX()) * (chunk.getZ() == 0 ? Integer.MAX_VALUE : chunk.getZ()))); - - PotionEffectType[] types = PotionEffectType.values(); - PotionEffectType type = types[random.nextInt(types.length)]; - - return type.createEffect(Integer.MAX_VALUE, random.nextInt(type.isInstant() ? 1 : 4)); - } + /* + * Saving potion effect to prevent the possibility that an effect remove was somehow skipped + */ + private Map currentPotionEffects = new HashMap<>(); + + private long worldSeed; + + public ChunkRandomEffectChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.EFFECT); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CAULDRON, Message.forName("item-chunk-effect-challenge")); + } + + @Override + protected void onEnable() { + currentPotionEffects = new HashMap<>(); + worldSeed = ChallengeAPI.getGameWorld(Environment.NORMAL).getSeed(); + broadcastFiltered(player -> { + addEffect(player, player.getLocation()); + }); + } + + @Override + protected void onDisable() { + broadcastFiltered(player -> { + removeEffect(player, player.getLocation()); + }); + worldSeed = 0; + currentPotionEffects = null; + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onGameModeChange(PlayerIgnoreStatusChangeEvent event) { + if (!shouldExecuteEffect()) return; + if (event.isIgnored()) { + removeEffect(event.getPlayer(), event.getPlayer().getLocation()); + } else { + addEffect(event.getPlayer(), event.getPlayer().getLocation()); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (event.getTo() == null) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo().getChunk() == event.getFrom().getChunk()) return; + removeEffect(event.getPlayer(), event.getFrom()); + addEffect(event.getPlayer(), event.getTo()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent event) { + if (event.getTo() == null) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo().getChunk() == event.getFrom().getChunk()) return; + removeEffect(event.getPlayer(), event.getFrom()); + addEffect(event.getPlayer(), event.getTo()); + } + + @ScheduledTask(ticks = 20, async = false) + public void onSecond() { + broadcastFiltered(player -> { + addEffect(player, player.getLocation()); + }); + } + + public void removeEffect(Player player, Location location) { + PotionEffectType type = getEffect(location.getChunk()).getType(); + player.removePotionEffect(type); + + removeEffectInCache(player); + } + + public void addEffect(Player player, Location location) { + Chunk chunk = location.getChunk(); + PotionEffect effect = getEffect(chunk); + + removeEffectInCache(player); + + if (player.hasPotionEffect(effect.getType())) return; + player.addPotionEffect(effect); + currentPotionEffects.put(player.getUniqueId(), effect); + } + + public void removeEffectInCache(Player player) { + PotionEffect currentEffect = currentPotionEffects.remove(player.getUniqueId()); + if (currentEffect != null) { + player.removePotionEffect(currentEffect.getType()); + } + } + + public PotionEffect getEffect(Chunk chunk) { + + IRandom random = new SeededRandomWrapper(worldSeed * ( + (long) (chunk.getX() == 0 ? Integer.MAX_VALUE : chunk.getX()) * (chunk.getZ() == 0 ? Integer.MAX_VALUE : chunk.getZ()))); + + PotionEffectType[] types = PotionEffectType.values(); + PotionEffectType type = types[random.nextInt(types.length)]; + + return type.createEffect(Integer.MAX_VALUE, random.nextInt(type.isInstant() ? 1 : 4)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java index 8296da817..637ce9f8b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java @@ -21,50 +21,50 @@ @Since("2.1.2") public class EntityRandomEffectChallenge extends Setting { - public EntityRandomEffectChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.EFFECT); - } + public EntityRandomEffectChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.EFFECT); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PHANTOM_MEMBRANE, Message.forName("item-entity-effect-challenge")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.PHANTOM_MEMBRANE, Message.forName("item-entity-effect-challenge")); + } - @Override - protected void onEnable() { - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - addRandomEffect(entity); - } - } - } + @Override + protected void onEnable() { + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + addRandomEffect(entity); + } + } + } - @Override - protected void onDisable() { - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - if (entity.getType() == EntityType.PLAYER) continue; - for (PotionEffect effect : entity.getActivePotionEffects()) { - entity.removePotionEffect(effect.getType()); - } - } - } - } + @Override + protected void onDisable() { + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + if (entity.getType() == EntityType.PLAYER) continue; + for (PotionEffect effect : entity.getActivePotionEffects()) { + entity.removePotionEffect(effect.getType()); + } + } + } + } - @EventHandler(priority = EventPriority.HIGH) - public void onSpawn(EntitySpawnEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof LivingEntity)) return; - addRandomEffect((LivingEntity) event.getEntity()); - } + @EventHandler(priority = EventPriority.HIGH) + public void onSpawn(EntitySpawnEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof LivingEntity)) return; + addRandomEffect((LivingEntity) event.getEntity()); + } - public void addRandomEffect(LivingEntity entity) { - if (entity.getType() == EntityType.PLAYER) return; - PotionEffectType[] types = PotionEffectType.values(); - PotionEffectType type = globalRandom.choose(types); - entity.addPotionEffect(type.createEffect(Integer.MAX_VALUE, 255)); - } + public void addRandomEffect(LivingEntity entity) { + if (entity.getType() == EntityType.PLAYER) return; + PotionEffectType[] types = PotionEffectType.values(); + PotionEffectType type = globalRandom.choose(types); + entity.addPotionEffect(type.createEffect(Integer.MAX_VALUE, 255)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java index 5d088d268..67ec37da2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java @@ -22,73 +22,73 @@ public class InfectionChallenge extends Setting { - public InfectionChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.EFFECT); - } + public InfectionChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.EFFECT); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SLIME_BALL, Message.forName("item-infection-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SLIME_BALL, Message.forName("item-infection-challenge")); + } - @Override - protected void onDisable() { - Bukkit.getOnlinePlayers().forEach(this::removeEffects); - } + @Override + protected void onDisable() { + Bukkit.getOnlinePlayers().forEach(this::removeEffects); + } - @ScheduledTask(ticks = 10, async = false) - public void onHalfSecond() { - if (!shouldExecuteEffect()) { - Bukkit.getOnlinePlayers().forEach(this::removeEffects); - return; - } - Bukkit.getOnlinePlayers().forEach(this::updateSickness); - } + @ScheduledTask(ticks = 10, async = false) + public void onHalfSecond() { + if (!shouldExecuteEffect()) { + Bukkit.getOnlinePlayers().forEach(this::removeEffects); + return; + } + Bukkit.getOnlinePlayers().forEach(this::updateSickness); + } - private void updateSickness(@Nonnull Player player) { - if (ignorePlayer(player)) { - removeEffects(player); - return; - } + private void updateSickness(@Nonnull Player player) { + if (ignorePlayer(player)) { + removeEffects(player); + return; + } - List entities = getNearbyTargets(player, 2); - if (entities.isEmpty()) { - player.removePotionEffect(MinecraftNameWrapper.NAUSEA); - return; - } + List entities = getNearbyTargets(player, 2); + if (entities.isEmpty()) { + player.removePotionEffect(MinecraftNameWrapper.NAUSEA); + return; + } - byte value = 1; - for (Entity currentEntity : entities) { - if (player.getLocation().distance(currentEntity.getLocation()) <= 1.5) value = 2; - } + byte value = 1; + for (Entity currentEntity : entities) { + if (player.getLocation().distance(currentEntity.getLocation()) <= 1.5) value = 2; + } - player.addPotionEffect(new PotionEffect(MinecraftNameWrapper.NAUSEA, Integer.MAX_VALUE, 15)); - if (value == 1) { - if (!player.hasPotionEffect(PotionEffectType.WITHER)) { - player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 5 * 20, 2)); - } - } else { - player.removePotionEffect(PotionEffectType.POISON); - player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 5 * 20, 4)); - } + player.addPotionEffect(new PotionEffect(MinecraftNameWrapper.NAUSEA, Integer.MAX_VALUE, 15)); + if (value == 1) { + if (!player.hasPotionEffect(PotionEffectType.WITHER)) { + player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 5 * 20, 2)); + } + } else { + player.removePotionEffect(PotionEffectType.POISON); + player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 5 * 20, 4)); + } - } + } - private void removeEffects(@Nonnull Player player) { - player.removePotionEffect(MinecraftNameWrapper.NAUSEA); - player.removePotionEffect(PotionEffectType.POISON); - player.removePotionEffect(PotionEffectType.WITHER); - } + private void removeEffects(@Nonnull Player player) { + player.removePotionEffect(MinecraftNameWrapper.NAUSEA); + player.removePotionEffect(PotionEffectType.POISON); + player.removePotionEffect(PotionEffectType.WITHER); + } - private List getNearbyTargets(@Nonnull Player player, double range) { - return player.getNearbyEntities(range, range, range).stream() - .filter(entity -> entity != player) - .filter(entity -> entity instanceof LivingEntity) - .filter(entity -> !(entity instanceof Player) - || (((Player) entity).getGameMode() != GameMode.CREATIVE - && ((Player) entity).getGameMode() != GameMode.SPECTATOR)).collect(Collectors.toList()); - } + private List getNearbyTargets(@Nonnull Player player, double range) { + return player.getNearbyEntities(range, range, range).stream() + .filter(entity -> entity != player) + .filter(entity -> entity instanceof LivingEntity) + .filter(entity -> !(entity instanceof Player) + || (((Player) entity).getGameMode() != GameMode.CREATIVE + && ((Player) entity).getGameMode() != GameMode.SPECTATOR)).collect(Collectors.toList()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java index cade26f94..14eec8b49 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java @@ -1,12 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Random; -import java.util.UUID; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import net.anweisen.utilities.bukkit.utils.logging.Logger; import net.anweisen.utilities.common.annotations.Since; import net.anweisen.utilities.common.collection.pair.Tuple; @@ -37,244 +30,248 @@ import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; + @Since("2.0") public class PermanentEffectOnDamageChallenge extends SettingModifier { - private static final int GLOBAL_EFFECT = 1; - private final Random random = new Random(); - - public PermanentEffectOnDamageChallenge() { - super(MenuType.CHALLENGES, 1, 2); - setCategory(SettingCategory.EFFECT); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MAGMA_CREAM, Message.forName("item-permanent-effect-on-damage-challenge")); - } - - @Override - protected void onEnable() { - if (!shouldExecuteEffect()) { - clearEffects(); - return; - } - updateEffects(); - } - - @Override - protected void onDisable() { - clearEffects(); - } - - @TimerTask(status = TimerStatus.RUNNING, async = false) - public void onTimerStart() { - if (!isEnabled()) return; - updateEffects(); - } - - @TimerTask(status = TimerStatus.PAUSED, async = false) - public void onTimerPause() { - if (!isEnabled()) return; - clearEffects(); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onConsume(@Nonnull PlayerItemConsumeEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getItem().getType() != Material.MILK_BUCKET) return; - Bukkit.getScheduler().runTask(plugin, this::updateEffects); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - updateEffects(); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerItemConsume(@Nonnull PlayerItemConsumeEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - updateEffects(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { - if (!shouldExecuteEffect()) return; - Bukkit.getScheduler().runTask(plugin, () -> { - clearEffects(); - updateEffects(); - }); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerDamage(@Nonnull EntityDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getFinalDamage() <= 0 && event.getDamage(DamageModifier.ABSORPTION) >= 0) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - DamageCause cause = event.getCause(); - if (cause == DamageCause.POISON || cause == DamageCause.WITHER) return; - - addRandomEffect(player); - updateEffects(); - } - - public void addRandomEffect(@Nonnull Player eventPlayer) { - PotionEffectType randomEffect = getNewRandomEffect(); - if (randomEffect == null) return; - applyNewEffect(eventPlayer, randomEffect); - } - - private void applyNewEffect(@Nonnull Player player, @Nonnull PotionEffectType potionEffectType) { - String path = player.getUniqueId().toString(); - Document effects = getGameStateData().getDocument(path); - - int amplifier = 1; - if (!effects.contains(potionEffectType.getName())) { - effects.set(potionEffectType.getName(), 1); - } else { - amplifier = effects.getInt(potionEffectType.getName()) + 1; - effects.set(potionEffectType.getName(), amplifier); - } - - if (effectsToEveryone()) { - Message.forName("new-effect").broadcast(Prefix.CHALLENGES, potionEffectType, amplifier); - } else { - Message.forName("new-effect").send(player, Prefix.CHALLENGES, potionEffectType, amplifier); - } - - getGameStateData().set(path, effects); - } - - @Nullable - private PotionEffectType getNewRandomEffect() { - ArrayList possibleEffects = new ArrayList<>(Arrays.asList(PotionEffectType.values())); - possibleEffects.remove(MinecraftNameWrapper.INSTANT_HEALTH); - possibleEffects.remove(MinecraftNameWrapper.INSTANT_DAMAGE); - return possibleEffects.get(random.nextInt(possibleEffects.size())); - } - - public void updateEffects() { - forEachEffect((player, effectType, amplifier) -> { - if (effectsToEveryone()) { - broadcastFiltered(currentPlayer -> { - addEffect(currentPlayer, effectType, amplifier); - }); - } else { - if (!ignorePlayer(player)) { - addEffect(player, effectType, amplifier); - } - } - }); - } - - private void addEffect(@Nonnull Player player, @Nonnull PotionEffectType effectType, int amplifier) { - - if (player.hasPotionEffect(effectType)) { - PotionEffect effect = player.getPotionEffect(effectType); - if (effect != null && effect.getAmplifier() == amplifier - 1) { - return; - } - } - - player.removePotionEffect(effectType); - player.addPotionEffect(new PotionEffect(effectType, Integer.MAX_VALUE, amplifier - 1)); - } - - private void clearEffects() { - forEachEffect((player, potionEffectType, amplifier) -> { - broadcast(currentPlayer -> { - currentPlayer.removePotionEffect(potionEffectType); - }); - }); - } - - private void forEachEffect(@Nonnull TriConsumer action) { - List> effects = new ArrayList<>(); - - for (String uuid : getGameStateData().keys()) { - - Document effectsDocument = getGameStateData().getDocument(uuid); - for (String effectName : effectsDocument.keys()) { - PotionEffectType effectType = PotionEffectType.getByName(effectName); - int amplifier = effectsDocument.getInt(effectName); - if (effectType == null) continue; - - if (effectsToEveryone()) { - addEffectToList(effects, effectType, amplifier); - } else { - try { - Player player = Bukkit.getPlayer(UUID.fromString(uuid)); - action.accept(player, effectType, amplifier); - } catch (Exception ex) { - Logger.debug("UUID formation for uuid '" + uuid + "' failed in permanent effect challenge!"); - } - } - } - - } - - effects.forEach(tuple -> { - broadcastFiltered(player -> { - action.accept(player, tuple.getFirst(), tuple.getSecond()); - }); - }); - } - - private void addEffectToList(@Nonnull List> effectsList, @Nonnull PotionEffectType effectType, int amplifier) { - Tuple effectTuple = effectsList.stream().filter(tuple -> tuple.getFirst() == effectType).findFirst() - .orElse(new Tuple<>(effectType, 0)); - effectTuple.setSecond(effectTuple.getSecond() + amplifier); - - if (!effectsList.contains(effectTuple)) effectsList.add(effectTuple); - } - - private boolean effectsToEveryone() { - return GLOBAL_EFFECT == getValue(); - } - - @Override - protected void onValueChange() { - if (!shouldExecuteEffect()) return; - clearEffects(); - updateEffects(); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (!isEnabled()) return DefaultItem.disabled(); - if (getValue() == GLOBAL_EFFECT) - return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone").asString()).appendLore("", Message.forName("item-permanent-effect-target-everyone-description").asString()); - return DefaultItem.create(Material.CHEST, Message.forName("player").asString()).appendLore("", Message.forName("item-permanent-effect-target-player-description").asString()); - } - - @Override - public void playValueChangeTitle() { - if (GLOBAL_EFFECT == getValue()) { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("everyone").asString()); - } else { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("player").asString()); - } - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - broadcast(player -> { - for (PotionEffect potionEffect : player.getActivePotionEffects()) { - player.removePotionEffect(potionEffect.getType()); - } - }); - if (shouldExecuteEffect()) { - updateEffects(); - } - } + private static final int GLOBAL_EFFECT = 1; + private final Random random = new Random(); + + public PermanentEffectOnDamageChallenge() { + super(MenuType.CHALLENGES, 1, 2); + setCategory(SettingCategory.EFFECT); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.MAGMA_CREAM, Message.forName("item-permanent-effect-on-damage-challenge")); + } + + @Override + protected void onEnable() { + if (!shouldExecuteEffect()) { + clearEffects(); + return; + } + updateEffects(); + } + + @Override + protected void onDisable() { + clearEffects(); + } + + @TimerTask(status = TimerStatus.RUNNING, async = false) + public void onTimerStart() { + if (!isEnabled()) return; + updateEffects(); + } + + @TimerTask(status = TimerStatus.PAUSED, async = false) + public void onTimerPause() { + if (!isEnabled()) return; + clearEffects(); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onConsume(@Nonnull PlayerItemConsumeEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getItem().getType() != Material.MILK_BUCKET) return; + Bukkit.getScheduler().runTask(plugin, this::updateEffects); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + updateEffects(); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerItemConsume(@Nonnull PlayerItemConsumeEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + updateEffects(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { + if (!shouldExecuteEffect()) return; + Bukkit.getScheduler().runTask(plugin, () -> { + clearEffects(); + updateEffects(); + }); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerDamage(@Nonnull EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getFinalDamage() <= 0 && event.getDamage(DamageModifier.ABSORPTION) >= 0) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + DamageCause cause = event.getCause(); + if (cause == DamageCause.POISON || cause == DamageCause.WITHER) return; + + addRandomEffect(player); + updateEffects(); + } + + public void addRandomEffect(@Nonnull Player eventPlayer) { + PotionEffectType randomEffect = getNewRandomEffect(); + if (randomEffect == null) return; + applyNewEffect(eventPlayer, randomEffect); + } + + private void applyNewEffect(@Nonnull Player player, @Nonnull PotionEffectType potionEffectType) { + String path = player.getUniqueId().toString(); + Document effects = getGameStateData().getDocument(path); + + int amplifier = 1; + if (!effects.contains(potionEffectType.getName())) { + effects.set(potionEffectType.getName(), 1); + } else { + amplifier = effects.getInt(potionEffectType.getName()) + 1; + effects.set(potionEffectType.getName(), amplifier); + } + + if (effectsToEveryone()) { + Message.forName("new-effect").broadcast(Prefix.CHALLENGES, potionEffectType, amplifier); + } else { + Message.forName("new-effect").send(player, Prefix.CHALLENGES, potionEffectType, amplifier); + } + + getGameStateData().set(path, effects); + } + + @Nullable + private PotionEffectType getNewRandomEffect() { + ArrayList possibleEffects = new ArrayList<>(Arrays.asList(PotionEffectType.values())); + possibleEffects.remove(MinecraftNameWrapper.INSTANT_HEALTH); + possibleEffects.remove(MinecraftNameWrapper.INSTANT_DAMAGE); + return possibleEffects.get(random.nextInt(possibleEffects.size())); + } + + public void updateEffects() { + forEachEffect((player, effectType, amplifier) -> { + if (effectsToEveryone()) { + broadcastFiltered(currentPlayer -> { + addEffect(currentPlayer, effectType, amplifier); + }); + } else { + if (!ignorePlayer(player)) { + addEffect(player, effectType, amplifier); + } + } + }); + } + + private void addEffect(@Nonnull Player player, @Nonnull PotionEffectType effectType, int amplifier) { + + if (player.hasPotionEffect(effectType)) { + PotionEffect effect = player.getPotionEffect(effectType); + if (effect != null && effect.getAmplifier() == amplifier - 1) { + return; + } + } + + player.removePotionEffect(effectType); + player.addPotionEffect(new PotionEffect(effectType, Integer.MAX_VALUE, amplifier - 1)); + } + + private void clearEffects() { + forEachEffect((player, potionEffectType, amplifier) -> { + broadcast(currentPlayer -> { + currentPlayer.removePotionEffect(potionEffectType); + }); + }); + } + + private void forEachEffect(@Nonnull TriConsumer action) { + List> effects = new ArrayList<>(); + + for (String uuid : getGameStateData().keys()) { + + Document effectsDocument = getGameStateData().getDocument(uuid); + for (String effectName : effectsDocument.keys()) { + PotionEffectType effectType = PotionEffectType.getByName(effectName); + int amplifier = effectsDocument.getInt(effectName); + if (effectType == null) continue; + + if (effectsToEveryone()) { + addEffectToList(effects, effectType, amplifier); + } else { + try { + Player player = Bukkit.getPlayer(UUID.fromString(uuid)); + action.accept(player, effectType, amplifier); + } catch (Exception ex) { + Logger.debug("UUID formation for uuid '" + uuid + "' failed in permanent effect challenge!"); + } + } + } + + } + + effects.forEach(tuple -> { + broadcastFiltered(player -> { + action.accept(player, tuple.getFirst(), tuple.getSecond()); + }); + }); + } + + private void addEffectToList(@Nonnull List> effectsList, @Nonnull PotionEffectType effectType, int amplifier) { + Tuple effectTuple = effectsList.stream().filter(tuple -> tuple.getFirst() == effectType).findFirst() + .orElse(new Tuple<>(effectType, 0)); + effectTuple.setSecond(effectTuple.getSecond() + amplifier); + + if (!effectsList.contains(effectTuple)) effectsList.add(effectTuple); + } + + private boolean effectsToEveryone() { + return GLOBAL_EFFECT == getValue(); + } + + @Override + protected void onValueChange() { + if (!shouldExecuteEffect()) return; + clearEffects(); + updateEffects(); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (!isEnabled()) return DefaultItem.disabled(); + if (getValue() == GLOBAL_EFFECT) + return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone").asString()).appendLore("", Message.forName("item-permanent-effect-target-everyone-description").asString()); + return DefaultItem.create(Material.CHEST, Message.forName("player").asString()).appendLore("", Message.forName("item-permanent-effect-target-player-description").asString()); + } + + @Override + public void playValueChangeTitle() { + if (GLOBAL_EFFECT == getValue()) { + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("everyone").asString()); + } else { + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("player").asString()); + } + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + broadcast(player -> { + for (PotionEffect potionEffect : player.getActivePotionEffects()) { + player.removePotionEffect(potionEffect.getType()); + } + }); + if (shouldExecuteEffect()) { + updateEffects(); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index 8895945de..a75beacdb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -27,83 +27,83 @@ @Since("2.0") public class RandomPotionEffectChallenge extends MenuSetting { - private final Random random = new Random(); - int currentTime = 0; - - public RandomPotionEffectChallenge() { - super(MenuType.CHALLENGES, Message.forName("menu-random-effect-challenge-settings")); - setCategory(SettingCategory.EFFECT); - registerSetting("time", new NumberSubSetting( - () -> new ItemBuilder(Material.CLOCK, Message.forName("item-random-effect-time-challenge")), - value -> null, - value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), - 1, - 60, - 30 - ) - ); - registerSetting("length", new NumberSubSetting( - () -> new ItemBuilder(Material.ARROW, Message.forName("item-random-effect-length-challenge")), - value -> null, - value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), - 1, - 20, - 10 - ) - ); - registerSetting("amplifier", new NumberSubSetting( - () -> new ItemBuilder(Material.STONE_SWORD, Message.forName("item-random-effect-amplifier-challenge")), - value -> null, - value -> "§7" + Message.forName("amplifier") + " §e" + value, - 1, - 8, - 3 - ) - ); - - } - - @Nullable - public static PotionEffectType getNewRandomEffect(@Nonnull LivingEntity entity) { - List activeEffects = entity.getActivePotionEffects().stream().map(PotionEffect::getType).collect(Collectors.toList()); - - ArrayList possibleEffects = new ArrayList<>(Arrays.asList(PotionEffectType.values())); - possibleEffects.removeAll(activeEffects); - possibleEffects.remove(MinecraftNameWrapper.INSTANT_HEALTH); - possibleEffects.remove(MinecraftNameWrapper.INSTANT_DAMAGE); - return possibleEffects.get(IRandom.threadLocal().nextInt(possibleEffects.size())); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BREWING_STAND, Message.forName("item-random-effect-challenge")); - } - - @ScheduledTask(ticks = 20, async = false) - public void onSecond() { - currentTime++; - - if (currentTime > getSetting("time").getAsInt()) { - currentTime = 0; - applyRandomEffect(); - } - - } - - private void applyRandomEffect() { - Bukkit.getOnlinePlayers().forEach(this::applyRandomEffect); - } - - private void applyRandomEffect(@Nonnull Player entity) { - PotionEffectType effect = getNewRandomEffect(entity); - if (effect == null) return; - applyEffect(entity, effect); - } - - private void applyEffect(@Nonnull Player player, @Nonnull PotionEffectType effectType) { - PotionEffect potionEffect = new PotionEffect(effectType, (getSetting("length").getAsInt() + 1) * 20, getSetting("amplifier").getAsInt() - 1); - player.addPotionEffect(potionEffect); - } + private final Random random = new Random(); + int currentTime = 0; + + public RandomPotionEffectChallenge() { + super(MenuType.CHALLENGES, Message.forName("menu-random-effect-challenge-settings")); + setCategory(SettingCategory.EFFECT); + registerSetting("time", new NumberSubSetting( + () -> new ItemBuilder(Material.CLOCK, Message.forName("item-random-effect-time-challenge")), + value -> null, + value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), + 1, + 60, + 30 + ) + ); + registerSetting("length", new NumberSubSetting( + () -> new ItemBuilder(Material.ARROW, Message.forName("item-random-effect-length-challenge")), + value -> null, + value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), + 1, + 20, + 10 + ) + ); + registerSetting("amplifier", new NumberSubSetting( + () -> new ItemBuilder(Material.STONE_SWORD, Message.forName("item-random-effect-amplifier-challenge")), + value -> null, + value -> "§7" + Message.forName("amplifier") + " §e" + value, + 1, + 8, + 3 + ) + ); + + } + + @Nullable + public static PotionEffectType getNewRandomEffect(@Nonnull LivingEntity entity) { + List activeEffects = entity.getActivePotionEffects().stream().map(PotionEffect::getType).collect(Collectors.toList()); + + ArrayList possibleEffects = new ArrayList<>(Arrays.asList(PotionEffectType.values())); + possibleEffects.removeAll(activeEffects); + possibleEffects.remove(MinecraftNameWrapper.INSTANT_HEALTH); + possibleEffects.remove(MinecraftNameWrapper.INSTANT_DAMAGE); + return possibleEffects.get(IRandom.threadLocal().nextInt(possibleEffects.size())); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BREWING_STAND, Message.forName("item-random-effect-challenge")); + } + + @ScheduledTask(ticks = 20, async = false) + public void onSecond() { + currentTime++; + + if (currentTime > getSetting("time").getAsInt()) { + currentTime = 0; + applyRandomEffect(); + } + + } + + private void applyRandomEffect() { + Bukkit.getOnlinePlayers().forEach(this::applyRandomEffect); + } + + private void applyRandomEffect(@Nonnull Player entity) { + PotionEffectType effect = getNewRandomEffect(entity); + if (effect == null) return; + applyEffect(entity, effect); + } + + private void applyEffect(@Nonnull Player player, @Nonnull PotionEffectType effectType) { + PotionEffect potionEffect = new PotionEffect(effectType, (getSetting("length").getAsInt() + 1) * 20, getSetting("amplifier").getAsInt() - 1); + player.addPotionEffect(potionEffect); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java index 6db0b57f0..f9f6943a8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java @@ -18,36 +18,36 @@ @Since("2.0") public class AllMobsToDeathPoint extends Setting { - public AllMobsToDeathPoint() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @EventHandler - public void onEntityDeath(@Nonnull EntityDeathByPlayerEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getEntity() instanceof EnderDragon || event.getEntity() instanceof Player) return; - if (!(event.getEntity() instanceof LivingEntity)) return; - if (ignorePlayer(event.getKiller())) return; - - teleportAllMobsOfType(event.getEntityType(), event.getEntity().getLocation()); - } - - private void teleportAllMobsOfType(@Nonnull EntityType entityType, @Nonnull Location location) { - if (location.getWorld() == null) return; - Collection entities = location.getWorld().getEntitiesByClasses(entityType.getEntityClass()); - for (Entity entity : entities) { - if (!(entity instanceof LivingEntity)) return; - ((LivingEntity) entity).setNoDamageTicks(20); - entity.teleport(location); - } - - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SPAWNER, Message.forName("item-all-mobs-to-death-position-challenge")); - } + public AllMobsToDeathPoint() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } + + @EventHandler + public void onEntityDeath(@Nonnull EntityDeathByPlayerEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getEntity() instanceof EnderDragon || event.getEntity() instanceof Player) return; + if (!(event.getEntity() instanceof LivingEntity)) return; + if (ignorePlayer(event.getKiller())) return; + + teleportAllMobsOfType(event.getEntityType(), event.getEntity().getLocation()); + } + + private void teleportAllMobsOfType(@Nonnull EntityType entityType, @Nonnull Location location) { + if (location.getWorld() == null) return; + Collection entities = location.getWorld().getEntitiesByClasses(entityType.getEntityClass()); + for (Entity entity : entities) { + if (!(entity instanceof LivingEntity)) return; + ((LivingEntity) entity).setNoDamageTicks(20); + entity.teleport(location); + } + + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SPAWNER, Message.forName("item-all-mobs-to-death-position-challenge")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java index 36225f70a..a60f5a536 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java @@ -27,81 +27,81 @@ @Since("2.1.3") public class BlockMobsChallenge extends Setting { - public BlockMobsChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } + public BlockMobsChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BRICKS, Message.forName("item-block-mob-challenge")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BRICKS, Message.forName("item-block-mob-challenge")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - EntityType type = globalRandom.choose(RandomMobAction.getLivingMobs()); - LivingEntity entity = (LivingEntity) event.getBlock().getWorld() - .spawnEntity(event.getBlock().getLocation().add(0.5, 0, 0.5), type); + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + EntityType type = globalRandom.choose(RandomMobAction.getLivingMobs()); + LivingEntity entity = (LivingEntity) event.getBlock().getWorld() + .spawnEntity(event.getBlock().getLocation().add(0.5, 0, 0.5), type); - Collection drops = event.getBlock().getDrops(Objects.requireNonNull(event.getPlayer().getEquipment()).getItemInMainHand()); + Collection drops = event.getBlock().getDrops(Objects.requireNonNull(event.getPlayer().getEquipment()).getItemInMainHand()); - int i = 0; - // Put every stack in a different slot to make sure everything drops properly - for (ItemStack drop : drops) { + int i = 0; + // Put every stack in a different slot to make sure everything drops properly + for (ItemStack drop : drops) { - EquipmentSlot slot = EquipmentSlot.HEAD; - EntityEquipment equipment = entity.getEquipment(); + EquipmentSlot slot = EquipmentSlot.HEAD; + EntityEquipment equipment = entity.getEquipment(); - switch (i) { - case 0: - assert equipment != null; - equipment.setHelmetDropChance(1); - break; - case 1: - slot = EquipmentSlot.CHEST; - equipment.setChestplateDropChance(1); - break; - case 2: - slot = EquipmentSlot.LEGS; - equipment.setLeggingsDropChance(1); - break; - case 3: - slot = EquipmentSlot.FEET; - equipment.setBootsDropChance(1); - break; - case 4: - slot = EquipmentSlot.HAND; - equipment.setItemInMainHandDropChance(1); - break; - case 5: - slot = EquipmentSlot.OFF_HAND; - equipment.setItemInOffHandDropChance(1); - break; - } - equipment.setItem(slot, drop); - i++; - } - event.setDropItems(false); - } + switch (i) { + case 0: + assert equipment != null; + equipment.setHelmetDropChance(1); + break; + case 1: + slot = EquipmentSlot.CHEST; + equipment.setChestplateDropChance(1); + break; + case 2: + slot = EquipmentSlot.LEGS; + equipment.setLeggingsDropChance(1); + break; + case 3: + slot = EquipmentSlot.FEET; + equipment.setBootsDropChance(1); + break; + case 4: + slot = EquipmentSlot.HAND; + equipment.setItemInMainHandDropChance(1); + break; + case 5: + slot = EquipmentSlot.OFF_HAND; + equipment.setItemInOffHandDropChance(1); + break; + } + equipment.setItem(slot, drop); + i++; + } + event.setDropItems(false); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityExplosion(EntityExplodeEvent event) { - if (!shouldExecuteEffect()) return; - for (Block block : event.blockList()) { - block.setType(Material.AIR); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityExplosion(EntityExplodeEvent event) { + if (!shouldExecuteEffect()) return; + for (Block block : event.blockList()) { + block.setType(Material.AIR); + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockExplosion(BlockExplodeEvent event) { - if (!shouldExecuteEffect()) return; - for (Block block : event.blockList()) { - block.setType(Material.AIR); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockExplosion(BlockExplodeEvent event) { + if (!shouldExecuteEffect()) return; + for (Block block : event.blockList()) { + block.setType(Material.AIR); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java index 9d9934636..7cd6d145e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java @@ -15,35 +15,35 @@ public class DupedSpawningChallenge extends Setting { - private boolean inCustomSpawn = false; - - public DupedSpawningChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ELDER_GUARDIAN_SPAWN_EGG, Message.forName("item-duped-spawning-challenge")); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSpawn(@Nonnull EntitySpawnEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof LivingEntity) - || event.getEntity() instanceof Player - || event.getEntity() instanceof EnderDragon - ) return; - if (inCustomSpawn) return; - inCustomSpawn = true; - Entity entity = event.getEntity().getWorld().spawnEntity(event.getLocation(), event.getEntityType()); - - if (entity instanceof Slime && event.getEntity() instanceof Slime) { - ((Slime) entity).setSize(((Slime) event.getEntity()).getSize()); - } - - inCustomSpawn = false; - } + private boolean inCustomSpawn = false; + + public DupedSpawningChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ELDER_GUARDIAN_SPAWN_EGG, Message.forName("item-duped-spawning-challenge")); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSpawn(@Nonnull EntitySpawnEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof LivingEntity) + || event.getEntity() instanceof Player + || event.getEntity() instanceof EnderDragon + ) return; + if (inCustomSpawn) return; + inCustomSpawn = true; + Entity entity = event.getEntity().getWorld().spawnEntity(event.getLocation(), event.getEntityType()); + + if (entity instanceof Slime && event.getEntity() instanceof Slime) { + ((Slime) entity).setSize(((Slime) event.getEntity()).getSize()); + } + + inCustomSpawn = false; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java index 3a359fa42..37d82eb9f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java @@ -12,19 +12,19 @@ public class HydraNormalChallenge extends HydraChallenge { - public HydraNormalChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } + public HydraNormalChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.WITCH_SPAWN_EGG, Message.forName("item-hydra-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.WITCH_SPAWN_EGG, Message.forName("item-hydra-challenge")); + } - @Override - public int getNewMobsCount(@Nonnull EntityType entityType) { - return 2; - } + @Override + public int getNewMobsCount(@Nonnull EntityType entityType) { + return 2; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java index 835fd5585..862aab974 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java @@ -14,29 +14,29 @@ @Since("2.0") public class HydraPlusChallenge extends HydraChallenge { - private static final int limit = 512; - - public HydraPlusChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BAT_SPAWN_EGG, Message.forName("item-hydra-plus-challenge")); - } - - @Override - public int getNewMobsCount(@Nonnull EntityType entityType) { - int currentCount = getGameStateData().getInt(entityType.name()); - if (currentCount == 0) { - currentCount = 2; - } else { - currentCount *= 2; - } - getGameStateData().set(entityType.name(), Math.min(currentCount, limit)); - return currentCount; - } + private static final int limit = 512; + + public HydraPlusChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BAT_SPAWN_EGG, Message.forName("item-hydra-plus-challenge")); + } + + @Override + public int getNewMobsCount(@Nonnull EntityType entityType) { + int currentCount = getGameStateData().getInt(entityType.name()); + if (currentCount == 0) { + currentCount = 2; + } else { + currentCount *= 2; + } + getGameStateData().set(entityType.name(), Math.min(currentCount, limit)); + return currentCount; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java index 24e76bf86..b5c05902a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java @@ -26,46 +26,46 @@ @Since("2.0") public class InvisibleMobsChallenge extends Setting { - public InvisibleMobsChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } + public InvisibleMobsChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } - @Override - protected void onEnable() { - addEffectForEveryEntity(); - } + @Override + protected void onEnable() { + addEffectForEveryEntity(); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new PotionBuilder(Material.POTION, Message.forName("item-invisible-mobs-challenge")).setColor(Color.WHITE); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new PotionBuilder(Material.POTION, Message.forName("item-invisible-mobs-challenge")).setColor(Color.WHITE); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSpawn(@Nonnull EntitySpawnEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof LivingEntity)) return; - addEffect(((LivingEntity) event.getEntity())); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSpawn(@Nonnull EntitySpawnEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof LivingEntity)) return; + addEffect(((LivingEntity) event.getEntity())); + } - @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.ALWAYS) - public void playEffects() { - if (!shouldExecuteEffect()) return; - addEffectForEveryEntity(); - } + @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.ALWAYS) + public void playEffects() { + if (!shouldExecuteEffect()) return; + addEffectForEveryEntity(); + } - private void addEffectForEveryEntity() { - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - if (entity instanceof Player) continue; - addEffect(entity); - } - } - } + private void addEffectForEveryEntity() { + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + if (entity instanceof Player) continue; + addEffect(entity); + } + } + } - private void addEffect(@Nonnull LivingEntity entity) { - entity.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 40, 1, true, false, false)); - } + private void addEffect(@Nonnull LivingEntity entity) { + entity.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 40, 1, true, false, false)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java index 4d1283419..de20c8bae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java @@ -22,56 +22,56 @@ @Since("2.0") public class MobSightDamageChallenge extends SettingModifier { - public MobSightDamageChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SPIDER_EYE, Message.forName("item-no-mob-sight-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - - @ScheduledTask(ticks = 1, async = false) - public void onTick() { - - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - - RayTraceResult result = player.getWorld().rayTraceEntities( - player.getEyeLocation(), - player.getLocation().getDirection(), - 30, - 0.01, - entity -> !(entity instanceof Player) && entity instanceof LivingEntity - ); - if (result == null) continue; - - Location location = result.getHitPosition().toLocation(player.getWorld()); - LivingEntity entity = ((LivingEntity) result.getHitEntity()); - if (entity == null) continue; - - double distance = entity.getEyeLocation().distance(location) * 5; - - BoundingBox box = entity.getBoundingBox(); - double volume = box.getWidthX() + box.getWidthZ() + box.getHeight(); - if (distance > volume) continue; - - player.damage(getValue()); - } - - } + public MobSightDamageChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SPIDER_EYE, Message.forName("item-no-mob-sight-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } + + @ScheduledTask(ticks = 1, async = false) + public void onTick() { + + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + + RayTraceResult result = player.getWorld().rayTraceEntities( + player.getEyeLocation(), + player.getLocation().getDirection(), + 30, + 0.01, + entity -> !(entity instanceof Player) && entity instanceof LivingEntity + ); + if (result == null) continue; + + Location location = result.getHitPosition().toLocation(player.getWorld()); + LivingEntity entity = ((LivingEntity) result.getHitEntity()); + if (entity == null) continue; + + double distance = entity.getEyeLocation().distance(location) * 5; + + BoundingBox box = entity.getBoundingBox(); + double volume = box.getWidthX() + box.getWidthZ() + box.getHeight(); + if (distance > volume) continue; + + player.damage(getValue()); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java index 47e444a1e..86dbb758e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java @@ -22,56 +22,56 @@ @Since("2.0") public class MobTransformationChallenge extends Setting { - public MobTransformationChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } + public MobTransformationChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - bossbar.setColor(BarColor.GREEN); - EntityType type = getPlayerData(player).getEnum("type", EntityType.class); - Object typeName = type == null ? "None" : type; - bossbar.setTitle(Message.forName("bossbar-mob-transformation").asString(typeName)); - }); - bossbar.show(); - } + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + bossbar.setColor(BarColor.GREEN); + EntityType type = getPlayerData(player).getEnum("type", EntityType.class); + Object typeName = type == null ? "None" : type; + bossbar.setTitle(Message.forName("bossbar-mob-transformation").asString(typeName)); + }); + bossbar.show(); + } - @Override - protected void onDisable() { - bossbar.hide(); - } + @Override + protected void onDisable() { + bossbar.hide(); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-mob-transformation-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-mob-transformation-challenge")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityDamageByPlayer(@Nonnull EntityDamageByPlayerEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getEntity() instanceof Player || !(event.getEntity() instanceof LivingEntity) || event.getEntity() instanceof EnderDragon) - return; + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityDamageByPlayer(@Nonnull EntityDamageByPlayerEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getEntity() instanceof Player || !(event.getEntity() instanceof LivingEntity) || event.getEntity() instanceof EnderDragon) + return; - Player player = event.getDamager(); - if (ignorePlayer(player)) return; + Player player = event.getDamager(); + if (ignorePlayer(player)) return; - EntityType type = getPlayerData(player).getEnum("type", event.getEntityType()); + EntityType type = getPlayerData(player).getEnum("type", event.getEntityType()); - if (type != event.getEntityType()) { - event.getEntity().remove(); - event.getEntity().getWorld().spawnEntity(event.getEntity().getLocation(), type); - } - getPlayerData(player).set("type", event.getEntityType()); - bossbar.update(player); - } + if (type != event.getEntityType()) { + event.getEntity().remove(); + event.getEntity().getWorld().spawnEntity(event.getEntity().getLocation(), type); + } + getPlayerData(player).set("type", event.getEntityType()); + bossbar.update(player); + } - private EntityType getType(@Nonnull Player player, @Nullable EntityType defaultType) { - EntityType type = getPlayerData(player).getEnum("type", EntityType.class); - if (type == null) return defaultType; - return type; - } + private EntityType getType(@Nonnull Player player, @Nullable EntityType defaultType) { + EntityType type = getPlayerData(player).getEnum("type", EntityType.class); + if (type == null) return defaultType; + return type; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java index bc34c69b3..2bce869e2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java @@ -29,97 +29,97 @@ @Since("2.1.2") public class MobsRespawnInEndChallenge extends Setting { - private final Map toSpawnEntities = new HashMap<>(); - private int totalMobsInEnd = 0; - - public MobsRespawnInEndChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENDER_EYE, Message.forName("item-respawn-end-challenge")); - } - - @Override - protected void onEnable() { - bossbar.setContent((bar, player) -> { - bar.setColor(BarColor.PURPLE); - bar.setTitle(Message.forName("bossbar-respawn-end").asString(totalMobsInEnd)); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Override - public void writeGameState(@NotNull Document document) { - document.set("total", totalMobsInEnd); - } - - @Override - public void loadGameState(@NotNull Document document) { - totalMobsInEnd = document.getInt("total"); - } - - private void addEntityToSpawn(EntityType type) { - if (!ChallengeAPI.isPlayerInGameWorld(World.Environment.THE_END)) { - increaseEntityToSpawnCount(type); - } else { - spawnEntityInEnd(type, 1); - } - totalMobsInEnd++; - bossbar.update(); - } - - private void spawnEntityInEnd(EntityType type, int count) { - World world = ChallengeAPI.getGameWorld(World.Environment.THE_END); - Location spawnLocation = world.getHighestBlockAt(0, 0).getLocation().add(0.5, 1, 0.5); - for (int i = 0; i < count; i++) { - Entity entity = world.spawnEntity(spawnLocation, type); - - if (entity instanceof LivingEntity) { - entity.setVelocity(Vector.getRandom().multiply(ThreadLocalRandom.current().nextBoolean() ? -1 : 1).setY(0)); - ((LivingEntity) entity).setNoDamageTicks(20 * 5); - } - } - } - - private void increaseEntityToSpawnCount(EntityType type) { - Integer count = toSpawnEntities.getOrDefault(type, 0); - toSpawnEntities.put(type, count + 1); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMobKill(EntityDeathByPlayerEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getEntity() instanceof Player || event.getEntity() instanceof EnderDragon) return; - if (event.getEntity().getLocation().getWorld() == null) return; - if (event.getEntity().getLocation().getWorld().getEnvironment() == World.Environment.THE_END) - return; - if (ChallengeHelper.ignoreDamager(event.getKiller())) return; - addEntityToSpawn(event.getEntityType()); - SoundSample.PLING.play((event.getKiller())); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onWorldChange(PlayerTeleportEvent event) { - if (event.getTo() == null || event.getTo().getWorld() == null || event.getTo().getWorld() == event.getFrom().getWorld()) - return; - if (event.getTo().getWorld().getEnvironment() != World.Environment.THE_END) return; - - for (Map.Entry entry : toSpawnEntities.entrySet()) { - EntityType type = entry.getKey(); - Integer count = entry.getValue(); - spawnEntityInEnd(type, count); - } - toSpawnEntities.clear(); - - } + private final Map toSpawnEntities = new HashMap<>(); + private int totalMobsInEnd = 0; + + public MobsRespawnInEndChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ENDER_EYE, Message.forName("item-respawn-end-challenge")); + } + + @Override + protected void onEnable() { + bossbar.setContent((bar, player) -> { + bar.setColor(BarColor.PURPLE); + bar.setTitle(Message.forName("bossbar-respawn-end").asString(totalMobsInEnd)); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Override + public void writeGameState(@NotNull Document document) { + document.set("total", totalMobsInEnd); + } + + @Override + public void loadGameState(@NotNull Document document) { + totalMobsInEnd = document.getInt("total"); + } + + private void addEntityToSpawn(EntityType type) { + if (!ChallengeAPI.isPlayerInGameWorld(World.Environment.THE_END)) { + increaseEntityToSpawnCount(type); + } else { + spawnEntityInEnd(type, 1); + } + totalMobsInEnd++; + bossbar.update(); + } + + private void spawnEntityInEnd(EntityType type, int count) { + World world = ChallengeAPI.getGameWorld(World.Environment.THE_END); + Location spawnLocation = world.getHighestBlockAt(0, 0).getLocation().add(0.5, 1, 0.5); + for (int i = 0; i < count; i++) { + Entity entity = world.spawnEntity(spawnLocation, type); + + if (entity instanceof LivingEntity) { + entity.setVelocity(Vector.getRandom().multiply(ThreadLocalRandom.current().nextBoolean() ? -1 : 1).setY(0)); + ((LivingEntity) entity).setNoDamageTicks(20 * 5); + } + } + } + + private void increaseEntityToSpawnCount(EntityType type) { + Integer count = toSpawnEntities.getOrDefault(type, 0); + toSpawnEntities.put(type, count + 1); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMobKill(EntityDeathByPlayerEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getEntity() instanceof Player || event.getEntity() instanceof EnderDragon) return; + if (event.getEntity().getLocation().getWorld() == null) return; + if (event.getEntity().getLocation().getWorld().getEnvironment() == World.Environment.THE_END) + return; + if (ChallengeHelper.ignoreDamager(event.getKiller())) return; + addEntityToSpawn(event.getEntityType()); + SoundSample.PLING.play((event.getKiller())); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onWorldChange(PlayerTeleportEvent event) { + if (event.getTo() == null || event.getTo().getWorld() == null || event.getTo().getWorld() == event.getFrom().getWorld()) + return; + if (event.getTo().getWorld().getEnvironment() != World.Environment.THE_END) return; + + for (Map.Entry entry : toSpawnEntities.entrySet()) { + EntityType type = entry.getKey(); + Integer count = entry.getValue(); + spawnEntityInEnd(type, count); + } + toSpawnEntities.clear(); + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java index 8ed950886..630d0ce7d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java @@ -21,28 +21,28 @@ @Since("2.0") public class NewEntityOnJumpChallenge extends Setting { - public NewEntityOnJumpChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-jump-entity-challenge")).setColor(Color.GREEN); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onJump(@Nonnull PlayerJumpEvent event) { - if (ignorePlayer(event.getPlayer())) return; - if (!shouldExecuteEffect()) return; - spawnRandomEntity(event.getPlayer().getLocation()); - } - - private void spawnRandomEntity(@Nonnull Location location) { - if (location.getWorld() == null) return; - EntityType type = globalRandom.choose(RandomMobAction.getSpawnableMobs()); - location.getWorld().spawnEntity(location, type); - } + public NewEntityOnJumpChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-jump-entity-challenge")).setColor(Color.GREEN); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJump(@Nonnull PlayerJumpEvent event) { + if (ignorePlayer(event.getPlayer())) return; + if (!shouldExecuteEffect()) return; + spawnRandomEntity(event.getPlayer().getLocation()); + } + + private void spawnRandomEntity(@Nonnull Location location) { + if (location.getWorld() == null) return; + EntityType type = globalRandom.choose(RandomMobAction.getSpawnableMobs()); + location.getWorld().spawnEntity(location, type); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java index 7f85c657e..60229a8b0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java @@ -23,63 +23,63 @@ @Since("2.0") public class StoneSightChallenge extends Setting { - private final Random random = new Random(); - - public StoneSightChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COBBLESTONE, Message.forName("item-stone-sight-challenge")); - } - - @ScheduledTask(ticks = 1, async = false) - public void onTick() { - - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - - RayTraceResult result = player.getWorld().rayTraceEntities( - player.getEyeLocation(), - player.getLocation().getDirection(), - 30, - 0.01, - entity -> !(entity instanceof Player) && !(entity instanceof EnderDragon) && entity instanceof LivingEntity - ); - if (result == null) continue; - - Location location = result.getHitPosition().toLocation(player.getWorld()); - LivingEntity entity = ((LivingEntity) result.getHitEntity()); - if (entity == null) continue; - - double distance = entity.getEyeLocation().distance(location) * 5; - - BoundingBox box = entity.getBoundingBox(); - double volume = box.getWidthX() + box.getWidthZ() + box.getHeight(); - if (distance > volume) continue; - - entity.getLocation().getBlock().setType(getRandomStone(), false); - entity.remove(); - SoundSample.BREAK.play(player); - - } - - } - - @Nonnull - private Material getRandomStone() { - Material[] materials = { - Material.STONE, - Material.STONE, - Material.STONE, - Material.COBBLESTONE, - Material.COBBLESTONE, - Material.MOSSY_COBBLESTONE - }; - return materials[random.nextInt(materials.length)]; - } + private final Random random = new Random(); + + public StoneSightChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.ENTITIES); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.COBBLESTONE, Message.forName("item-stone-sight-challenge")); + } + + @ScheduledTask(ticks = 1, async = false) + public void onTick() { + + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + + RayTraceResult result = player.getWorld().rayTraceEntities( + player.getEyeLocation(), + player.getLocation().getDirection(), + 30, + 0.01, + entity -> !(entity instanceof Player) && !(entity instanceof EnderDragon) && entity instanceof LivingEntity + ); + if (result == null) continue; + + Location location = result.getHitPosition().toLocation(player.getWorld()); + LivingEntity entity = ((LivingEntity) result.getHitEntity()); + if (entity == null) continue; + + double distance = entity.getEyeLocation().distance(location) * 5; + + BoundingBox box = entity.getBoundingBox(); + double volume = box.getWidthX() + box.getWidthZ() + box.getHeight(); + if (distance > volume) continue; + + entity.getLocation().getBlock().setType(getRandomStone(), false); + entity.remove(); + SoundSample.BREAK.play(player); + + } + + } + + @Nonnull + private Material getRandomStone() { + Material[] materials = { + Material.STONE, + Material.STONE, + Material.STONE, + Material.COBBLESTONE, + Material.COBBLESTONE, + Material.MOSSY_COBBLESTONE + }; + return materials[random.nextInt(materials.length)]; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java index d9be4fb72..dd68e68e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java @@ -20,7 +20,10 @@ import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; -import org.bukkit.*; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -37,196 +40,196 @@ public class JumpAndRunChallenge extends WorldDependentChallenge { - private final List lastPlayers = new ArrayList<>(); - - private int jumps = 4; - private int currentJump; - private int jumpsDone; - - private Block targetBlock; - private Block lastBlock; - - private UUID currentPlayer; - - public JumpAndRunChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, false); - setCategory(SettingCategory.EXTRA_WORLD); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ACACIA_STAIRS, Message.forName("item-jump-and-run-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Override - public void onDisable() { - if (isInExtraWorld()) - exitJumpAndRun(); - } - - @Override - protected void handleCountdown() { - switch (getSecondsLeftUntilNextActivation()) { - case 1: - Message.forName("jnr-countdown-one").broadcast(Prefix.CHALLENGES); - SoundSample.BASS_OFF.broadcast(); - break; - case 2: - case 3: - case 5: - Message.forName("jnr-countdown").broadcast(Prefix.CHALLENGES, getSecondsLeftUntilNextActivation()); - SoundSample.BASS_OFF.broadcast(); - break; - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onQuit(@Nonnull PlayerQuitEvent event) { - if (currentPlayer == null) return; - if (!currentPlayer.equals(event.getPlayer().getUniqueId())) return; - exitJumpAndRun(); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 30); - } - - @Override - public void startWorldChallenge() { - startJumpAndRun(); - } - - protected void startJumpAndRun() { - currentJump = 0; - currentPlayer = getNextPlayer().getUniqueId(); - lastPlayers.add(currentPlayer); - - buildNextJump(); - teleportToWorld(true, (player, index) -> { - player.setGameMode(player.getUniqueId().equals(currentPlayer) ? GameMode.SURVIVAL : GameMode.SPECTATOR); - player.teleport(new Location(getExtraWorld(), 0.5, 101, 0.5)); - }); - } - - protected void buildNextJump() { - - if (lastBlock != null) lastBlock.setType(Material.AIR); - - lastBlock = targetBlock != null ? targetBlock : getExtraWorld().getBlockAt(0, 100, 0); - lastBlock.setType(Material.GOLD_BLOCK); - - Material type = getRandomBlockType(); - targetBlock = new RandomJumpGenerator().next(globalRandom, lastBlock, type == Material.CYAN_TERRACOTTA || type == Material.EMERALD_BLOCK, type != Material.COBBLESTONE_WALL && type != Material.SPRUCE_FENCE); - targetBlock.setType(type); - - } - - @Nonnull - protected Material getRandomBlockType() { - if (currentJump == jumps - 1) return Material.EMERALD_BLOCK; - - Material[] materials = { - Material.CYAN_TERRACOTTA, - Material.CYAN_TERRACOTTA, - Material.CYAN_TERRACOTTA, - Material.CYAN_TERRACOTTA, - Material.END_ROD, - Material.COBBLESTONE_WALL, - Material.SPRUCE_FENCE - }; - return globalRandom.choose(materials); - } - - @Nonnull - protected Player getNextPlayer() { - List players = new ArrayList<>(Bukkit.getOnlinePlayers()); - players.removeIf(AbstractChallenge::ignorePlayer); - players.removeIf(player -> lastPlayers.contains(player.getUniqueId())); - - if (players.isEmpty()) { - players = new ArrayList<>(Bukkit.getOnlinePlayers()); - lastPlayers.clear(); - } - return globalRandom.choose(players); - } - - protected void finishJumpAndRun() { - jumps++; - jumpsDone++; - - Message.forName("jnr-finished").broadcast(Prefix.CHALLENGES, Optional.ofNullable(currentPlayer).map(Bukkit::getPlayer).map(NameHelper::getName).orElse("?")); - exitJumpAndRun(); - SoundSample.KLING.broadcast(); - } - - protected void exitJumpAndRun() { - currentPlayer = null; - teleportBack(); - breakJumpAndRun(); - restartTimer(); - } - - protected void breakJumpAndRun() { - if (lastBlock != null) lastBlock.setType(Material.AIR); - if (targetBlock != null) targetBlock.setType(Material.AIR); - - lastBlock = null; - targetBlock = null; - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - document.set("jumps", jumps); - document.set("jumpsDone", jumpsDone); - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - jumps = document.getInt("jumps", jumps); - jumpsDone = document.getInt("jumpsDone", jumpsDone); - } - - @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.ALWAYS, worldPolicy = ExtraWorldPolicy.USED) - public void spawnParticles() { - if (targetBlock == null) return; - ParticleUtils.spawnParticleCircle(targetBlock.getLocation().add(0.5, 1.05, 0.5), - MinecraftNameWrapper.INSTANT_EFFECT, 13, 0.35); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!event.getPlayer().getUniqueId().equals(currentPlayer)) return; - if (!isInExtraWorld()) return; - if (targetBlock == null) return; - if (event.getTo() == null) return; - - if (BlockUtils.isSameBlockLocation(event.getTo(), targetBlock.getLocation().add(0, 1, 0))) { - if (++currentJump >= jumps) { - finishJumpAndRun(); - } else { - SoundSample.PLOP.broadcast(); - buildNextJump(); - } - } else if (event.getTo().getBlockY() < targetBlock.getY() - 2) { - exitJumpAndRun(); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_FAILED); - } - - } + private final List lastPlayers = new ArrayList<>(); + + private int jumps = 4; + private int currentJump; + private int jumpsDone; + + private Block targetBlock; + private Block lastBlock; + + private UUID currentPlayer; + + public JumpAndRunChallenge() { + super(MenuType.CHALLENGES, 1, 10, 5, false); + setCategory(SettingCategory.EXTRA_WORLD); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ACACIA_STAIRS, Message.forName("item-jump-and-run-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Override + public void onDisable() { + if (isInExtraWorld()) + exitJumpAndRun(); + } + + @Override + protected void handleCountdown() { + switch (getSecondsLeftUntilNextActivation()) { + case 1: + Message.forName("jnr-countdown-one").broadcast(Prefix.CHALLENGES); + SoundSample.BASS_OFF.broadcast(); + break; + case 2: + case 3: + case 5: + Message.forName("jnr-countdown").broadcast(Prefix.CHALLENGES, getSecondsLeftUntilNextActivation()); + SoundSample.BASS_OFF.broadcast(); + break; + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onQuit(@Nonnull PlayerQuitEvent event) { + if (currentPlayer == null) return; + if (!currentPlayer.equals(event.getPlayer().getUniqueId())) return; + exitJumpAndRun(); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 30); + } + + @Override + public void startWorldChallenge() { + startJumpAndRun(); + } + + protected void startJumpAndRun() { + currentJump = 0; + currentPlayer = getNextPlayer().getUniqueId(); + lastPlayers.add(currentPlayer); + + buildNextJump(); + teleportToWorld(true, (player, index) -> { + player.setGameMode(player.getUniqueId().equals(currentPlayer) ? GameMode.SURVIVAL : GameMode.SPECTATOR); + player.teleport(new Location(getExtraWorld(), 0.5, 101, 0.5)); + }); + } + + protected void buildNextJump() { + + if (lastBlock != null) lastBlock.setType(Material.AIR); + + lastBlock = targetBlock != null ? targetBlock : getExtraWorld().getBlockAt(0, 100, 0); + lastBlock.setType(Material.GOLD_BLOCK); + + Material type = getRandomBlockType(); + targetBlock = new RandomJumpGenerator().next(globalRandom, lastBlock, type == Material.CYAN_TERRACOTTA || type == Material.EMERALD_BLOCK, type != Material.COBBLESTONE_WALL && type != Material.SPRUCE_FENCE); + targetBlock.setType(type); + + } + + @Nonnull + protected Material getRandomBlockType() { + if (currentJump == jumps - 1) return Material.EMERALD_BLOCK; + + Material[] materials = { + Material.CYAN_TERRACOTTA, + Material.CYAN_TERRACOTTA, + Material.CYAN_TERRACOTTA, + Material.CYAN_TERRACOTTA, + Material.END_ROD, + Material.COBBLESTONE_WALL, + Material.SPRUCE_FENCE + }; + return globalRandom.choose(materials); + } + + @Nonnull + protected Player getNextPlayer() { + List players = new ArrayList<>(Bukkit.getOnlinePlayers()); + players.removeIf(AbstractChallenge::ignorePlayer); + players.removeIf(player -> lastPlayers.contains(player.getUniqueId())); + + if (players.isEmpty()) { + players = new ArrayList<>(Bukkit.getOnlinePlayers()); + lastPlayers.clear(); + } + return globalRandom.choose(players); + } + + protected void finishJumpAndRun() { + jumps++; + jumpsDone++; + + Message.forName("jnr-finished").broadcast(Prefix.CHALLENGES, Optional.ofNullable(currentPlayer).map(Bukkit::getPlayer).map(NameHelper::getName).orElse("?")); + exitJumpAndRun(); + SoundSample.KLING.broadcast(); + } + + protected void exitJumpAndRun() { + currentPlayer = null; + teleportBack(); + breakJumpAndRun(); + restartTimer(); + } + + protected void breakJumpAndRun() { + if (lastBlock != null) lastBlock.setType(Material.AIR); + if (targetBlock != null) targetBlock.setType(Material.AIR); + + lastBlock = null; + targetBlock = null; + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + document.set("jumps", jumps); + document.set("jumpsDone", jumpsDone); + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + jumps = document.getInt("jumps", jumps); + jumpsDone = document.getInt("jumpsDone", jumpsDone); + } + + @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.ALWAYS, worldPolicy = ExtraWorldPolicy.USED) + public void spawnParticles() { + if (targetBlock == null) return; + ParticleUtils.spawnParticleCircle(targetBlock.getLocation().add(0.5, 1.05, 0.5), + MinecraftNameWrapper.INSTANT_EFFECT, 13, 0.35); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!event.getPlayer().getUniqueId().equals(currentPlayer)) return; + if (!isInExtraWorld()) return; + if (targetBlock == null) return; + if (event.getTo() == null) return; + + if (BlockUtils.isSameBlockLocation(event.getTo(), targetBlock.getLocation().add(0, 1, 0))) { + if (++currentJump >= jumps) { + finishJumpAndRun(); + } else { + SoundSample.PLOP.broadcast(); + buildNextJump(); + } + } else if (event.getTo().getBlockY() < targetBlock.getY() - 2) { + exitJumpAndRun(); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_FAILED); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java index 17fcfe654..c5b34d165 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java @@ -23,74 +23,74 @@ public class WaterMLGChallenge extends WorldDependentChallenge { - public WaterMLGChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, false); - setCategory(SettingCategory.EXTRA_WORLD); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.WATER_BUCKET, Message.forName("item-water-mlg-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 10, getValue() * 60 + 10); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 10, getValue() * 60 + 10); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 10); - } - - @Override - public void startWorldChallenge() { - Location currentLocation = new Location(getExtraWorld(), 0, 150, 0); - - teleportToWorld(false, (player, index) -> { - currentLocation.add(100, 0, 0); - player.getInventory().setHeldItemSlot(4); - player.getInventory().setItem(4, new ItemStack(Material.WATER_BUCKET)); - player.teleport(currentLocation); - }); - - Bukkit.getScheduler().runTaskLater(plugin, () -> { - teleportBack(); - restartTimer(); - }, 10 * 20); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerBucketEmpty(@Nonnull PlayerBucketEmptyEvent event) { - if (!isInExtraWorld()) return; - - Bukkit.getScheduler().runTaskLater(plugin, () -> { - event.getBlock().setType(Material.AIR); - Bukkit.getScheduler().runTaskLater(plugin, () -> { - teleportBack(event.getPlayer()); - }, 40); - }, 10); - - } - - @EventHandler(priority = EventPriority.HIGH) - public void onEntityDamage(@Nonnull EntityDamageEvent event) { - if (!(event.getEntity() instanceof Player)) return; - if (!isInExtraWorld()) return; - - if (AbstractChallenge.getFirstInstance(OneTeamLifeSetting.class).isEnabled()) { - teleportBack(); - } else { - Player player = (Player) event.getEntity(); - teleportBack(player); - } - } + public WaterMLGChallenge() { + super(MenuType.CHALLENGES, 1, 10, 5, false); + setCategory(SettingCategory.EXTRA_WORLD); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.WATER_BUCKET, Message.forName("item-water-mlg-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 10, getValue() * 60 + 10); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 10, getValue() * 60 + 10); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 10); + } + + @Override + public void startWorldChallenge() { + Location currentLocation = new Location(getExtraWorld(), 0, 150, 0); + + teleportToWorld(false, (player, index) -> { + currentLocation.add(100, 0, 0); + player.getInventory().setHeldItemSlot(4); + player.getInventory().setItem(4, new ItemStack(Material.WATER_BUCKET)); + player.teleport(currentLocation); + }); + + Bukkit.getScheduler().runTaskLater(plugin, () -> { + teleportBack(); + restartTimer(); + }, 10 * 20); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerBucketEmpty(@Nonnull PlayerBucketEmptyEvent event) { + if (!isInExtraWorld()) return; + + Bukkit.getScheduler().runTaskLater(plugin, () -> { + event.getBlock().setType(Material.AIR); + Bukkit.getScheduler().runTaskLater(plugin, () -> { + teleportBack(event.getPlayer()); + }, 40); + }, 10); + + } + + @EventHandler(priority = EventPriority.HIGH) + public void onEntityDamage(@Nonnull EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!isInExtraWorld()) return; + + if (AbstractChallenge.getFirstInstance(OneTeamLifeSetting.class).isEnabled()) { + teleportBack(); + } else { + Player player = (Player) event.getEntity(); + teleportBack(player); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java index e9be24ecc..cf65586a8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java @@ -35,118 +35,118 @@ @ExcludeFromRandomChallenges public class ForceBiomeChallenge extends CompletableForceChallenge { - private Biome biome; - - public ForceBiomeChallenge() { - super(MenuType.CHALLENGES, 2, 20, 5); - setCategory(SettingCategory.FORCE); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CHAINMAIL_BOOTS, Message.forName("item-force-biome-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60 * 3, 60); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 * 3 - 60, getValue() * 60 * 3 + 60); - } - - @Nonnull - @Override - protected BiConsumer setupBossbar() { - return (bossbar, player) -> { - if (getState() == WAITING) { - bossbar.setTitle(Message.forName("bossbar-force-biome-waiting").asString()); - return; - } - - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-force-biome-instruction").asComponent(biome, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); - }; - } - - @Override - protected void broadcastFailedMessage() { - Message.forName("force-biome-fail").broadcast(Prefix.CHALLENGES, BukkitStringUtils.getBiomeName(biome)); - } - - @Override - protected void broadcastSuccessMessage(@Nonnull Player player) { - Message.forName("force-biome-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), BukkitStringUtils.getBiomeName(biome)); - } - - @Override - protected void chooseForcing() { - Biome[] biomes = Arrays.stream(Biome.values()) - .filter(biome -> !biome.name().contains("END")) - .filter(biome -> !biome.name().contains("MUSHROOM")) - .filter(biome -> !biome.name().contains("VOID")) - .filter(biome -> !biome.name().equals("CUSTOM")) - .toArray(Biome[]::new); - - biome = globalRandom.choose(biomes); - } - - @Override - protected int getForcingTime() { - return globalRandom.around(getRarity(biome) * 60 * 6, 60); - } - - private int getRarity(@Nonnull Biome biome) { - Object[][] mapping = { - {"BADLANDS", 5}, - {"JUNGLE", 4}, - {"BAMBOO", 4}, - {"MODIFIED", 3}, - {"TALL", 3}, - {"SWAMP", 2}, - }; - - for (Object[] pair : mapping) { - String key = (String) pair[0]; - if (biome.name().contains(key)) - return (int) pair[1]; - } - return 1; - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60 * 3, 60); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getTo() == null) return; - if (event.getTo().getBlock().getBiome() != biome) return; - completeForcing(event.getPlayer()); - } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - if (document.contains("target")) { - String biomeName = document.getString("target"); - biome = Registry.BIOME.get(NamespacedKey.minecraft(Objects.requireNonNull(biomeName).toLowerCase())); - setState(biome == null ? WAITING : COUNTDOWN); - } - } - - - @Override - public void writeGameState(@NotNull Document document) { - super.writeGameState(document); - document.set("target", biome); - } + private Biome biome; + + public ForceBiomeChallenge() { + super(MenuType.CHALLENGES, 2, 20, 5); + setCategory(SettingCategory.FORCE); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CHAINMAIL_BOOTS, Message.forName("item-force-biome-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return ChallengeHelper.getTimeRangeSettingsDescription(this, 60 * 3, 60); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 * 3 - 60, getValue() * 60 * 3 + 60); + } + + @Nonnull + @Override + protected BiConsumer setupBossbar() { + return (bossbar, player) -> { + if (getState() == WAITING) { + bossbar.setTitle(Message.forName("bossbar-force-biome-waiting").asString()); + return; + } + + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(getProgress()); + bossbar.setTitle(Message.forName("bossbar-force-biome-instruction").asComponent(biome, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); + }; + } + + @Override + protected void broadcastFailedMessage() { + Message.forName("force-biome-fail").broadcast(Prefix.CHALLENGES, BukkitStringUtils.getBiomeName(biome)); + } + + @Override + protected void broadcastSuccessMessage(@Nonnull Player player) { + Message.forName("force-biome-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), BukkitStringUtils.getBiomeName(biome)); + } + + @Override + protected void chooseForcing() { + Biome[] biomes = Arrays.stream(Biome.values()) + .filter(biome -> !biome.name().contains("END")) + .filter(biome -> !biome.name().contains("MUSHROOM")) + .filter(biome -> !biome.name().contains("VOID")) + .filter(biome -> !biome.name().equals("CUSTOM")) + .toArray(Biome[]::new); + + biome = globalRandom.choose(biomes); + } + + @Override + protected int getForcingTime() { + return globalRandom.around(getRarity(biome) * 60 * 6, 60); + } + + private int getRarity(@Nonnull Biome biome) { + Object[][] mapping = { + {"BADLANDS", 5}, + {"JUNGLE", 4}, + {"BAMBOO", 4}, + {"MODIFIED", 3}, + {"TALL", 3}, + {"SWAMP", 2}, + }; + + for (Object[] pair : mapping) { + String key = (String) pair[0]; + if (biome.name().contains(key)) + return (int) pair[1]; + } + return 1; + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60 * 3, 60); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getTo() == null) return; + if (event.getTo().getBlock().getBiome() != biome) return; + completeForcing(event.getPlayer()); + } + + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + if (document.contains("target")) { + String biomeName = document.getString("target"); + biome = Registry.BIOME.get(NamespacedKey.minecraft(Objects.requireNonNull(biomeName).toLowerCase())); + setState(biome == null ? WAITING : COUNTDOWN); + } + } + + + @Override + public void writeGameState(@NotNull Document document) { + super.writeGameState(document); + document.set("target", biome); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java index d72b25a1b..8d60cccb2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.anweisen.utilities.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; @@ -12,6 +11,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; @@ -28,102 +28,102 @@ @ExcludeFromRandomChallenges public class ForceBlockChallenge extends EndingForceChallenge { - private Material block; - - public ForceBlockChallenge() { - super(MenuType.CHALLENGES, 2, 15); - setCategory(SettingCategory.FORCE); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_BOOTS, Message.forName("item-force-block-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Nonnull - @Override - protected BiConsumer setupBossbar() { - return (bossbar, player) -> { - if (getState() == WAITING) { - bossbar.setTitle(Message.forName("bossbar-force-block-waiting").asString()); - return; - } - - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-force-block-instruction").asComponent(block, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); - }; - } - - @Override - protected boolean isFailing(@Nonnull Player player) { - for (int x = -1; x <= 1; x++) { - for (int z = -1; z <= 1; z++) { - for (int y = -1; y <= 1; y++) { - Material type = player.getLocation().add(x, y, z).getBlock().getType(); - if (type == block) return false; - } - } - } - return true; - } - - @Override - protected void broadcastFailedMessage(@Nonnull Player player) { - Message.forName("force-block-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), player.getLocation().subtract(0, 1, 0).getBlock().getType()); - } - - @Override - protected void broadcastSuccessMessage() { - Message.forName("force-block-success").broadcast(Prefix.CHALLENGES); - } - - @Override - protected void chooseForcing() { - Material[] materials = Arrays.stream(ExperimentalUtils.getMaterials()) - .filter(Material::isBlock) - .filter(ItemUtils::isObtainableInSurvival) - .filter(material -> !BlockUtils.isTooHardToGet(material)) - .filter(material -> !material.name().contains("WALL")) - .toArray(length -> new Material[length]); - block = globalRandom.choose(materials); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 30); - } - - @Override - protected int getForcingTime() { - return globalRandom.range(4 * 60, 6 * 60); - } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - if (document.contains("target")) { - block = document.getEnum("target", Material.class); - setState(block == null ? WAITING : COUNTDOWN); - } - } - - @Override - public void writeGameState(@NotNull Document document) { - super.writeGameState(document); - document.set("target", block); - } + private Material block; + + public ForceBlockChallenge() { + super(MenuType.CHALLENGES, 2, 15); + setCategory(SettingCategory.FORCE); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GOLDEN_BOOTS, Message.forName("item-force-block-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Nonnull + @Override + protected BiConsumer setupBossbar() { + return (bossbar, player) -> { + if (getState() == WAITING) { + bossbar.setTitle(Message.forName("bossbar-force-block-waiting").asString()); + return; + } + + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(getProgress()); + bossbar.setTitle(Message.forName("bossbar-force-block-instruction").asComponent(block, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); + }; + } + + @Override + protected boolean isFailing(@Nonnull Player player) { + for (int x = -1; x <= 1; x++) { + for (int z = -1; z <= 1; z++) { + for (int y = -1; y <= 1; y++) { + Material type = player.getLocation().add(x, y, z).getBlock().getType(); + if (type == block) return false; + } + } + } + return true; + } + + @Override + protected void broadcastFailedMessage(@Nonnull Player player) { + Message.forName("force-block-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), player.getLocation().subtract(0, 1, 0).getBlock().getType()); + } + + @Override + protected void broadcastSuccessMessage() { + Message.forName("force-block-success").broadcast(Prefix.CHALLENGES); + } + + @Override + protected void chooseForcing() { + Material[] materials = Arrays.stream(ExperimentalUtils.getMaterials()) + .filter(Material::isBlock) + .filter(ItemUtils::isObtainableInSurvival) + .filter(material -> !BlockUtils.isTooHardToGet(material)) + .filter(material -> !material.name().contains("WALL")) + .toArray(length -> new Material[length]); + block = globalRandom.choose(materials); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 30); + } + + @Override + protected int getForcingTime() { + return globalRandom.range(4 * 60, 6 * 60); + } + + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + if (document.contains("target")) { + block = document.getEnum("target", Material.class); + setState(block == null ? WAITING : COUNTDOWN); + } + } + + @Override + public void writeGameState(@NotNull Document document) { + super.writeGameState(document); + document.set("target", block); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java index 1de673480..838947644 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java @@ -27,89 +27,89 @@ @ExcludeFromRandomChallenges public class ForceHeightChallenge extends EndingForceChallenge { - private int height; - - public ForceHeightChallenge() { - super(MenuType.CHALLENGES, 2, 15); - setCategory(SettingCategory.FORCE); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.IRON_BOOTS, Message.forName("item-force-height-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Nonnull - @Override - protected BiConsumer setupBossbar() { - return (bossbar, player) -> { - if (getState() == WAITING) { - bossbar.setTitle(Message.forName("bossbar-force-height-waiting").asString()); - return; - } - - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-force-height-instruction").asString(height, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); - }; - } - - @Override - protected boolean isFailing(@Nonnull Player player) { - return player.getLocation().getBlockY() != height; - } - - @Override - protected void broadcastFailedMessage(@Nonnull Player player) { - Message.forName("force-height-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), player.getLocation().getBlockY()); - } - - @Override - protected void broadcastSuccessMessage() { - Message.forName("force-height-success").broadcast(Prefix.CHALLENGES); - } - - @Override - protected void chooseForcing() { - World world = ChallengeAPI.getGameWorld(Environment.NORMAL); - height = globalRandom.range(BukkitReflectionUtils.getMinHeight(world), world.getMaxHeight()); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 30); - } - - @Override - protected int getForcingTime() { - return globalRandom.range(3 * 60 + 30, 5 * 60); - } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - if (document.contains("target")) { - height = document.getInt("target"); - setState(COUNTDOWN); - } - } - - @Override - public void writeGameState(@NotNull Document document) { - super.writeGameState(document); - document.set("target", height); - } + private int height; + + public ForceHeightChallenge() { + super(MenuType.CHALLENGES, 2, 15); + setCategory(SettingCategory.FORCE); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.IRON_BOOTS, Message.forName("item-force-height-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Nonnull + @Override + protected BiConsumer setupBossbar() { + return (bossbar, player) -> { + if (getState() == WAITING) { + bossbar.setTitle(Message.forName("bossbar-force-height-waiting").asString()); + return; + } + + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(getProgress()); + bossbar.setTitle(Message.forName("bossbar-force-height-instruction").asString(height, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); + }; + } + + @Override + protected boolean isFailing(@Nonnull Player player) { + return player.getLocation().getBlockY() != height; + } + + @Override + protected void broadcastFailedMessage(@Nonnull Player player) { + Message.forName("force-height-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), player.getLocation().getBlockY()); + } + + @Override + protected void broadcastSuccessMessage() { + Message.forName("force-height-success").broadcast(Prefix.CHALLENGES); + } + + @Override + protected void chooseForcing() { + World world = ChallengeAPI.getGameWorld(Environment.NORMAL); + height = globalRandom.range(BukkitReflectionUtils.getMinHeight(world), world.getMaxHeight()); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 30); + } + + @Override + protected int getForcingTime() { + return globalRandom.range(3 * 60 + 30, 5 * 60); + } + + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + if (document.contains("target")) { + height = document.getInt("target"); + setState(COUNTDOWN); + } + } + + @Override + public void writeGameState(@NotNull Document document) { + super.writeGameState(document); + document.set("target", height); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java index f589ddc4b..7bcd5ab9f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.anweisen.utilities.common.annotations.Since; import net.anweisen.utilities.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; @@ -15,6 +14,7 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; @@ -39,113 +39,113 @@ @ExcludeFromRandomChallenges public class ForceItemChallenge extends CompletableForceChallenge { - private Material item; - - public ForceItemChallenge() { - super(MenuType.CHALLENGES, 2, 15); - setCategory(SettingCategory.FORCE); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.LEATHER_BOOTS, Message.forName("item-force-item-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Nonnull - @Override - protected BiConsumer setupBossbar() { - return (bossbar, player) -> { - if (getState() == WAITING) { - bossbar.setTitle(Message.forName("bossbar-force-item-waiting").asString()); - return; - } - - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-force-item-instruction").asComponent(item, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); - }; - } - - @Override - protected void broadcastFailedMessage() { - Message.forName("force-item-fail").broadcast(Prefix.CHALLENGES, item); - } - - @Override - protected void broadcastSuccessMessage(@Nonnull Player player) { - Message.forName("force-item-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), item); - } - - @Override - protected void chooseForcing() { - List items = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - items.removeIf(material -> !ItemUtils.isObtainableInSurvival(material)); - items.removeIf(material -> !material.isItem()); - items.removeIf(BlockUtils::isTooHardToGet); - - item = globalRandom.choose(items); - } - - @Override - protected int getForcingTime() { - return globalRandom.range(5 * 60, 8 * 60); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 30); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onClick(@Nonnull PlayerInventoryClickEvent event) { - ItemStack item = event.getCurrentItem(); - if (item == null) return; - if (item.getType() != this.item) return; - completeForcing(event.getPlayer()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPickUp(@Nonnull PlayerPickupItemEvent event) { - Material material = event.getItem().getItemStack().getType(); - if (material != item) return; - completeForcing(event.getPlayer()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInteract(@Nonnull PlayerInteractEvent event) { - Bukkit.getScheduler().runTaskLater(plugin, () -> { - ItemStack item = event.getPlayer().getInventory().getItemInMainHand(); - Material material = item.getType(); - if (material != this.item) return; - completeForcing(event.getPlayer()); - }, 1); - } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - if (document.contains("target")) { - item = document.getEnum("target", Material.class); - setState(item == null ? WAITING : COUNTDOWN); - } - } - - @Override - public void writeGameState(@NotNull Document document) { - super.writeGameState(document); - document.set("target", item); - } + private Material item; + + public ForceItemChallenge() { + super(MenuType.CHALLENGES, 2, 15); + setCategory(SettingCategory.FORCE); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.LEATHER_BOOTS, Message.forName("item-force-item-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Nonnull + @Override + protected BiConsumer setupBossbar() { + return (bossbar, player) -> { + if (getState() == WAITING) { + bossbar.setTitle(Message.forName("bossbar-force-item-waiting").asString()); + return; + } + + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(getProgress()); + bossbar.setTitle(Message.forName("bossbar-force-item-instruction").asComponent(item, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); + }; + } + + @Override + protected void broadcastFailedMessage() { + Message.forName("force-item-fail").broadcast(Prefix.CHALLENGES, item); + } + + @Override + protected void broadcastSuccessMessage(@Nonnull Player player) { + Message.forName("force-item-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), item); + } + + @Override + protected void chooseForcing() { + List items = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + items.removeIf(material -> !ItemUtils.isObtainableInSurvival(material)); + items.removeIf(material -> !material.isItem()); + items.removeIf(BlockUtils::isTooHardToGet); + + item = globalRandom.choose(items); + } + + @Override + protected int getForcingTime() { + return globalRandom.range(5 * 60, 8 * 60); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 30); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onClick(@Nonnull PlayerInventoryClickEvent event) { + ItemStack item = event.getCurrentItem(); + if (item == null) return; + if (item.getType() != this.item) return; + completeForcing(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPickUp(@Nonnull PlayerPickupItemEvent event) { + Material material = event.getItem().getItemStack().getType(); + if (material != item) return; + completeForcing(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onInteract(@Nonnull PlayerInteractEvent event) { + Bukkit.getScheduler().runTaskLater(plugin, () -> { + ItemStack item = event.getPlayer().getInventory().getItemInMainHand(); + Material material = item.getType(); + if (material != this.item) return; + completeForcing(event.getPlayer()); + }, 1); + } + + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + if (document.contains("target")) { + item = document.getEnum("target", Material.class); + setState(item == null ? WAITING : COUNTDOWN); + } + } + + @Override + public void writeGameState(@NotNull Document document) { + super.writeGameState(document); + document.set("target", item); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java index 54fbc8b28..a726d2019 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java @@ -33,97 +33,97 @@ @ExcludeFromRandomChallenges public class ForceMobChallenge extends CompletableForceChallenge { - private EntityType entity; - - public ForceMobChallenge() { - super(MenuType.CHALLENGES, 2, 15); - setCategory(SettingCategory.FORCE); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-mob-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Nonnull - @Override - protected BiConsumer setupBossbar() { - return (bossbar, player) -> { - if (getState() == WAITING) { - bossbar.setTitle(Message.forName("bossbar-force-mob-waiting").asString()); - return; - } - - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-force-mob-instruction").asComponent(entity, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); - }; - } - - @Override - protected void broadcastFailedMessage() { - Message.forName("force-mob-fail").broadcast(Prefix.CHALLENGES, entity); - } - - @Override - protected void broadcastSuccessMessage(@Nonnull Player player) { - Message.forName("force-mob-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), entity); - } - - @Override - protected void chooseForcing() { - List entities = new ArrayList<>(Arrays.asList(EntityType.values())); - entities.removeIf(type -> !type.isSpawnable()); - entities.removeIf(type -> !type.isAlive()); - Utils.removeEnums(entities, "ENDER_DRAGON", "ILLUSIONER", "ARMOR_STAND", "ZOMBIE_HORSE", "SKELETON_HORSE", "SHULKER", "WITHER", "GIANT"); - - entity = globalRandom.choose(entities); - } - - @Override - protected int getForcingTime() { - return globalRandom.range(5 * 60, 8 * 60); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 30); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onKill(@Nonnull EntityDeathEvent event) { - LivingEntity entity = event.getEntity(); - if (entity.getType() != this.entity) return; - Player killer = entity.getKiller(); - if (killer == null) return; - completeForcing(killer); - } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - if (document.contains("target")) { - entity = document.getEnum("target", EntityType.class); - setState(entity == null ? WAITING : COUNTDOWN); - } - } - - @Override - public void writeGameState(@NotNull Document document) { - super.writeGameState(document); - document.set("target", entity); - } + private EntityType entity; + + public ForceMobChallenge() { + super(MenuType.CHALLENGES, 2, 15); + setCategory(SettingCategory.FORCE); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-mob-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Nonnull + @Override + protected BiConsumer setupBossbar() { + return (bossbar, player) -> { + if (getState() == WAITING) { + bossbar.setTitle(Message.forName("bossbar-force-mob-waiting").asString()); + return; + } + + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(getProgress()); + bossbar.setTitle(Message.forName("bossbar-force-mob-instruction").asComponent(entity, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); + }; + } + + @Override + protected void broadcastFailedMessage() { + Message.forName("force-mob-fail").broadcast(Prefix.CHALLENGES, entity); + } + + @Override + protected void broadcastSuccessMessage(@Nonnull Player player) { + Message.forName("force-mob-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), entity); + } + + @Override + protected void chooseForcing() { + List entities = new ArrayList<>(Arrays.asList(EntityType.values())); + entities.removeIf(type -> !type.isSpawnable()); + entities.removeIf(type -> !type.isAlive()); + Utils.removeEnums(entities, "ENDER_DRAGON", "ILLUSIONER", "ARMOR_STAND", "ZOMBIE_HORSE", "SKELETON_HORSE", "SHULKER", "WITHER", "GIANT"); + + entity = globalRandom.choose(entities); + } + + @Override + protected int getForcingTime() { + return globalRandom.range(5 * 60, 8 * 60); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 30); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onKill(@Nonnull EntityDeathEvent event) { + LivingEntity entity = event.getEntity(); + if (entity.getType() != this.entity) return; + Player killer = entity.getKiller(); + if (killer == null) return; + completeForcing(killer); + } + + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + if (document.contains("target")) { + entity = document.getEnum("target", EntityType.class); + setState(entity == null ? WAITING : COUNTDOWN); + } + } + + @Override + public void writeGameState(@NotNull Document document) { + super.writeGameState(document); + document.set("target", entity); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java index 3c9f20982..ed7861ba1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java @@ -17,44 +17,44 @@ public class DamageInventoryClearChallenge extends SettingModifier { - public DamageInventoryClearChallenge() { - super(MenuType.CHALLENGES, 1, 2); - setCategory(SettingCategory.INVENTORY); - } - - @EventHandler - public void onDamage(@Nonnull EntityDamageEvent event) { - if (!(event.getEntity() instanceof Player)) return; - if (!shouldExecuteEffect()) return; - if (ChallengeHelper.finalDamageIsNull(event)) return; - - if (getValue() == 1) { - Bukkit.getOnlinePlayers().forEach(player -> player.getInventory().clear()); - } else { - Player player = (Player) event.getEntity(); - player.getInventory().clear(); - } - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CHEST, Message.forName("item-damage-inv-clear-challenge")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (getValue() == 1) { - return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone")); - } else { - return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("player")); - } - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 0 ? Message.forName("everyone").asString() : Message.forName("player").asString()); - } + public DamageInventoryClearChallenge() { + super(MenuType.CHALLENGES, 1, 2); + setCategory(SettingCategory.INVENTORY); + } + + @EventHandler + public void onDamage(@Nonnull EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!shouldExecuteEffect()) return; + if (ChallengeHelper.finalDamageIsNull(event)) return; + + if (getValue() == 1) { + Bukkit.getOnlinePlayers().forEach(player -> player.getInventory().clear()); + } else { + Player player = (Player) event.getEntity(); + player.getInventory().clear(); + } + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CHEST, Message.forName("item-damage-inv-clear-challenge")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (getValue() == 1) { + return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone")); + } else { + return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("player")); + } + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 0 ? Message.forName("everyone").asString() : Message.forName("player").asString()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java index decb35544..56fb97ae6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java @@ -1,7 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; import net.anweisen.utilities.common.annotations.Since; @@ -16,6 +15,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.md_5.bungee.api.chat.BaseComponent; @@ -42,199 +42,199 @@ @Since("2.0") public class MissingItemsChallenge extends TimedChallenge implements PlayerCommand { - private final Map> inventories = new HashMap<>(); - private List materials; + private final Map> inventories = new HashMap<>(); + private List materials; - public MissingItemsChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, false); - setCategory(SettingCategory.INVENTORY); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 10, getValue() * 60 + 10); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 10, getValue() * 60 + 10); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 10); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FISHING_ROD, Message.forName("item-missing-items-challenge")); - } + public MissingItemsChallenge() { + super(MenuType.CHALLENGES, 1, 10, 5, false); + setCategory(SettingCategory.INVENTORY); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 10, getValue() * 60 + 10); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 10, getValue() * 60 + 10); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 10); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FISHING_ROD, Message.forName("item-missing-items-challenge")); + } - @Override - protected void onEnable() { - materials = Arrays.stream(ExperimentalUtils.getMaterials()) - .filter(Material::isItem) - .filter(ItemUtils::isObtainableInSurvival) - .collect(Collectors.toList()); - } + @Override + protected void onEnable() { + materials = Arrays.stream(ExperimentalUtils.getMaterials()) + .filter(Material::isItem) + .filter(ItemUtils::isObtainableInSurvival) + .collect(Collectors.toList()); + } - @Override - protected void onDisable() { - materials = null; - } - - @Override - protected void onTimeActivation() { - broadcastFiltered(this::startGuessingGame); - - if (inventories.isEmpty()) { - restartTimer(); - } - - } - - private void startGuessingGame(@Nonnull Player player) { - - BukkitTask task = new BukkitRunnable() { - - int timeLeft = (int) (2.5 * 60); - - @Override - public void run() { - timeLeft--; - - if (!inventories.containsKey(player.getUniqueId())) { - cancel(); - return; - } - - if (timeLeft == 0) { - cancel(); - Tuple tuple = inventories.remove(player.getUniqueId()); - tuple.getSecond().handleClick(new MenuClickInfo(player, tuple.getFirst(), false, false, 1000)); - } else if (timeLeft <= 5) { - new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BASS, 0.5F, (float) (timeLeft - 1) / 10 + 1).play(player); - } - - } - - }.runTaskTimer(plugin, 20, 20); - - createMissingItemsInventory(player, unused -> { - if (!anyRunningGame()) { - inventories.clear(); - restartTimer(); - } - task.cancel(); - }); - - } - - private void createMissingItemsInventory(@Nonnull Player player, Consumer onFinish) { - - int targetSlot = InventoryUtils.getRandomFullSlot(player.getInventory()); - if (targetSlot == -1) return; - - SoundSample.PLOP.play(player); - - ItemStack targetItem = player.getInventory().getItem(targetSlot); - if (targetItem == null) return; - Tuple tuple = generateMissingItemsInventory(targetItem); - - Tuple inventoryTuple = new Tuple<>(tuple.getFirst(), menuClickInfo -> { - InventoryUtils.giveItem(player, targetItem); - inventories.remove(player.getUniqueId()); - onFinish.accept(null); - if (menuClickInfo.getSlot() == tuple.getSecond()) { - SoundSample.LEVEL_UP.play(player); - player.closeInventory(); - } else { - player.closeInventory(); - kill(player); - } - }); - inventories.put(player.getUniqueId(), inventoryTuple); - - player.getInventory().setItem(targetSlot, null); - - sendInfoText(player); - - } - - private void sendInfoText(@Nonnull Player player) { - String message = Message.forName("missing-items-inventory").asString("§7"); - String openMessage = Message.forName("missing-items-inventory-open").asString(); - - TextComponent messageComponent = new TextComponent(Prefix.CHALLENGES + message + " "); - - TextComponent clickComponent = new TextComponent(openMessage); - clickComponent.setClickEvent(new ClickEvent(Action.RUN_COMMAND, "/openmissingitems")); - clickComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Collections.singletonList(new TextComponent("§2§l✔ §8┃ §7" + Message.forName("open").asString())).toArray(new BaseComponent[0]))); - - messageComponent.addExtra(clickComponent); - player.spigot().sendMessage(messageComponent); - } - - private boolean openGameInventory(@Nonnull Player player) { - Tuple inventoryTuple = inventories.get(player.getUniqueId()); - if (inventoryTuple == null) return false; - player.openInventory(inventoryTuple.getFirst()); - MenuPosition.set(player, inventoryTuple.getSecond()); - return true; - } + @Override + protected void onDisable() { + materials = null; + } + + @Override + protected void onTimeActivation() { + broadcastFiltered(this::startGuessingGame); + + if (inventories.isEmpty()) { + restartTimer(); + } + + } + + private void startGuessingGame(@Nonnull Player player) { + + BukkitTask task = new BukkitRunnable() { + + int timeLeft = (int) (2.5 * 60); + + @Override + public void run() { + timeLeft--; + + if (!inventories.containsKey(player.getUniqueId())) { + cancel(); + return; + } + + if (timeLeft == 0) { + cancel(); + Tuple tuple = inventories.remove(player.getUniqueId()); + tuple.getSecond().handleClick(new MenuClickInfo(player, tuple.getFirst(), false, false, 1000)); + } else if (timeLeft <= 5) { + new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BASS, 0.5F, (float) (timeLeft - 1) / 10 + 1).play(player); + } + + } + + }.runTaskTimer(plugin, 20, 20); + + createMissingItemsInventory(player, unused -> { + if (!anyRunningGame()) { + inventories.clear(); + restartTimer(); + } + task.cancel(); + }); + + } + + private void createMissingItemsInventory(@Nonnull Player player, Consumer onFinish) { + + int targetSlot = InventoryUtils.getRandomFullSlot(player.getInventory()); + if (targetSlot == -1) return; + + SoundSample.PLOP.play(player); + + ItemStack targetItem = player.getInventory().getItem(targetSlot); + if (targetItem == null) return; + Tuple tuple = generateMissingItemsInventory(targetItem); + + Tuple inventoryTuple = new Tuple<>(tuple.getFirst(), menuClickInfo -> { + InventoryUtils.giveItem(player, targetItem); + inventories.remove(player.getUniqueId()); + onFinish.accept(null); + if (menuClickInfo.getSlot() == tuple.getSecond()) { + SoundSample.LEVEL_UP.play(player); + player.closeInventory(); + } else { + player.closeInventory(); + kill(player); + } + }); + inventories.put(player.getUniqueId(), inventoryTuple); + + player.getInventory().setItem(targetSlot, null); + + sendInfoText(player); + + } + + private void sendInfoText(@Nonnull Player player) { + String message = Message.forName("missing-items-inventory").asString("§7"); + String openMessage = Message.forName("missing-items-inventory-open").asString(); + + TextComponent messageComponent = new TextComponent(Prefix.CHALLENGES + message + " "); + + TextComponent clickComponent = new TextComponent(openMessage); + clickComponent.setClickEvent(new ClickEvent(Action.RUN_COMMAND, "/openmissingitems")); + clickComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Collections.singletonList(new TextComponent("§2§l✔ §8┃ §7" + Message.forName("open").asString())).toArray(new BaseComponent[0]))); + + messageComponent.addExtra(clickComponent); + player.spigot().sendMessage(messageComponent); + } + + private boolean openGameInventory(@Nonnull Player player) { + Tuple inventoryTuple = inventories.get(player.getUniqueId()); + if (inventoryTuple == null) return false; + player.openInventory(inventoryTuple.getFirst()); + MenuPosition.set(player, inventoryTuple.getSecond()); + return true; + } - private Tuple generateMissingItemsInventory(@Nonnull ItemStack itemStack) { - Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(Message.forName("missing-items-inventory").asString(Message.forName("inventory-color").asString()))); + private Tuple generateMissingItemsInventory(@Nonnull ItemStack itemStack) { + Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(Message.forName("missing-items-inventory").asString(Message.forName("inventory-color").asString()))); - int targetSlot = globalRandom.nextInt(inventory.getSize()); - inventory.setItem(targetSlot, itemStack); + int targetSlot = globalRandom.nextInt(inventory.getSize()); + inventory.setItem(targetSlot, itemStack); - for (int slot = 0; slot < inventory.getSize(); slot++) { - if (slot == targetSlot) continue; - try { - inventory.setItem(slot, getRandomItem(itemStack)); - } catch (Exception exception) { - inventory.setItem(slot, new ItemStack(Material.BARRIER)); - Challenges.getInstance().getLogger().error("", exception); - } - - } - - return new Tuple<>(inventory, targetSlot); - } - - private ItemStack getRandomItem(@Nonnull ItemStack blacklisted) { - if (materials == null) onEnable(); - - Material material = globalRandom.choose(materials); - ItemStack itemStack = new ItemStack(material); - - if (itemStack.getItemMeta() instanceof Damageable && 1 < material.getMaxDurability()) { - ((Damageable) itemStack.getItemMeta()).setDamage(globalRandom.range(1, material.getMaxDurability())); - } else if (1 < itemStack.getMaxStackSize() && globalRandom.nextInt(100) <= 20) { - itemStack.setAmount(globalRandom.range(1, itemStack.getMaxStackSize())); - } - - if (itemStack.isSimilar(blacklisted) && itemStack.getAmount() == blacklisted.getAmount()) { - return getRandomItem(blacklisted); - } - - return itemStack; - } - - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - if (openGameInventory(player)) { - SoundSample.OPEN.play(player); - } else { - SoundSample.BASS_OFF.play(player); - } - } - - private boolean anyRunningGame() { - return inventories.keySet().stream().anyMatch(uuid -> Bukkit.getOfflinePlayer(uuid).isOnline()); - } + for (int slot = 0; slot < inventory.getSize(); slot++) { + if (slot == targetSlot) continue; + try { + inventory.setItem(slot, getRandomItem(itemStack)); + } catch (Exception exception) { + inventory.setItem(slot, new ItemStack(Material.BARRIER)); + Challenges.getInstance().getLogger().error("", exception); + } + + } + + return new Tuple<>(inventory, targetSlot); + } + + private ItemStack getRandomItem(@Nonnull ItemStack blacklisted) { + if (materials == null) onEnable(); + + Material material = globalRandom.choose(materials); + ItemStack itemStack = new ItemStack(material); + + if (itemStack.getItemMeta() instanceof Damageable && 1 < material.getMaxDurability()) { + ((Damageable) itemStack.getItemMeta()).setDamage(globalRandom.range(1, material.getMaxDurability())); + } else if (1 < itemStack.getMaxStackSize() && globalRandom.nextInt(100) <= 20) { + itemStack.setAmount(globalRandom.range(1, itemStack.getMaxStackSize())); + } + + if (itemStack.isSimilar(blacklisted) && itemStack.getAmount() == blacklisted.getAmount()) { + return getRandomItem(blacklisted); + } + + return itemStack; + } + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + if (openGameInventory(player)) { + SoundSample.OPEN.play(player); + } else { + SoundSample.BASS_OFF.play(player); + } + } + + private boolean anyRunningGame() { + return inventories.keySet().stream().anyMatch(uuid -> Bukkit.getOfflinePlayer(uuid).isOnline()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java index 7a2504bc3..e086bd6ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java @@ -20,47 +20,50 @@ @Since("2.0") public class MovementItemRemovingChallenge extends SettingModifier { - public static final int BLOCK = 1; + public static final int BLOCK = 1; - public MovementItemRemovingChallenge() { - super(MenuType.CHALLENGES, 1, 2, 2); - setCategory(SettingCategory.INVENTORY); - } + public MovementItemRemovingChallenge() { + super(MenuType.CHALLENGES, 1, 2, 2); + setCategory(SettingCategory.INVENTORY); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DETECTOR_RAIL, Message.forName("item-block-chunk-item-remove-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DETECTOR_RAIL, Message.forName("item-block-chunk-item-remove-challenge")); + } - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (!isEnabled()) return DefaultItem.disabled(); - if (getValue() == BLOCK) return DefaultItem.create(Material.GRASS_BLOCK, Message.forName("item-block-chunk-item-remove-challenge-block")); - return DefaultItem.create(Material.BOOK, Message.forName("item-block-chunk-item-remove-challenge-chunk")); - } + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (!isEnabled()) return DefaultItem.disabled(); + if (getValue() == BLOCK) + return DefaultItem.create(Material.GRASS_BLOCK, Message.forName("item-block-chunk-item-remove-challenge-block")); + return DefaultItem.create(Material.BOOK, Message.forName("item-block-chunk-item-remove-challenge-chunk")); + } - @Override - public void playValueChangeTitle() { - if (getValue() == BLOCK) ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-block-chunk-item-remove-challenge-block")); - else ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-block-chunk-item-remove-challenge-chunk")); - } + @Override + public void playValueChangeTitle() { + if (getValue() == BLOCK) + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-block-chunk-item-remove-challenge-block")); + else + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-block-chunk-item-remove-challenge-chunk")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; - if (getValue() == BLOCK) { - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; - } else { - if (BlockUtils.isSameChunk(event.getFrom().getChunk(), event.getTo().getChunk())) - return; - } + if (getValue() == BLOCK) { + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; + } else { + if (BlockUtils.isSameChunk(event.getFrom().getChunk(), event.getTo().getChunk())) + return; + } - InventoryUtils.removeRandomItem(event.getPlayer().getInventory()); - } + InventoryUtils.removeRandomItem(event.getPlayer().getInventory()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java index 54081b17e..762143d4a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java @@ -32,82 +32,82 @@ @CanInstaKillOnEnable public class NoDupedItemsChallenge extends Setting { - public NoDupedItemsChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.INVENTORY); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.OBSERVER, Message.forName("item-no-duped-items-challenge")); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - checkInventories(); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onEntityPickUpItem(@Nonnull PlayerPickupItemEvent event) { - Bukkit.getScheduler().runTaskLater(plugin, () -> { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - checkInventories(); - }, 1); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInteract(@Nonnull PlayerInteractEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getClickedBlock() == null) return; - checkInventories(); - } - - private void checkInventories() { - Map> blackList = new HashMap<>(); - - for (Player player : Bukkit.getOnlinePlayers()) { - Triple result = checkInventory(player, blackList); - if (result != null) { - Message.forName("no-duped-items-failed").broadcast( - Prefix.CHALLENGES, - NameHelper.getName(result.getFirst()), - NameHelper.getName(result.getSecond()), - result.getThird() - ); - ChallengeHelper.kill(result.getFirst()); - ChallengeHelper.kill(result.getSecond()); - } - - } - - } - - private Triple checkInventory(@Nonnull Player player, Map> blacklist) { - List localBlacklist = new ArrayList<>(); - List playerBlacklist = blacklist.getOrDefault(player, new ArrayList<>()); - blacklist.put(player, playerBlacklist); - - for (ItemStack item : player.getInventory().getContents()) { - if (item == null) continue; - if (localBlacklist.contains(item.getType())) continue; - localBlacklist.add(item.getType()); - - for (Entry> entry : blacklist.entrySet()) { - List currentBlacklist = entry.getValue(); - if (currentBlacklist.contains(item.getType())) { - return new Triple<>(player, entry.getKey(), item.getType()); - } - - } - playerBlacklist.add(item.getType()); - } - - return null; - } + public NoDupedItemsChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.INVENTORY); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.OBSERVER, Message.forName("item-no-duped-items-challenge")); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + checkInventories(); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onEntityPickUpItem(@Nonnull PlayerPickupItemEvent event) { + Bukkit.getScheduler().runTaskLater(plugin, () -> { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + checkInventories(); + }, 1); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onInteract(@Nonnull PlayerInteractEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getClickedBlock() == null) return; + checkInventories(); + } + + private void checkInventories() { + Map> blackList = new HashMap<>(); + + for (Player player : Bukkit.getOnlinePlayers()) { + Triple result = checkInventory(player, blackList); + if (result != null) { + Message.forName("no-duped-items-failed").broadcast( + Prefix.CHALLENGES, + NameHelper.getName(result.getFirst()), + NameHelper.getName(result.getSecond()), + result.getThird() + ); + ChallengeHelper.kill(result.getFirst()); + ChallengeHelper.kill(result.getSecond()); + } + + } + + } + + private Triple checkInventory(@Nonnull Player player, Map> blacklist) { + List localBlacklist = new ArrayList<>(); + List playerBlacklist = blacklist.getOrDefault(player, new ArrayList<>()); + blacklist.put(player, playerBlacklist); + + for (ItemStack item : player.getInventory().getContents()) { + if (item == null) continue; + if (localBlacklist.contains(item.getType())) continue; + localBlacklist.add(item.getType()); + + for (Entry> entry : blacklist.entrySet()) { + List currentBlacklist = entry.getValue(); + if (currentBlacklist.contains(item.getType())) { + return new Triple<>(player, entry.getKey(), item.getType()); + } + + } + playerBlacklist.add(item.getType()); + } + + return null; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java index 37d0671ce..52747ff62 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java @@ -21,40 +21,40 @@ @Since("2.0") public class PermanentItemChallenge extends Setting { - public PermanentItemChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.INVENTORY); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.VINE, Message.forName("item-permanent-item-challenge")); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - Player player = event.getPlayer(); - if (!shouldExecuteEffect()) return; - if (ignorePlayer(player)) return; - Inventory clickedInventory = event.getClickedInventory(); - if (event.getCursor() == null) return; - if (clickedInventory == null) return; - InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); - if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; - if (clickedInventory.getType() == InventoryType.CRAFTING) return; - if (clickedInventory.getType() == InventoryType.PLAYER) { - if (event.getInventory().getType() != InventoryType.PLAYER) { - event.setCancelled(true); - } - } - - } - - @EventHandler - public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { - if (!shouldExecuteEffect()) return; - event.setCancelled(true); - } + public PermanentItemChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.INVENTORY); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.VINE, Message.forName("item-permanent-item-challenge")); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + Player player = event.getPlayer(); + if (!shouldExecuteEffect()) return; + if (ignorePlayer(player)) return; + Inventory clickedInventory = event.getClickedInventory(); + if (event.getCursor() == null) return; + if (clickedInventory == null) return; + InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); + if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; + if (clickedInventory.getType() == InventoryType.CRAFTING) return; + if (clickedInventory.getType() == InventoryType.PLAYER) { + if (event.getInventory().getType() != InventoryType.PLAYER) { + event.setCancelled(true); + } + } + + } + + @EventHandler + public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { + if (!shouldExecuteEffect()) return; + event.setCancelled(true); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java index 90d325935..dca729ffa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java @@ -21,36 +21,36 @@ @Since("2.0") public class PickupItemLaunchChallenge extends SettingModifier { - public PickupItemLaunchChallenge() { - super(MenuType.CHALLENGES, 1, 10, 2); - setCategory(SettingCategory.INVENTORY); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOW, Message.forName("item-pickup-launch-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-launcher-description").asArray(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-launcher-description").asString(getValue())); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerPickUpItem(@Nonnull PlayerPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - - Vector velocityToAdd = new Vector(0, getValue() / 2, 0); - Vector newVelocity = EntityUtils.getSucceedingVelocity(event.getPlayer().getVelocity()).add(velocityToAdd); - event.getPlayer().setVelocity(newVelocity); - } + public PickupItemLaunchChallenge() { + super(MenuType.CHALLENGES, 1, 10, 2); + setCategory(SettingCategory.INVENTORY); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BOW, Message.forName("item-pickup-launch-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-launcher-description").asArray(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-launcher-description").asString(getValue())); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerPickUpItem(@Nonnull PlayerPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + + Vector velocityToAdd = new Vector(0, getValue() / 2, 0); + Vector newVelocity = EntityUtils.getSucceedingVelocity(event.getPlayer().getVelocity()).add(velocityToAdd); + event.getPlayer().setVelocity(newVelocity); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java index 2f87be910..47e33eabd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java @@ -22,120 +22,120 @@ @Since("2.0.2") public class UncraftItemsChallenge extends TimedChallenge { - public UncraftItemsChallenge() { - super(MenuType.CHALLENGES, 5, 60, 20); - setCategory(SettingCategory.INVENTORY); - } - - public static void uncraftInventory(@Nonnull Player player) { - - PlayerInventory inventory = player.getInventory(); - - List itemsToAdd = new ArrayList<>(); - - for (int slot = 0; slot < inventory.getContents().length; slot++) { - ItemStack item = inventory.getItem(slot); - if (item == null) continue; - List recipes = Bukkit.getRecipesFor(new ItemStack(item.getType())); - if (recipes.isEmpty()) continue; + public UncraftItemsChallenge() { + super(MenuType.CHALLENGES, 5, 60, 20); + setCategory(SettingCategory.INVENTORY); + } + + public static void uncraftInventory(@Nonnull Player player) { + + PlayerInventory inventory = player.getInventory(); + + List itemsToAdd = new ArrayList<>(); + + for (int slot = 0; slot < inventory.getContents().length; slot++) { + ItemStack item = inventory.getItem(slot); + if (item == null) continue; + List recipes = Bukkit.getRecipesFor(new ItemStack(item.getType())); + if (recipes.isEmpty()) continue; - Recipe recipe = null; - for (Recipe currentRecipe : recipes) { + Recipe recipe = null; + for (Recipe currentRecipe : recipes) { - if (canCraft(recipes, item.getType())) { - continue; - } + if (canCraft(recipes, item.getType())) { + continue; + } - recipe = currentRecipe; - } + recipe = currentRecipe; + } - if (recipe == null) continue; + if (recipe == null) continue; - ItemStack[] ingredients = getIngredientsOfRecipe(recipe).toArray(new ItemStack[0]); + ItemStack[] ingredients = getIngredientsOfRecipe(recipe).toArray(new ItemStack[0]); - for (int i = 0; i < item.getAmount() / recipe.getResult().getAmount(); i++) { - for (ItemStack ingredient : ingredients) { - if (ingredient == null) { - continue; - } - itemsToAdd.add(ingredient); - } - } - inventory.setItem(slot, null); - } + for (int i = 0; i < item.getAmount() / recipe.getResult().getAmount(); i++) { + for (ItemStack ingredient : ingredients) { + if (ingredient == null) { + continue; + } + itemsToAdd.add(ingredient); + } + } + inventory.setItem(slot, null); + } - itemsToAdd.forEach(itemStack -> InventoryUtils.giveItem(player, itemStack)); + itemsToAdd.forEach(itemStack -> InventoryUtils.giveItem(player, itemStack)); - } + } - private static boolean canCraft(List recipes, Material material) { + private static boolean canCraft(List recipes, Material material) { - for (Recipe recipe : recipes) { - for (ItemStack ingredient : getIngredientsOfRecipe(recipe)) { - if (ingredient == null) continue; + for (Recipe recipe : recipes) { + for (ItemStack ingredient : getIngredientsOfRecipe(recipe)) { + if (ingredient == null) continue; - List ingredientRecipes = Bukkit.getRecipesFor(ingredient); + List ingredientRecipes = Bukkit.getRecipesFor(ingredient); - for (Recipe ingredientRecipe : ingredientRecipes) { - for (ItemStack itemStack : getIngredientsOfRecipe(ingredientRecipe)) { - if (itemStack == null) continue; - if (itemStack.getType() == material) { - return true; - } + for (Recipe ingredientRecipe : ingredientRecipes) { + for (ItemStack itemStack : getIngredientsOfRecipe(ingredientRecipe)) { + if (itemStack == null) continue; + if (itemStack.getType() == material) { + return true; + } - } + } - } + } - } - } - return false; - } + } + } + return false; + } - private static List getIngredientsOfRecipe(@Nonnull Recipe recipe) { - List ingredients = new ArrayList<>(); - if (recipe instanceof ShapedRecipe) { - ShapedRecipe shaped = (ShapedRecipe) recipe; - ingredients.addAll(shaped.getIngredientMap().values()); - } else if (recipe instanceof ShapelessRecipe) { - ShapelessRecipe shapeless = (ShapelessRecipe) recipe; - ingredients.addAll(shapeless.getIngredientList()); - } else if (recipe instanceof FurnaceRecipe) { - FurnaceRecipe furnace = (FurnaceRecipe) recipe; - ingredients.add(furnace.getInput()); - } else if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14) && recipe instanceof SmithingRecipe) { - SmithingRecipe smithing = (SmithingRecipe) recipe; - ingredients.add(Objects.requireNonNull(smithing.getBase()).getItemStack()); - ingredients.add(Objects.requireNonNull(smithing.getAddition()).getItemStack()); - } + private static List getIngredientsOfRecipe(@Nonnull Recipe recipe) { + List ingredients = new ArrayList<>(); + if (recipe instanceof ShapedRecipe) { + ShapedRecipe shaped = (ShapedRecipe) recipe; + ingredients.addAll(shaped.getIngredientMap().values()); + } else if (recipe instanceof ShapelessRecipe) { + ShapelessRecipe shapeless = (ShapelessRecipe) recipe; + ingredients.addAll(shapeless.getIngredientList()); + } else if (recipe instanceof FurnaceRecipe) { + FurnaceRecipe furnace = (FurnaceRecipe) recipe; + ingredients.add(furnace.getInput()); + } else if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14) && recipe instanceof SmithingRecipe) { + SmithingRecipe smithing = (SmithingRecipe) recipe; + ingredients.add(Objects.requireNonNull(smithing.getBase()).getItemStack()); + ingredients.add(Objects.requireNonNull(smithing.getAddition()).getItemStack()); + } - return ingredients; - } + return ingredients; + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CRAFTING_TABLE, Message.forName("item-uncraft-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CRAFTING_TABLE, Message.forName("item-uncraft-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } - @Override - protected int getSecondsUntilNextActivation() { - return getValue(); - } - - @Override - protected void onTimeActivation() { - restartTimer(); - - broadcastFiltered(UncraftItemsChallenge::uncraftInventory); - - } + @Override + protected int getSecondsUntilNextActivation() { + return getValue(); + } + + @Override + protected void onTimeActivation() { + restartTimer(); + + broadcastFiltered(UncraftItemsChallenge::uncraftInventory); + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index cc621e5c7..cfd3921b5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -23,56 +23,56 @@ @Since("2.0") public class EnderGamesChallenge extends TimedChallenge { - public EnderGamesChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, false); - } + public EnderGamesChallenge() { + super(MenuType.CHALLENGES, 1, 10, 5, false); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENDER_PEARL, Message.forName("item-ender-games-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ENDER_PEARL, Message.forName("item-ender-games-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); + } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 20, getValue() * 60 + 20); - } + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 20, getValue() * 60 + 20); + } - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 20); - } + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 20); + } - @Override - protected void onTimeActivation() { - restartTimer(); - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - teleportRandom(player); - } - SoundSample.TELEPORT.broadcast(); - } + @Override + protected void onTimeActivation() { + restartTimer(); + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + teleportRandom(player); + } + SoundSample.TELEPORT.broadcast(); + } - private void teleportRandom(@Nonnull Player player) { + private void teleportRandom(@Nonnull Player player) { - List list = player.getWorld().getNearbyEntities(player.getLocation(), 200, 200, 200).stream() - .filter(entity -> !(entity instanceof Player)) - .filter(entity -> entity instanceof LivingEntity) - .collect(Collectors.toList()); + List list = player.getWorld().getNearbyEntities(player.getLocation(), 200, 200, 200).stream() + .filter(entity -> !(entity instanceof Player)) + .filter(entity -> entity instanceof LivingEntity) + .collect(Collectors.toList()); - Entity targetEntity = list.get(globalRandom.nextInt(list.size())); + Entity targetEntity = list.get(globalRandom.nextInt(list.size())); - Location playerLocation = player.getLocation().clone(); - player.teleport(targetEntity.getLocation()); - Message.forName("endergames-teleport").send(player, Prefix.CHALLENGES, targetEntity.getType()); - targetEntity.teleport(playerLocation); + Location playerLocation = player.getLocation().clone(); + player.teleport(targetEntity.getLocation()); + Message.forName("endergames-teleport").send(player, Prefix.CHALLENGES, targetEntity.getType()); + targetEntity.teleport(playerLocation); - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java index 7c1b57e4d..8f1df0fb9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java @@ -20,35 +20,35 @@ @Since("2.0.2") public class FoodLaunchChallenge extends SettingModifier { - public FoodLaunchChallenge() { - super(MenuType.CHALLENGES, 1, 10, 2); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CAKE, Message.forName("item-consume-launch-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-launcher-description").asArray(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-launcher-description").asString(getValue())); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerItemConsume(@Nonnull PlayerItemConsumeEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - - Vector velocityToAdd = new Vector(0, getValue() / 2, 0); - Vector newVelocity = EntityUtils.getSucceedingVelocity(event.getPlayer().getVelocity()).add(velocityToAdd); - event.getPlayer().setVelocity(newVelocity); - } + public FoodLaunchChallenge() { + super(MenuType.CHALLENGES, 1, 10, 2); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CAKE, Message.forName("item-consume-launch-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-launcher-description").asArray(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-launcher-description").asString(getValue())); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerItemConsume(@Nonnull PlayerItemConsumeEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + + Vector velocityToAdd = new Vector(0, getValue() / 2, 0); + Vector newVelocity = EntityUtils.getSucceedingVelocity(event.getPlayer().getVelocity()).add(velocityToAdd); + event.getPlayer().setVelocity(newVelocity); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java index 354eacae6..cf3a29206 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java @@ -19,89 +19,89 @@ public class FoodOnceChallenge extends SettingModifier { - public FoodOnceChallenge() { - super(MenuType.CHALLENGES, 2); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COOKED_BEEF, Message.forName("item-food-once-challenge")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - switch (getValue()) { - case 1: - return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("item-food-once-challenge-player")); - case 2: - return DefaultItem.create(Material.ENDER_CHEST, Message.forName("item-food-once-challenge-everyone")); - default: - return super.createSettingsItem(); - } - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 1 ? Message.forName("item-food-once-challenge-player") : Message.forName("item-food-once-challenge-everyone")); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerItemConsume(@Nonnull PlayerItemConsumeEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - - Material type = event.getItem().getType(); - if (hasEaten(event.getPlayer(), type)) { - Message.forName("food-once-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); - ChallengeHelper.kill(event.getPlayer(), 1); - } else { - addFood(event.getPlayer(), type); - if (teamFoodsActivated()) { - Message.forName("food-once-new-food-team").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); - } else { - Message.forName("food-once-new-food").send(event.getPlayer(), Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); - - } - } - - } - - private void addFood(Player player, Material type) { - if (teamFoodsActivated()) { - addTeamFood(type); - } else { - addPlayerFood(player, type); - } - } - - private void addPlayerFood(@Nonnull Player player, @Nonnull Material material) { - List foods = getPlayerData(player).getEnumList("foods", Material.class); - foods.add(material); - getPlayerData(player).set("foods", foods); - } - - private boolean hasEaten(@Nonnull Player player, @Nonnull Material material) { - if (teamFoodsActivated()) { - return hasBeenEatenByTeam(material); - } - - return getPlayerData(player).getEnumList("foods", Material.class).contains(material); - } - - private void addTeamFood(@Nonnull Material material) { - List foods = getGameStateData().getEnumList("foods", Material.class); - foods.add(material); - getGameStateData().set("foods", foods); - } - - private boolean hasBeenEatenByTeam(@Nonnull Material material) { - return getGameStateData().getEnumList("foods", Material.class).contains(material); - } - - private boolean teamFoodsActivated() { - return getValue() == 2; - } + public FoodOnceChallenge() { + super(MenuType.CHALLENGES, 2); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.COOKED_BEEF, Message.forName("item-food-once-challenge")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + switch (getValue()) { + case 1: + return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("item-food-once-challenge-player")); + case 2: + return DefaultItem.create(Material.ENDER_CHEST, Message.forName("item-food-once-challenge-everyone")); + default: + return super.createSettingsItem(); + } + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 1 ? Message.forName("item-food-once-challenge-player") : Message.forName("item-food-once-challenge-everyone")); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerItemConsume(@Nonnull PlayerItemConsumeEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + + Material type = event.getItem().getType(); + if (hasEaten(event.getPlayer(), type)) { + Message.forName("food-once-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); + ChallengeHelper.kill(event.getPlayer(), 1); + } else { + addFood(event.getPlayer(), type); + if (teamFoodsActivated()) { + Message.forName("food-once-new-food-team").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); + } else { + Message.forName("food-once-new-food").send(event.getPlayer(), Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); + + } + } + + } + + private void addFood(Player player, Material type) { + if (teamFoodsActivated()) { + addTeamFood(type); + } else { + addPlayerFood(player, type); + } + } + + private void addPlayerFood(@Nonnull Player player, @Nonnull Material material) { + List foods = getPlayerData(player).getEnumList("foods", Material.class); + foods.add(material); + getPlayerData(player).set("foods", foods); + } + + private boolean hasEaten(@Nonnull Player player, @Nonnull Material material) { + if (teamFoodsActivated()) { + return hasBeenEatenByTeam(material); + } + + return getPlayerData(player).getEnumList("foods", Material.class).contains(material); + } + + private void addTeamFood(@Nonnull Material material) { + List foods = getGameStateData().getEnumList("foods", Material.class); + foods.add(material); + getGameStateData().set("foods", foods); + } + + private boolean hasBeenEatenByTeam(@Nonnull Material material) { + return getGameStateData().getEnumList("foods", Material.class).contains(material); + } + + private boolean teamFoodsActivated() { + return getValue() == 2; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java index dd9640cfd..772f3e71f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java @@ -20,50 +20,50 @@ @ExcludeFromRandomChallenges public class InvertHealthChallenge extends TimedChallenge { - public InvertHealthChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, false); - } + public InvertHealthChallenge() { + super(MenuType.CHALLENGES, 1, 10, 5, false); + } - public static void invertHealth(Player player) { - double health = player.getMaxHealth() - player.getHealth(); - if (health <= 0) { - ChallengeHelper.kill(player); - return; - } - player.setHealth(health); - } + public static void invertHealth(Player player) { + double health = player.getMaxHealth() - player.getHealth(); + if (health <= 0) { + ChallengeHelper.kill(player); + return; + } + player.setHealth(health); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.POPPY, Message.forName("item-invert-health-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.POPPY, Message.forName("item-invert-health-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); + } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 20, getValue() * 60 + 20); - } + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 20, getValue() * 60 + 20); + } - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 20); - } + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 20); + } - @Override - protected void onTimeActivation() { - SoundSample.PLOP.broadcast(); - Message.forName("health-inverted").broadcast(Prefix.CHALLENGES); - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - invertHealth(player); - } - restartTimer(); - } + @Override + protected void onTimeActivation() { + SoundSample.PLOP.broadcast(); + Message.forName("health-inverted").broadcast(Prefix.CHALLENGES); + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + invertHealth(player); + } + restartTimer(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java index eaca7adcb..2bafe978f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java @@ -19,48 +19,48 @@ @Since("2.0") public class LowDropRateChallenge extends SettingModifier { - private final Random random = new Random(); + private final Random random = new Random(); - public LowDropRateChallenge() { - super(MenuType.CHALLENGES, 9); - } + public LowDropRateChallenge() { + super(MenuType.CHALLENGES, 9); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.WOODEN_AXE, Message.forName("item-low-drop-rate-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.WOODEN_AXE, Message.forName("item-low-drop-rate-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-chance-description").asArray(getValue() * 10); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-chance-description").asArray(getValue() * 10); + } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() * 10 + "%"); - } + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, getValue() * 10 + "%"); + } - @Override - protected void onValueChange() { - reloadChances(); - } + @Override + protected void onValueChange() { + reloadChances(); + } - @Override - protected void onEnable() { - reloadChances(); - } + @Override + protected void onEnable() { + reloadChances(); + } - @Override - protected void onDisable() { - Challenges.getInstance().getBlockDropManager().resetDropChance(DropPriority.CHANCE); - } + @Override + protected void onDisable() { + Challenges.getInstance().getBlockDropManager().resetDropChance(DropPriority.CHANCE); + } - protected void reloadChances() { - Arrays.stream(ExperimentalUtils.getMaterials()).filter(Material::isBlock).forEach(block -> { - Challenges.getInstance().getBlockDropManager().setDropChance(block, DropPriority.CHANCE, () -> random.nextInt(10) < getValue()); - }); - } + protected void reloadChances() { + Arrays.stream(ExperimentalUtils.getMaterials()).filter(Material::isBlock).forEach(block -> { + Challenges.getInstance().getBlockDropManager().setDropChance(block, DropPriority.CHANCE, () -> random.nextInt(10) < getValue()); + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java index 1383b56fe..60597c942 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java @@ -16,23 +16,23 @@ public class NoExpChallenge extends Setting { - public NoExpChallenge() { - super(MenuType.CHALLENGES); - } + public NoExpChallenge() { + super(MenuType.CHALLENGES); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onExp(PlayerExpChangeEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getAmount() <= 0) return; - Message.forName("exp-picked-up").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - ChallengeHelper.kill(event.getPlayer()); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onExp(PlayerExpChangeEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getAmount() <= 0) return; + Message.forName("exp-picked-up").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + ChallengeHelper.kill(event.getPlayer()); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-no-exp-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-no-exp-challenge")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java index 23feeba3e..d62b3dfcc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java @@ -23,49 +23,49 @@ @Since("2.2.0") public class NoSharedAdvancementsChallenge extends Setting { - private final List advancementsDone = new LinkedList<>(); + private final List advancementsDone = new LinkedList<>(); - public NoSharedAdvancementsChallenge() { - super(MenuType.CHALLENGES); - } + public NoSharedAdvancementsChallenge() { + super(MenuType.CHALLENGES); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.KNOWLEDGE_BOOK, Message.forName("item-no-shared-advancements-challenge")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.KNOWLEDGE_BOOK, Message.forName("item-no-shared-advancements-challenge")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onAdvancementDone(PlayerAdvancementDoneEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; - if (advancementsDone.contains(event.getAdvancement())) { - ChallengeHelper.kill(event.getPlayer()); - } else { - advancementsDone.add(event.getAdvancement()); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onAdvancementDone(PlayerAdvancementDoneEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; + if (advancementsDone.contains(event.getAdvancement())) { + ChallengeHelper.kill(event.getPlayer()); + } else { + advancementsDone.add(event.getAdvancement()); + } + } - @Override - public void loadGameState(@NotNull Document document) { - advancementsDone.clear(); - List advancementKeys = document.getStringList("advancements"); - for (String advancementKey : advancementKeys) { - try { - advancementsDone.add(Bukkit.getAdvancement(Objects.requireNonNull(BukkitReflectionUtils.fromString(advancementKey)))); - } catch (Exception exception) { - // DON'T EXIST - } - } - } + @Override + public void loadGameState(@NotNull Document document) { + advancementsDone.clear(); + List advancementKeys = document.getStringList("advancements"); + for (String advancementKey : advancementKeys) { + try { + advancementsDone.add(Bukkit.getAdvancement(Objects.requireNonNull(BukkitReflectionUtils.fromString(advancementKey)))); + } catch (Exception exception) { + // DON'T EXIST + } + } + } - @Override - public void writeGameState(@NotNull Document document) { - List foundItems = new LinkedList<>(); - for (Advancement advancement : advancementsDone) { - foundItems.add(advancement.getKey().toString()); - } - document.set("advancements", foundItems); - } + @Override + public void writeGameState(@NotNull Document document) { + List foundItems = new LinkedList<>(); + for (Advancement advancement : advancementsDone) { + foundItems.add(advancement.getKey().toString()); + } + document.set("advancements", foundItems); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java index f0a09e06d..aaf281b19 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java @@ -16,34 +16,34 @@ public class NoTradingChallenge extends Setting { - public NoTradingChallenge() { - super(MenuType.CHALLENGES); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.EMERALD, Message.forName("item-no-trading-challenge")); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onInteract(@Nonnull PlayerInteractEntityEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getRightClicked() instanceof Villager) { - event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ENTITY_VILLAGER_NO, 1F, 1F); - event.setCancelled(true); - } else if (event.getRightClicked().getType().name().equals("PIGLIN")) { - event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ENTITY_PIGLIN_ADMIRING_ITEM, 1F, 1F); - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityPickupItem(@Nonnull EntityPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getEntityType().name().equals("PIGLIN")) { - event.setCancelled(true); - } - } + public NoTradingChallenge() { + super(MenuType.CHALLENGES); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.EMERALD, Message.forName("item-no-trading-challenge")); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onInteract(@Nonnull PlayerInteractEntityEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getRightClicked() instanceof Villager) { + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ENTITY_VILLAGER_NO, 1F, 1F); + event.setCancelled(true); + } else if (event.getRightClicked().getType().name().equals("PIGLIN")) { + event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ENTITY_PIGLIN_ADMIRING_ITEM, 1F, 1F); + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityPickupItem(@Nonnull EntityPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getEntityType().name().equals("PIGLIN")) { + event.setCancelled(true); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java index ed2c5fa85..e2783a952 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java @@ -19,50 +19,50 @@ public class OneDurabilityChallenge extends Setting { - public OneDurabilityChallenge() { - super(MenuType.CHALLENGES); - } + public OneDurabilityChallenge() { + super(MenuType.CHALLENGES); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.WOODEN_HOE, Message.forName("item-one-durability-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.WOODEN_HOE, Message.forName("item-one-durability-challenge")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onInventoryClick(@Nonnull InventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getWhoClicked() instanceof Player && ignorePlayer((Player) event.getWhoClicked())) - return; - if (event.getCurrentItem() != null) setDurability(event.getCurrentItem()); - if (event.getCursor() != null) setDurability(event.getCursor()); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onInventoryClick(@Nonnull InventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getWhoClicked() instanceof Player && ignorePlayer((Player) event.getWhoClicked())) + return; + if (event.getCurrentItem() != null) setDurability(event.getCurrentItem()); + if (event.getCursor() != null) setDurability(event.getCursor()); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onInteract(PlayerInteractEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getItem() == null) return; - setDurability(event.getItem()); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onInteract(PlayerInteractEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getItem() == null) return; + setDurability(event.getItem()); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onInteract(EntityPickupItemEvent event) { - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (!shouldExecuteEffect()) return; - if (ignorePlayer(player)) return; - setDurability(event.getItem().getItemStack()); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onInteract(EntityPickupItemEvent event) { + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (!shouldExecuteEffect()) return; + if (ignorePlayer(player)) return; + setDurability(event.getItem().getItemStack()); + } - private void setDurability(@Nonnull ItemStack item) { - ItemMeta meta = item.getItemMeta(); - if (meta instanceof Damageable) { - meta.setUnbreakable(false); - int durability = item.getType().getMaxDurability() - 1; - ((Damageable) meta).setDamage(durability); - item.setItemMeta(meta); - } - } + private void setDurability(@Nonnull ItemStack item) { + ItemMeta meta = item.getItemMeta(); + if (meta instanceof Damageable) { + meta.setUnbreakable(false); + int durability = item.getType().getMaxDurability() - 1; + ((Damageable) meta).setDamage(durability); + item.setItemMeta(meta); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java index 21bd6897a..5b7f33b5e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java @@ -17,44 +17,44 @@ @Since("2.0") public class AlwaysRunningChallenge extends Setting { - public AlwaysRunningChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.MOVEMENT); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CARROT_ON_A_STICK, Message.forName("item-always-running-challenge")); - } - - @ScheduledTask(ticks = 1) - public void setVelocity() { - broadcastFiltered(player -> { - if (player.isSprinting()) return; - - Location location = player.getLocation(); - Vector velocity = new Vector(); - - double rotX = location.getYaw(); - double xz = Math.cos(Math.toRadians(0)); - velocity.setX(-xz * Math.sin(Math.toRadians(rotX))); - velocity.setZ(xz * Math.cos(Math.toRadians(rotX))); - velocity.multiply(0.5); - - if (player.isSneaking()) - velocity.multiply(0.5); - else if (BukkitReflectionUtils.isInWater(player)) - velocity.multiply(0.5); - else if (!player.isOnGround()) - velocity.multiply(0.85); - - Vector oldVelocity = player.getVelocity(); - if (oldVelocity.getY() > 0) - oldVelocity.multiply(0.9); - velocity.setY(oldVelocity.getY()); - player.setVelocity(velocity); - }); - } + public AlwaysRunningChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.MOVEMENT); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CARROT_ON_A_STICK, Message.forName("item-always-running-challenge")); + } + + @ScheduledTask(ticks = 1) + public void setVelocity() { + broadcastFiltered(player -> { + if (player.isSprinting()) return; + + Location location = player.getLocation(); + Vector velocity = new Vector(); + + double rotX = location.getYaw(); + double xz = Math.cos(Math.toRadians(0)); + velocity.setX(-xz * Math.sin(Math.toRadians(rotX))); + velocity.setZ(xz * Math.cos(Math.toRadians(rotX))); + velocity.multiply(0.5); + + if (player.isSneaking()) + velocity.multiply(0.5); + else if (BukkitReflectionUtils.isInWater(player)) + velocity.multiply(0.5); + else if (!player.isOnGround()) + velocity.multiply(0.85); + + Vector oldVelocity = player.getVelocity(); + if (oldVelocity.getY() > 0) + oldVelocity.multiply(0.9); + velocity.setY(oldVelocity.getY()); + player.setVelocity(velocity); + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java index 74196fa3f..e69bb3116 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java @@ -24,80 +24,80 @@ @Since("2.0.2") public class DontStopRunningChallenge extends SettingModifier { - private static final int YELLOW = 5, RED = 3; - - private final Map playerStandingCount = new HashMap<>(); - - public DontStopRunningChallenge() { - super(MenuType.CHALLENGES, 3, 30, 10); - setCategory(SettingCategory.MOVEMENT); - } - - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - int count = playerStandingCount.getOrDefault(player, 1); - int timeLeft = getValue() - count + 1; - - if (timeLeft <= RED) bossbar.setColor(BarColor.RED); - else if (timeLeft <= YELLOW) bossbar.setColor(BarColor.YELLOW); - else bossbar.setColor(BarColor.GREEN); - - String time = "§e" + timeLeft + " §7" + (timeLeft == 1 ? Message.forName("second").asString() : Message.forName("seconds").asString()); - - bossbar.setTitle(Message.forName("bossbar-dont-stop-running").asString(time)); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SADDLE, Message.forName("item-dont-stop-running-challenge")); - } - - @ScheduledTask(ticks = 20) - public void onSecond() { - removeOfflinePlayers(); - countUpOrKillEveryone(); - bossbar.update(); - } - - private void removeOfflinePlayers() { - for (Player player : new ArrayList<>(playerStandingCount.keySet())) { - if (!player.isOnline() || ignorePlayer(player)) playerStandingCount.remove(player); - } - } - - private void countUpOrKillEveryone() { - - broadcastFiltered(player -> { - Integer count = playerStandingCount.getOrDefault(player, 0); - if (count >= getValue()) { - Message.forName("stopped-moving").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); - playerStandingCount.remove(player); - kill(player); - return; - } - playerStandingCount.put(player, count + 1); - - }); - - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - if (event.getFrom().getX() == event.getTo().getX() && event.getFrom().getZ() == event.getTo().getZ() && event.getFrom().getY() == event.getTo().getY()) - return; - playerStandingCount.remove(event.getPlayer()); - } + private static final int YELLOW = 5, RED = 3; + + private final Map playerStandingCount = new HashMap<>(); + + public DontStopRunningChallenge() { + super(MenuType.CHALLENGES, 3, 30, 10); + setCategory(SettingCategory.MOVEMENT); + } + + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + int count = playerStandingCount.getOrDefault(player, 1); + int timeLeft = getValue() - count + 1; + + if (timeLeft <= RED) bossbar.setColor(BarColor.RED); + else if (timeLeft <= YELLOW) bossbar.setColor(BarColor.YELLOW); + else bossbar.setColor(BarColor.GREEN); + + String time = "§e" + timeLeft + " §7" + (timeLeft == 1 ? Message.forName("second").asString() : Message.forName("seconds").asString()); + + bossbar.setTitle(Message.forName("bossbar-dont-stop-running").asString(time)); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SADDLE, Message.forName("item-dont-stop-running-challenge")); + } + + @ScheduledTask(ticks = 20) + public void onSecond() { + removeOfflinePlayers(); + countUpOrKillEveryone(); + bossbar.update(); + } + + private void removeOfflinePlayers() { + for (Player player : new ArrayList<>(playerStandingCount.keySet())) { + if (!player.isOnline() || ignorePlayer(player)) playerStandingCount.remove(player); + } + } + + private void countUpOrKillEveryone() { + + broadcastFiltered(player -> { + Integer count = playerStandingCount.getOrDefault(player, 0); + if (count >= getValue()) { + Message.forName("stopped-moving").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + playerStandingCount.remove(player); + kill(player); + return; + } + playerStandingCount.put(player, count + 1); + + }); + + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + if (event.getFrom().getX() == event.getTo().getX() && event.getFrom().getZ() == event.getTo().getZ() && event.getFrom().getY() == event.getTo().getY()) + return; + playerStandingCount.remove(event.getPlayer()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java index 6376c38e7..68310cd3d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java @@ -37,155 +37,155 @@ @Since("2.1.0") public class FiveHundredBlocksChallenge extends SettingModifier { - private final Map blocksWalked = new HashMap<>(); - - public FiveHundredBlocksChallenge() { - super(MenuType.CHALLENGES, 1, 5, 5); - setCategory(SettingCategory.MOVEMENT); - - // Loot Generate Event was added in 1.15 - try { - Listener listener = new Listener() { - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onLootGenerate(LootGenerateEvent event) { - if (!shouldExecuteEffect()) - return; - event.setLoot(new LinkedList<>()); - } - }; - - Challenges.getInstance().registerListener(listener); - } catch (NoClassDefFoundError noClassDefFoundError) { - Challenges.getInstance().getLogger().warning("Loot Generation couldn't be blocked in FiveHundredBlocks Challenge: Please Use 1.15 or higher"); - } - - - } - - @Override - protected void onEnable() { - bossbar.setContent((bar, player) -> { - int walked = blocksWalked.getOrDefault(player.getUniqueId(), 0); - bar.setTitle(Message.forName("bossbar-five-hundred-blocks").asString(walked, getBlocksToWalk())); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(MinecraftNameWrapper.SIGN, Message.forName("item-five-hundred-blocks-challenges")); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-blocks").asString(getBlocksToWalk())); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-blocks-description").asArray(getBlocksToWalk()); - } - - private int getBlocksToWalk() { - return getValue() * 100; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - Player player = event.getPlayer(); - if (ignorePlayer(player)) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; - - if (updateOrReset(player)) { - InventoryUtils.giveItem(player.getInventory(), player.getLocation(), InventoryUtils.getRandomItem(false, false)); - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - event.setDropItems(false); - event.setExpToDrop(0); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityDeath(EntityDeathEvent event) { - if (!shouldExecuteEffect()) return; - event.getDrops().clear(); - event.setDroppedExp(0); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityExplosion(EntityExplodeEvent event) { - if (!shouldExecuteEffect()) return; - for (Block block : event.blockList()) { - block.setType(Material.AIR); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockExplosion(BlockExplodeEvent event) { - if (!shouldExecuteEffect()) return; - for (Block block : event.blockList()) { - block.setType(Material.AIR); - } - } - - /** - * @return if 500 blocks were reached - */ - private boolean updateOrReset(@Nonnull Player player) { - UUID uuid = player.getUniqueId(); - - int blocksWalked = this.blocksWalked.getOrDefault(uuid, 0); - - blocksWalked++; - - boolean reached = false; - if (blocksWalked >= getBlocksToWalk()) { - blocksWalked = 0; - reached = true; - } - - this.blocksWalked.put(uuid, blocksWalked); - - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { - bossbar.update(player); - }); - return reached; - } - - @Override - public void loadGameState(@NotNull Document document) { - blocksWalked.clear(); - for (String key : document.keys()) { - try { - UUID uuid = UUID.fromString(key); - int blocks = document.getInt(key); - blocksWalked.put(uuid, blocks); - } catch (IllegalArgumentException exception) { - plugin.getLogger().severe("Error while loading 500 Blocks Challenge, " - + "key '" + key + "' is not a valid uuid"); - Challenges.getInstance().getLogger().error("", exception); - } - } - } - - @Override - public void writeGameState(@NotNull Document document) { - blocksWalked.forEach((uuid, integer) -> { - document.set(uuid.toString(), integer); - }); - } + private final Map blocksWalked = new HashMap<>(); + + public FiveHundredBlocksChallenge() { + super(MenuType.CHALLENGES, 1, 5, 5); + setCategory(SettingCategory.MOVEMENT); + + // Loot Generate Event was added in 1.15 + try { + Listener listener = new Listener() { + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onLootGenerate(LootGenerateEvent event) { + if (!shouldExecuteEffect()) + return; + event.setLoot(new LinkedList<>()); + } + }; + + Challenges.getInstance().registerListener(listener); + } catch (NoClassDefFoundError noClassDefFoundError) { + Challenges.getInstance().getLogger().warning("Loot Generation couldn't be blocked in FiveHundredBlocks Challenge: Please Use 1.15 or higher"); + } + + + } + + @Override + protected void onEnable() { + bossbar.setContent((bar, player) -> { + int walked = blocksWalked.getOrDefault(player.getUniqueId(), 0); + bar.setTitle(Message.forName("bossbar-five-hundred-blocks").asString(walked, getBlocksToWalk())); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(MinecraftNameWrapper.SIGN, Message.forName("item-five-hundred-blocks-challenges")); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-blocks").asString(getBlocksToWalk())); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-blocks-description").asArray(getBlocksToWalk()); + } + + private int getBlocksToWalk() { + return getValue() * 100; + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + Player player = event.getPlayer(); + if (ignorePlayer(player)) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; + + if (updateOrReset(player)) { + InventoryUtils.giveItem(player.getInventory(), player.getLocation(), InventoryUtils.getRandomItem(false, false)); + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + event.setDropItems(false); + event.setExpToDrop(0); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityDeath(EntityDeathEvent event) { + if (!shouldExecuteEffect()) return; + event.getDrops().clear(); + event.setDroppedExp(0); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityExplosion(EntityExplodeEvent event) { + if (!shouldExecuteEffect()) return; + for (Block block : event.blockList()) { + block.setType(Material.AIR); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockExplosion(BlockExplodeEvent event) { + if (!shouldExecuteEffect()) return; + for (Block block : event.blockList()) { + block.setType(Material.AIR); + } + } + + /** + * @return if 500 blocks were reached + */ + private boolean updateOrReset(@Nonnull Player player) { + UUID uuid = player.getUniqueId(); + + int blocksWalked = this.blocksWalked.getOrDefault(uuid, 0); + + blocksWalked++; + + boolean reached = false; + if (blocksWalked >= getBlocksToWalk()) { + blocksWalked = 0; + reached = true; + } + + this.blocksWalked.put(uuid, blocksWalked); + + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + bossbar.update(player); + }); + return reached; + } + + @Override + public void loadGameState(@NotNull Document document) { + blocksWalked.clear(); + for (String key : document.keys()) { + try { + UUID uuid = UUID.fromString(key); + int blocks = document.getInt(key); + blocksWalked.put(uuid, blocks); + } catch (IllegalArgumentException exception) { + plugin.getLogger().severe("Error while loading 500 Blocks Challenge, " + + "key '" + key + "' is not a valid uuid"); + Challenges.getInstance().getLogger().error("", exception); + } + } + } + + @Override + public void writeGameState(@NotNull Document document) { + blocksWalked.forEach((uuid, integer) -> { + document.set(uuid.toString(), integer); + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java index 8e69d18e5..0047eacc9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java @@ -15,27 +15,27 @@ public class HigherJumpsChallenge extends Setting { - public HigherJumpsChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.MOVEMENT); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.RABBIT_FOOT, Message.forName("item-higher-jumps-challenge")); - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onJump(@Nonnull PlayerJumpEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - - int jumps = getPlayerData(event.getPlayer()).getInt("jumps") + 1; - getPlayerData(event.getPlayer()).set("jumps", jumps); - - float y = jumps / 7f; - event.getPlayer().setVelocity(new Vector().setY(y)); - } + public HigherJumpsChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.MOVEMENT); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.RABBIT_FOOT, Message.forName("item-higher-jumps-challenge")); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onJump(@Nonnull PlayerJumpEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + + int jumps = getPlayerData(event.getPlayer()).getInt("jumps") + 1; + getPlayerData(event.getPlayer()).set("jumps", jumps); + + float y = jumps / 7f; + event.getPlayer().setVelocity(new Vector().setY(y)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java index 65359282a..3e7c18af7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java @@ -17,24 +17,24 @@ @Since("2.0") public class HungerPerBlockChallenge extends SettingModifier { - public HungerPerBlockChallenge() { - super(MenuType.CHALLENGES, 1, 20, 2); - setCategory(SettingCategory.MOVEMENT); - } + public HungerPerBlockChallenge() { + super(MenuType.CHALLENGES, 1, 20, 2); + setCategory(SettingCategory.MOVEMENT); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ROTTEN_FLESH, Message.forName("item-hunger-block-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ROTTEN_FLESH, Message.forName("item-hunger-block-challenge")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; - int newFoodLevel = event.getPlayer().getFoodLevel() - getValue(); - event.getPlayer().setFoodLevel(Math.max(newFoodLevel, 0)); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; + int newFoodLevel = event.getPlayer().getFoodLevel() - getValue(); + event.getPlayer().setFoodLevel(Math.max(newFoodLevel, 0)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java index f31e51b72..a85e9bcc3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java @@ -26,59 +26,59 @@ @Since("2.0") public class MoveMouseDamage extends SettingModifier { - private final Map> lastView = new HashMap<>(); + private final Map> lastView = new HashMap<>(); - public MoveMouseDamage() { - super(MenuType.CHALLENGES, 60); - setCategory(SettingCategory.MOVEMENT); - } + public MoveMouseDamage() { + super(MenuType.CHALLENGES, 60); + setCategory(SettingCategory.MOVEMENT); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COMPASS, Message.forName("item-no-mouse-move-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.COMPASS, Message.forName("item-no-mouse-move-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); + } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() / 2); - } + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() / 2); + } - @ScheduledTask(ticks = 1, timerPolicy = TimerPolicy.ALWAYS) - public void onTick() { - if (!shouldExecuteEffect()) { - lastView.clear(); - return; - } + @ScheduledTask(ticks = 1, timerPolicy = TimerPolicy.ALWAYS) + public void onTick() { + if (!shouldExecuteEffect()) { + lastView.clear(); + return; + } - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) { - lastView.remove(player.getUniqueId()); - continue; - } - if (player.getNoDamageTicks() > 0) continue; + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) { + lastView.remove(player.getUniqueId()); + continue; + } + if (player.getNoDamageTicks() > 0) continue; - float yaw = player.getLocation().getYaw(); - float pitch = player.getLocation().getPitch(); - Entry pair = lastView.getOrDefault(player.getUniqueId(), new SimpleEntry<>(yaw, pitch)); - lastView.put(player.getUniqueId(), pair); + float yaw = player.getLocation().getYaw(); + float pitch = player.getLocation().getPitch(); + Entry pair = lastView.getOrDefault(player.getUniqueId(), new SimpleEntry<>(yaw, pitch)); + lastView.put(player.getUniqueId(), pair); - if (yaw != pair.getKey() || pitch != pair.getValue()) { - Bukkit.getScheduler().runTask(plugin, () -> { - if (player.getNoDamageTicks() > 0) return; - Message.forName("no-mouse-move-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); - player.damage(getValue()); - player.setNoDamageTicks(5); - Bukkit.getScheduler().runTaskLater(plugin, () -> lastView.remove(player.getUniqueId()), 3); - }); - } - } - } + if (yaw != pair.getKey() || pitch != pair.getValue()) { + Bukkit.getScheduler().runTask(plugin, () -> { + if (player.getNoDamageTicks() > 0) return; + Message.forName("no-mouse-move-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + player.damage(getValue()); + player.setNoDamageTicks(5); + Bukkit.getScheduler().runTaskLater(plugin, () -> lastView.remove(player.getUniqueId()), 3); + }); + } + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java index a642787b5..40caffe17 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java @@ -23,46 +23,46 @@ @CanInstaKillOnEnable public class OnlyDirtChallenge extends Setting { - public OnlyDirtChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.MOVEMENT); - } + public OnlyDirtChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.MOVEMENT); + } - @Nonnull - @Override - public ItemStack getSettingsItem() { - return super.getSettingsItem(); - } + @Nonnull + @Override + public ItemStack getSettingsItem() { + return super.getSettingsItem(); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIRT, Message.forName("item-only-dirt-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIRT, Message.forName("item-only-dirt-challenge")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; - Block blockBelow = BlockUtils.getBlockBelow(event.getTo()); - if (blockBelow == null) return; - if (blockBelow.getType() != Material.DIRT && !BukkitReflectionUtils.isAir(blockBelow.getType())) { - Message.forName("only-dirt-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - kill(event.getPlayer()); - } + Block blockBelow = BlockUtils.getBlockBelow(event.getTo()); + if (blockBelow == null) return; + if (blockBelow.getType() != Material.DIRT && !BukkitReflectionUtils.isAir(blockBelow.getType())) { + Message.forName("only-dirt-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + kill(event.getPlayer()); + } - } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockSpread(@Nonnull BlockSpreadEvent event) { - if (!shouldExecuteEffect()) return; + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockSpread(@Nonnull BlockSpreadEvent event) { + if (!shouldExecuteEffect()) return; - if (event.getNewState().getType() == Material.GRASS_BLOCK) { - event.setCancelled(true); - } + if (event.getNewState().getType() == Material.GRASS_BLOCK) { + event.setCancelled(true); + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java index 8cbe2613b..9d63f1bd2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java @@ -18,25 +18,25 @@ @Since("2.0") public class OnlyDownChallenge extends Setting { - public OnlyDownChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.MOVEMENT); - } + public OnlyDownChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.MOVEMENT); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ACACIA_SLAB, Message.forName("item-only-down-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ACACIA_SLAB, Message.forName("item-only-down-challenge")); + } - @EventHandler - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - if (event.getTo().getBlockY() <= event.getFrom().getBlockY()) return; - Message.forName("only-down-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - ChallengeHelper.kill(event.getPlayer()); - } + @EventHandler + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + if (event.getTo().getBlockY() <= event.getFrom().getBlockY()) return; + Message.forName("only-down-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + ChallengeHelper.kill(event.getPlayer()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java index 13a0dd130..cbbf640d3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java @@ -24,102 +24,102 @@ @Since("1.3") public class TrafficLightChallenge extends TimedChallenge { - private static final int GREEN = 0, YELLOW = 1, RED = 2; - - private int state; - - public TrafficLightChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5); - setCategory(SettingCategory.MOVEMENT); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.LIME_STAINED_GLASS, Message.forName("item-traffic-light-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 20, getValue() * 60 + 20); - } - - @Override - public void onEnable() { - bossbar.setContent((bossbar, player) -> { - switch (state) { - case GREEN: - bossbar.setColor(BarColor.GREEN); - bossbar.setTitle("§8{ §a§l■■■ §8} §8{ §7§l■■■ §8} §8{ §7§l■■■ §8}"); - break; - case YELLOW: - bossbar.setColor(BarColor.YELLOW); - bossbar.setTitle("§8{ §7§l■■■ §8} §8{ §e§l■■■ §8} §8{ §7§l■■■ §8}"); - break; - case RED: - bossbar.setColor(BarColor.RED); - bossbar.setTitle("§8{ §7§l■■■ §8} §8{ §7§l■■■ §8} §8{ §c§l■■■ §8}"); - break; - } - }); - bossbar.show(); - } - - @Override - public void onDisable() { - bossbar.hide(); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 20); - } - - @Override - protected void onTimeActivation() { - switch (state) { - case GREEN: - state = YELLOW; - restartTimer(2); - SoundSample.BASS_OFF.broadcast(); - bossbar.update(); - break; - case YELLOW: - state = RED; - restartTimer(3); - SoundSample.BASS_OFF.broadcast(); - bossbar.update(); - break; - case RED: - state = GREEN; - restartTimer(); - SoundSample.BASS_ON.broadcast(); - bossbar.update(); - break; - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (state != RED) return; - if (event.getTo() == null) return; - if (BlockUtils.isSameLocation(event.getFrom(), event.getTo())) return; - - state = GREEN; - bossbar.update(); - restartTimer(); - - Player player = event.getPlayer(); - Message.forName("traffic-light-challenge-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); - kill(player); - } + private static final int GREEN = 0, YELLOW = 1, RED = 2; + + private int state; + + public TrafficLightChallenge() { + super(MenuType.CHALLENGES, 1, 10, 5); + setCategory(SettingCategory.MOVEMENT); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.LIME_STAINED_GLASS, Message.forName("item-traffic-light-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 20, getValue() * 60 + 20); + } + + @Override + public void onEnable() { + bossbar.setContent((bossbar, player) -> { + switch (state) { + case GREEN: + bossbar.setColor(BarColor.GREEN); + bossbar.setTitle("§8{ §a§l■■■ §8} §8{ §7§l■■■ §8} §8{ §7§l■■■ §8}"); + break; + case YELLOW: + bossbar.setColor(BarColor.YELLOW); + bossbar.setTitle("§8{ §7§l■■■ §8} §8{ §e§l■■■ §8} §8{ §7§l■■■ §8}"); + break; + case RED: + bossbar.setColor(BarColor.RED); + bossbar.setTitle("§8{ §7§l■■■ §8} §8{ §7§l■■■ §8} §8{ §c§l■■■ §8}"); + break; + } + }); + bossbar.show(); + } + + @Override + public void onDisable() { + bossbar.hide(); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 20); + } + + @Override + protected void onTimeActivation() { + switch (state) { + case GREEN: + state = YELLOW; + restartTimer(2); + SoundSample.BASS_OFF.broadcast(); + bossbar.update(); + break; + case YELLOW: + state = RED; + restartTimer(3); + SoundSample.BASS_OFF.broadcast(); + bossbar.update(); + break; + case RED: + state = GREEN; + restartTimer(); + SoundSample.BASS_ON.broadcast(); + bossbar.update(); + break; + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (state != RED) return; + if (event.getTo() == null) return; + if (BlockUtils.isSameLocation(event.getFrom(), event.getTo())) return; + + state = GREEN; + bossbar.update(); + restartTimer(); + + Player player = event.getPlayer(); + Message.forName("traffic-light-challenge-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + kill(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index f49b6e2af..e540ea849 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -46,527 +46,533 @@ public class QuizChallenge extends TimedChallenge implements PlayerCommand, TabCompleter { - private static QuizChallenge instance; - - private final Prefix prefix = Prefix.forName("quiz", "§6Quiz"); - private final IRandom random = IRandom.create(); - - private IQuestion currentQuestion; - private Player currentQuestionedPlayer; - private int timeLeft; - - public QuizChallenge() { - super(MenuType.CHALLENGES, 1, 20, 5); - instance = this; - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BARRIER); - } - - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - if (currentQuestion == null) { - bossbar.setColor(BarColor.YELLOW); - bossbar.setTitle(Message.forName("bossbar-quiz-waiting").asString()); - return; - } - String time = "§e" + timeLeft + " §7" + (timeLeft == 1 ? Message.forName("second").asString() : Message.forName("seconds").asString()); - if (currentQuestionedPlayer != player) { - bossbar.setColor(BarColor.GREEN); - bossbar.setTitle(Message.forName("bossbar-quiz-question-other").asString(time, NameHelper.getName(currentQuestionedPlayer))); - return; - } - bossbar.setColor(BarColor.RED); - bossbar.setTitle(Message.forName("bossbar-quiz-question").asString(time)); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60 * 3, 60); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 * 3 - 60, getValue() * 60 * 3 + 60); - } - - @Override - protected int getSecondsUntilNextActivation() { - return random.around(getValue() * 60 * 3, 60); - } - - private void broadcastMessage(@Nonnull String questionedPlayerMessage, @Nonnull String othersMessage, Object... args) { - broadcast(player1 -> { - if (currentQuestionedPlayer == player1) { - Message.forName(questionedPlayerMessage).send(player1, prefix, args); - } else { - Message.forName(othersMessage).send(player1, prefix, NameHelper.getName(currentQuestionedPlayer)); - } - }); - } - - @Override - protected void onTimeActivation() { - - SavedStatistic[] statistics = SavedStatistic.values(); - SavedStatistic statistic = statistics[random.nextInt(statistics.length)]; - - IQuestion[] questions = statistic.getQuestions(); - currentQuestion = questions[random.nextInt(questions.length)]; - - List ingamePlayers = ChallengeHelper.getIngamePlayers(); - currentQuestionedPlayer = ingamePlayers.get(random.nextInt(ingamePlayers.size())); - - List answers = currentQuestion.createAnswers(statistic, currentQuestionedPlayer); - if (answers.isEmpty()) { - onTimeActivation(); - return; - } - Message.forName("quiz-how-to").send(currentQuestionedPlayer, Prefix.CHALLENGES); - timeLeft = 60; - - bossbar.update(); - } - - @ScheduledTask(ticks = 20, async = false) - public void onSecond() { - if (currentQuestion == null) return; - if (!currentQuestionedPlayer.isOnline() || ignorePlayer(currentQuestionedPlayer)) { - Message.forName("quiz-cancel").broadcast(prefix); - cancelQuestion(); - } - - timeLeft--; - - if (timeLeft <= 0) { - Message.forName("quiz-time-up").broadcast(prefix); - cancelQuestion(); - } - - bossbar.update(); - } - - private void cancelQuestion() { - restartTimer(); - - List rightAnswers = currentQuestion.getRightAnswers(); - Message.forName("quiz-right-answer-was" + (rightAnswers.size() != 1 ? "-multiple" : "")).send(currentQuestionedPlayer, prefix, StringUtils.getArrayAsString(rightAnswers.toArray(new String[0]), "§7, §e")); - SoundSample.BREAK.play(currentQuestionedPlayer); - - currentQuestion = null; - AttributeInstance attribute = currentQuestionedPlayer.getAttribute(AttributeWrapper.MAX_HEALTH); - if (attribute == null) return; - if (attribute.getBaseValue() == 2) { - kill(currentQuestionedPlayer); - attribute.setBaseValue(20); - return; - } - - attribute.setBaseValue(attribute.getBaseValue() - 2); - } - - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - - if (currentQuestion == null || currentQuestionedPlayer != player) { - // TODO: REMOVE RESTART TIMER HERE - restartTimer(3); - SoundSample.BASS_OFF.play(player); - return; - } - - if (args.length == 0) { - Message.forName("syntax").send(player, prefix, "guess "); - return; - } - - String answer = StringUtils.getArrayAsString(args, " "); - if (!currentQuestion.isRightAnswer(answer)) { - broadcastMessage("quiz-wrong-answer", "quiz-wrong-answer-other", answer); - cancelQuestion(); - bossbar.update(); - return; - } - - broadcastMessage("quiz-right-answer", "quiz-right-answer-other", answer); - SoundSample.LEVEL_UP.play(player); - currentQuestion = null; - bossbar.update(); - restartTimer(); - } - - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String s, @Nonnull String[] strings) { - return new ArrayList<>(); - } - - interface IQuestion { - - List createAnswers(@Nonnull SavedStatistic statistic, @Nonnull Player player); - List getRightAnswers(); - boolean isRightAnswer(@Nonnull String answer); - - static void sendMessage(@Nonnull String question, @Nonnull List answers) { - Player player = instance.currentQuestionedPlayer; - - player.sendMessage(" "); - player.sendMessage("§e" + question); - player.sendMessage(" "); - - for (String answer : answers) { - player.sendMessage("§8-> §e" + answer); - } - - player.sendMessage(" "); - } - - class Question implements IQuestion { - - private final TriFunction, List> questionCreator; - private List currentRightAnswers; - - public Question(TriFunction, List> questionCreator) { - this.questionCreator = questionCreator; - } - - @Override - public List createAnswers(@Nonnull SavedStatistic statistic, @Nonnull Player player) { - ArrayList answers = new ArrayList<>(); - currentRightAnswers = questionCreator.apply(statistic, player, answers); - return answers; - } - - @Override - public boolean isRightAnswer(@Nonnull String answer) { - if (currentRightAnswers == null) return false; - - for (String currentRightAnswer : currentRightAnswers) { - if (currentRightAnswer.equalsIgnoreCase(answer)) { - return true; - } - } - return false; - } - - @Override - public List getRightAnswers() { - return currentRightAnswers; - } - - } - - } - - private interface SavedStatistic { - - IntegerStatistic BLOCKS_MOVED = new IntegerStatistic("blocks-traveled", "traveled", "far", "be"); - IntegerStatistic JUMPED = new IntegerStatistic("jumped", "jumped", "often", "be"); - IntegerStatistic SNEAKED = new IntegerStatistic("sneaked", "sneaked", "often", "be"); - DocumentCountStatistic MOB_KILLED = new DocumentCountStatistic("mob-killed", "killed", "often", "have"); - DocumentCountStatistic MOB_DAMAGED = new DocumentCountStatistic("mobs-damaged", "damaged", "damage", "have"); - DocumentCountStatistic BLOCKS_PLACED = new DocumentCountStatistic("blocks-placed", "placed", "often", "have"); - DocumentCountStatistic BLOCKS_DESTROYED = new DocumentCountStatistic("blocks-destroyed", "broken", "often", "have"); - DocumentCountStatistic ITEMS_DROPPED = new DocumentCountStatistic("items-dropped", "dropped", "often", "have"); - DocumentCountStatistic DAMAGE_TAKEN = new DocumentCountStatistic("damage-taken", "suffered", "damage-taken", "have"); - - String getKey(); - String getVerb(); - String getQuestionVerb(); - String getQuestionSuffix(); - IQuestion[] getQuestions(); - - static SavedStatistic[] values() { - return new SavedStatistic[] { BLOCKS_MOVED, JUMPED, SNEAKED, MOB_DAMAGED, MOB_KILLED, BLOCKS_PLACED, BLOCKS_DESTROYED, ITEMS_DROPPED, DAMAGE_TAKEN }; - } + private static QuizChallenge instance; + + private final Prefix prefix = Prefix.forName("quiz", "§6Quiz"); + private final IRandom random = IRandom.create(); + + private IQuestion currentQuestion; + private Player currentQuestionedPlayer; + private int timeLeft; + + public QuizChallenge() { + super(MenuType.CHALLENGES, 1, 20, 5); + instance = this; + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BARRIER); + } + + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + if (currentQuestion == null) { + bossbar.setColor(BarColor.YELLOW); + bossbar.setTitle(Message.forName("bossbar-quiz-waiting").asString()); + return; + } + String time = "§e" + timeLeft + " §7" + (timeLeft == 1 ? Message.forName("second").asString() : Message.forName("seconds").asString()); + if (currentQuestionedPlayer != player) { + bossbar.setColor(BarColor.GREEN); + bossbar.setTitle(Message.forName("bossbar-quiz-question-other").asString(time, NameHelper.getName(currentQuestionedPlayer))); + return; + } + bossbar.setColor(BarColor.RED); + bossbar.setTitle(Message.forName("bossbar-quiz-question").asString(time)); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return ChallengeHelper.getTimeRangeSettingsDescription(this, 60 * 3, 60); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 * 3 - 60, getValue() * 60 * 3 + 60); + } + + @Override + protected int getSecondsUntilNextActivation() { + return random.around(getValue() * 60 * 3, 60); + } + + private void broadcastMessage(@Nonnull String questionedPlayerMessage, @Nonnull String othersMessage, Object... args) { + broadcast(player1 -> { + if (currentQuestionedPlayer == player1) { + Message.forName(questionedPlayerMessage).send(player1, prefix, args); + } else { + Message.forName(othersMessage).send(player1, prefix, NameHelper.getName(currentQuestionedPlayer)); + } + }); + } + + @Override + protected void onTimeActivation() { + + SavedStatistic[] statistics = SavedStatistic.values(); + SavedStatistic statistic = statistics[random.nextInt(statistics.length)]; + + IQuestion[] questions = statistic.getQuestions(); + currentQuestion = questions[random.nextInt(questions.length)]; + + List ingamePlayers = ChallengeHelper.getIngamePlayers(); + currentQuestionedPlayer = ingamePlayers.get(random.nextInt(ingamePlayers.size())); + + List answers = currentQuestion.createAnswers(statistic, currentQuestionedPlayer); + if (answers.isEmpty()) { + onTimeActivation(); + return; + } + Message.forName("quiz-how-to").send(currentQuestionedPlayer, Prefix.CHALLENGES); + timeLeft = 60; + + bossbar.update(); + } + + @ScheduledTask(ticks = 20, async = false) + public void onSecond() { + if (currentQuestion == null) return; + if (!currentQuestionedPlayer.isOnline() || ignorePlayer(currentQuestionedPlayer)) { + Message.forName("quiz-cancel").broadcast(prefix); + cancelQuestion(); + } + + timeLeft--; + + if (timeLeft <= 0) { + Message.forName("quiz-time-up").broadcast(prefix); + cancelQuestion(); + } + + bossbar.update(); + } + + private void cancelQuestion() { + restartTimer(); + + List rightAnswers = currentQuestion.getRightAnswers(); + Message.forName("quiz-right-answer-was" + (rightAnswers.size() != 1 ? "-multiple" : "")).send(currentQuestionedPlayer, prefix, StringUtils.getArrayAsString(rightAnswers.toArray(new String[0]), "§7, §e")); + SoundSample.BREAK.play(currentQuestionedPlayer); + + currentQuestion = null; + AttributeInstance attribute = currentQuestionedPlayer.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return; + if (attribute.getBaseValue() == 2) { + kill(currentQuestionedPlayer); + attribute.setBaseValue(20); + return; + } + + attribute.setBaseValue(attribute.getBaseValue() - 2); + } + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + + if (currentQuestion == null || currentQuestionedPlayer != player) { + // TODO: REMOVE RESTART TIMER HERE + restartTimer(3); + SoundSample.BASS_OFF.play(player); + return; + } + + if (args.length == 0) { + Message.forName("syntax").send(player, prefix, "guess "); + return; + } + + String answer = StringUtils.getArrayAsString(args, " "); + if (!currentQuestion.isRightAnswer(answer)) { + broadcastMessage("quiz-wrong-answer", "quiz-wrong-answer-other", answer); + cancelQuestion(); + bossbar.update(); + return; + } + + broadcastMessage("quiz-right-answer", "quiz-right-answer-other", answer); + SoundSample.LEVEL_UP.play(player); + currentQuestion = null; + bossbar.update(); + restartTimer(); + } - default Message getVerbMessage() { - return Message.forName("quiz-verb-" + getVerb()); - } + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String s, @Nonnull String[] strings) { + return new ArrayList<>(); + } - class IntegerStatistic implements SavedStatistic { + interface IQuestion { - private final static Question INTEGER_QUESTION = new Question((statistic, player, answers) -> { - IntegerStatistic integerStatistic = (IntegerStatistic) statistic; - int rightAnswer = integerStatistic.getStatistic(player); + List createAnswers(@Nonnull SavedStatistic statistic, @Nonnull Player player); - for (int i = rightAnswer; i < rightAnswer + 4; i++) { - answers.add(i + ""); - } + List getRightAnswers(); - IQuestion.sendMessage(Message.forName("quiz-question-" + statistic.getQuestionSuffix() + "-" + statistic.getQuestionVerb()).asString(statistic.getVerbMessage(), ""), answers); + boolean isRightAnswer(@Nonnull String answer); - return Collections.singletonList(rightAnswer + ""); - }); + static void sendMessage(@Nonnull String question, @Nonnull List answers) { + Player player = instance.currentQuestionedPlayer; - private final String key; - private final String questionVerb; - private final String questionSuffix; - private final String verb; - - public IntegerStatistic(String key, String verbMessage, String questionSuffix, String questionVerb) { - this.key = key; - this.verb = verbMessage; - this.questionSuffix = questionSuffix; - this.questionVerb = questionVerb; - } - - @Override - public String getKey() { - return key; - } + player.sendMessage(" "); + player.sendMessage("§e" + question); + player.sendMessage(" "); + + for (String answer : answers) { + player.sendMessage("§8-> §e" + answer); + } + + player.sendMessage(" "); + } - @Override - public String getVerb() { - return verb; - } + class Question implements IQuestion { - @Override - public String getQuestionVerb() { - return questionVerb; - } + private final TriFunction, List> questionCreator; + private List currentRightAnswers; - @Override - public String getQuestionSuffix() { - return questionSuffix; - } - - @Override - public IQuestion[] getQuestions() { - return new Question[] { INTEGER_QUESTION }; - } + public Question(TriFunction, List> questionCreator) { + this.questionCreator = questionCreator; + } - public void increaseStatistic(@Nonnull Player player) { - increaseStatistic(player, 1); - } + @Override + public List createAnswers(@Nonnull SavedStatistic statistic, @Nonnull Player player) { + ArrayList answers = new ArrayList<>(); + currentRightAnswers = questionCreator.apply(statistic, player, answers); + return answers; + } - public void increaseStatistic(@Nonnull Player player, int amount) { - instance.getPlayerData(player).set(key, getStatistic(player) + amount); - } + @Override + public boolean isRightAnswer(@Nonnull String answer) { + if (currentRightAnswers == null) return false; - public int getStatistic(@Nonnull Player player) { - return instance.getPlayerData(player).getInt(key); - } + for (String currentRightAnswer : currentRightAnswers) { + if (currentRightAnswer.equalsIgnoreCase(answer)) { + return true; + } + } + return false; + } + + @Override + public List getRightAnswers() { + return currentRightAnswers; + } - } + } - abstract class DocumentStatistic implements SavedStatistic { + } - private final String key; + private interface SavedStatistic { - public DocumentStatistic(String key) { - this.key = key; - } + IntegerStatistic BLOCKS_MOVED = new IntegerStatistic("blocks-traveled", "traveled", "far", "be"); + IntegerStatistic JUMPED = new IntegerStatistic("jumped", "jumped", "often", "be"); + IntegerStatistic SNEAKED = new IntegerStatistic("sneaked", "sneaked", "often", "be"); + DocumentCountStatistic MOB_KILLED = new DocumentCountStatistic("mob-killed", "killed", "often", "have"); + DocumentCountStatistic MOB_DAMAGED = new DocumentCountStatistic("mobs-damaged", "damaged", "damage", "have"); + DocumentCountStatistic BLOCKS_PLACED = new DocumentCountStatistic("blocks-placed", "placed", "often", "have"); + DocumentCountStatistic BLOCKS_DESTROYED = new DocumentCountStatistic("blocks-destroyed", "broken", "often", "have"); + DocumentCountStatistic ITEMS_DROPPED = new DocumentCountStatistic("items-dropped", "dropped", "often", "have"); + DocumentCountStatistic DAMAGE_TAKEN = new DocumentCountStatistic("damage-taken", "suffered", "damage-taken", "have"); - @Override - public String getKey() { - return key; - } + String getKey(); - public Document getDocument(@Nonnull Player player) { - return instance.getPlayerData(player).getDocument(key); - } + String getVerb(); - } + String getQuestionVerb(); - class DocumentCountStatistic extends DocumentStatistic { + String getQuestionSuffix(); - private final static Question CHOOSE_QUESTION = new Question((statistic, player, answers) -> { - DocumentCountStatistic documentCountStatistic = (DocumentCountStatistic) statistic; - Document document = documentCountStatistic.getDocument(player); + IQuestion[] getQuestions(); - Map entries = new HashMap<>(); + static SavedStatistic[] values() { + return new SavedStatistic[]{BLOCKS_MOVED, JUMPED, SNEAKED, MOB_DAMAGED, MOB_KILLED, BLOCKS_PLACED, BLOCKS_DESTROYED, ITEMS_DROPPED, DAMAGE_TAKEN}; + } - ArrayList keysLeft = new ArrayList<>(document.keys()); + default Message getVerbMessage() { + return Message.forName("quiz-verb-" + getVerb()); + } - if (keysLeft.isEmpty() || keysLeft.size() == 1) return null; + class IntegerStatistic implements SavedStatistic { - Collections.shuffle(keysLeft); - for (byte i = 0; i < 4; i++) { - if (keysLeft.isEmpty()) break; - String key = keysLeft.remove(0); - entries.put(key, documentCountStatistic.getStatistic(player, key)); - } + private final static Question INTEGER_QUESTION = new Question((statistic, player, answers) -> { + IntegerStatistic integerStatistic = (IntegerStatistic) statistic; + int rightAnswer = integerStatistic.getStatistic(player); - answers.addAll(entries.keySet()); + for (int i = rightAnswer; i < rightAnswer + 4; i++) { + answers.add(i + ""); + } - double highestValue = -1; - List highestEntries = new ArrayList<>(); + IQuestion.sendMessage(Message.forName("quiz-question-" + statistic.getQuestionSuffix() + "-" + statistic.getQuestionVerb()).asString(statistic.getVerbMessage(), ""), answers); - for (Entry entry : entries.entrySet()) { - if (highestValue == -1) { - highestEntries.add(entry.getKey()); - highestValue = entry.getValue(); - } else if (highestValue == entry.getValue()) { - highestEntries.add(entry.getKey()); - } else if (highestValue < entry.getValue()) { - highestEntries.clear(); - highestEntries.add(entry.getKey()); - highestValue = entry.getValue(); - } - } - - List newAnswers = answers.stream().map(StringUtils::getEnumName).collect(Collectors.toList()); - answers.clear(); - answers.addAll(newAnswers); + return Collections.singletonList(rightAnswer + ""); + }); - IQuestion.sendMessage(Message.forName("quiz-question-most").asString(statistic.getVerbMessage(), answers.size()), answers); + private final String key; + private final String questionVerb; + private final String questionSuffix; + private final String verb; - highestEntries = highestEntries.stream().map(StringUtils::getEnumName).collect(Collectors.toList()); + public IntegerStatistic(String key, String verbMessage, String questionSuffix, String questionVerb) { + this.key = key; + this.verb = verbMessage; + this.questionSuffix = questionSuffix; + this.questionVerb = questionVerb; + } - return highestEntries; - }), - COUNT_QUESTIONS = new Question((statistic, player, answers) -> { - DocumentCountStatistic documentCountStatistic = (DocumentCountStatistic) statistic; - Document document = documentCountStatistic.getDocument(player); + @Override + public String getKey() { + return key; + } - ArrayList keys = new ArrayList<>(document.keys()); + @Override + public String getVerb() { + return verb; + } - if (keys.isEmpty()) { - return null; - } + @Override + public String getQuestionVerb() { + return questionVerb; + } - String key = keys.get(instance.random.nextInt(keys.size())); - int rightAnswer = (int) documentCountStatistic.getStatistic(player, key); + @Override + public String getQuestionSuffix() { + return questionSuffix; + } - for (int i = rightAnswer; i < rightAnswer + 4; i++) { - answers.add(i + ""); - } + @Override + public IQuestion[] getQuestions() { + return new Question[]{INTEGER_QUESTION}; + } - IQuestion.sendMessage(Message.forName("quiz-question-" + statistic.getQuestionSuffix() + "-" + statistic.getQuestionVerb()).asString(StringUtils.getEnumName(key), " " + statistic.getVerbMessage().asString()), answers); + public void increaseStatistic(@Nonnull Player player) { + increaseStatistic(player, 1); + } - return new ArrayList<>(Collections.singleton(rightAnswer + "")); - }); + public void increaseStatistic(@Nonnull Player player, int amount) { + instance.getPlayerData(player).set(key, getStatistic(player) + amount); + } - private final String verb; - private final String questionSuffix; - private final String questionVerb; + public int getStatistic(@Nonnull Player player) { + return instance.getPlayerData(player).getInt(key); + } - public DocumentCountStatistic(String key, String verbMessage, String questionSuffix, String questionVerb) { - super(key); - this.verb = verbMessage; - this.questionSuffix = questionSuffix; - this.questionVerb = questionVerb; - } - - public void increaseStatistic(@Nonnull Player player, @Nonnull String key) { - increaseStatistic(player, key, 1); - } - - public void increaseStatistic(@Nonnull Player player, @Nonnull String key, double amount) { - getDocument(player).set(key, getStatistic(player, key) + amount); - } - - public double getStatistic(@Nonnull Player player, @Nonnull String key) { - return getDocument(player).getDouble(key); - } - - @Override - public String getVerb() { - return verb; - } - - @Override - public String getQuestionVerb() { - return questionVerb; - } - - @Override - public String getQuestionSuffix() { - return questionSuffix; - } - - @Override - public IQuestion[] getQuestions() { - return new IQuestion[] { CHOOSE_QUESTION, COUNT_QUESTIONS }; - } - - } - - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onJump(@Nonnull PlayerJumpEvent event) { - if (!shouldExecuteEffect()) return; - if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; - SavedStatistic.JUMPED.increaseStatistic(event.getPlayer()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onJump(@Nonnull PlayerToggleSneakEvent event) { - if (!shouldExecuteEffect()) return; - if (!event.isSneaking()) return; - if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; - SavedStatistic.SNEAKED.increaseStatistic(event.getPlayer()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onEntityKill(@Nonnull EntityDamageByEntityEvent event) { - if (!shouldExecuteEffect()) return; - - if (!(event.getDamager() instanceof Player)) return; - Player player = (Player) event.getDamager(); - if (ignorePlayer(player)) return; - - if (!(event.getEntity() instanceof LivingEntity)) return; - - SavedStatistic.MOB_DAMAGED.increaseStatistic(player, event.getEntity().getType().name(), ChallengeHelper.getFinalDamage(event)); - - LivingEntity entity = (LivingEntity) event.getEntity(); - if (entity.getHealth() - ChallengeHelper.getFinalDamage(event) > 0) return; - - SavedStatistic.MOB_KILLED.increaseStatistic(player, event.getEntity().getType().name()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - SavedStatistic.BLOCKS_PLACED.increaseStatistic(event.getPlayer(), event.getBlockPlaced().getType().name()); - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (BukkitReflectionUtils.isAir(event.getBlock().getType())) return; - SavedStatistic.BLOCKS_DESTROYED.increaseStatistic(event.getPlayer(), event.getBlock().getType().name()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - if (BlockUtils.isSameBlockIgnoreHeight(event.getFrom(), event.getTo())) return; - SavedStatistic.BLOCKS_MOVED.increaseStatistic(event.getPlayer()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(@Nonnull PlayerDropItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - SavedStatistic.ITEMS_DROPPED.increaseStatistic(event.getPlayer(), event.getItemDrop().getItemStack().getType().name()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(@Nonnull EntityDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - SavedStatistic.DAMAGE_TAKEN.increaseStatistic(player, event.getCause().name(), ChallengeHelper.getFinalDamage(event)); - } + } + + abstract class DocumentStatistic implements SavedStatistic { + + private final String key; + + public DocumentStatistic(String key) { + this.key = key; + } + + @Override + public String getKey() { + return key; + } + + public Document getDocument(@Nonnull Player player) { + return instance.getPlayerData(player).getDocument(key); + } + + } + + class DocumentCountStatistic extends DocumentStatistic { + + private final static Question CHOOSE_QUESTION = new Question((statistic, player, answers) -> { + DocumentCountStatistic documentCountStatistic = (DocumentCountStatistic) statistic; + Document document = documentCountStatistic.getDocument(player); + + Map entries = new HashMap<>(); + + ArrayList keysLeft = new ArrayList<>(document.keys()); + + if (keysLeft.isEmpty() || keysLeft.size() == 1) return null; + + Collections.shuffle(keysLeft); + for (byte i = 0; i < 4; i++) { + if (keysLeft.isEmpty()) break; + String key = keysLeft.remove(0); + entries.put(key, documentCountStatistic.getStatistic(player, key)); + } + + answers.addAll(entries.keySet()); + + double highestValue = -1; + List highestEntries = new ArrayList<>(); + + for (Entry entry : entries.entrySet()) { + if (highestValue == -1) { + highestEntries.add(entry.getKey()); + highestValue = entry.getValue(); + } else if (highestValue == entry.getValue()) { + highestEntries.add(entry.getKey()); + } else if (highestValue < entry.getValue()) { + highestEntries.clear(); + highestEntries.add(entry.getKey()); + highestValue = entry.getValue(); + } + } + + List newAnswers = answers.stream().map(StringUtils::getEnumName).collect(Collectors.toList()); + answers.clear(); + answers.addAll(newAnswers); + + IQuestion.sendMessage(Message.forName("quiz-question-most").asString(statistic.getVerbMessage(), answers.size()), answers); + + highestEntries = highestEntries.stream().map(StringUtils::getEnumName).collect(Collectors.toList()); + + return highestEntries; + }), + COUNT_QUESTIONS = new Question((statistic, player, answers) -> { + DocumentCountStatistic documentCountStatistic = (DocumentCountStatistic) statistic; + Document document = documentCountStatistic.getDocument(player); + + ArrayList keys = new ArrayList<>(document.keys()); + + if (keys.isEmpty()) { + return null; + } + + String key = keys.get(instance.random.nextInt(keys.size())); + int rightAnswer = (int) documentCountStatistic.getStatistic(player, key); + + for (int i = rightAnswer; i < rightAnswer + 4; i++) { + answers.add(i + ""); + } + + IQuestion.sendMessage(Message.forName("quiz-question-" + statistic.getQuestionSuffix() + "-" + statistic.getQuestionVerb()).asString(StringUtils.getEnumName(key), " " + statistic.getVerbMessage().asString()), answers); + + return new ArrayList<>(Collections.singleton(rightAnswer + "")); + }); + + private final String verb; + private final String questionSuffix; + private final String questionVerb; + + public DocumentCountStatistic(String key, String verbMessage, String questionSuffix, String questionVerb) { + super(key); + this.verb = verbMessage; + this.questionSuffix = questionSuffix; + this.questionVerb = questionVerb; + } + + public void increaseStatistic(@Nonnull Player player, @Nonnull String key) { + increaseStatistic(player, key, 1); + } + + public void increaseStatistic(@Nonnull Player player, @Nonnull String key, double amount) { + getDocument(player).set(key, getStatistic(player, key) + amount); + } + + public double getStatistic(@Nonnull Player player, @Nonnull String key) { + return getDocument(player).getDouble(key); + } + + @Override + public String getVerb() { + return verb; + } + + @Override + public String getQuestionVerb() { + return questionVerb; + } + + @Override + public String getQuestionSuffix() { + return questionSuffix; + } + + @Override + public IQuestion[] getQuestions() { + return new IQuestion[]{CHOOSE_QUESTION, COUNT_QUESTIONS}; + } + + } + + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onJump(@Nonnull PlayerJumpEvent event) { + if (!shouldExecuteEffect()) return; + if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; + SavedStatistic.JUMPED.increaseStatistic(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onJump(@Nonnull PlayerToggleSneakEvent event) { + if (!shouldExecuteEffect()) return; + if (!event.isSneaking()) return; + if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; + SavedStatistic.SNEAKED.increaseStatistic(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onEntityKill(@Nonnull EntityDamageByEntityEvent event) { + if (!shouldExecuteEffect()) return; + + if (!(event.getDamager() instanceof Player)) return; + Player player = (Player) event.getDamager(); + if (ignorePlayer(player)) return; + + if (!(event.getEntity() instanceof LivingEntity)) return; + + SavedStatistic.MOB_DAMAGED.increaseStatistic(player, event.getEntity().getType().name(), ChallengeHelper.getFinalDamage(event)); + + LivingEntity entity = (LivingEntity) event.getEntity(); + if (entity.getHealth() - ChallengeHelper.getFinalDamage(event) > 0) return; + + SavedStatistic.MOB_KILLED.increaseStatistic(player, event.getEntity().getType().name()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + SavedStatistic.BLOCKS_PLACED.increaseStatistic(event.getPlayer(), event.getBlockPlaced().getType().name()); + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (BukkitReflectionUtils.isAir(event.getBlock().getType())) return; + SavedStatistic.BLOCKS_DESTROYED.increaseStatistic(event.getPlayer(), event.getBlock().getType().name()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + if (BlockUtils.isSameBlockIgnoreHeight(event.getFrom(), event.getTo())) return; + SavedStatistic.BLOCKS_MOVED.increaseStatistic(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(@Nonnull PlayerDropItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + SavedStatistic.ITEMS_DROPPED.increaseStatistic(event.getPlayer(), event.getItemDrop().getItemStack().getType().name()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(@Nonnull EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + SavedStatistic.DAMAGE_TAKEN.increaseStatistic(player, event.getCause().name(), ChallengeHelper.getFinalDamage(event)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java index 1bdde937a..7dabca933 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java @@ -1,9 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import javax.annotation.Nonnull; import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; @@ -16,47 +12,52 @@ import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import org.bukkit.Material; +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + public class BlockRandomizerChallenge extends RandomizerSetting { - public BlockRandomizerChallenge() { - super(MenuType.CHALLENGES); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MINECART, Message.forName("item-block-randomizer-challenge")); - } - - @Override - protected void reloadRandomization() { - BlockDropManager manager = Challenges.getInstance().getBlockDropManager(); - - List blocks = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - blocks.removeIf(material -> !ItemUtils.isObtainableInSurvival(material) || !material.isBlock() || BukkitReflectionUtils.isAir(material)); - random.shuffle(blocks); - - List drops = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - drops.removeIf(material -> !material.isItem() || !ItemUtils.isObtainableInSurvival(material)); - random.shuffle(drops); - - while (!blocks.isEmpty()) { - Material block = blocks.remove(0); - List items = new ArrayList<>(); - - int addDrops = getMatches(blocks.size(), drops.size()); - for (int i = 0; i < addDrops && !drops.isEmpty(); i++) { - items.add(drops.remove(0)); - } - manager.setCustomDrops(block, items, DropPriority.RANDOMIZER); - } - - } - - @Override - protected void onDisable() { - BlockDropManager manager = Challenges.getInstance().getBlockDropManager(); - manager.resetCustomDrops(DropPriority.RANDOMIZER); - } + public BlockRandomizerChallenge() { + super(MenuType.CHALLENGES); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.MINECART, Message.forName("item-block-randomizer-challenge")); + } + + @Override + protected void reloadRandomization() { + BlockDropManager manager = Challenges.getInstance().getBlockDropManager(); + + List blocks = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + blocks.removeIf(material -> !ItemUtils.isObtainableInSurvival(material) || !material.isBlock() || BukkitReflectionUtils.isAir(material)); + random.shuffle(blocks); + + List drops = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + drops.removeIf(material -> !material.isItem() || !ItemUtils.isObtainableInSurvival(material)); + random.shuffle(drops); + + while (!blocks.isEmpty()) { + Material block = blocks.remove(0); + List items = new ArrayList<>(); + + int addDrops = getMatches(blocks.size(), drops.size()); + for (int i = 0; i < addDrops && !drops.isEmpty(); i++) { + items.add(drops.remove(0)); + } + manager.setCustomDrops(block, items, DropPriority.RANDOMIZER); + } + + } + + @Override + protected void onDisable() { + BlockDropManager manager = Challenges.getInstance().getBlockDropManager(); + manager.resetCustomDrops(DropPriority.RANDOMIZER); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java index 829be3904..a4ea3360c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; @@ -17,51 +17,51 @@ public class CraftingRandomizerChallenge extends RandomizerSetting { - protected final Map randomization = new HashMap<>(); + protected final Map randomization = new HashMap<>(); - public CraftingRandomizerChallenge() { - super(MenuType.CHALLENGES); - } + public CraftingRandomizerChallenge() { + super(MenuType.CHALLENGES); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CHEST_MINECART, Message.forName("item-crafting-randomizer-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CHEST_MINECART, Message.forName("item-crafting-randomizer-challenge")); + } - @Override - protected void reloadRandomization() { + @Override + protected void reloadRandomization() { - List from = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - from.removeIf(material -> !material.isItem() || !ItemUtils.isObtainableInSurvival(material)); - random.shuffle(from); + List from = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + from.removeIf(material -> !material.isItem() || !ItemUtils.isObtainableInSurvival(material)); + random.shuffle(from); - List to = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - to.removeIf(material -> !material.isItem() || !ItemUtils.isObtainableInSurvival(material)); - random.shuffle(to); + List to = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + to.removeIf(material -> !material.isItem() || !ItemUtils.isObtainableInSurvival(material)); + random.shuffle(to); - while (!from.isEmpty()) { - Material item = from.remove(0); - Material result = to.remove(0); + while (!from.isEmpty()) { + Material item = from.remove(0); + Material result = to.remove(0); - randomization.put(item, result); - } + randomization.put(item, result); + } - } + } - @Override - protected void onDisable() { - randomization.clear(); - } + @Override + protected void onDisable() { + randomization.clear(); + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onCraftItem(@Nonnull CraftItemEvent event) { - if (!isEnabled()) return; - ItemStack item = event.getCurrentItem(); - if (item == null) return; - Material result = randomization.get(item.getType()); - if (result == null) return; - event.setCurrentItem(new ItemBuilder(result).amount(item.getAmount()).build()); - } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onCraftItem(@Nonnull CraftItemEvent event) { + if (!isEnabled()) return; + ItemStack item = event.getCurrentItem(); + if (item == null) return; + Material result = randomization.get(item.getType()); + if (result == null) return; + event.setCurrentItem(new ItemBuilder(result).amount(item.getAmount()).build()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java index 888998e35..a0b258204 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java @@ -33,151 +33,151 @@ @Since("2.2.0") public class EntityLootRandomizerChallenge extends RandomizerSetting implements SenderCommand, Completer { - protected Map randomization; - - public EntityLootRandomizerChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.RANDOMIZER); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FURNACE_MINECART, Message.forName("item-entity-loot-randomizer-challenge")); - } - - @Override - protected void reloadRandomization() { - randomization = new HashMap<>(); - - List from = new ArrayList<>(Arrays.asList(EntityType.values())); - from.removeIf(entityType -> !getLootableEntities().contains(entityType)); - random.shuffle(from); - from.removeIf(Objects::isNull); - - List entityTypesToRemove = new ArrayList<>(); - List to = from.stream().map(entityType -> { - if (entityType == null) return null; - try { - return LootTables.valueOf(entityType.name()).getLootTable(); - } catch (IllegalArgumentException exception) { - entityTypesToRemove.add(entityType); - return null; - } - }).filter(Objects::nonNull).collect(Collectors.toList()); - from.removeAll(entityTypesToRemove); - random.shuffle(to); - - while (!from.isEmpty()) { - EntityType entityType = from.remove(0); - LootTable lootTable = to.remove(0); - - randomization.put(entityType, lootTable); - } - } - - public List getLootableEntities() { - return new ListBuilder<>(EntityType.values()) - .removeIf(type -> !type.isSpawnable()) - .removeIf(type -> !type.isAlive()) - .remove(EntityType.ENDER_DRAGON) - .remove(EntityType.GIANT) - .remove(EntityType.ILLUSIONER) - .remove(EntityType.ZOMBIE_HORSE) - .build(); - } - - @Override - protected void onDisable() { - randomization.clear(); - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityDeath(EntityDeathEvent event) { - if (!isEnabled()) return; - LivingEntity entity = event.getEntity(); - if (!getLootableEntities().contains(entity.getType())) return; - event.getDrops().clear(); - if (!randomization.containsKey(entity.getType())) return; - - LootTable lootTable = randomization.get(entity.getType()); - LootContext.Builder builder = new LootContext.Builder(entity.getLocation()) - .lootedEntity(entity); - - if (entity.getKiller() == null) { - builder.lootingModifier(0); - } else { - builder.killer(entity.getKiller()); - } - - Collection newDrops = lootTable.populateLoot(random.asRandom(), builder.build()); - event.getDrops().addAll(newDrops); - } - - public LootTable getLootTableForEntity(EntityType entityType) { - return randomization.get(entityType); - } - - public Optional getEntityForLootTable(LootTable lootTable) { - return randomization.entrySet().stream() - .filter(entry -> entry.getValue().equals(lootTable)) - .map(Map.Entry::getKey) - .findFirst(); - } - - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - - if (!isEnabled()) { - Message.forName("command-searchloot-disabled").send(sender, Prefix.CHALLENGES); - return; - } - - if (args.length == 0) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "searchloot "); - return; - } - - String input = String.join("_", args).toUpperCase(); - EntityType entityType = Utils.getEntityType(input); - - if (entityType == null) { - Message.forName("no-such-entity").send(sender, Prefix.CHALLENGES); - return; - } - if (!entityType.isAlive()) { - Message.forName("not-alive").send(sender, Prefix.CHALLENGES, entityType); - return; - } - - LootTable givenLootTable; - try { - givenLootTable = LootTables.valueOf(entityType.name()).getLootTable(); - } catch (IllegalArgumentException exception) { - Message.forName("no-loot").send(sender, Prefix.CHALLENGES, entityType); - return; - } - - Optional optionalEntity = getEntityForLootTable(givenLootTable); - LootTable droppedLootTable = getLootTableForEntity(entityType); - - if (optionalEntity.isPresent()) { - Message.forName("command-searchloot-result").send(sender, Prefix.CHALLENGES, entityType, droppedLootTable, optionalEntity.get()); - } else { - Message.forName("command-searchloot-nothing").send(sender, Prefix.CHALLENGES, entityType); - } - - } - - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - EntityLootRandomizerChallenge instance = AbstractChallenge.getFirstInstance(EntityLootRandomizerChallenge.class); - return args.length != 1 ? null : - instance.getLootableEntities().stream() - .map(material -> material.name().toLowerCase()) - .collect(Collectors.toList() - ); - } + protected Map randomization; + + public EntityLootRandomizerChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.RANDOMIZER); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FURNACE_MINECART, Message.forName("item-entity-loot-randomizer-challenge")); + } + + @Override + protected void reloadRandomization() { + randomization = new HashMap<>(); + + List from = new ArrayList<>(Arrays.asList(EntityType.values())); + from.removeIf(entityType -> !getLootableEntities().contains(entityType)); + random.shuffle(from); + from.removeIf(Objects::isNull); + + List entityTypesToRemove = new ArrayList<>(); + List to = from.stream().map(entityType -> { + if (entityType == null) return null; + try { + return LootTables.valueOf(entityType.name()).getLootTable(); + } catch (IllegalArgumentException exception) { + entityTypesToRemove.add(entityType); + return null; + } + }).filter(Objects::nonNull).collect(Collectors.toList()); + from.removeAll(entityTypesToRemove); + random.shuffle(to); + + while (!from.isEmpty()) { + EntityType entityType = from.remove(0); + LootTable lootTable = to.remove(0); + + randomization.put(entityType, lootTable); + } + } + + public List getLootableEntities() { + return new ListBuilder<>(EntityType.values()) + .removeIf(type -> !type.isSpawnable()) + .removeIf(type -> !type.isAlive()) + .remove(EntityType.ENDER_DRAGON) + .remove(EntityType.GIANT) + .remove(EntityType.ILLUSIONER) + .remove(EntityType.ZOMBIE_HORSE) + .build(); + } + + @Override + protected void onDisable() { + randomization.clear(); + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityDeath(EntityDeathEvent event) { + if (!isEnabled()) return; + LivingEntity entity = event.getEntity(); + if (!getLootableEntities().contains(entity.getType())) return; + event.getDrops().clear(); + if (!randomization.containsKey(entity.getType())) return; + + LootTable lootTable = randomization.get(entity.getType()); + LootContext.Builder builder = new LootContext.Builder(entity.getLocation()) + .lootedEntity(entity); + + if (entity.getKiller() == null) { + builder.lootingModifier(0); + } else { + builder.killer(entity.getKiller()); + } + + Collection newDrops = lootTable.populateLoot(random.asRandom(), builder.build()); + event.getDrops().addAll(newDrops); + } + + public LootTable getLootTableForEntity(EntityType entityType) { + return randomization.get(entityType); + } + + public Optional getEntityForLootTable(LootTable lootTable) { + return randomization.entrySet().stream() + .filter(entry -> entry.getValue().equals(lootTable)) + .map(Map.Entry::getKey) + .findFirst(); + } + + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + + if (!isEnabled()) { + Message.forName("command-searchloot-disabled").send(sender, Prefix.CHALLENGES); + return; + } + + if (args.length == 0) { + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "searchloot "); + return; + } + + String input = String.join("_", args).toUpperCase(); + EntityType entityType = Utils.getEntityType(input); + + if (entityType == null) { + Message.forName("no-such-entity").send(sender, Prefix.CHALLENGES); + return; + } + if (!entityType.isAlive()) { + Message.forName("not-alive").send(sender, Prefix.CHALLENGES, entityType); + return; + } + + LootTable givenLootTable; + try { + givenLootTable = LootTables.valueOf(entityType.name()).getLootTable(); + } catch (IllegalArgumentException exception) { + Message.forName("no-loot").send(sender, Prefix.CHALLENGES, entityType); + return; + } + + Optional optionalEntity = getEntityForLootTable(givenLootTable); + LootTable droppedLootTable = getLootTableForEntity(entityType); + + if (optionalEntity.isPresent()) { + Message.forName("command-searchloot-result").send(sender, Prefix.CHALLENGES, entityType, droppedLootTable, optionalEntity.get()); + } else { + Message.forName("command-searchloot-nothing").send(sender, Prefix.CHALLENGES, entityType); + } + + } + + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + EntityLootRandomizerChallenge instance = AbstractChallenge.getFirstInstance(EntityLootRandomizerChallenge.class); + return args.length != 1 ? null : + instance.getLootableEntities().stream() + .map(material -> material.name().toLowerCase()) + .collect(Collectors.toList() + ); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 5def17398..004217c96 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -33,121 +33,121 @@ @Since("2.1.2") public class HotBarRandomizerChallenge extends TimedChallenge { - public HotBarRandomizerChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5); - setCategory(SettingCategory.RANDOMIZER); - } - - /** - * @param force if true only sets items if inventory is empty - */ - public static void addItems(Player player, boolean force) { - - if (!force && !player.getInventory().isEmpty()) { - return; - } - - player.getInventory().clear(); - for (int i = 0; i < 9; i++) { - player.getInventory().setItem(i, InventoryUtils.getRandomItem(false, true)); - } - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.HOPPER_MINECART, Message.forName("item-hotbar-randomizer-challenge")); - } - - @Override - protected int getSecondsUntilNextActivation() { - return getValue() * 60; - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-minutes-description").asArray(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeMinutesValueChangeTitle(this, getValue()); - } - - @Override - protected void onTimeActivation() { - - broadcastFiltered(player -> { - addItems(player, true); - }); - restartTimer(); - } - - @TimerTask(status = TimerStatus.RUNNING) - public void onStart() { - // Execute after hotbar items are removed - Bukkit.getScheduler().runTask(plugin, () -> { - broadcastFiltered(player -> { - addItems(player, false); - }); - - }); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onJoin(PlayerJoinEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - addItems(event.getPlayer(), false); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBreak(BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - event.setDropItems(false); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - Player player = event.getPlayer(); - if (!shouldExecuteEffect()) return; - if (ignorePlayer(player)) return; - Inventory clickedInventory = event.getClickedInventory(); - if (event.getCursor() == null) return; - if (clickedInventory == null) return; - InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); - if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; - if (clickedInventory.getType() == InventoryType.CRAFTING) return; - if (clickedInventory.getType() == InventoryType.PLAYER) { - if (event.getInventory().getType() != InventoryType.PLAYER) { - event.setCancelled(true); - } - } - - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { - if (!shouldExecuteEffect()) return; - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityExplosion(EntityExplodeEvent event) { - if (!shouldExecuteEffect()) return; - for (Block block : event.blockList()) { - block.setType(Material.AIR); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockExplosion(BlockExplodeEvent event) { - if (!shouldExecuteEffect()) return; - for (Block block : event.blockList()) { - block.setType(Material.AIR); - } - } + public HotBarRandomizerChallenge() { + super(MenuType.CHALLENGES, 1, 10, 5); + setCategory(SettingCategory.RANDOMIZER); + } + + /** + * @param force if true only sets items if inventory is empty + */ + public static void addItems(Player player, boolean force) { + + if (!force && !player.getInventory().isEmpty()) { + return; + } + + player.getInventory().clear(); + for (int i = 0; i < 9; i++) { + player.getInventory().setItem(i, InventoryUtils.getRandomItem(false, true)); + } + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.HOPPER_MINECART, Message.forName("item-hotbar-randomizer-challenge")); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue() * 60; + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-minutes-description").asArray(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeMinutesValueChangeTitle(this, getValue()); + } + + @Override + protected void onTimeActivation() { + + broadcastFiltered(player -> { + addItems(player, true); + }); + restartTimer(); + } + + @TimerTask(status = TimerStatus.RUNNING) + public void onStart() { + // Execute after hotbar items are removed + Bukkit.getScheduler().runTask(plugin, () -> { + broadcastFiltered(player -> { + addItems(player, false); + }); + + }); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJoin(PlayerJoinEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + addItems(event.getPlayer(), false); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBreak(BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + event.setDropItems(false); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + Player player = event.getPlayer(); + if (!shouldExecuteEffect()) return; + if (ignorePlayer(player)) return; + Inventory clickedInventory = event.getClickedInventory(); + if (event.getCursor() == null) return; + if (clickedInventory == null) return; + InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); + if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; + if (clickedInventory.getType() == InventoryType.CRAFTING) return; + if (clickedInventory.getType() == InventoryType.PLAYER) { + if (event.getInventory().getType() != InventoryType.PLAYER) { + event.setCancelled(true); + } + } + + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { + if (!shouldExecuteEffect()) return; + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityExplosion(EntityExplodeEvent event) { + if (!shouldExecuteEffect()) return; + for (Block block : event.blockList()) { + block.setType(Material.AIR); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockExplosion(BlockExplodeEvent event) { + if (!shouldExecuteEffect()) return; + for (Block block : event.blockList()) { + block.setType(Material.AIR); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java index e08dcbe0c..d454c4c65 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java @@ -1,10 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.annotation.Nonnull; import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; import net.anweisen.utilities.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; @@ -21,208 +16,207 @@ import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; -import org.bukkit.entity.Animals; -import org.bukkit.entity.Drowned; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Guardian; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Monster; -import org.bukkit.entity.SpawnCategory; -import org.bukkit.entity.WaterMob; +import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntitySpawnEvent; +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @Since("2.0") public class MobRandomizerChallenge extends RandomizerSetting { - private final Map entityRandomizer = new HashMap<>(); - private final Map inverseRandomizer = new HashMap<>(); - - private boolean inSpawn = false; - private boolean initialSpawn = false; - - public MobRandomizerChallenge() { - super(MenuType.CHALLENGES); - } - - @Override - protected void onEnable() { - super.onEnable(); - if (!shouldExecuteEffect()) return; - initialSpawn = true; - loadAllEntities(); - initialSpawn = false; - } - - @Override - protected void onDisable() { - super.onDisable(); - unLoadAllEntities(); - } - - @TimerTask(status = TimerStatus.PAUSED, async = false) - public void onPause() { - unLoadAllEntities(); - } - - private void loadAllEntities() { - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - if (!entityRandomizer.containsKey(entity.getType())) return; - entity.remove(); - entity.getWorld().spawnEntity(entity.getLocation(), entityRandomizer.get(entity.getType())); - }); - } - - } - } - - private void unLoadAllEntities() { - inSpawn = true; - - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - if (!inverseRandomizer.containsKey(entity.getType())) continue; - entity.remove(); - EntityType entityType = inverseRandomizer.get(entity.getType()); - entity.getWorld().spawnEntity(entity.getLocation(), entityType); - - } - - } - - inSpawn = false; - } - - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COMMAND_BLOCK_MINECART, Message.forName("item-mob-randomizer-challenge")); - } - - @Override - protected void reloadRandomization() { - List entityTypes = getSpawnAbleEntities(); - List randomEntityTypes = new ArrayList<>(entityTypes); - random.shuffle(randomEntityTypes); - - for (int i = 0; i < entityTypes.size(); i++) { - EntityType type = entityTypes.get(i); - EntityType randomType = randomEntityTypes.get(i); - entityRandomizer.put(type, randomType); - inverseRandomizer.put(randomType, type); - } - - } - - public List getSpawnAbleEntities() { - ListBuilder builder = new ListBuilder<>(ExperimentalUtils.getEntityTypes()) - .removeIf(type -> !type.isSpawnable()) - .removeIf(type -> !type.isAlive()) - .remove(EntityType.ENDER_DRAGON) - .remove(EntityType.WITHER) - .remove(EntityType.GIANT) - .remove(EntityType.ILLUSIONER); - - return builder.build(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntitySpawn(@Nonnull EntitySpawnEvent event) { - if (!shouldExecuteEffect()) return; - if (!entityRandomizer.containsKey(event.getEntityType())) return; - if (inSpawn) return; - - event.setCancelled(true); - - EntityType type = entityRandomizer.get(event.getEntityType()); - Location location = event.getLocation(); - if (location.getWorld() == null) return; - if (!initialSpawn && !maySpawn(type, location.getWorld())) return; - inSpawn = true; - event.getEntity().getWorld().spawnEntity(location, type); - inSpawn = false; - } - - private boolean maySpawn(@Nonnull EntityType newType, @Nonnull World world) { - EntityCategory category = getEntityCategory(newType); - int currentMobCount = getCurrentMobCount(category, world); - int spawnLimit = getEntityCategory(newType).getSpawnLimit(world); - return currentMobCount < spawnLimit; - } - - private int getCurrentMobCount(@Nonnull EntityCategory entityState, @Nonnull World world) { - - int mobCount = 0; - - for (Entity entity : world.getLivingEntities()) { - if (!(entity instanceof LivingEntity)) continue; - EntityCategory entityTypeState = getEntityCategory(entity.getType()); - if (entityState == entityTypeState) { - mobCount++; - } - - } - - return mobCount; - } - - private EntityCategory getEntityCategory(@Nonnull EntityType type) { - Class entity = type.getEntityClass(); - if (entity == null) return EntityCategory.OTHER; - - if (Animals.class.isAssignableFrom(entity)) { - return EntityCategory.ANIMAL; - } - if (Drowned.class.isAssignableFrom(entity) || Guardian.class.isAssignableFrom(entity)) { - return EntityCategory.WATER_AMBIENT; - } - if (Monster.class.isAssignableFrom(entity)) { - return EntityCategory.HOSTILE; - } - if (WaterMob.class.isAssignableFrom(entity)) { - return EntityCategory.WATER_ANIMAL; - } - - return EntityCategory.AMBIENT; - } - - public enum EntityCategory { - - HOSTILE, - AMBIENT, - ANIMAL, - WATER_ANIMAL, - WATER_AMBIENT, - OTHER; - - private int getSpawnLimit(@Nonnull World world) { - boolean useSpawnCategories = MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_19); // World#getSpawnLimit was added in 1.19 - switch (this) { - case AMBIENT: - return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.AMBIENT) : world.getAmbientSpawnLimit(); - case HOSTILE: - return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.MONSTER) : world.getMonsterSpawnLimit(); - case ANIMAL: - return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.ANIMAL) : world.getAnimalSpawnLimit(); - case WATER_AMBIENT: { // getWaterAmbientSpawnLimit is not available in lower versions like 1.13, default to water animal then - try { - return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.WATER_AMBIENT) : world.getWaterAmbientSpawnLimit(); - } catch (Throwable throwable) { - Challenges.getInstance().getLogger().error("", throwable); - } - } - case WATER_ANIMAL: - return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.WATER_ANIMAL) : world.getWaterAnimalSpawnLimit(); - default: - return 0; - } - } - - } + private final Map entityRandomizer = new HashMap<>(); + private final Map inverseRandomizer = new HashMap<>(); + + private boolean inSpawn = false; + private boolean initialSpawn = false; + + public MobRandomizerChallenge() { + super(MenuType.CHALLENGES); + } + + @Override + protected void onEnable() { + super.onEnable(); + if (!shouldExecuteEffect()) return; + initialSpawn = true; + loadAllEntities(); + initialSpawn = false; + } + + @Override + protected void onDisable() { + super.onDisable(); + unLoadAllEntities(); + } + + @TimerTask(status = TimerStatus.PAUSED, async = false) + public void onPause() { + unLoadAllEntities(); + } + + private void loadAllEntities() { + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + if (!entityRandomizer.containsKey(entity.getType())) return; + entity.remove(); + entity.getWorld().spawnEntity(entity.getLocation(), entityRandomizer.get(entity.getType())); + }); + } + + } + } + + private void unLoadAllEntities() { + inSpawn = true; + + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + if (!inverseRandomizer.containsKey(entity.getType())) continue; + entity.remove(); + EntityType entityType = inverseRandomizer.get(entity.getType()); + entity.getWorld().spawnEntity(entity.getLocation(), entityType); + + } + + } + + inSpawn = false; + } + + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.COMMAND_BLOCK_MINECART, Message.forName("item-mob-randomizer-challenge")); + } + + @Override + protected void reloadRandomization() { + List entityTypes = getSpawnAbleEntities(); + List randomEntityTypes = new ArrayList<>(entityTypes); + random.shuffle(randomEntityTypes); + + for (int i = 0; i < entityTypes.size(); i++) { + EntityType type = entityTypes.get(i); + EntityType randomType = randomEntityTypes.get(i); + entityRandomizer.put(type, randomType); + inverseRandomizer.put(randomType, type); + } + + } + + public List getSpawnAbleEntities() { + ListBuilder builder = new ListBuilder<>(ExperimentalUtils.getEntityTypes()) + .removeIf(type -> !type.isSpawnable()) + .removeIf(type -> !type.isAlive()) + .remove(EntityType.ENDER_DRAGON) + .remove(EntityType.WITHER) + .remove(EntityType.GIANT) + .remove(EntityType.ILLUSIONER); + + return builder.build(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntitySpawn(@Nonnull EntitySpawnEvent event) { + if (!shouldExecuteEffect()) return; + if (!entityRandomizer.containsKey(event.getEntityType())) return; + if (inSpawn) return; + + event.setCancelled(true); + + EntityType type = entityRandomizer.get(event.getEntityType()); + Location location = event.getLocation(); + if (location.getWorld() == null) return; + if (!initialSpawn && !maySpawn(type, location.getWorld())) return; + inSpawn = true; + event.getEntity().getWorld().spawnEntity(location, type); + inSpawn = false; + } + + private boolean maySpawn(@Nonnull EntityType newType, @Nonnull World world) { + EntityCategory category = getEntityCategory(newType); + int currentMobCount = getCurrentMobCount(category, world); + int spawnLimit = getEntityCategory(newType).getSpawnLimit(world); + return currentMobCount < spawnLimit; + } + + private int getCurrentMobCount(@Nonnull EntityCategory entityState, @Nonnull World world) { + + int mobCount = 0; + + for (Entity entity : world.getLivingEntities()) { + if (!(entity instanceof LivingEntity)) continue; + EntityCategory entityTypeState = getEntityCategory(entity.getType()); + if (entityState == entityTypeState) { + mobCount++; + } + + } + + return mobCount; + } + + private EntityCategory getEntityCategory(@Nonnull EntityType type) { + Class entity = type.getEntityClass(); + if (entity == null) return EntityCategory.OTHER; + + if (Animals.class.isAssignableFrom(entity)) { + return EntityCategory.ANIMAL; + } + if (Drowned.class.isAssignableFrom(entity) || Guardian.class.isAssignableFrom(entity)) { + return EntityCategory.WATER_AMBIENT; + } + if (Monster.class.isAssignableFrom(entity)) { + return EntityCategory.HOSTILE; + } + if (WaterMob.class.isAssignableFrom(entity)) { + return EntityCategory.WATER_ANIMAL; + } + + return EntityCategory.AMBIENT; + } + + public enum EntityCategory { + + HOSTILE, + AMBIENT, + ANIMAL, + WATER_ANIMAL, + WATER_AMBIENT, + OTHER; + + private int getSpawnLimit(@Nonnull World world) { + boolean useSpawnCategories = MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_19); // World#getSpawnLimit was added in 1.19 + switch (this) { + case AMBIENT: + return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.AMBIENT) : world.getAmbientSpawnLimit(); + case HOSTILE: + return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.MONSTER) : world.getMonsterSpawnLimit(); + case ANIMAL: + return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.ANIMAL) : world.getAnimalSpawnLimit(); + case + WATER_AMBIENT: { // getWaterAmbientSpawnLimit is not available in lower versions like 1.13, default to water animal then + try { + return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.WATER_AMBIENT) : world.getWaterAmbientSpawnLimit(); + } catch (Throwable throwable) { + Challenges.getInstance().getLogger().error("", throwable); + } + } + case WATER_ANIMAL: + return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.WATER_ANIMAL) : world.getWaterAnimalSpawnLimit(); + default: + return 0; + } + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java index e1904812f..c5c5e477e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java @@ -23,108 +23,108 @@ @Since("2.0") public class RandomChallengeChallenge extends TimedChallenge { - private AbstractChallenge lastUsed; - - public RandomChallengeChallenge() { - super(MenuType.CHALLENGES, 3, 60, 6, false); - setCategory(SettingCategory.RANDOMIZER); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.REDSTONE, Message.forName("item-random-challenge-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 10); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 10); - } - - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - if (lastUsed == null) { - bossbar.setTitle(Message.forName("bossbar-random-challenge-waiting").asString()); - return; - } - bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-random-challenge-current").asString(ChallengeHelper.getColoredChallengeName(lastUsed))); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - if (lastUsed != null) { - setEnabled(lastUsed, false); - lastUsed = null; - } - bossbar.hide(); - } - - @Override - protected int getSecondsUntilNextActivation() { - return getValue() * 10; - } - - @Override - protected void handleCountdown() { - bossbar.update(); - } - - @Override - protected void onTimeActivation() { - restartTimer(); - - if (lastUsed != null) { - setEnabled(lastUsed, false); - lastUsed = null; - } - - List challenges = new ArrayList<>(Challenges.getInstance().getChallengeManager().getChallenges()); - challenges.remove(this); - challenges.removeIf(challenge -> challenge.getType() != MenuType.CHALLENGES); - challenges.removeIf(challenge -> !(challenge instanceof AbstractChallenge)); - challenges.removeIf(ChallengeHelper::canInstaKillOnEnable); - challenges.removeIf(ChallengeHelper::isExcludedFromRandomChallenges); - challenges.removeIf(IChallenge::isEnabled); - if (challenges.isEmpty()) return; - - AbstractChallenge challenge = (AbstractChallenge) globalRandom.choose(challenges); - String name = ChallengeHelper.getColoredChallengeName(challenge); - Message.forName("random-challenge-enabled").broadcast(Prefix.CHALLENGES, name); - - setEnabled(challenge, true); - lastUsed = challenge; - bossbar.update(); - - } - - private void setEnabled(@Nonnull IChallenge challenge, boolean enabled) { - if (challenge instanceof Setting) { - Setting setting = (Setting) challenge; - setting.setEnabled(enabled); - } - if (challenge instanceof SettingModifier) { - SettingModifier setting = (SettingModifier) challenge; - setting.setEnabled(enabled); - } - - if (enabled && challenge instanceof TimedChallenge) { - TimedChallenge timedChallenge = (TimedChallenge) challenge; - if (timedChallenge.isTimerRunning()) { - int seconds = globalRandom.range(10, 20); - if (seconds < timedChallenge.getSecondsLeftUntilNextActivation()) - timedChallenge.shortCountDownTo(seconds); - } - } - } + private AbstractChallenge lastUsed; + + public RandomChallengeChallenge() { + super(MenuType.CHALLENGES, 3, 60, 6, false); + setCategory(SettingCategory.RANDOMIZER); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.REDSTONE, Message.forName("item-random-challenge-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue() * 10); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 10); + } + + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + if (lastUsed == null) { + bossbar.setTitle(Message.forName("bossbar-random-challenge-waiting").asString()); + return; + } + bossbar.setProgress(getProgress()); + bossbar.setTitle(Message.forName("bossbar-random-challenge-current").asString(ChallengeHelper.getColoredChallengeName(lastUsed))); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + if (lastUsed != null) { + setEnabled(lastUsed, false); + lastUsed = null; + } + bossbar.hide(); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue() * 10; + } + + @Override + protected void handleCountdown() { + bossbar.update(); + } + + @Override + protected void onTimeActivation() { + restartTimer(); + + if (lastUsed != null) { + setEnabled(lastUsed, false); + lastUsed = null; + } + + List challenges = new ArrayList<>(Challenges.getInstance().getChallengeManager().getChallenges()); + challenges.remove(this); + challenges.removeIf(challenge -> challenge.getType() != MenuType.CHALLENGES); + challenges.removeIf(challenge -> !(challenge instanceof AbstractChallenge)); + challenges.removeIf(ChallengeHelper::canInstaKillOnEnable); + challenges.removeIf(ChallengeHelper::isExcludedFromRandomChallenges); + challenges.removeIf(IChallenge::isEnabled); + if (challenges.isEmpty()) return; + + AbstractChallenge challenge = (AbstractChallenge) globalRandom.choose(challenges); + String name = ChallengeHelper.getColoredChallengeName(challenge); + Message.forName("random-challenge-enabled").broadcast(Prefix.CHALLENGES, name); + + setEnabled(challenge, true); + lastUsed = challenge; + bossbar.update(); + + } + + private void setEnabled(@Nonnull IChallenge challenge, boolean enabled) { + if (challenge instanceof Setting) { + Setting setting = (Setting) challenge; + setting.setEnabled(enabled); + } + if (challenge instanceof SettingModifier) { + SettingModifier setting = (SettingModifier) challenge; + setting.setEnabled(enabled); + } + + if (enabled && challenge instanceof TimedChallenge) { + TimedChallenge timedChallenge = (TimedChallenge) challenge; + if (timedChallenge.isTimerRunning()) { + int seconds = globalRandom.range(10, 20); + if (seconds < timedChallenge.getSecondsLeftUntilNextActivation()) + timedChallenge.shortCountDownTo(seconds); + } + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java index d39094ba3..e876a7287 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java @@ -27,209 +27,209 @@ @Since("2.0") public class RandomEventChallenge extends TimedChallenge { - private final Event[] events; - - public RandomEventChallenge() { - super(MenuType.CHALLENGES, 1, 10, 3, false); - setCategory(SettingCategory.RANDOMIZER); - events = new Event[]{ - new SpeedEvent(), - new SpawnEntitiesEvent(), - new HoleEvent(), - new FlyEvent(), - new CobWebEvent(), - new ReplaceOresEvent(), - new SicknessEvent() - }; - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CLOCK, Message.forName("item-random-event-challenge").asItemDescription(events.length)); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); - } - - @Override - protected int getSecondsUntilNextActivation() { - return globalRandom.around(getValue() * 60, 30); - } - - @Override - protected void onTimeActivation() { - restartTimer(); - Event event = globalRandom.choose(events); - Logger.debug("Running random event {}", event.getClass().getSimpleName()); - event.getActivationMessage().broadcastRandom(globalRandom, Prefix.CHALLENGES); - broadcastFiltered(event::run); - } - - public interface Event { - - @Nonnull - Message getActivationMessage(); - - void run(@Nonnull Player player); - - } - - public static class SpeedEvent implements Event { - - @Nonnull - @Override - public Message getActivationMessage() { - return Message.forName("random-event-speed"); - } - - @Override - public void run(@Nonnull Player player) { - player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 10 * 20, 99)); - } - - } - - public static class HoleEvent implements Event { - - @Nonnull - @Override - public Message getActivationMessage() { - return Message.forName("random-event-hole"); - } - - @Override - public void run(@Nonnull Player player) { - Location location = player.getLocation().getBlock().getLocation(); - for (int x = -1; x <= 1; x++) { - for (int z = -1; z <= 1; z++) { - for (int y = 1; y >= -8; y--) { - location.clone().add(x, y, z).getBlock().setType(Material.AIR, true); - } - } - } - } - - } - - public static class FlyEvent implements Event { - - @Nonnull - @Override - public Message getActivationMessage() { - return Message.forName("random-event-fly"); - } - - @Override - public void run(@Nonnull Player player) { - player.addPotionEffect(new PotionEffect(PotionEffectType.LEVITATION, 3 * 20, 5)); - } - - } - - public static class ReplaceOresEvent implements Event { - - @Nonnull - @Override - public Message getActivationMessage() { - return Message.forName("random-event-ores"); - } - - @Override - public void run(@Nonnull Player player) { - Location location = player.getLocation(); - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { - for (int x = -100; x <= 100; x++) { - for (int z = -100; z <= 100; z++) { - int finalZ = z; - int finalX = x; - Bukkit.getScheduler().runTask(plugin, () -> { - if (location.getWorld() == null) return; - for (int y = BukkitReflectionUtils.getMinHeight(location.getWorld()); y < 80; y++) { - Location current = location.clone().add(finalX, 0, finalZ); - current.setY(y); - Block block = current.getBlock(); - if (block.getType().name().contains("ORE")) { - Environment environment = location.getWorld().getEnvironment(); - block.setType(environment == Environment.NETHER ? Material.NETHERRACK : environment == Environment.THE_END ? Material.END_STONE : Material.STONE, true); - } - } - }); - } - } - }); - } - - } - - public static class SicknessEvent implements Event { - - @Nonnull - @Override - public Message getActivationMessage() { - return Message.forName("random-event-sickness"); - } - - @Override - public void run(@Nonnull Player player) { - player.addPotionEffect(new PotionEffect(MinecraftNameWrapper.NAUSEA, 7 * 20, 0)); - player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 3 * 20, 1)); - player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 5 * 20, 1)); - } - } - - public static class SpawnEntitiesEvent implements Event { - - @Nonnull - @Override - public Message getActivationMessage() { - return Message.forName("random-event-entities"); - } - - @Override - public void run(@Nonnull Player player) { - EntityType type = globalRandom.choose(EntityType.PIG, EntityType.CHICKEN, EntityType.CAT, EntityType.SILVERFISH, EntityType.WOLF); - - for (int i = 0; i < globalRandom.nextInt(5) + 5; i++) { - Location randomLocation = player.getLocation().add(globalRandom.nextInt(10) - 5, -10, globalRandom.nextInt(10 - 5)); - if (randomLocation.getWorld() == null) return; - while (!randomLocation.getBlock().isPassable() && randomLocation.getBlockY() < randomLocation.getWorld().getMaxHeight()) - randomLocation.add(0, 1, 0); - - randomLocation.getWorld().spawnEntity(randomLocation, type); - } - } - - } - - public static class CobWebEvent implements Event { - - @Nonnull - @Override - public Message getActivationMessage() { - return Message.forName("random-event-webs"); - } - - @Override - public void run(@Nonnull Player player) { - for (int i = 0; i < 13; i++) { - Location randomLocation = player.getLocation().add(globalRandom.nextInt(10) - 5, -20, globalRandom.nextInt(10 - 5)); - if (randomLocation.getWorld() == null) return; - while (!randomLocation.getBlock().isPassable() && randomLocation.getBlockY() < randomLocation.getWorld().getMaxHeight()) - randomLocation.add(0, 1, 0); - - randomLocation.getBlock().setType(Material.COBWEB, false); - } - } - - } + private final Event[] events; + + public RandomEventChallenge() { + super(MenuType.CHALLENGES, 1, 10, 3, false); + setCategory(SettingCategory.RANDOMIZER); + events = new Event[]{ + new SpeedEvent(), + new SpawnEntitiesEvent(), + new HoleEvent(), + new FlyEvent(), + new CobWebEvent(), + new ReplaceOresEvent(), + new SicknessEvent() + }; + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CLOCK, Message.forName("item-random-event-challenge").asItemDescription(events.length)); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + } + + @Override + protected int getSecondsUntilNextActivation() { + return globalRandom.around(getValue() * 60, 30); + } + + @Override + protected void onTimeActivation() { + restartTimer(); + Event event = globalRandom.choose(events); + Logger.debug("Running random event {}", event.getClass().getSimpleName()); + event.getActivationMessage().broadcastRandom(globalRandom, Prefix.CHALLENGES); + broadcastFiltered(event::run); + } + + public interface Event { + + @Nonnull + Message getActivationMessage(); + + void run(@Nonnull Player player); + + } + + public static class SpeedEvent implements Event { + + @Nonnull + @Override + public Message getActivationMessage() { + return Message.forName("random-event-speed"); + } + + @Override + public void run(@Nonnull Player player) { + player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 10 * 20, 99)); + } + + } + + public static class HoleEvent implements Event { + + @Nonnull + @Override + public Message getActivationMessage() { + return Message.forName("random-event-hole"); + } + + @Override + public void run(@Nonnull Player player) { + Location location = player.getLocation().getBlock().getLocation(); + for (int x = -1; x <= 1; x++) { + for (int z = -1; z <= 1; z++) { + for (int y = 1; y >= -8; y--) { + location.clone().add(x, y, z).getBlock().setType(Material.AIR, true); + } + } + } + } + + } + + public static class FlyEvent implements Event { + + @Nonnull + @Override + public Message getActivationMessage() { + return Message.forName("random-event-fly"); + } + + @Override + public void run(@Nonnull Player player) { + player.addPotionEffect(new PotionEffect(PotionEffectType.LEVITATION, 3 * 20, 5)); + } + + } + + public static class ReplaceOresEvent implements Event { + + @Nonnull + @Override + public Message getActivationMessage() { + return Message.forName("random-event-ores"); + } + + @Override + public void run(@Nonnull Player player) { + Location location = player.getLocation(); + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + for (int x = -100; x <= 100; x++) { + for (int z = -100; z <= 100; z++) { + int finalZ = z; + int finalX = x; + Bukkit.getScheduler().runTask(plugin, () -> { + if (location.getWorld() == null) return; + for (int y = BukkitReflectionUtils.getMinHeight(location.getWorld()); y < 80; y++) { + Location current = location.clone().add(finalX, 0, finalZ); + current.setY(y); + Block block = current.getBlock(); + if (block.getType().name().contains("ORE")) { + Environment environment = location.getWorld().getEnvironment(); + block.setType(environment == Environment.NETHER ? Material.NETHERRACK : environment == Environment.THE_END ? Material.END_STONE : Material.STONE, true); + } + } + }); + } + } + }); + } + + } + + public static class SicknessEvent implements Event { + + @Nonnull + @Override + public Message getActivationMessage() { + return Message.forName("random-event-sickness"); + } + + @Override + public void run(@Nonnull Player player) { + player.addPotionEffect(new PotionEffect(MinecraftNameWrapper.NAUSEA, 7 * 20, 0)); + player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 3 * 20, 1)); + player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 5 * 20, 1)); + } + } + + public static class SpawnEntitiesEvent implements Event { + + @Nonnull + @Override + public Message getActivationMessage() { + return Message.forName("random-event-entities"); + } + + @Override + public void run(@Nonnull Player player) { + EntityType type = globalRandom.choose(EntityType.PIG, EntityType.CHICKEN, EntityType.CAT, EntityType.SILVERFISH, EntityType.WOLF); + + for (int i = 0; i < globalRandom.nextInt(5) + 5; i++) { + Location randomLocation = player.getLocation().add(globalRandom.nextInt(10) - 5, -10, globalRandom.nextInt(10 - 5)); + if (randomLocation.getWorld() == null) return; + while (!randomLocation.getBlock().isPassable() && randomLocation.getBlockY() < randomLocation.getWorld().getMaxHeight()) + randomLocation.add(0, 1, 0); + + randomLocation.getWorld().spawnEntity(randomLocation, type); + } + } + + } + + public static class CobWebEvent implements Event { + + @Nonnull + @Override + public Message getActivationMessage() { + return Message.forName("random-event-webs"); + } + + @Override + public void run(@Nonnull Player player) { + for (int i = 0; i < 13; i++) { + Location randomLocation = player.getLocation().add(globalRandom.nextInt(10) - 5, -20, globalRandom.nextInt(10 - 5)); + if (randomLocation.getWorld() == null) return; + while (!randomLocation.getBlock().isPassable() && randomLocation.getBlockY() < randomLocation.getWorld().getMaxHeight()) + randomLocation.add(0, 1, 0); + + randomLocation.getBlock().setType(Material.COBWEB, false); + } + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java index 8ce471fdc..7e897854d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java @@ -16,37 +16,37 @@ @Since("2.0") public class RandomItemChallenge extends TimedChallenge { - public RandomItemChallenge() { - super(MenuType.CHALLENGES, 1, 60, 30, false); - setCategory(SettingCategory.RANDOMIZER); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BEACON, Message.forName("item-random-item-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); - } - - @Override - protected int getSecondsUntilNextActivation() { - return getValue(); - } - - @Override - protected void onTimeActivation() { - restartTimer(); - broadcastFiltered(RandomItemAction::giveRandomItemToPlayer); - } + public RandomItemChallenge() { + super(MenuType.CHALLENGES, 1, 60, 30, false); + setCategory(SettingCategory.RANDOMIZER); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BEACON, Message.forName("item-random-item-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue(); + } + + @Override + protected void onTimeActivation() { + restartTimer(); + broadcastFiltered(RandomItemAction::giveRandomItemToPlayer); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java index fd613961d..bb87ca313 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java @@ -21,59 +21,59 @@ @Since("2.0") public class RandomItemDroppingChallenge extends TimedChallenge { - public RandomItemDroppingChallenge() { - super(MenuType.CHALLENGES, 1, 60, 5); - setCategory(SettingCategory.RANDOMIZER); - } + public RandomItemDroppingChallenge() { + super(MenuType.CHALLENGES, 1, 60, 5); + setCategory(SettingCategory.RANDOMIZER); + } - public static void dropRandomItem(Player player) { - if (player.getInventory().getContents().length == 0) return; - dropRandomItem(player.getLocation(), player.getInventory()); - } + public static void dropRandomItem(Player player) { + if (player.getInventory().getContents().length == 0) return; + dropRandomItem(player.getLocation(), player.getInventory()); + } - public static void dropRandomItem(@Nonnull Location location, @Nonnull Inventory inventory) { - if (location.getWorld() == null) return; - int slot = InventoryUtils.getRandomFullSlot(inventory); - if (slot == -1) return; - ItemStack item = inventory.getItem(slot); - if (item == null) return; - inventory.setItem(slot, null); - InventoryUtils.dropItemByPlayer(location, item); - } + public static void dropRandomItem(@Nonnull Location location, @Nonnull Inventory inventory) { + if (location.getWorld() == null) return; + int slot = InventoryUtils.getRandomFullSlot(inventory); + if (slot == -1) return; + ItemStack item = inventory.getItem(slot); + if (item == null) return; + inventory.setItem(slot, null); + InventoryUtils.dropItemByPlayer(location, item); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DISPENSER, Message.forName("item-random-dropping-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DISPENSER, Message.forName("item-random-dropping-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); - } + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); + } - @Override - protected int getSecondsUntilNextActivation() { - return getValue(); - } + @Override + protected int getSecondsUntilNextActivation() { + return getValue(); + } - @Override - protected void onTimeActivation() { - restartTimer(); + @Override + protected void onTimeActivation() { + restartTimer(); - Bukkit.getScheduler().runTask(plugin, () -> { - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; + Bukkit.getScheduler().runTask(plugin, () -> { + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; - dropRandomItem(player); - } - }); - } + dropRandomItem(player); + } + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java index ae705f94f..94d4b7ec5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java @@ -18,45 +18,45 @@ @Since("2.0") public class RandomItemRemovingChallenge extends TimedChallenge { - public RandomItemRemovingChallenge() { - super(MenuType.CHALLENGES, 1, 30, 30); - setCategory(SettingCategory.RANDOMIZER); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DROPPER, Message.forName("item-random-removing-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 10); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 10); - } - - @Override - protected int getSecondsUntilNextActivation() { - return getValue(); - } - - @Override - protected void onTimeActivation() { - restartTimer(); - - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - if (player.getInventory().getContents().length == 0) continue; - - Bukkit.getScheduler().runTask(plugin, () -> { - InventoryUtils.removeRandomItem(player.getInventory()); - }); - } - } + public RandomItemRemovingChallenge() { + super(MenuType.CHALLENGES, 1, 30, 30); + setCategory(SettingCategory.RANDOMIZER); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DROPPER, Message.forName("item-random-removing-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue() * 10); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 10); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue(); + } + + @Override + protected void onTimeActivation() { + restartTimer(); + + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + if (player.getInventory().getContents().length == 0) continue; + + Bukkit.getScheduler().runTask(plugin, () -> { + InventoryUtils.removeRandomItem(player.getInventory()); + }); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java index 9e21a2a80..f20c39856 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java @@ -20,65 +20,65 @@ @Since("2.0") public class RandomItemSwappingChallenge extends TimedChallenge { - public RandomItemSwappingChallenge() { - super(MenuType.CHALLENGES, 1, 60, 5); - setCategory(SettingCategory.RANDOMIZER); - } - - public static void swapRandomItems(Player player) { - if (player.getInventory().getContents().length == 0) return; - int slot = InventoryUtils.getRandomFullSlot(player.getInventory()); - if (slot == -1) return; - swapItemToRandomSlot( - player.getInventory(), - InventoryUtils.getRandomFullSlot(player.getInventory()), - InventoryUtils.getRandomSlot(player.getInventory()) - ); - } - - private static void swapItemToRandomSlot(@Nonnull Inventory inventory, int slot1, int slot2) { - if (slot1 == -1 || slot2 == -1) return; - ItemStack item1 = inventory.getItem(slot1); - ItemStack item2 = inventory.getItem(slot2); - inventory.setItem(slot1, item2); - inventory.setItem(slot2, item1); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.HOPPER, Message.forName("item-random-swapping-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); - } - - @Override - protected int getSecondsUntilNextActivation() { - return getValue(); - } - - @Override - protected void onTimeActivation() { - restartTimer(); - - Bukkit.getScheduler().runTask(plugin, () -> { - - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - swapRandomItems(player); - } - - }); - - } + public RandomItemSwappingChallenge() { + super(MenuType.CHALLENGES, 1, 60, 5); + setCategory(SettingCategory.RANDOMIZER); + } + + public static void swapRandomItems(Player player) { + if (player.getInventory().getContents().length == 0) return; + int slot = InventoryUtils.getRandomFullSlot(player.getInventory()); + if (slot == -1) return; + swapItemToRandomSlot( + player.getInventory(), + InventoryUtils.getRandomFullSlot(player.getInventory()), + InventoryUtils.getRandomSlot(player.getInventory()) + ); + } + + private static void swapItemToRandomSlot(@Nonnull Inventory inventory, int slot1, int slot2) { + if (slot1 == -1 || slot2 == -1) return; + ItemStack item1 = inventory.getItem(slot1); + ItemStack item2 = inventory.getItem(slot2); + inventory.setItem(slot1, item2); + inventory.setItem(slot2, item1); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.HOPPER, Message.forName("item-random-swapping-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue(); + } + + @Override + protected void onTimeActivation() { + restartTimer(); + + Bukkit.getScheduler().runTask(plugin, () -> { + + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + swapRandomItems(player); + } + + }); + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java index ff3a10448..007749f92 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java @@ -22,38 +22,38 @@ @Since("2.1.3") public class RandomTeleportOnHitChallenge extends Setting { - public RandomTeleportOnHitChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.RANDOMIZER); - } - - public static void switchEntityLocations(LivingEntity entity1, LivingEntity entity2) { - entity1.setInvisible(true); - entity2.setInvisible(false); - Location entity2Location = entity2.getLocation().clone(); - entity2.teleport(entity1.getLocation()); - entity1.teleport(entity2Location); - entity2.setInvisible(false); - entity1.setInvisible(false); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENDER_CHEST, Message.forName("item-mob-damage-teleport-challenge")); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityDamageByPlayer(EntityDamageByPlayerEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getDamager())) return; - - World world = event.getDamager().getWorld(); - List livingEntities = new ArrayList<>(world.getLivingEntities()); - livingEntities.removeIf(entity -> entity == event.getDamager() || entity instanceof Player && ignorePlayer((Player) entity)); - LivingEntity entity = globalRandom.choose(livingEntities); - - switchEntityLocations(entity, event.getDamager()); - } + public RandomTeleportOnHitChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.RANDOMIZER); + } + + public static void switchEntityLocations(LivingEntity entity1, LivingEntity entity2) { + entity1.setInvisible(true); + entity2.setInvisible(false); + Location entity2Location = entity2.getLocation().clone(); + entity2.teleport(entity1.getLocation()); + entity1.teleport(entity2Location); + entity2.setInvisible(false); + entity1.setInvisible(false); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ENDER_CHEST, Message.forName("item-mob-damage-teleport-challenge")); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityDamageByPlayer(EntityDamageByPlayerEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getDamager())) return; + + World world = event.getDamager().getWorld(); + List livingEntities = new ArrayList<>(world.getLivingEntities()); + livingEntities.removeIf(entity -> entity == event.getDamager() || entity instanceof Player && ignorePlayer((Player) entity)); + LivingEntity entity = globalRandom.choose(livingEntities); + + switchEntityLocations(entity, event.getDamager()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java index 1bb679ef7..8dd334665 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java @@ -31,107 +31,107 @@ public class RandomizedHPChallenge extends SettingModifier { - private final Random random = new Random(); - - public RandomizedHPChallenge() { - super(MenuType.CHALLENGES, 5); - setCategory(SettingCategory.RANDOMIZER); - randomizeExistingEntityHealth(); - } - - @Override - protected void onDisable() { - resetExistingEntityHealth(); - } - - @Override - public void onEnable() { - randomizeExistingEntityHealth(); - } - - @Override - protected void onValueChange() { - randomizeExistingEntityHealth(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSpawn(@Nonnull EntitySpawnEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof LivingEntity)) return; - LivingEntity entity = (LivingEntity) event.getEntity(); - randomizeEntityHealth(entity); - } - - private void randomizeEntityHealth(@Nonnull LivingEntity entity) { - if (entity instanceof Player) return; - if (!isEnabled()) { - entity.resetMaxHealth(); - entity.setHealth(entity.getMaxHealth()); - return; - } - int health = random.nextInt(getValue() * 100) + 1; - entity.setHealth(health); - AttributeInstance attribute = entity.getAttribute(AttributeWrapper.MAX_HEALTH); - if (attribute == null) return; - attribute.setBaseValue(health); - } - - private void randomizeExistingEntityHealth() { - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - randomizeEntityHealth(entity); - } - } - } - - private void resetExistingEntityHealth() { - Map entityDefaultHealth = new HashMap<>(); - for (World world : ChallengeAPI.getGameWorlds()) { - for (LivingEntity entity : world.getLivingEntities()) { - if (entity instanceof Player) continue; - EntityType type = entity.getType(); - double health = entityDefaultHealth.getOrDefault(type, getDefaultHealth(type)); - entityDefaultHealth.put(type, health); - - AttributeInstance attribute = entity.getAttribute(AttributeWrapper.MAX_HEALTH); - if (attribute == null) return; - attribute.setBaseValue(health); - entity.setHealth(health); - } - } - } - - private double getDefaultHealth(@Nonnull EntityType entityType) { - World world = ChallengeAPI.getGameWorld(Environment.NORMAL); - Entity entity = world.spawnEntity(new Location(world, 0, 0, 0), entityType); - entity.remove(); - if (!(entity instanceof LivingEntity)) return 0; - AttributeInstance attribute = ((LivingEntity) entity).getAttribute(AttributeWrapper.MAX_HEALTH); - if (attribute == null) return 10; - return attribute.getBaseValue(); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new PotionBuilder(Material.POTION, Message.forName("item-randomized-hp-challenge")).setColor(Color.RED); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - return super.createSettingsItem().amount(isEnabled() ? getValue() * 5 : 1); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() * 100); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-max-health-description").asArray(getValue() * 50); - } + private final Random random = new Random(); + + public RandomizedHPChallenge() { + super(MenuType.CHALLENGES, 5); + setCategory(SettingCategory.RANDOMIZER); + randomizeExistingEntityHealth(); + } + + @Override + protected void onDisable() { + resetExistingEntityHealth(); + } + + @Override + public void onEnable() { + randomizeExistingEntityHealth(); + } + + @Override + protected void onValueChange() { + randomizeExistingEntityHealth(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSpawn(@Nonnull EntitySpawnEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof LivingEntity)) return; + LivingEntity entity = (LivingEntity) event.getEntity(); + randomizeEntityHealth(entity); + } + + private void randomizeEntityHealth(@Nonnull LivingEntity entity) { + if (entity instanceof Player) return; + if (!isEnabled()) { + entity.resetMaxHealth(); + entity.setHealth(entity.getMaxHealth()); + return; + } + int health = random.nextInt(getValue() * 100) + 1; + entity.setHealth(health); + AttributeInstance attribute = entity.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return; + attribute.setBaseValue(health); + } + + private void randomizeExistingEntityHealth() { + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + randomizeEntityHealth(entity); + } + } + } + + private void resetExistingEntityHealth() { + Map entityDefaultHealth = new HashMap<>(); + for (World world : ChallengeAPI.getGameWorlds()) { + for (LivingEntity entity : world.getLivingEntities()) { + if (entity instanceof Player) continue; + EntityType type = entity.getType(); + double health = entityDefaultHealth.getOrDefault(type, getDefaultHealth(type)); + entityDefaultHealth.put(type, health); + + AttributeInstance attribute = entity.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return; + attribute.setBaseValue(health); + entity.setHealth(health); + } + } + } + + private double getDefaultHealth(@Nonnull EntityType entityType) { + World world = ChallengeAPI.getGameWorld(Environment.NORMAL); + Entity entity = world.spawnEntity(new Location(world, 0, 0, 0), entityType); + entity.remove(); + if (!(entity instanceof LivingEntity)) return 0; + AttributeInstance attribute = ((LivingEntity) entity).getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return 10; + return attribute.getBaseValue(); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new PotionBuilder(Material.POTION, Message.forName("item-randomized-hp-challenge")).setColor(Color.RED); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + return super.createSettingsItem().amount(isEnabled() ? getValue() * 5 : 1); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() * 100); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-max-health-description").asArray(getValue() * 50); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java index 1b6db8258..b76cfe7c1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java @@ -21,87 +21,87 @@ @Since("2.0") public class MaxBiomeTimeChallenge extends SettingModifier { - public MaxBiomeTimeChallenge() { - super(MenuType.CHALLENGES, 3, 20); - setCategory(SettingCategory.LIMITED_TIME); - } - - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - int currentTime = getCurrentTime(player); - int maxTime = (getValue() * 60); - bossbar.setTitle(Message.forName("bossbar-biome-time-left").asComponent(getBiome(player), maxTime - currentTime)); - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(1 - ((float) currentTime / maxTime)); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Override - protected void onValueChange() { - bossbar.update(); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SPRUCE_SAPLING, Message.forName("item-max-biome-time-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 60); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 60); - } - - @EventHandler - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - if (event.getFrom().getBlock().getBiome() == event.getTo().getBlock().getBiome()) return; - bossbar.update(event.getPlayer()); - } - - @ScheduledTask(ticks = 20) - public void onSecond() { - broadcast(this::updateBiomeTime); - } - - private void updateBiomeTime(@Nonnull Player player) { - if (ignorePlayer(player)) { - bossbar.update(player); - return; - } - - Biome biome = player.getLocation().getBlock().getBiome(); - int time = getCurrentTime(player) + 1; - if (time > getValue() * 60) { - kill(player); - } - if (time < getValue() * 60) { - getPlayerData(player).set(biome.name(), time); - } - bossbar.update(player); - } - - private int getCurrentTime(@Nonnull Player player) { - return getPlayerData(player).getInt(getBiome(player).name(), 0); - } - - private Biome getBiome(@Nonnull Player player) { - return player.getLocation().getBlock().getBiome(); - } + public MaxBiomeTimeChallenge() { + super(MenuType.CHALLENGES, 3, 20); + setCategory(SettingCategory.LIMITED_TIME); + } + + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + int currentTime = getCurrentTime(player); + int maxTime = (getValue() * 60); + bossbar.setTitle(Message.forName("bossbar-biome-time-left").asComponent(getBiome(player), maxTime - currentTime)); + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(1 - ((float) currentTime / maxTime)); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Override + protected void onValueChange() { + bossbar.update(); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SPRUCE_SAPLING, Message.forName("item-max-biome-time-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue() * 60); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 60); + } + + @EventHandler + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + if (event.getFrom().getBlock().getBiome() == event.getTo().getBlock().getBiome()) return; + bossbar.update(event.getPlayer()); + } + + @ScheduledTask(ticks = 20) + public void onSecond() { + broadcast(this::updateBiomeTime); + } + + private void updateBiomeTime(@Nonnull Player player) { + if (ignorePlayer(player)) { + bossbar.update(player); + return; + } + + Biome biome = player.getLocation().getBlock().getBiome(); + int time = getCurrentTime(player) + 1; + if (time > getValue() * 60) { + kill(player); + } + if (time < getValue() * 60) { + getPlayerData(player).set(biome.name(), time); + } + bossbar.update(player); + } + + private int getCurrentTime(@Nonnull Player player) { + return getPlayerData(player).getInt(getBiome(player).name(), 0); + } + + private Biome getBiome(@Nonnull Player player) { + return player.getLocation().getBlock().getBiome(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java index 8d44f4d3f..f8f582a8b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java @@ -21,82 +21,82 @@ @Since("2.0") public class MaxHeightTimeChallenge extends SettingModifier { - public MaxHeightTimeChallenge() { - super(MenuType.CHALLENGES, 3, 20); - setCategory(SettingCategory.LIMITED_TIME); - } - - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - int currentTime = getCurrentTime(player); - int maxTime = (getValue() * 60); - bossbar.setTitle(Message.forName("bossbar-height-time-left").asString(player.getLocation().getBlockY(), maxTime - currentTime)); - bossbar.setColor(BarColor.GREEN); - bossbar.setProgress(1 - ((float) currentTime / maxTime)); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Override - protected void onValueChange() { - bossbar.update(); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PARROT_SPAWN_EGG, Message.forName("item-max-height-time-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 60); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 60); - } - - @EventHandler - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - if (event.getFrom().getBlockY() == event.getTo().getBlockY()) return; - Bukkit.getScheduler().runTask(plugin, () -> bossbar.update(event.getPlayer())); - } - - @ScheduledTask(ticks = 20) - public void onSecond() { - broadcast(this::updateHeightTime); - } - - private void updateHeightTime(@Nonnull Player player) { - if (ignorePlayer(player)) { - bossbar.update(player); - return; - } - - int time = getCurrentTime(player) + 1; - if (time > getValue() * 60) { - kill(player); - } - if (time < getValue() * 60) { - getPlayerData(player).set(String.valueOf(player.getLocation().getBlockY()), time); - } - bossbar.update(player); - } - - private int getCurrentTime(@Nonnull Player player) { - return getPlayerData(player).getInt(String.valueOf(player.getLocation().getBlockY()), 0); - } + public MaxHeightTimeChallenge() { + super(MenuType.CHALLENGES, 3, 20); + setCategory(SettingCategory.LIMITED_TIME); + } + + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + int currentTime = getCurrentTime(player); + int maxTime = (getValue() * 60); + bossbar.setTitle(Message.forName("bossbar-height-time-left").asString(player.getLocation().getBlockY(), maxTime - currentTime)); + bossbar.setColor(BarColor.GREEN); + bossbar.setProgress(1 - ((float) currentTime / maxTime)); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Override + protected void onValueChange() { + bossbar.update(); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.PARROT_SPAWN_EGG, Message.forName("item-max-height-time-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue() * 60); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 60); + } + + @EventHandler + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + if (event.getFrom().getBlockY() == event.getTo().getBlockY()) return; + Bukkit.getScheduler().runTask(plugin, () -> bossbar.update(event.getPlayer())); + } + + @ScheduledTask(ticks = 20) + public void onSecond() { + broadcast(this::updateHeightTime); + } + + private void updateHeightTime(@Nonnull Player player) { + if (ignorePlayer(player)) { + bossbar.update(player); + return; + } + + int time = getCurrentTime(player) + 1; + if (time > getValue() * 60) { + kill(player); + } + if (time < getValue() * 60) { + getPlayerData(player).set(String.valueOf(player.getLocation().getBlockY()), time); + } + bossbar.update(player); + } + + private int getCurrentTime(@Nonnull Player player) { + return getPlayerData(player).getInt(String.valueOf(player.getLocation().getBlockY()), 0); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java index 884d4e679..a2a6021aa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java @@ -31,115 +31,115 @@ @Since("2.0") public class AllBlocksDisappearChallenge extends MenuSetting { - private final int stackDropLimit; - - public AllBlocksDisappearChallenge() { - super(MenuType.CHALLENGES, Message.forName("menu-all-blocks-disappear-challenge-settings")); - setCategory(SettingCategory.WORLD); - registerSetting("break", new BooleanSubSetting( - () -> new ItemBuilder(Material.DIAMOND_PICKAXE, Message.forName("item-all-blocks-disappear-break-challenge")), - true - )); - registerSetting("place", new BooleanSubSetting( - () -> new ItemBuilder(Material.DIAMOND_BLOCK, Message.forName("item-all-blocks-disappear-place-challenge")) - )); - - Document document = ChallengeConfigHelper.getSettingsDocument(); - stackDropLimit = document.contains("all-block-disappear-stack-drop-limit") ? document.getInt("all-block-disappear-stack-drop-limit") : 50; - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.TNT, Message.forName("item-all-blocks-disappear-challenge")); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (!getSetting("break").getAsBoolean()) return; - if (ignorePlayer(event.getPlayer())) return; - PlayerInventory inventory = event.getPlayer().getInventory(); - event.setDropItems(false); - breakBlocks(event.getBlock(), inventory.getItemInMainHand(), inventory); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - if (!getSetting("place").getAsBoolean()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getBlockAgainst().getType() == Material.BEDROCK) return; - if (event.getBlockAgainst().getType() == Material.END_PORTAL) return; - breakBlocks(event.getBlockAgainst(), null, event.getPlayer().getInventory()); - } - - private void breakBlocks(@Nonnull Block block, @Nullable ItemStack tool, @Nonnull Inventory inventory) { - Chunk chunk = block.getChunk(); - List blocks = getAllBlocksToBreak(chunk, block.getType()); - - List allDrops = new ArrayList<>(); - - for (Block current : blocks) { - Collection drops = Challenges.getInstance().getBlockDropManager().getDrops(current, tool); - current.setType(Material.AIR); - - for (ItemStack currentBlockDrop : drops) { - boolean containsType = false; - - for (ItemStack currentAllDrop : allDrops) { - if (currentAllDrop.getType() == currentBlockDrop.getType() && (currentAllDrop.getAmount() + currentBlockDrop.getAmount()) <= currentAllDrop.getMaxStackSize()) { - containsType = true; - currentAllDrop.setAmount(currentAllDrop.getAmount() + currentBlockDrop.getAmount()); - } - } - - if (!containsType) { - allDrops.add(currentBlockDrop); - } - - } - - } - - dropList(allDrops, block.getLocation(), inventory); - } - - private void dropList(@Nonnull Collection itemStacks, @Nonnull Location location, @Nonnull Inventory inventory) { - if (location.getWorld() == null) return; - Map stackCount = new HashMap<>(); - - for (ItemStack itemStack : itemStacks) { - if (increaseStackCount(stackCount, itemStack.getType())) { - ChallengeHelper.dropItem(itemStack, location, inventory); - location.getWorld().dropItemNaturally(location, itemStack); - } - } - } - - private boolean increaseStackCount(Map map, Material material) { - int droppedStacks = map.getOrDefault(material, 0); - if (droppedStacks >= stackDropLimit) return false; - droppedStacks++; - map.put(material, droppedStacks); - return true; - } - - protected List getAllBlocksToBreak(@Nonnull Chunk chunk, @Nonnull Material material) { - return new ListBuilder() - .fill(builder -> { - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - for (int y = BukkitReflectionUtils.getMinHeight(chunk.getWorld()); y < chunk.getWorld().getMaxHeight(); y++) { - Block block = chunk.getBlock(x, y, z); - if (block.getType() == material) { - builder.add(block); - } - } - } - } - }) - .build(); - } + private final int stackDropLimit; + + public AllBlocksDisappearChallenge() { + super(MenuType.CHALLENGES, Message.forName("menu-all-blocks-disappear-challenge-settings")); + setCategory(SettingCategory.WORLD); + registerSetting("break", new BooleanSubSetting( + () -> new ItemBuilder(Material.DIAMOND_PICKAXE, Message.forName("item-all-blocks-disappear-break-challenge")), + true + )); + registerSetting("place", new BooleanSubSetting( + () -> new ItemBuilder(Material.DIAMOND_BLOCK, Message.forName("item-all-blocks-disappear-place-challenge")) + )); + + Document document = ChallengeConfigHelper.getSettingsDocument(); + stackDropLimit = document.contains("all-block-disappear-stack-drop-limit") ? document.getInt("all-block-disappear-stack-drop-limit") : 50; + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.TNT, Message.forName("item-all-blocks-disappear-challenge")); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (!getSetting("break").getAsBoolean()) return; + if (ignorePlayer(event.getPlayer())) return; + PlayerInventory inventory = event.getPlayer().getInventory(); + event.setDropItems(false); + breakBlocks(event.getBlock(), inventory.getItemInMainHand(), inventory); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (!getSetting("place").getAsBoolean()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getBlockAgainst().getType() == Material.BEDROCK) return; + if (event.getBlockAgainst().getType() == Material.END_PORTAL) return; + breakBlocks(event.getBlockAgainst(), null, event.getPlayer().getInventory()); + } + + private void breakBlocks(@Nonnull Block block, @Nullable ItemStack tool, @Nonnull Inventory inventory) { + Chunk chunk = block.getChunk(); + List blocks = getAllBlocksToBreak(chunk, block.getType()); + + List allDrops = new ArrayList<>(); + + for (Block current : blocks) { + Collection drops = Challenges.getInstance().getBlockDropManager().getDrops(current, tool); + current.setType(Material.AIR); + + for (ItemStack currentBlockDrop : drops) { + boolean containsType = false; + + for (ItemStack currentAllDrop : allDrops) { + if (currentAllDrop.getType() == currentBlockDrop.getType() && (currentAllDrop.getAmount() + currentBlockDrop.getAmount()) <= currentAllDrop.getMaxStackSize()) { + containsType = true; + currentAllDrop.setAmount(currentAllDrop.getAmount() + currentBlockDrop.getAmount()); + } + } + + if (!containsType) { + allDrops.add(currentBlockDrop); + } + + } + + } + + dropList(allDrops, block.getLocation(), inventory); + } + + private void dropList(@Nonnull Collection itemStacks, @Nonnull Location location, @Nonnull Inventory inventory) { + if (location.getWorld() == null) return; + Map stackCount = new HashMap<>(); + + for (ItemStack itemStack : itemStacks) { + if (increaseStackCount(stackCount, itemStack.getType())) { + ChallengeHelper.dropItem(itemStack, location, inventory); + location.getWorld().dropItemNaturally(location, itemStack); + } + } + } + + private boolean increaseStackCount(Map map, Material material) { + int droppedStacks = map.getOrDefault(material, 0); + if (droppedStacks >= stackDropLimit) return false; + droppedStacks++; + map.put(material, droppedStacks); + return true; + } + + protected List getAllBlocksToBreak(@Nonnull Chunk chunk, @Nonnull Material material) { + return new ListBuilder() + .fill(builder -> { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y = BukkitReflectionUtils.getMinHeight(chunk.getWorld()); y < chunk.getWorld().getMaxHeight(); y++) { + Block block = chunk.getBlock(x, y, z); + if (block.getType() == material) { + builder.add(block); + } + } + } + } + }) + .build(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java index 2a6c0c514..b6ee091f0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java @@ -25,207 +25,207 @@ public class AnvilRainChallenge extends MenuSetting { - private final Random random = new Random(); - int currentTime = 0; - - public AnvilRainChallenge() { - super(MenuType.CHALLENGES, Message.forName("menu-anvil-rain-challenge-settings")); - setCategory(SettingCategory.WORLD); - registerSetting("time", new NumberSubSetting( - () -> new ItemBuilder(Material.CLOCK, Message.forName("item-anvil-rain-time-challenge")), - value -> null, - value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), - 1, - 30, - 7 - ) - ); - registerSetting("count", new NumberSubSetting( - () -> new ItemBuilder(Material.FLINT, Message.forName("item-anvil-rain-count-challenge")), - 1, - 30, - 8 - ) - ); - registerSetting("range", new NumberSubSetting( - () -> new ItemBuilder(Material.COMPASS, Message.forName("item-anvil-rain-range-challenge")), - value -> null, - value -> "§e" + value + " §7" + (value == 1 ? "chunk" : "chunks"), - 1, - 3, - 2 - ) - ); - registerSetting("damage", new NumberSubSetting( - () -> new ItemBuilder(Material.IRON_SWORD, Message.forName("item-anvil-rain-damage-challenge")), - value -> null, - value -> "§e" + Display.HEARTS.formatChat(value), - 1, - 60, - 30 - ) - ); - } - - @Override - protected void onDisable() { - removeAnvils(); - } - - @TimerTask(async = false, status = TimerStatus.PAUSED) - public void onPause() { - removeAnvils(); - } - - private void removeAnvils() { - for (World world : Bukkit.getWorlds()) { - for (FallingBlock entity : world.getEntitiesByClass(FallingBlock.class)) { - // TODO: SWITCH CASE - String name = entity.getBlockData().getMaterial().name(); - if (!name.contains("ANVIL")) continue; - entity.remove(); - } - } - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ANVIL, Message.forName("item-anvil-rain-challenge")); - } - - @ScheduledTask(ticks = 20, async = false) - public void onSecond() { - currentTime++; - - if (currentTime > getSetting("time").getAsInt()) { - currentTime = 0; - handleTimeActivation(); - } - - } - - private void handleTimeActivation() { - List chunks = new ArrayList<>(); - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - - List targetChunks = getTargetChunks(player.getLocation().getChunk()); - for (Chunk targetChunk : targetChunks) { - if (chunks.contains(targetChunk)) continue; - chunks.add(targetChunk); - spawnAnvils(targetChunk, getHeight(player.getLocation().getBlockY())); - } - } - - } - - private void spawnAnvils(@Nonnull Chunk chunk, int height) { - for (int i = 0; i < getCount(); i++) { - Block block = getRandomBlockInChunk(chunk, height); - Location location = block.getLocation().add(0.5, 0, 0.5); - block.getWorld().spawnFallingBlock(location, Material.ANVIL, ((byte) 0)); - } - } - - private List getTargetChunks(@Nonnull Chunk origin) { - List chunks = new ArrayList<>(); - - int originX = origin.getX(); - int originZ = origin.getZ(); - - int range = getRange(); - for (int x = -range; x <= range; x++) { - for (int z = -range; z <= range; z++) { - Chunk chunkAt = origin.getWorld().getChunkAt(originX + x, originZ + z); - chunks.add(chunkAt); - } - - } - - return chunks; - } - - private Block getRandomBlockInChunk(@Nonnull Chunk chunk, int y) { - int x = random.nextInt(16); - int z = random.nextInt(16); - return chunk.getBlock(x, y, z); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityChangeBlock(@Nonnull EntityChangeBlockEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof FallingBlock)) return; - - String name = ((FallingBlock) event.getEntity()).getBlockData().getMaterial().name(); - if (!name.contains("ANVIL")) return; - - Block block = event.getBlock().getLocation().subtract(0, 1, 0).getBlock(); - if (BukkitReflectionUtils.isAir(block.getType())) return; - - event.getBlock().setType(Material.AIR); - event.setCancelled(true); - event.getEntity().remove(); - destroyRandomBlocks(event.getBlock().getLocation()); - applyDamageToNearEntities(event.getBlock().getLocation().add(0.5, 0.5, 0.5)); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDrop(@Nonnull EntityDropItemEvent event) { - if (event.getItemDrop().getItemStack().getType() != Material.ANVIL) return; - if (event.getEntityType() != EntityType.FALLING_BLOCK) return; - String name = ((FallingBlock) event.getEntity()).getBlockData().getMaterial().name(); - if (!name.contains("ANVIL")) return; - - event.setCancelled(true); - - destroyRandomBlocks(event.getEntity().getLocation()); - applyDamageToNearEntities(event.getEntity().getLocation().getBlock().getLocation().add(0.5, 0.5, 0.5)); - } - - public void destroyRandomBlocks(@Nonnull Location origin) { - int i = random.nextInt(2); - - if (i == 0) return; - int blocks = getCount() < 16 ? 0 : 1; - while (blocks < 2 && origin.getBlockY() > 1) { - - if (origin.getBlock().getType() == Material.WATER || origin.getBlock().getType() == Material.LAVA) - return; - origin.subtract(0, 1, 0); - if (origin.getBlock().isPassable()) blocks--; - - origin.getBlock().setType(Material.AIR); - blocks++; - } - - } - - public void applyDamageToNearEntities(@Nonnull Location location) { - if (location.getWorld() == null) return; - for (Entity entity : location.getWorld().getNearbyEntities(location, 0.25, 0.25, 0.25)) { - if (!(entity instanceof LivingEntity)) continue; - LivingEntity livingEntity = (LivingEntity) entity; - livingEntity.damage(getDamage()); - } - - } - - private int getRange() { - return getSetting("range").getAsInt(); - } - - private int getCount() { - return getSetting("count").getAsInt(); - } - - private int getDamage() { - return getSetting("damage").getAsInt(); - } - - private int getHeight(int currentHeight) { - return currentHeight + 50; - } + private final Random random = new Random(); + int currentTime = 0; + + public AnvilRainChallenge() { + super(MenuType.CHALLENGES, Message.forName("menu-anvil-rain-challenge-settings")); + setCategory(SettingCategory.WORLD); + registerSetting("time", new NumberSubSetting( + () -> new ItemBuilder(Material.CLOCK, Message.forName("item-anvil-rain-time-challenge")), + value -> null, + value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), + 1, + 30, + 7 + ) + ); + registerSetting("count", new NumberSubSetting( + () -> new ItemBuilder(Material.FLINT, Message.forName("item-anvil-rain-count-challenge")), + 1, + 30, + 8 + ) + ); + registerSetting("range", new NumberSubSetting( + () -> new ItemBuilder(Material.COMPASS, Message.forName("item-anvil-rain-range-challenge")), + value -> null, + value -> "§e" + value + " §7" + (value == 1 ? "chunk" : "chunks"), + 1, + 3, + 2 + ) + ); + registerSetting("damage", new NumberSubSetting( + () -> new ItemBuilder(Material.IRON_SWORD, Message.forName("item-anvil-rain-damage-challenge")), + value -> null, + value -> "§e" + Display.HEARTS.formatChat(value), + 1, + 60, + 30 + ) + ); + } + + @Override + protected void onDisable() { + removeAnvils(); + } + + @TimerTask(async = false, status = TimerStatus.PAUSED) + public void onPause() { + removeAnvils(); + } + + private void removeAnvils() { + for (World world : Bukkit.getWorlds()) { + for (FallingBlock entity : world.getEntitiesByClass(FallingBlock.class)) { + // TODO: SWITCH CASE + String name = entity.getBlockData().getMaterial().name(); + if (!name.contains("ANVIL")) continue; + entity.remove(); + } + } + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ANVIL, Message.forName("item-anvil-rain-challenge")); + } + + @ScheduledTask(ticks = 20, async = false) + public void onSecond() { + currentTime++; + + if (currentTime > getSetting("time").getAsInt()) { + currentTime = 0; + handleTimeActivation(); + } + + } + + private void handleTimeActivation() { + List chunks = new ArrayList<>(); + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + + List targetChunks = getTargetChunks(player.getLocation().getChunk()); + for (Chunk targetChunk : targetChunks) { + if (chunks.contains(targetChunk)) continue; + chunks.add(targetChunk); + spawnAnvils(targetChunk, getHeight(player.getLocation().getBlockY())); + } + } + + } + + private void spawnAnvils(@Nonnull Chunk chunk, int height) { + for (int i = 0; i < getCount(); i++) { + Block block = getRandomBlockInChunk(chunk, height); + Location location = block.getLocation().add(0.5, 0, 0.5); + block.getWorld().spawnFallingBlock(location, Material.ANVIL, ((byte) 0)); + } + } + + private List getTargetChunks(@Nonnull Chunk origin) { + List chunks = new ArrayList<>(); + + int originX = origin.getX(); + int originZ = origin.getZ(); + + int range = getRange(); + for (int x = -range; x <= range; x++) { + for (int z = -range; z <= range; z++) { + Chunk chunkAt = origin.getWorld().getChunkAt(originX + x, originZ + z); + chunks.add(chunkAt); + } + + } + + return chunks; + } + + private Block getRandomBlockInChunk(@Nonnull Chunk chunk, int y) { + int x = random.nextInt(16); + int z = random.nextInt(16); + return chunk.getBlock(x, y, z); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityChangeBlock(@Nonnull EntityChangeBlockEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof FallingBlock)) return; + + String name = ((FallingBlock) event.getEntity()).getBlockData().getMaterial().name(); + if (!name.contains("ANVIL")) return; + + Block block = event.getBlock().getLocation().subtract(0, 1, 0).getBlock(); + if (BukkitReflectionUtils.isAir(block.getType())) return; + + event.getBlock().setType(Material.AIR); + event.setCancelled(true); + event.getEntity().remove(); + destroyRandomBlocks(event.getBlock().getLocation()); + applyDamageToNearEntities(event.getBlock().getLocation().add(0.5, 0.5, 0.5)); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDrop(@Nonnull EntityDropItemEvent event) { + if (event.getItemDrop().getItemStack().getType() != Material.ANVIL) return; + if (event.getEntityType() != EntityType.FALLING_BLOCK) return; + String name = ((FallingBlock) event.getEntity()).getBlockData().getMaterial().name(); + if (!name.contains("ANVIL")) return; + + event.setCancelled(true); + + destroyRandomBlocks(event.getEntity().getLocation()); + applyDamageToNearEntities(event.getEntity().getLocation().getBlock().getLocation().add(0.5, 0.5, 0.5)); + } + + public void destroyRandomBlocks(@Nonnull Location origin) { + int i = random.nextInt(2); + + if (i == 0) return; + int blocks = getCount() < 16 ? 0 : 1; + while (blocks < 2 && origin.getBlockY() > 1) { + + if (origin.getBlock().getType() == Material.WATER || origin.getBlock().getType() == Material.LAVA) + return; + origin.subtract(0, 1, 0); + if (origin.getBlock().isPassable()) blocks--; + + origin.getBlock().setType(Material.AIR); + blocks++; + } + + } + + public void applyDamageToNearEntities(@Nonnull Location location) { + if (location.getWorld() == null) return; + for (Entity entity : location.getWorld().getNearbyEntities(location, 0.25, 0.25, 0.25)) { + if (!(entity instanceof LivingEntity)) continue; + LivingEntity livingEntity = (LivingEntity) entity; + livingEntity.damage(getDamage()); + } + + } + + private int getRange() { + return getSetting("range").getAsInt(); + } + + private int getCount() { + return getSetting("count").getAsInt(); + } + + private int getDamage() { + return getSetting("damage").getAsInt(); + } + + private int getHeight(int currentHeight) { + return currentHeight + 50; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java index b7cb7d1d6..20cfef5a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java @@ -17,24 +17,24 @@ public class BedrockPathChallenge extends Setting { - public BedrockPathChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-bedrock-path-challenge")).setColor(Color.GRAY); - } - - @EventHandler - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) - return; - - BlockUtils.createBlockPath(event.getFrom(), event.getTo(), Material.BEDROCK); - } + public BedrockPathChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.WORLD); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-bedrock-path-challenge")).setColor(Color.GRAY); + } + + @EventHandler + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) + return; + + BlockUtils.createBlockPath(event.getFrom(), event.getTo(), Material.BEDROCK); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java index 4e8d42903..79eb21ac8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java @@ -19,51 +19,51 @@ public class BedrockWallChallenge extends SettingModifier { - public BedrockWallChallenge() { - super(MenuType.CHALLENGES, 1, 60, 30); - setCategory(SettingCategory.WORLD); - } + public BedrockWallChallenge() { + super(MenuType.CHALLENGES, 1, 60, 30); + setCategory(SettingCategory.WORLD); + } - @EventHandler - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) - return; + @EventHandler + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) + return; - Location location = event.getTo(); - if (location == null) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), location)) return; + Location location = event.getTo(); + if (location == null) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), location)) return; - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { - World world = event.getPlayer().getWorld(); + Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { + World world = event.getPlayer().getWorld(); - List blocks = new ArrayList<>(); - for (int y = BukkitReflectionUtils.getMinHeight(world) + 1; y < world.getMaxHeight(); y++) { - Location blockLocation = location.clone(); - blockLocation.setY(y); - blocks.add(blockLocation.getBlock()); - } + List blocks = new ArrayList<>(); + for (int y = BukkitReflectionUtils.getMinHeight(world) + 1; y < world.getMaxHeight(); y++) { + Location blockLocation = location.clone(); + blockLocation.setY(y); + blocks.add(blockLocation.getBlock()); + } - Bukkit.getScheduler().runTask(plugin, () -> { - for (Block block : blocks) { - block.setType(Material.BEDROCK, false); - } - }); + Bukkit.getScheduler().runTask(plugin, () -> { + for (Block block : blocks) { + block.setType(Material.BEDROCK, false); + } + }); - }, getValue() * 20L); + }, getValue() * 20L); - } + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BEDROCK, Message.forName("item-bedrock-walls-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BEDROCK, Message.forName("item-bedrock-walls-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java index 8a4c39d71..fa448c186 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java @@ -20,43 +20,43 @@ @Since("2.1.1") public class BlockFlyInAirChallenge extends Setting { - public BlockFlyInAirChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FERN, Message.forName("item-blocks-fly-challenge")); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getTo() == null) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - - Block blockBelow = BlockUtils.getBlockBelow(event.getTo()); - if (blockBelow == null) return; - if (!blockBelow.getType().isSolid()) return; - - Bukkit.getScheduler().runTaskLater(plugin, () -> { - boostBlockInAir(blockBelow); - }, 20); - - } - - private void boostBlockInAir(Block block) { - if (!block.getType().isSolid()) return; - - FallingBlock fallingBlock = block.getWorld() - .spawnFallingBlock(block.getLocation().add(0.5, 0, 0.5), block.getBlockData()); - fallingBlock.setInvulnerable(true); - fallingBlock.setVelocity(new Vector(0, 1, 0)); - - block.setType(Material.AIR); - } + public BlockFlyInAirChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.WORLD); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FERN, Message.forName("item-blocks-fly-challenge")); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (event.getTo() == null) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + + Block blockBelow = BlockUtils.getBlockBelow(event.getTo()); + if (blockBelow == null) return; + if (!blockBelow.getType().isSolid()) return; + + Bukkit.getScheduler().runTaskLater(plugin, () -> { + boostBlockInAir(blockBelow); + }, 20); + + } + + private void boostBlockInAir(Block block) { + if (!block.getType().isSolid()) return; + + FallingBlock fallingBlock = block.getWorld() + .spawnFallingBlock(block.getLocation().add(0.5, 0, 0.5), block.getBlockData()); + fallingBlock.setInvulnerable(true); + fallingBlock.setVelocity(new Vector(0, 1, 0)); + + block.setType(Material.AIR); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java index eaa0fee8b..f61e93990 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java @@ -23,47 +23,47 @@ @Since("2.0") public class BlocksDisappearAfterTimeChallenge extends SettingModifier { - private final Map tasks = new HashMap<>(); + private final Map tasks = new HashMap<>(); - public BlocksDisappearAfterTimeChallenge() { - super(MenuType.CHALLENGES, 60, 300); - setCategory(SettingCategory.WORLD); - } + public BlocksDisappearAfterTimeChallenge() { + super(MenuType.CHALLENGES, 60, 300); + setCategory(SettingCategory.WORLD); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STRING, Message.forName("item-blocks-disappear-time-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.STRING, Message.forName("item-blocks-disappear-time-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; - BukkitTask oldTask = tasks.remove(event.getBlock()); - if (oldTask != null) oldTask.cancel(); - tasks.put(event.getBlock(), runTask(event.getBlock())); + BukkitTask oldTask = tasks.remove(event.getBlock()); + if (oldTask != null) oldTask.cancel(); + tasks.put(event.getBlock(), runTask(event.getBlock())); - } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPlace(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; - BukkitTask oldTask = tasks.remove(event.getBlock()); - if (oldTask != null) oldTask.cancel(); - } + BukkitTask oldTask = tasks.remove(event.getBlock()); + if (oldTask != null) oldTask.cancel(); + } - private BukkitTask runTask(@Nonnull Block block) { - return Bukkit.getScheduler().runTaskLater(plugin, () -> block.setType(Material.AIR), getValue() * 20L); - } + private BukkitTask runTask(@Nonnull Block block) { + return Bukkit.getScheduler().runTaskLater(plugin, () -> block.setType(Material.AIR), getValue() * 20L); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java index 253ff1834..c2e0120a4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java @@ -18,90 +18,90 @@ public class ChunkDeconstructionChallenge extends TimedChallenge { - public ChunkDeconstructionChallenge() { - super(MenuType.CHALLENGES, 1, 60, 20); - setCategory(SettingCategory.WORLD); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_PICKAXE, Message.forName("item-chunk-deconstruction-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); - } - - @Override - protected int getSecondsUntilNextActivation() { - return getValue(); - } - - @Override - protected void onTimeActivation() { - if (ChallengeAPI.isWorldInUse()) return; - - for (Chunk chunk : getChunksToDeconstruct()) { - if (!chunk.isLoaded()) continue; - deconstructChunk(chunk); - } - - restartTimer(); - } - - private void deconstructChunk(@Nonnull Chunk chunk) { - - for (int x = 0; x < 16; x++) { - int finalX = x; - Bukkit.getScheduler().runTask(plugin, () -> { - for (int z = 0; z < 16; z++) { - deconstructAtLocation(chunk.getBlock(finalX, 0, z)); - } - }); - } - - } - - private void deconstructAtLocation(@Nonnull Block block) { - Block lowestBreakableBlock = getLowestBreakableBlock(block); - if (lowestBreakableBlock == null) return; - - lowestBreakableBlock.setType(Material.AIR, true); - } - - @Nullable - private Block getLowestBreakableBlock(@Nonnull Block block) { - Location location = block.getLocation(); - location.setY(block.getWorld().getMaxHeight()); - - while (location.getY() >= BukkitReflectionUtils.getMinHeight(block.getWorld()) && !isBreakable(location.getBlock())) { - location.subtract(0, 1, 0); - } - - Block currentBlock = location.getBlock(); - return currentBlock.getType() == Material.BEDROCK || currentBlock.isLiquid() ? null : location.getBlock(); - } - - private boolean isBreakable(@Nonnull Block block) { - return block.getType() != Material.BEDROCK && !BukkitReflectionUtils.isAir(block.getType()) && !block.isLiquid(); - } - - private List getChunksToDeconstruct() { - return new ListBuilder().fill(builder -> - Bukkit.getOnlinePlayers().forEach(player -> { - if (player.getGameMode() == GameMode.SPECTATOR || player.getGameMode() == GameMode.CREATIVE) - return; - builder.addIfNotContains(player.getLocation().getChunk()); - }) - ).build(); - } + public ChunkDeconstructionChallenge() { + super(MenuType.CHALLENGES, 1, 60, 20); + setCategory(SettingCategory.WORLD); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIAMOND_PICKAXE, Message.forName("item-chunk-deconstruction-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue(); + } + + @Override + protected void onTimeActivation() { + if (ChallengeAPI.isWorldInUse()) return; + + for (Chunk chunk : getChunksToDeconstruct()) { + if (!chunk.isLoaded()) continue; + deconstructChunk(chunk); + } + + restartTimer(); + } + + private void deconstructChunk(@Nonnull Chunk chunk) { + + for (int x = 0; x < 16; x++) { + int finalX = x; + Bukkit.getScheduler().runTask(plugin, () -> { + for (int z = 0; z < 16; z++) { + deconstructAtLocation(chunk.getBlock(finalX, 0, z)); + } + }); + } + + } + + private void deconstructAtLocation(@Nonnull Block block) { + Block lowestBreakableBlock = getLowestBreakableBlock(block); + if (lowestBreakableBlock == null) return; + + lowestBreakableBlock.setType(Material.AIR, true); + } + + @Nullable + private Block getLowestBreakableBlock(@Nonnull Block block) { + Location location = block.getLocation(); + location.setY(block.getWorld().getMaxHeight()); + + while (location.getY() >= BukkitReflectionUtils.getMinHeight(block.getWorld()) && !isBreakable(location.getBlock())) { + location.subtract(0, 1, 0); + } + + Block currentBlock = location.getBlock(); + return currentBlock.getType() == Material.BEDROCK || currentBlock.isLiquid() ? null : location.getBlock(); + } + + private boolean isBreakable(@Nonnull Block block) { + return block.getType() != Material.BEDROCK && !BukkitReflectionUtils.isAir(block.getType()) && !block.isLiquid(); + } + + private List getChunksToDeconstruct() { + return new ListBuilder().fill(builder -> + Bukkit.getOnlinePlayers().forEach(player -> { + if (player.getGameMode() == GameMode.SPECTATOR || player.getGameMode() == GameMode.CREATIVE) + return; + builder.addIfNotContains(player.getLocation().getChunk()); + }) + ).build(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java index 82e68bb0f..b730729d6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import java.util.HashMap; import net.anweisen.utilities.common.collection.pair.Tuple; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; @@ -8,11 +7,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.World; +import org.bukkit.*; import org.bukkit.World.Environment; import org.bukkit.block.Block; import org.bukkit.boss.BarColor; @@ -24,6 +19,8 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.HashMap; + public class ChunkDeletionChallenge extends SettingModifier { private final HashMap> chunks = new HashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java index 1252c24b0..94ec501fe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java @@ -18,45 +18,45 @@ public class FloorIsLavaChallenge extends SettingModifier { - public FloorIsLavaChallenge() { - super(MenuType.CHALLENGES, 1, 60, 30); - setCategory(SettingCategory.WORLD); - } - - @EventHandler - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) - return; - if (event.getTo() == null) return; - if (!BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; - - Bukkit.getScheduler().runTaskLater(plugin, () -> { - createMagmaFloor(event.getTo()); - }, getValue() * 20L); - } - - private void createMagmaFloor(@Nonnull Location to) { - BlockUtils.setBlockNatural(BlockUtils.getBlockBelow(to, 0.6), Material.MAGMA_BLOCK, true); - Bukkit.getScheduler().runTaskLater(plugin, () -> { - createLavaFloor(to); - }, getValue() * 20L); - } - - private void createLavaFloor(@Nonnull Location to) { - BlockUtils.setBlockNatural(BlockUtils.getBlockBelow(to), Material.LAVA, true); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MAGMA_BLOCK, Message.forName("item-floor-lava-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } + public FloorIsLavaChallenge() { + super(MenuType.CHALLENGES, 1, 60, 30); + setCategory(SettingCategory.WORLD); + } + + @EventHandler + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) + return; + if (event.getTo() == null) return; + if (!BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; + + Bukkit.getScheduler().runTaskLater(plugin, () -> { + createMagmaFloor(event.getTo()); + }, getValue() * 20L); + } + + private void createMagmaFloor(@Nonnull Location to) { + BlockUtils.setBlockNatural(BlockUtils.getBlockBelow(to, 0.6), Material.MAGMA_BLOCK, true); + Bukkit.getScheduler().runTaskLater(plugin, () -> { + createLavaFloor(to); + }, getValue() * 20L); + } + + private void createLavaFloor(@Nonnull Location to) { + BlockUtils.setBlockNatural(BlockUtils.getBlockBelow(to), Material.LAVA, true); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.MAGMA_BLOCK, Message.forName("item-floor-lava-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java index fb0e5b290..93c033f50 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java @@ -27,80 +27,80 @@ @Since("2.0") public class IceFloorChallenge extends Setting { - private final List ignoredPlayers = new ArrayList<>(); - - public IceFloorChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PACKED_ICE, Message.forName("item-ice-floor-challenge")); - } - - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - bossbar.setTitle(Message.forName("bossbar-ice-floor").asString(ignoreIce(player) ? Message.forName("disabled") : Message.forName("enabled"))); - bossbar.setColor(ignoreIce(player) ? BarColor.RED : BarColor.GREEN); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { - Player player = event.getPlayer(); - if (!shouldExecuteEffect()) return; - if (ignorePlayer(player)) return; - if (ignoredPlayers.contains(player)) return; - createIceFloorForPlayer(player); - } - - private void createIceFloorForPlayer(@Nonnull Player player) { - Block middleBlock = player.getLocation().clone().subtract(0, 1, 0).getBlock(); - createIceFloor(middleBlock); - } - - private void createIceFloor(@Nonnull Block middleBlock) { - - for (int x = -1; x <= 1; x++) { - for (int z = -1; z <= 1; z++) { - Location iceLocation = middleBlock.getLocation().add(x, 0, z); - Block iceBlock = iceLocation.getBlock(); - if (iceBlock.getType().isSolid()) continue; - if (!BukkitReflectionUtils.isAir(iceBlock.getType())) { - ChallengeHelper.breakBlock(iceBlock, new ItemStack(Material.AIR)); - } - iceBlock.setType(Material.PACKED_ICE); - } - } - - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onSneak(@Nonnull PlayerToggleSneakEvent event) { - if (!shouldExecuteEffect()) return; - if (!event.isSneaking()) return; - if (ignorePlayer(event.getPlayer())) return; - if (ignoredPlayers.contains(event.getPlayer())) { - ignoredPlayers.remove(event.getPlayer()); - event.getPlayer().setVelocity(new Vector(0, 0, 0)); - createIceFloorForPlayer(event.getPlayer()); - } else { - ignoredPlayers.add(event.getPlayer()); - } - bossbar.update(event.getPlayer()); - } - - private boolean ignoreIce(@Nonnull Player player) { - return ignoredPlayers.contains(player); - } + private final List ignoredPlayers = new ArrayList<>(); + + public IceFloorChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.WORLD); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.PACKED_ICE, Message.forName("item-ice-floor-challenge")); + } + + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + bossbar.setTitle(Message.forName("bossbar-ice-floor").asString(ignoreIce(player) ? Message.forName("disabled") : Message.forName("enabled"))); + bossbar.setColor(ignoreIce(player) ? BarColor.RED : BarColor.GREEN); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + Player player = event.getPlayer(); + if (!shouldExecuteEffect()) return; + if (ignorePlayer(player)) return; + if (ignoredPlayers.contains(player)) return; + createIceFloorForPlayer(player); + } + + private void createIceFloorForPlayer(@Nonnull Player player) { + Block middleBlock = player.getLocation().clone().subtract(0, 1, 0).getBlock(); + createIceFloor(middleBlock); + } + + private void createIceFloor(@Nonnull Block middleBlock) { + + for (int x = -1; x <= 1; x++) { + for (int z = -1; z <= 1; z++) { + Location iceLocation = middleBlock.getLocation().add(x, 0, z); + Block iceBlock = iceLocation.getBlock(); + if (iceBlock.getType().isSolid()) continue; + if (!BukkitReflectionUtils.isAir(iceBlock.getType())) { + ChallengeHelper.breakBlock(iceBlock, new ItemStack(Material.AIR)); + } + iceBlock.setType(Material.PACKED_ICE); + } + } + + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onSneak(@Nonnull PlayerToggleSneakEvent event) { + if (!shouldExecuteEffect()) return; + if (!event.isSneaking()) return; + if (ignorePlayer(event.getPlayer())) return; + if (ignoredPlayers.contains(event.getPlayer())) { + ignoredPlayers.remove(event.getPlayer()); + event.getPlayer().setVelocity(new Vector(0, 0, 0)); + createIceFloorForPlayer(event.getPlayer()); + } else { + ignoredPlayers.add(event.getPlayer()); + } + bossbar.update(event.getPlayer()); + } + + private boolean ignoreIce(@Nonnull Player player) { + return ignoredPlayers.contains(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java index 921f74194..5a66768cb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java @@ -37,309 +37,309 @@ @ExcludeFromRandomChallenges public class LevelBorderChallenge extends Setting { - private final Map worldCenters = new HashMap<>(); - private final Map playerWorldBorders = new HashMap<>(); - private final Map packetBorders = new HashMap<>(); - - private final boolean useAPI = MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_19); - - private UUID bestPlayerUUID = null; - private int bestPlayerLevel = 0; - - public LevelBorderChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @Override - protected void onEnable() { - for (World world : ChallengeAPI.getGameWorlds()) { - if(useAPI) { - playerWorldBorders.put(world, Bukkit.createWorldBorder()); - } else { - packetBorders.put(world, NMSProvider.createPacketBorder(world)); - } - } - - bossbar.setContent((bar, player) -> { - bar.setTitle(Message.forName("bossbar-level-border").asString(bestPlayerLevel)); - }); - bossbar.show(); - updateBorderSize(false); - worldCenters.put(ChallengeAPI.getGameWorld(World.Environment.NORMAL), getDefaultWorldSpawn()); - } - - @Override - protected void onDisable() { - borderReset(); - bossbar.hide(); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENCHANTING_TABLE, Message.forName("item-level-border-challenges")); + private final Map worldCenters = new HashMap<>(); + private final Map playerWorldBorders = new HashMap<>(); + private final Map packetBorders = new HashMap<>(); + + private final boolean useAPI = MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_19); + + private UUID bestPlayerUUID = null; + private int bestPlayerLevel = 0; + + public LevelBorderChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.WORLD); + } + + @Override + protected void onEnable() { + for (World world : ChallengeAPI.getGameWorlds()) { + if (useAPI) { + playerWorldBorders.put(world, Bukkit.createWorldBorder()); + } else { + packetBorders.put(world, NMSProvider.createPacketBorder(world)); + } } - public void checkBorderSize(boolean animate) { - Player currentBestPlayer = bestPlayerUUID != null ? Bukkit.getPlayer(bestPlayerUUID) : null; - - for (Player player : ChallengeAPI.getIngamePlayers()) { - int level = player.getLevel(); - - if (bestPlayerUUID == null || currentBestPlayer == null) { - bestPlayerLevel = level; - bestPlayerUUID = player.getUniqueId(); - // Checks if the player is better than the saved level or if online the current player level. - // Checking with the player instance is required to fix issues with dying and the level of the best player being 0. - } else if (level > bestPlayerLevel || level > currentBestPlayer.getLevel()) { - bestPlayerLevel = level; - bestPlayerUUID = player.getUniqueId(); - } else if (player.getUniqueId().equals(bestPlayerUUID)) { - bestPlayerLevel = level; - } - } - - updateBorderSize(animate); - bossbar.update(); + bossbar.setContent((bar, player) -> { + bar.setTitle(Message.forName("bossbar-level-border").asString(bestPlayerLevel)); + }); + bossbar.show(); + updateBorderSize(false); + worldCenters.put(ChallengeAPI.getGameWorld(World.Environment.NORMAL), getDefaultWorldSpawn()); + } + + @Override + protected void onDisable() { + borderReset(); + bossbar.hide(); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ENCHANTING_TABLE, Message.forName("item-level-border-challenges")); + } + + public void checkBorderSize(boolean animate) { + Player currentBestPlayer = bestPlayerUUID != null ? Bukkit.getPlayer(bestPlayerUUID) : null; + + for (Player player : ChallengeAPI.getIngamePlayers()) { + int level = player.getLevel(); + + if (bestPlayerUUID == null || currentBestPlayer == null) { + bestPlayerLevel = level; + bestPlayerUUID = player.getUniqueId(); + // Checks if the player is better than the saved level or if online the current player level. + // Checking with the player instance is required to fix issues with dying and the level of the best player being 0. + } else if (level > bestPlayerLevel || level > currentBestPlayer.getLevel()) { + bestPlayerLevel = level; + bestPlayerUUID = player.getUniqueId(); + } else if (player.getUniqueId().equals(bestPlayerUUID)) { + bestPlayerLevel = level; + } } - @ScheduledTask(ticks = 100, async = false, timerPolicy = TimerPolicy.STARTED) - public void checkBorderSize() { - checkBorderSize(true); + updateBorderSize(animate); + bossbar.update(); + } + + @ScheduledTask(ticks = 100, async = false, timerPolicy = TimerPolicy.STARTED) + public void checkBorderSize() { + checkBorderSize(true); + } + + @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.STARTED) + public void playerSpawnTeleport() { + broadcastFiltered(player -> { + if (player.isDead()) return; + World world = player.getWorld(); + if (isOutsideBorder(player.getLocation())) { + teleportInsideBorder(world, player); + } + }); + } + + public boolean isOutsideBorder(Location location) { + double size = bestPlayerLevel + 1; + Location center = worldCenters.get(location.getWorld()); + if (center == null) return false; + double x = Math.abs(location.getX()) - Math.abs(center.getX()); + double z = Math.abs(location.getZ()) - Math.abs(center.getZ()); + return Math.abs(x) > size || Math.abs(z) > size; + } + + private Location getCenter(World world) { + Location center; + if (useAPI) { + center = playerWorldBorders.get(world).getCenter().subtract(0.5, 0, 0.5); + center.setY(world.getHighestBlockYAt((int) center.getX(), (int) center.getZ())); + } else { + PacketBorder packetBorder = packetBorders.get(world); + double centerX = packetBorder.getCenterX(); + double centerZ = packetBorder.getCenterZ(); + center = new Location(world, centerX, world.getHighestBlockYAt((int) centerX, (int) centerZ), centerZ); } - - @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.STARTED) - public void playerSpawnTeleport() { - broadcastFiltered(player -> { - if (player.isDead()) return; - World world = player.getWorld(); - if (isOutsideBorder(player.getLocation())) { - teleportInsideBorder(world, player); - } - }); + return center; + } + + public void teleportInsideBorder(@NotNull World world, Player player) { + Location center = getCenter(world).clone(); + center.setWorld(world); + if (world.getEnvironment() != World.Environment.NORMAL) { + player.teleport(center); + } else { + player.teleport(center.add(0.5, 1, 0.5)); } + } - public boolean isOutsideBorder(Location location) { - double size = bestPlayerLevel + 1; - Location center = worldCenters.get(location.getWorld()); - if (center == null) return false; - double x = Math.abs(location.getX()) - Math.abs(center.getX()); - double z = Math.abs(location.getZ()) - Math.abs(center.getZ()); - return Math.abs(x) > size || Math.abs(z) > size; + private Location getDefaultWorldSpawn() { + World world = ChallengeAPI.getGameWorld(World.Environment.NORMAL); + if (worldCenters.containsKey(world)) { + return worldCenters.get(world); } - - private Location getCenter(World world) { - Location center; - if (useAPI) { - center = playerWorldBorders.get(world).getCenter().subtract(0.5, 0, 0.5); - center.setY(world.getHighestBlockYAt((int) center.getX(), (int) center.getZ())); - } else { - PacketBorder packetBorder = packetBorders.get(world); - double centerX = packetBorder.getCenterX(); - double centerZ = packetBorder.getCenterZ(); - center = new Location(world, centerX, world.getHighestBlockYAt((int) centerX, (int) centerZ), centerZ); - } - return center; + Location location = world.getSpawnLocation(); + location.setX(location.getBlockX() + 0.5); + location.setZ(location.getBlockZ() + 0.5); + return location; + } + + private void updateBorderSize(boolean animate) { + for (World world : ChallengeAPI.getGameWorlds()) { + if (world.getPlayers().isEmpty()) { + continue; + } + updateBorderSize(world, animate); } - - public void teleportInsideBorder(@NotNull World world, Player player) { - Location center = getCenter(world).clone(); - center.setWorld(world); - if (world.getEnvironment() != World.Environment.NORMAL) { - player.teleport(center); - } else { - player.teleport(center.add(0.5, 1, 0.5)); - } + } + + private void updateBorderSize(@Nonnull World world, boolean animate) { + Location location = worldCenters.get(world); + if (location == null) return; + int newSize = bestPlayerLevel + 1; + updateBorder(world, location, newSize == 0 ? 1 : newSize, animate); + for (Player player : world.getPlayers()) { + sendBorder(player); } + } - private Location getDefaultWorldSpawn() { - World world = ChallengeAPI.getGameWorld(World.Environment.NORMAL); - if (worldCenters.containsKey(world)) { - return worldCenters.get(world); - } - Location location = world.getSpawnLocation(); - location.setX(location.getBlockX() + 0.5); - location.setZ(location.getBlockZ() + 0.5); - return location; + public void borderReset() { + if (useAPI) { + playerWorldBorders.values().forEach(WorldBorder::reset); + } else { + broadcast(player -> packetBorders.get(player.getWorld()).reset(player)); } - - private void updateBorderSize(boolean animate) { - for (World world : ChallengeAPI.getGameWorlds()) { - if (world.getPlayers().isEmpty()) { - continue; - } - updateBorderSize(world, animate); - } + } + + @TimerTask(status = TimerStatus.RUNNING, async = false) + public void onTimerStart() { + if (!isEnabled()) return; + checkBorderSize(false); + playerSpawnTeleport(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onLevelChange(@Nonnull PlayerLevelChangeEvent event) { + if (!shouldExecuteEffect()) return; + checkBorderSize(true); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + Bukkit.getScheduler().runTaskLater(plugin, () -> checkBorderSize(false), 1); + playerSpawnTeleport(); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerLeave(@Nonnull PlayerQuitEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + Bukkit.getScheduler().runTaskLater(plugin, () -> checkBorderSize(false), 1); + } + + /** + * Teleports the player back inside border if spawnpoint is outside of it. + * Will rarely occur by beds since minecraft blocks bed respawn outside the border but + * because of the random spawning mechanic at the world spawn. + */ + @EventHandler(priority = EventPriority.HIGH) + public void onRespawn(@Nonnull PlayerRespawnEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + Bukkit.getScheduler().runTaskLater(plugin, () -> { + checkBorderSize(false); + playerSpawnTeleport(); + }, 1); + } + + /** + * Execute level change event when dying instead of respawning like spigot does it + */ + @EventHandler(priority = EventPriority.HIGH) + public void onDeath(@Nonnull PlayerDeathEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getEntity())) return; + PlayerLevelChangeEvent lvlEvent = new PlayerLevelChangeEvent( + event.getEntity(), event.getEntity().getLevel(), 0); + event.getEntity().setLevel(0); + onLevelChange(lvlEvent); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getDamager().getType() != EntityType.PLAYER) return; + if (!event.isCancelled()) return; + if (isOutsideBorder(event.getEntity().getLocation()) && + !isOutsideBorder(event.getDamager().getLocation())) { + event.setCancelled(false); } - - private void updateBorderSize(@Nonnull World world, boolean animate) { - Location location = worldCenters.get(world); - if (location == null) return; - int newSize = bestPlayerLevel + 1; - updateBorder(world, location, newSize == 0 ? 1 : newSize, animate); - for (Player player : world.getPlayers()) { - sendBorder(player); - } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onTeleport(@Nonnull PlayerTeleportEvent event) { + if (event.getTo() == null) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getCause() != PlayerTeleportEvent.TeleportCause.NETHER_PORTAL && + event.getCause() != PlayerTeleportEvent.TeleportCause.END_PORTAL) return; + World world = event.getTo().getWorld(); + if (world == null) return; + if (world == Challenges.getInstance().getWorldManager().getExtraWorld()) return; + Location location = event.getTo().getBlock().getLocation().add(0.5, 0, 0.5); + if (!worldCenters.containsKey(world)) worldCenters.put(world, location); + updateBorderSize(world, false); + } + + @Override + public void loadGameState(@NotNull Document document) { + bestPlayerLevel = document.getInt("level"); + String uuid = document.getString("uuid"); + if (uuid != null) { + bestPlayerUUID = UUID.fromString(uuid); } - - public void borderReset() { - if (useAPI) { - playerWorldBorders.values().forEach(WorldBorder::reset); - } else { - broadcast(player -> packetBorders.get(player.getWorld()).reset(player)); - } - } - - @TimerTask(status = TimerStatus.RUNNING, async = false) - public void onTimerStart() { - if (!isEnabled()) return; - checkBorderSize(false); - playerSpawnTeleport(); + worldCenters.clear(); + Document worlds = document.getDocument("worlds"); + for (String worldName : worlds.keys()) { + World world = Bukkit.getWorld(worldName); + if (world == null) continue; + worldCenters.put(world, worlds.getInstance(worldName, Location.class)); } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onLevelChange(@Nonnull PlayerLevelChangeEvent event) { - if (!shouldExecuteEffect()) return; - checkBorderSize(true); + if (isEnabled()) { + checkBorderSize(false); } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - Bukkit.getScheduler().runTaskLater(plugin, () -> checkBorderSize(false), 1); - playerSpawnTeleport(); + } + + @Override + public void writeGameState(@NotNull Document document) { + document.set("level", bestPlayerLevel); + GsonDocument doc = new GsonDocument(); + worldCenters.forEach((world, location) -> doc.set(world.getName(), location)); + document.set("worlds", doc); + document.set("uuid", bestPlayerUUID); + } + + private void updateBorder(World world, Location center, int size, boolean animate) { + if (useAPI) { + WorldBorder border = playerWorldBorders.get(world); + border.setCenter(center); + double x = center.getX(); + double z = center.getZ(); + // fix bug that causes border to be misplaced + if (world.getEnvironment() == World.Environment.NETHER) { + x *= 8; + z *= 8; + } + border.setCenter(x, z); + if (animate) { + border.setSize(size, 1); + } else { + border.setSize(size); + } + border.setWarningDistance(0); + border.setWarningTime(0); + } else { + PacketBorder border = packetBorders.get(world); + border.setCenter(center.getX(), center.getZ()); + if (animate) { + border.setSize(size, 1); + } else { + border.setSize(size); + } + border.setWarningDistance(0); + border.setWarningTime(0); } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerLeave(@Nonnull PlayerQuitEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - Bukkit.getScheduler().runTaskLater(plugin, () -> checkBorderSize(false), 1); - } - - /** - * Teleports the player back inside border if spawnpoint is outside of it. - * Will rarely occur by beds since minecraft blocks bed respawn outside the border but - * because of the random spawning mechanic at the world spawn. - */ - @EventHandler(priority = EventPriority.HIGH) - public void onRespawn(@Nonnull PlayerRespawnEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - Bukkit.getScheduler().runTaskLater(plugin, () -> { - checkBorderSize(false); - playerSpawnTeleport(); - }, 1); - } - - /** - * Execute level change event when dying instead of respawning like spigot does it - */ - @EventHandler(priority = EventPriority.HIGH) - public void onDeath(@Nonnull PlayerDeathEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getEntity())) return; - PlayerLevelChangeEvent lvlEvent = new PlayerLevelChangeEvent( - event.getEntity(), event.getEntity().getLevel(), 0); - event.getEntity().setLevel(0); - onLevelChange(lvlEvent); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getDamager().getType() != EntityType.PLAYER) return; - if (!event.isCancelled()) return; - if (isOutsideBorder(event.getEntity().getLocation()) && - !isOutsideBorder(event.getDamager().getLocation())) { - event.setCancelled(false); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onTeleport(@Nonnull PlayerTeleportEvent event) { - if (event.getTo() == null) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getCause() != PlayerTeleportEvent.TeleportCause.NETHER_PORTAL && - event.getCause() != PlayerTeleportEvent.TeleportCause.END_PORTAL) return; - World world = event.getTo().getWorld(); - if (world == null) return; - if (world == Challenges.getInstance().getWorldManager().getExtraWorld()) return; - Location location = event.getTo().getBlock().getLocation().add(0.5, 0, 0.5); - if (!worldCenters.containsKey(world)) worldCenters.put(world, location); - updateBorderSize(world, false); - } - - @Override - public void loadGameState(@NotNull Document document) { - bestPlayerLevel = document.getInt("level"); - String uuid = document.getString("uuid"); - if (uuid != null) { - bestPlayerUUID = UUID.fromString(uuid); - } - worldCenters.clear(); - Document worlds = document.getDocument("worlds"); - for (String worldName : worlds.keys()) { - World world = Bukkit.getWorld(worldName); - if (world == null) continue; - worldCenters.put(world, worlds.getInstance(worldName, Location.class)); - } - - if (isEnabled()) { - checkBorderSize(false); - } - } - - @Override - public void writeGameState(@NotNull Document document) { - document.set("level", bestPlayerLevel); - GsonDocument doc = new GsonDocument(); - worldCenters.forEach((world, location) -> doc.set(world.getName(), location)); - document.set("worlds", doc); - document.set("uuid", bestPlayerUUID); - } - - private void updateBorder(World world, Location center, int size, boolean animate) { - if (useAPI) { - WorldBorder border = playerWorldBorders.get(world); - border.setCenter(center); - double x = center.getX(); - double z = center.getZ(); - // fix bug that causes border to be misplaced - if (world.getEnvironment() == World.Environment.NETHER) { - x *= 8; - z *= 8; - } - border.setCenter(x, z); - if (animate) { - border.setSize(size, 1); - } else { - border.setSize(size); - } - border.setWarningDistance(0); - border.setWarningTime(0); - } else { - PacketBorder border = packetBorders.get(world); - border.setCenter(center.getX(), center.getZ()); - if (animate) { - border.setSize(size, 1); - } else { - border.setSize(size); - } - border.setWarningDistance(0); - border.setWarningTime(0); - } - } - - private void sendBorder(@Nonnull Player player) { - if (useAPI) { - WorldBorder border = playerWorldBorders.get(player.getWorld()); - player.setWorldBorder(border); - } else { - packetBorders.get(player.getWorld()).send(player, PacketBorder.UpdateType.values()); - } + } + + private void sendBorder(@Nonnull Player player) { + if (useAPI) { + WorldBorder border = playerWorldBorders.get(player.getWorld()); + player.setWorldBorder(border); + } else { + packetBorders.get(player.getWorld()).send(player, PacketBorder.UpdateType.values()); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index 11352c5de..72ab023d9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -36,7 +36,6 @@ import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerToggleSneakEvent; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.projectiles.ProjectileSource; import org.bukkit.util.RayTraceResult; import org.bukkit.util.Vector; @@ -48,322 +47,322 @@ @Since("2.0.2") public class LoopChallenge extends Setting { - private static final Map loops = new HashMap<>(); - - public LoopChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.LEAD, Message.forName("item-loop-challenge")); - } + private static final Map loops = new HashMap<>(); + + public LoopChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.WORLD); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.LEAD, Message.forName("item-loop-challenge")); + } - @ScheduledTask(ticks = 1, async = false) - public void onTick() { - long currentTimeMillis = System.currentTimeMillis(); + @ScheduledTask(ticks = 1, async = false) + public void onTick() { + long currentTimeMillis = System.currentTimeMillis(); - for (Entry entry : new ArrayList<>(loops.entrySet())) { - - if (entry.getValue() + 1000 <= currentTimeMillis) { - entry.getKey().execute(); - loops.put(entry.getKey(), currentTimeMillis); - } - - } - - } - - @TimerTask(status = TimerStatus.PAUSED, async = false, playerPolicy = PlayerCountPolicy.ALWAYS) - public void onPause() { - clearLoops(); - } - - private void clearLoops() { - if (loops.isEmpty()) return; - broadcast(player -> new SoundSample().addSound(Sound.ENTITY_ITEM_BREAK, 0.5f).play(player)); - Message.forName("loops-cleared").broadcast(Prefix.CHALLENGES, loops.size()); - loops.clear(); - } - - private void createLoop(@Nonnull Loop loop) { - loops.put(loop, System.currentTimeMillis()); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onSneak(@Nonnull PlayerToggleSneakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (!event.isSneaking()) return; - clearLoops(); - } - - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onProjectileLaunch(@Nonnull ProjectileLaunchEvent event) { - if (!shouldExecuteEffect()) return; - ProjectileSource shooter = event.getEntity().getShooter(); - if (shooter == null) return; - if (shooter instanceof Player && ignorePlayer(((Player) shooter))) return; - createLoop(new ProjectileLaunchLoop(event)); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof LivingEntity)) return; - double damage = event.getFinalDamage() + event.getDamage(DamageModifier.ABSORPTION); - if (damage == 0) return; - createLoop(new EntityDamageLoop(((LivingEntity) event.getEntity()), event.getCause(), damage)); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - createLoop(new BlockPlaceLoop(event.getBlock().getType(), event.getPlayer(), event.getBlockAgainst().getFace(event.getBlock()), event.getBlock())); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - Player player = event.getPlayer(); - if (ignorePlayer(player)) return; - - - RayTraceResult result = player.getWorld().rayTraceBlocks(player.getEyeLocation(), player.getLocation().getDirection(), 5); - if (result == null) return; - if (result.getHitBlockFace() == null) return; - - - createLoop(new BlockBreakLoop(player.getInventory().getItemInMainHand(), player, result.getHitBlockFace().getOppositeFace(), event.getBlock())); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull PlayerDropItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - createLoop(new DropLoop(event.getItemDrop().getItemStack(), event.getPlayer())); - } - - private interface Loop { - - void execute(); - - default void cancel() { - loops.remove(this); - } - - } - - private static class ProjectileLaunchLoop implements Loop { - - private final Vector launchVelocity; - private final Location launchLocation; - private final EntityType entityType; - - public ProjectileLaunchLoop(ProjectileLaunchEvent event) { - this.launchVelocity = event.getEntity().getVelocity(); - this.launchLocation = event.getLocation(); - this.entityType = event.getEntityType(); - } - - @Override - public void execute() { - if (launchLocation.getWorld() == null) return; - Projectile projectile = (Projectile) launchLocation.getWorld().spawnEntity(launchLocation, entityType); - projectile.setVelocity(launchVelocity); - if (projectile instanceof Arrow) { - ((Arrow) projectile).setPickupStatus(PickupStatus.DISALLOWED); - } - } - - } - - private static class EntityDamageLoop implements Loop { - - private final LivingEntity entity; - private final double damage; - - public EntityDamageLoop(LivingEntity entity, DamageCause cause, double damage) { - this.entity = entity; - this.damage = damage; - } - - @Override - public void execute() { - if (entity.isDead()) { - cancel(); - return; - } - if (entity instanceof Player && ignorePlayer(((Player) entity))) return; - entity.damage(damage); - } - } - - private static class BlockPlaceLoop implements Loop { - - private final Material material; - private final Player player; - private final BlockFace blockFace; - private Block currentBlock; - - public BlockPlaceLoop(Material material, Player player, BlockFace blockFace, Block currentBlock) { - this.material = material; - this.player = player; - this.blockFace = blockFace; - this.currentBlock = currentBlock; - } - - @Override - public void execute() { - if (ignorePlayer(player)) return; - - currentBlock = currentBlock.getRelative(blockFace); - - if (currentBlock.getY() > currentBlock.getWorld().getMaxHeight() || currentBlock.getY() < BukkitReflectionUtils.getMinHeight(currentBlock.getWorld())) { - cancel(); - return; - } else if (!BukkitReflectionUtils.isAir(currentBlock.getType()) && currentBlock.getType().isSolid()) { - return; - } else if (!decreaseMaterial()) { - cancel(); - return; - } - - currentBlock.setType(material); - } - - private boolean decreaseMaterial() { - ItemStack item = Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).filter(itemStack -> itemStack.getType() == material).findFirst().orElse(null); - if (item == null) return false; - item.setAmount(item.getAmount() - 1); - return true; - } - - } - - private static class BlockBreakLoop implements Loop { - - private final Player player; - private final BlockFace blockFace; - private ItemStack itemStack; - private Block currentBlock; - - public BlockBreakLoop(ItemStack itemStack, Player player, BlockFace blockFace, Block currentBlock) { - this.itemStack = itemStack; - this.player = player; - this.blockFace = blockFace; - this.currentBlock = currentBlock; - } - - @Override - public void execute() { - if (ignorePlayer(player)) return; - - currentBlock = currentBlock.getRelative(blockFace); - - if (currentBlock.getY() > currentBlock.getWorld().getMaxHeight() || currentBlock.getY() < BukkitReflectionUtils.getMinHeight(currentBlock.getWorld())) { - cancel(); - return; - } else if (BukkitReflectionUtils.isAir(currentBlock.getType())) { - return; - } else if (!decreaseDurability()) { - cancel(); - return; - } - - if (currentBlock.getType() == Material.BEDROCK) return; - - if (cantBeBroken(currentBlock, itemStack)) { - currentBlock.setType(Material.AIR); - return; - } - - - ChallengeHelper.breakBlock(currentBlock, itemStack, player.getInventory()); - } - - private boolean decreaseDurability() { - if (itemStack.getType() == Material.AIR) return true; - if (!isTool(itemStack)) return true; - - - itemStack = Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).filter(itemStack -> itemStack.isSimilar(this.itemStack)).findFirst().orElse(null); - if (itemStack == null) return false; - - if (itemStack.getItemMeta() == null) return true; - org.bukkit.inventory.meta.Damageable damageable = (org.bukkit.inventory.meta.Damageable) itemStack.getItemMeta(); - if (damageable == null) return false; - damageable.setDamage(damageable.getDamage() + 1); - itemStack.setItemMeta(damageable); - - for (int slot = 0; slot < player.getInventory().getSize(); slot++) { - ItemStack item = player.getInventory().getItem(slot); - if (item == null) continue; - if (!isTool(item)) continue; - if (item.getItemMeta() == null) continue; - if (((org.bukkit.inventory.meta.Damageable) item.getItemMeta()).getDamage() >= item.getType().getMaxDurability()) { - player.getInventory().setItem(slot, null); - } - } - - return true; - } - - private boolean isTool(@Nonnull ItemStack itemStack) { - if (itemStack.getItemMeta() != null) { - try { - Attribute attribute = AttributeWrapper.MAX_HEALTH; - Collection attributeModifiers = itemStack.getItemMeta().getAttributeModifiers(attribute); - return attributeModifiers == null || !attributeModifiers.isEmpty(); - - } catch (NullPointerException exception) { - return false; - } - } - return true; - } - - private boolean cantBeBroken(@Nonnull Block block, @Nonnull ItemStack tool) { - return block.getDrops(tool).isEmpty(); - } - - } - - private static class DropLoop implements Loop { - - private final ItemStack itemStack; - private final Player player; - - public DropLoop(ItemStack itemStack, Player player) { - itemStack = itemStack.clone(); - itemStack.setAmount(1); - this.itemStack = itemStack; - this.player = player; - } - - @Override - public void execute() { - if (ignorePlayer(player)) return; - - if (!decreaseItem()) { - cancel(); - return; - } - - InventoryUtils.dropItemByPlayer(player.getLocation(), itemStack); - } - - private boolean decreaseItem() { - ItemStack item = Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).filter(itemStack -> itemStack.isSimilar(this.itemStack)).findFirst().orElse(null); - if (item == null) return false; - item.setAmount(item.getAmount() - 1); - return true; - } - - } + for (Entry entry : new ArrayList<>(loops.entrySet())) { + + if (entry.getValue() + 1000 <= currentTimeMillis) { + entry.getKey().execute(); + loops.put(entry.getKey(), currentTimeMillis); + } + + } + + } + + @TimerTask(status = TimerStatus.PAUSED, async = false, playerPolicy = PlayerCountPolicy.ALWAYS) + public void onPause() { + clearLoops(); + } + + private void clearLoops() { + if (loops.isEmpty()) return; + broadcast(player -> new SoundSample().addSound(Sound.ENTITY_ITEM_BREAK, 0.5f).play(player)); + Message.forName("loops-cleared").broadcast(Prefix.CHALLENGES, loops.size()); + loops.clear(); + } + + private void createLoop(@Nonnull Loop loop) { + loops.put(loop, System.currentTimeMillis()); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onSneak(@Nonnull PlayerToggleSneakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (!event.isSneaking()) return; + clearLoops(); + } + + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onProjectileLaunch(@Nonnull ProjectileLaunchEvent event) { + if (!shouldExecuteEffect()) return; + ProjectileSource shooter = event.getEntity().getShooter(); + if (shooter == null) return; + if (shooter instanceof Player && ignorePlayer(((Player) shooter))) return; + createLoop(new ProjectileLaunchLoop(event)); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof LivingEntity)) return; + double damage = event.getFinalDamage() + event.getDamage(DamageModifier.ABSORPTION); + if (damage == 0) return; + createLoop(new EntityDamageLoop(((LivingEntity) event.getEntity()), event.getCause(), damage)); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + createLoop(new BlockPlaceLoop(event.getBlock().getType(), event.getPlayer(), event.getBlockAgainst().getFace(event.getBlock()), event.getBlock())); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + Player player = event.getPlayer(); + if (ignorePlayer(player)) return; + + + RayTraceResult result = player.getWorld().rayTraceBlocks(player.getEyeLocation(), player.getLocation().getDirection(), 5); + if (result == null) return; + if (result.getHitBlockFace() == null) return; + + + createLoop(new BlockBreakLoop(player.getInventory().getItemInMainHand(), player, result.getHitBlockFace().getOppositeFace(), event.getBlock())); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPlace(@Nonnull PlayerDropItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + createLoop(new DropLoop(event.getItemDrop().getItemStack(), event.getPlayer())); + } + + private interface Loop { + + void execute(); + + default void cancel() { + loops.remove(this); + } + + } + + private static class ProjectileLaunchLoop implements Loop { + + private final Vector launchVelocity; + private final Location launchLocation; + private final EntityType entityType; + + public ProjectileLaunchLoop(ProjectileLaunchEvent event) { + this.launchVelocity = event.getEntity().getVelocity(); + this.launchLocation = event.getLocation(); + this.entityType = event.getEntityType(); + } + + @Override + public void execute() { + if (launchLocation.getWorld() == null) return; + Projectile projectile = (Projectile) launchLocation.getWorld().spawnEntity(launchLocation, entityType); + projectile.setVelocity(launchVelocity); + if (projectile instanceof Arrow) { + ((Arrow) projectile).setPickupStatus(PickupStatus.DISALLOWED); + } + } + + } + + private static class EntityDamageLoop implements Loop { + + private final LivingEntity entity; + private final double damage; + + public EntityDamageLoop(LivingEntity entity, DamageCause cause, double damage) { + this.entity = entity; + this.damage = damage; + } + + @Override + public void execute() { + if (entity.isDead()) { + cancel(); + return; + } + if (entity instanceof Player && ignorePlayer(((Player) entity))) return; + entity.damage(damage); + } + } + + private static class BlockPlaceLoop implements Loop { + + private final Material material; + private final Player player; + private final BlockFace blockFace; + private Block currentBlock; + + public BlockPlaceLoop(Material material, Player player, BlockFace blockFace, Block currentBlock) { + this.material = material; + this.player = player; + this.blockFace = blockFace; + this.currentBlock = currentBlock; + } + + @Override + public void execute() { + if (ignorePlayer(player)) return; + + currentBlock = currentBlock.getRelative(blockFace); + + if (currentBlock.getY() > currentBlock.getWorld().getMaxHeight() || currentBlock.getY() < BukkitReflectionUtils.getMinHeight(currentBlock.getWorld())) { + cancel(); + return; + } else if (!BukkitReflectionUtils.isAir(currentBlock.getType()) && currentBlock.getType().isSolid()) { + return; + } else if (!decreaseMaterial()) { + cancel(); + return; + } + + currentBlock.setType(material); + } + + private boolean decreaseMaterial() { + ItemStack item = Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).filter(itemStack -> itemStack.getType() == material).findFirst().orElse(null); + if (item == null) return false; + item.setAmount(item.getAmount() - 1); + return true; + } + + } + + private static class BlockBreakLoop implements Loop { + + private final Player player; + private final BlockFace blockFace; + private ItemStack itemStack; + private Block currentBlock; + + public BlockBreakLoop(ItemStack itemStack, Player player, BlockFace blockFace, Block currentBlock) { + this.itemStack = itemStack; + this.player = player; + this.blockFace = blockFace; + this.currentBlock = currentBlock; + } + + @Override + public void execute() { + if (ignorePlayer(player)) return; + + currentBlock = currentBlock.getRelative(blockFace); + + if (currentBlock.getY() > currentBlock.getWorld().getMaxHeight() || currentBlock.getY() < BukkitReflectionUtils.getMinHeight(currentBlock.getWorld())) { + cancel(); + return; + } else if (BukkitReflectionUtils.isAir(currentBlock.getType())) { + return; + } else if (!decreaseDurability()) { + cancel(); + return; + } + + if (currentBlock.getType() == Material.BEDROCK) return; + + if (cantBeBroken(currentBlock, itemStack)) { + currentBlock.setType(Material.AIR); + return; + } + + + ChallengeHelper.breakBlock(currentBlock, itemStack, player.getInventory()); + } + + private boolean decreaseDurability() { + if (itemStack.getType() == Material.AIR) return true; + if (!isTool(itemStack)) return true; + + + itemStack = Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).filter(itemStack -> itemStack.isSimilar(this.itemStack)).findFirst().orElse(null); + if (itemStack == null) return false; + + if (itemStack.getItemMeta() == null) return true; + org.bukkit.inventory.meta.Damageable damageable = (org.bukkit.inventory.meta.Damageable) itemStack.getItemMeta(); + if (damageable == null) return false; + damageable.setDamage(damageable.getDamage() + 1); + itemStack.setItemMeta(damageable); + + for (int slot = 0; slot < player.getInventory().getSize(); slot++) { + ItemStack item = player.getInventory().getItem(slot); + if (item == null) continue; + if (!isTool(item)) continue; + if (item.getItemMeta() == null) continue; + if (((org.bukkit.inventory.meta.Damageable) item.getItemMeta()).getDamage() >= item.getType().getMaxDurability()) { + player.getInventory().setItem(slot, null); + } + } + + return true; + } + + private boolean isTool(@Nonnull ItemStack itemStack) { + if (itemStack.getItemMeta() != null) { + try { + Attribute attribute = AttributeWrapper.MAX_HEALTH; + Collection attributeModifiers = itemStack.getItemMeta().getAttributeModifiers(attribute); + return attributeModifiers == null || !attributeModifiers.isEmpty(); + + } catch (NullPointerException exception) { + return false; + } + } + return true; + } + + private boolean cantBeBroken(@Nonnull Block block, @Nonnull ItemStack tool) { + return block.getDrops(tool).isEmpty(); + } + + } + + private static class DropLoop implements Loop { + + private final ItemStack itemStack; + private final Player player; + + public DropLoop(ItemStack itemStack, Player player) { + itemStack = itemStack.clone(); + itemStack.setAmount(1); + this.itemStack = itemStack; + this.player = player; + } + + @Override + public void execute() { + if (ignorePlayer(player)) return; + + if (!decreaseItem()) { + cancel(); + return; + } + + InventoryUtils.dropItemByPlayer(player.getLocation(), itemStack); + } + + private boolean decreaseItem() { + ItemStack item = Arrays.stream(player.getInventory().getContents()).filter(Objects::nonNull).filter(itemStack -> itemStack.isSimilar(this.itemStack)).findFirst().orElse(null); + if (item == null) return false; + item.setAmount(item.getAmount() - 1); + return true; + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java index ebad2721a..6588aa766 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java @@ -37,268 +37,268 @@ @Since("2.1.1") public class RepeatInChunkChallenge extends Setting { - private final Map, BlockData>> changedBlocks = new HashMap<>(); - private final Set updatedChunks = new HashSet<>(); + private final Map, BlockData>> changedBlocks = new HashMap<>(); + private final Set updatedChunks = new HashSet<>(); - public RepeatInChunkChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-repeat-chunk-challenge")); - } + public RepeatInChunkChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.WORLD); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-repeat-chunk-challenge")); + } - @Override - public void writeGameState(@NotNull Document document) { + @Override + public void writeGameState(@NotNull Document document) { - GsonDocument changedDocument = new GsonDocument(); + GsonDocument changedDocument = new GsonDocument(); - for (Entry, BlockData>> entry : changedBlocks.entrySet()) { + for (Entry, BlockData>> entry : changedBlocks.entrySet()) { - List list = Lists.newLinkedList(); + List list = Lists.newLinkedList(); - for (Entry, BlockData> blockEntry : entry.getValue().entrySet()) { - GsonDocument blockDocument = new GsonDocument(); - Triple pos = blockEntry.getKey(); - blockDocument.set("x", pos.getFirst()); - blockDocument.set("y", pos.getSecond()); - blockDocument.set("z", pos.getThird()); - blockDocument.set("data", blockEntry.getValue().getAsString()); - list.add(blockDocument); - } - if (!list.isEmpty()) { - changedDocument.set(entry.getKey(), list); - } - } + for (Entry, BlockData> blockEntry : entry.getValue().entrySet()) { + GsonDocument blockDocument = new GsonDocument(); + Triple pos = blockEntry.getKey(); + blockDocument.set("x", pos.getFirst()); + blockDocument.set("y", pos.getSecond()); + blockDocument.set("z", pos.getThird()); + blockDocument.set("data", blockEntry.getValue().getAsString()); + list.add(blockDocument); + } + if (!list.isEmpty()) { + changedDocument.set(entry.getKey(), list); + } + } - document.set("changed-blocks", changedDocument); - } + document.set("changed-blocks", changedDocument); + } - @Override - public void loadGameState(@NotNull Document document) { - changedBlocks.clear(); + @Override + public void loadGameState(@NotNull Document document) { + changedBlocks.clear(); - Document changedDocument = document.getDocument("changed-blocks"); + Document changedDocument = document.getDocument("changed-blocks"); - for (World world : Bukkit.getWorlds()) { - List list = changedDocument.getDocumentList(world.getName()); - Map, BlockData> blockMap = changedBlocks.getOrDefault(world.getName(), new HashMap<>()); - changedBlocks.putIfAbsent(world.getName(), blockMap); + for (World world : Bukkit.getWorlds()) { + List list = changedDocument.getDocumentList(world.getName()); + Map, BlockData> blockMap = changedBlocks.getOrDefault(world.getName(), new HashMap<>()); + changedBlocks.putIfAbsent(world.getName(), blockMap); - for (Document blockDocument : list) { + for (Document blockDocument : list) { - int x = blockDocument.getInt("x"); - int y = blockDocument.getInt("y"); - int z = blockDocument.getInt("z"); + int x = blockDocument.getInt("x"); + int y = blockDocument.getInt("y"); + int z = blockDocument.getInt("z"); - if (x < 0 || z < 0) { - Logger.error("RepeatInChunkChallenge: Invalid Change Position: {}, {}, {}, {}", world.getName(), x, y, z); - continue; - } + if (x < 0 || z < 0) { + Logger.error("RepeatInChunkChallenge: Invalid Change Position: {}, {}, {}, {}", world.getName(), x, y, z); + continue; + } - Triple pos = new Triple<>(x, y, z); + Triple pos = new Triple<>(x, y, z); - String data = blockDocument.getString("data"); - BlockData blockData; - if (data != null) { - try { - blockData = Bukkit.createBlockData(data); - } catch (IllegalArgumentException exception) { - Logger.error("RepeatInChunkChallenge: Invalid Change Data: {}, {}, {}, {}, {}", world.getName(), x, y, z, data); - continue; - } - } else { - Logger.error("RepeatInChunkChallenge: Invalid Change Data: {}, {}, {}, {}, {}", world.getName(), x, y, z, null); - continue; - } + String data = blockDocument.getString("data"); + BlockData blockData; + if (data != null) { + try { + blockData = Bukkit.createBlockData(data); + } catch (IllegalArgumentException exception) { + Logger.error("RepeatInChunkChallenge: Invalid Change Data: {}, {}, {}, {}, {}", world.getName(), x, y, z, data); + continue; + } + } else { + Logger.error("RepeatInChunkChallenge: Invalid Change Data: {}, {}, {}, {}, {}", world.getName(), x, y, z, null); + continue; + } - blockMap.put(pos, blockData); - } + blockMap.put(pos, blockData); + } - } + } - } + } - @Override - protected void onEnable() { + @Override + protected void onEnable() { - for (Player player : ChallengeAPI.getIngamePlayers()) { - updateSurroundingChunks(player.getLocation().getChunk(), false); - } - } + for (Player player : ChallengeAPI.getIngamePlayers()) { + updateSurroundingChunks(player.getLocation().getChunk(), false); + } + } - private void changeBlockInEveryChunk(World world, int x, int y, int z, BlockData data, Block exception) { - updatedChunks.clear(); + private void changeBlockInEveryChunk(World world, int x, int y, int z, BlockData data, Block exception) { + updatedChunks.clear(); - Bukkit.getScheduler().runTask(plugin, () -> { + Bukkit.getScheduler().runTask(plugin, () -> { - Map, BlockData> map = changedBlocks - .getOrDefault(world.getName(), new HashMap<>()); - changedBlocks.putIfAbsent(world.getName(), map); - map.put(new Triple<>(x, y, z), data); + Map, BlockData> map = changedBlocks + .getOrDefault(world.getName(), new HashMap<>()); + changedBlocks.putIfAbsent(world.getName(), map); + map.put(new Triple<>(x, y, z), data); - for (Player player : ChallengeAPI.getIngamePlayers()) { + for (Player player : ChallengeAPI.getIngamePlayers()) { - for (Chunk chunk : getSurroundingChunks(player.getLocation().getChunk(), false)) { - Block block = chunk.getBlock(x, y, z); - if (!Objects.equals(exception, block)) { - setBlockData(block, data, true); - } - } + for (Chunk chunk : getSurroundingChunks(player.getLocation().getChunk(), false)) { + Block block = chunk.getBlock(x, y, z); + if (!Objects.equals(exception, block)) { + setBlockData(block, data, true); + } + } - } + } - }); - } + }); + } - private List getSurroundingChunks(Chunk center, boolean onlyBorder) { - int range = 8; - - int centerX = center.getX(); - int centerZ = center.getZ(); - - List chunks = Lists.newLinkedList(); - - for (int x = -range; x <= range; x++) { - - for (int z = -range; z <= range; z++) { - - if (onlyBorder) { - - if (x != -range && x != range && z != -range && z != range) { - continue; - } - - } + private List getSurroundingChunks(Chunk center, boolean onlyBorder) { + int range = 8; + + int centerX = center.getX(); + int centerZ = center.getZ(); + + List chunks = Lists.newLinkedList(); + + for (int x = -range; x <= range; x++) { + + for (int z = -range; z <= range; z++) { + + if (onlyBorder) { + + if (x != -range && x != range && z != -range && z != range) { + continue; + } + + } - Chunk chunkAt = center.getWorld().getChunkAt(centerX + x, centerZ + z); - if (updatedChunks.contains(chunkAt)) continue; - chunks.add(chunkAt); - } - } - - return chunks; - } - - private void updateSurroundingChunks(Chunk center, boolean onlyBorder) { - - for (Chunk chunk : getSurroundingChunks(center, onlyBorder)) { - updateChunk(chunk); - } - - } - - private void updateChunk(Chunk chunk) { - updatedChunks.add(chunk); - - Map, BlockData> dataMap = changedBlocks.getOrDefault(chunk.getWorld().getName(), new HashMap<>()); - - for (Entry, BlockData> blockEntry : dataMap.entrySet()) { - Triple pos = blockEntry.getKey(); - BlockData blockData = blockEntry.getValue(); - Block block = chunk.getBlock(pos.getFirst(), pos.getSecond(), pos.getThird()); - if (!block.getBlockData().matches(blockData)) { - setBlockData(block, blockData, false); - } - - } - - - } - - private void setBlockData(Block block, BlockData blockData, boolean update) { - if (block.getType() == Material.END_PORTAL || - block.getType() == Material.END_PORTAL_FRAME || - block.getType() == Material.END_GATEWAY) return; - block.setBlockData(blockData, update); - } - - private int getRelativeChunkCoordinate(int worldCoordinate) { - return worldCoordinate & 0xF; - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlace(BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - - Block block = event.getBlock(); - changeBlockInEveryChunk( - event.getBlock().getWorld(), - getRelativeChunkCoordinate(block.getX()), - block.getY(), - getRelativeChunkCoordinate(block.getZ()), - block.getBlockData(), - event.getBlock() - ); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBreak(BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - - Block block = event.getBlock(); - changeBlockInEveryChunk( - event.getBlock().getWorld(), - getRelativeChunkCoordinate(block.getX()), - block.getY(), - getRelativeChunkCoordinate(block.getZ()), - Bukkit.createBlockData(Material.AIR), - event.getBlock() - ); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getTo() == null) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo().getChunk() == event.getFrom().getChunk()) return; - updateSurroundingChunks(event.getTo().getChunk(), true); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(VehicleMoveEvent event) { - if (!shouldExecuteEffect()) return; - - boolean anyMatch = false; - for (Entity passenger : event.getVehicle().getPassengers()) { - if (passenger instanceof Player) { - anyMatch = true; - break; - } - } - if (!anyMatch) return; - - if (event.getTo().getChunk() == event.getFrom().getChunk()) return; - updateSurroundingChunks(event.getTo().getChunk(), true); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onTeleport(PlayerTeleportEvent event) { - if (event.getTo() == null) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo().getChunk() == event.getFrom().getChunk()) return; - updateSurroundingChunks(event.getTo().getChunk(), false); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onGamemodeChange(PlayerIgnoreStatusChangeEvent event) { - if (!shouldExecuteEffect()) return; - if (event.isNotIgnored()) { - updateSurroundingChunks(event.getPlayer().getLocation().getChunk(), false); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onChunkUnload(ChunkUnloadEvent event) { - if (!shouldExecuteEffect()) return; - updatedChunks.remove(event.getChunk()); - } + Chunk chunkAt = center.getWorld().getChunkAt(centerX + x, centerZ + z); + if (updatedChunks.contains(chunkAt)) continue; + chunks.add(chunkAt); + } + } + + return chunks; + } + + private void updateSurroundingChunks(Chunk center, boolean onlyBorder) { + + for (Chunk chunk : getSurroundingChunks(center, onlyBorder)) { + updateChunk(chunk); + } + + } + + private void updateChunk(Chunk chunk) { + updatedChunks.add(chunk); + + Map, BlockData> dataMap = changedBlocks.getOrDefault(chunk.getWorld().getName(), new HashMap<>()); + + for (Entry, BlockData> blockEntry : dataMap.entrySet()) { + Triple pos = blockEntry.getKey(); + BlockData blockData = blockEntry.getValue(); + Block block = chunk.getBlock(pos.getFirst(), pos.getSecond(), pos.getThird()); + if (!block.getBlockData().matches(blockData)) { + setBlockData(block, blockData, false); + } + + } + + + } + + private void setBlockData(Block block, BlockData blockData, boolean update) { + if (block.getType() == Material.END_PORTAL || + block.getType() == Material.END_PORTAL_FRAME || + block.getType() == Material.END_GATEWAY) return; + block.setBlockData(blockData, update); + } + + private int getRelativeChunkCoordinate(int worldCoordinate) { + return worldCoordinate & 0xF; + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlace(BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + + Block block = event.getBlock(); + changeBlockInEveryChunk( + event.getBlock().getWorld(), + getRelativeChunkCoordinate(block.getX()), + block.getY(), + getRelativeChunkCoordinate(block.getZ()), + block.getBlockData(), + event.getBlock() + ); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBreak(BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + + Block block = event.getBlock(); + changeBlockInEveryChunk( + event.getBlock().getWorld(), + getRelativeChunkCoordinate(block.getX()), + block.getY(), + getRelativeChunkCoordinate(block.getZ()), + Bukkit.createBlockData(Material.AIR), + event.getBlock() + ); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (event.getTo() == null) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo().getChunk() == event.getFrom().getChunk()) return; + updateSurroundingChunks(event.getTo().getChunk(), true); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(VehicleMoveEvent event) { + if (!shouldExecuteEffect()) return; + + boolean anyMatch = false; + for (Entity passenger : event.getVehicle().getPassengers()) { + if (passenger instanceof Player) { + anyMatch = true; + break; + } + } + if (!anyMatch) return; + + if (event.getTo().getChunk() == event.getFrom().getChunk()) return; + updateSurroundingChunks(event.getTo().getChunk(), true); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent event) { + if (event.getTo() == null) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo().getChunk() == event.getFrom().getChunk()) return; + updateSurroundingChunks(event.getTo().getChunk(), false); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onGamemodeChange(PlayerIgnoreStatusChangeEvent event) { + if (!shouldExecuteEffect()) return; + if (event.isNotIgnored()) { + updateSurroundingChunks(event.getPlayer().getLocation().getChunk(), false); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onChunkUnload(ChunkUnloadEvent event) { + if (!shouldExecuteEffect()) return; + updatedChunks.remove(event.getChunk()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index f494c35dd..4af53408c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -26,80 +26,80 @@ public class SnakeChallenge extends Setting { - private final ArrayList blocks = new ArrayList<>(); - - public SnakeChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BLUE_TERRACOTTA, Message.forName("item-snake-challenge")); - } - - @Override - protected void onDisable() { - blocks.clear(); - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - - List locations = blocks.stream().map(Block::getLocation).collect(Collectors.toList()); - document.set("blocks", locations); - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - - blocks.addAll(document.getSerializableList("blocks", Location.class).stream().map(Location::getBlock).collect(Collectors.toList())); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getTo() == null) return; - if (event.getFrom().getBlock().equals(event.getTo().getBlock())) return; - if (event.getPlayer().getGameMode() == GameMode.SPECTATOR || event.getPlayer().getGameMode() == GameMode.CREATIVE) - return; - - Block from = event.getFrom().clone().subtract(0, 1, 0).getBlock(); - Block to = event.getTo().clone().subtract(0, 0.15, 0).getBlock(); - - if (from.getType().isSolid()) { - from.setType(BlockUtils.getTerracotta(getPlayersColor(event.getPlayer())), false); - blocks.add(from); - } - - if (blocks.contains(to)) { - Message.forName("snake-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - kill(event.getPlayer()); - return; - } - - if (to.getType().isSolid()) { - to.setType(Material.BLACK_TERRACOTTA, false); - - Block block = event.getPlayer().getLocation().getBlock(); - if (!block.getType().isSolid()) { - block.breakNaturally(); - } - } - - } - - public int getPlayersColor(Player player) { - int i = 0; - for (Player currentPlayer : Bukkit.getOnlinePlayers()) { - i++; - if (i > 17) i = 0; - if (currentPlayer == player) return i; - } - return 0; - } + private final ArrayList blocks = new ArrayList<>(); + + public SnakeChallenge() { + super(MenuType.CHALLENGES); + setCategory(SettingCategory.WORLD); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BLUE_TERRACOTTA, Message.forName("item-snake-challenge")); + } + + @Override + protected void onDisable() { + blocks.clear(); + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + + List locations = blocks.stream().map(Block::getLocation).collect(Collectors.toList()); + document.set("blocks", locations); + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + + blocks.addAll(document.getSerializableList("blocks", Location.class).stream().map(Location::getBlock).collect(Collectors.toList())); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getTo() == null) return; + if (event.getFrom().getBlock().equals(event.getTo().getBlock())) return; + if (event.getPlayer().getGameMode() == GameMode.SPECTATOR || event.getPlayer().getGameMode() == GameMode.CREATIVE) + return; + + Block from = event.getFrom().clone().subtract(0, 1, 0).getBlock(); + Block to = event.getTo().clone().subtract(0, 0.15, 0).getBlock(); + + if (from.getType().isSolid()) { + from.setType(BlockUtils.getTerracotta(getPlayersColor(event.getPlayer())), false); + blocks.add(from); + } + + if (blocks.contains(to)) { + Message.forName("snake-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + kill(event.getPlayer()); + return; + } + + if (to.getType().isSolid()) { + to.setType(Material.BLACK_TERRACOTTA, false); + + Block block = event.getPlayer().getLocation().getBlock(); + if (!block.getType().isSolid()) { + block.breakNaturally(); + } + } + + } + + public int getPlayersColor(Player player) { + int i = 0; + for (Player currentPlayer : Bukkit.getOnlinePlayers()) { + i++; + if (i > 17) i = 0; + if (currentPlayer == player) return i; + } + return 0; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java index c07addb57..50fcc15d6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java @@ -19,53 +19,53 @@ public class SurfaceHoleChallenge extends SettingModifier { - public SurfaceHoleChallenge() { - super(MenuType.CHALLENGES, 1, 60, 30); - setCategory(SettingCategory.WORLD); - } + public SurfaceHoleChallenge() { + super(MenuType.CHALLENGES, 1, 60, 30); + setCategory(SettingCategory.WORLD); + } - @EventHandler - public void onMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) - return; + @EventHandler + public void onMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) + return; - Location location = event.getTo(); - if (location == null) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), location)) return; + Location location = event.getTo(); + if (location == null) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), location)) return; - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { - if (!shouldExecuteEffect()) return; + Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { + if (!shouldExecuteEffect()) return; - World world = event.getPlayer().getWorld(); + World world = event.getPlayer().getWorld(); - List blocks = new ArrayList<>(); - for (int y = BukkitReflectionUtils.getMinHeight(world); y < world.getMaxHeight(); y++) { - Location blockLocation = location.clone(); - blockLocation.setY(y); - blocks.add(blockLocation.getBlock()); - } + List blocks = new ArrayList<>(); + for (int y = BukkitReflectionUtils.getMinHeight(world); y < world.getMaxHeight(); y++) { + Location blockLocation = location.clone(); + blockLocation.setY(y); + blocks.add(blockLocation.getBlock()); + } - Bukkit.getScheduler().runTask(plugin, () -> { - for (Block block : blocks) { - block.setType(Material.AIR, false); - } - }); + Bukkit.getScheduler().runTask(plugin, () -> { + for (Block block : blocks) { + block.setType(Material.AIR, false); + } + }); - }, getValue() * 20L); + }, getValue() * 20L); - } + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BARRIER, Message.forName("item-surface-hole-challenge")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BARRIER, Message.forName("item-surface-hole-challenge")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java index 90189cadd..5e8518a16 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java @@ -35,200 +35,200 @@ @Since("2.0") public class TsunamiChallenge extends TimedChallenge { - public static final int RANGE = 5; - - private final List floodedChunks = new ArrayList<>(); - - private int waterHeight = Integer.MAX_VALUE, - lavaHeight = 0; - - public TsunamiChallenge() { - super(MenuType.CHALLENGES, 1, 40, 4); - setCategory(SettingCategory.WORLD); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ICE, Message.forName("item-tsunami-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 15); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 15); - } - - @Override - protected void onEnable() { - - if (waterHeight == Integer.MAX_VALUE) { - waterHeight = BukkitReflectionUtils.getMinHeight(ChallengeAPI.getGameWorld(Environment.NORMAL)); - } - bossbar.setContent((bossbar, player) -> { - World world = player.getWorld(); - Environment environment = world.getEnvironment(); - int height = environment == Environment.NORMAL ? waterHeight : lavaHeight; - if (height < (world.getMaxHeight() - 1)) - bossbar.setProgress(getProgress()); - - if (environment == Environment.NORMAL) { - bossbar.setColor(BarColor.BLUE); - bossbar.setTitle(Message.forName("bossbar-tsunami-water").asString(waterHeight)); - } else if (environment == Environment.NETHER) { - bossbar.setColor(BarColor.RED); - bossbar.setTitle(Message.forName("bossbar-tsunami-lava").asString(lavaHeight)); - } else { - bossbar.setVisible(false); - } - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Override - protected int getSecondsUntilNextActivation() { - return getValue() * 15; - } - - @Override - protected void handleCountdown() { - bossbar.update(); - } - - @Override - protected void onTimeActivation() { - restartTimer(); - - for (World world : ChallengeAPI.getGameWorlds()) { - if (!world.getPlayers().isEmpty()) { - if (world.getEnvironment() == Environment.NORMAL) { - if (waterHeight >= (world.getMaxHeight() - 1)) continue; - waterHeight++; - } else if (world.getEnvironment() == Environment.NETHER) { - if (lavaHeight >= (world.getMaxHeight() - 1)) continue; - lavaHeight++; - } - } - } - - List previouslyFlooded = new ArrayList<>(floodedChunks); - bossbar.update(); - floodedChunks.clear(); - for (Chunk chunk : getChunksToFlood()) { - floodChunk(chunk, !previouslyFlooded.contains(chunk)); - } - - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - private void onPlayerMove(@Nonnull PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo() == null) return; - - Chunk newChunk = event.getTo().getChunk(); - if (event.getFrom().getChunk() == newChunk) return; - - for (Chunk chunk : getChunksAroundChunk(newChunk)) { - floodChunk(chunk, true); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onTeleport(@Nonnull PlayerTeleportEvent event) { - if (ignorePlayer(event.getPlayer())) return; - if (!shouldExecuteEffect()) return; - if (event.getTo() == null) return; - - Chunk newChunk = event.getTo().getChunk(); - if (event.getFrom().getChunk() == newChunk) return; - - bossbar.update(); - - for (Chunk chunk : getChunksAroundChunk(newChunk)) { - floodChunk(chunk, true); - } - } - - @EventHandler - public void onChunkUnload(@Nonnull ChunkUnloadEvent event) { - floodedChunks.remove(event.getChunk()); - } - - private void floodChunk(@Nonnull Chunk chunk, boolean discovered) { - if (floodedChunks.contains(chunk)) return; - floodedChunks.add(chunk); - if (chunk.getWorld().getEnvironment() == Environment.THE_END) return; - - boolean overworld = chunk.getWorld().getEnvironment() == Environment.NORMAL; - int height = overworld ? waterHeight : lavaHeight; - floodChunk0(chunk, discovered ? null : height - 1, height, overworld, (delay, task) -> Bukkit.getScheduler().runTaskLater(plugin, task, delay)); - } - - private void floodChunk0(@Nonnull Chunk chunk, @Nullable Integer givenStartAt, int height, boolean overworld, @Nonnull BiConsumer executor) { - int startAt = givenStartAt != null ? Math.max(BukkitReflectionUtils.getMinHeight(chunk.getWorld()) + 1, givenStartAt) : BukkitReflectionUtils - .getMinHeight(chunk.getWorld()) + 1; - Map> blocksByDelay = new HashMap<>(); - Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - for (int y = startAt + 1; y <= height; y++) { - List blocks = blocksByDelay.computeIfAbsent(0, key -> new ArrayList<>(16)); - Block block = chunk.getBlock(x, y, z); - Material type = block.getType(); - if (type != Material.WATER && type != Material.LAVA && block.isPassable() || (overworld && type == Material.LAVA)) - blocks.add(block); - } - } - } - blocksByDelay.forEach((delay, blocks) -> { - executor.accept(delay, () -> { - for (Block block : blocks) { - block.setType(overworld ? Material.WATER : Material.LAVA, false); - } - }); - }); - }); - } - - private List getChunksToFlood() { - return new ListBuilder().fill(chunkListBuilder -> { - broadcastFiltered(player -> chunkListBuilder.addAllIfNotContains(getChunksAroundChunk(player.getLocation().getChunk()))); - }).build(); - } - - private List getChunksAroundChunk(@Nonnull Chunk origin) { - return new ListBuilder().fill(builder -> { - for (int x = -RANGE; x <= RANGE; x++) { - for (int z = -RANGE; z <= RANGE; z++) { - builder.addIfNotContains(origin.getWorld().getChunkAt(origin.getX() + x, origin.getZ() + z)); - } - } - }).build(); - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - document.set("waterHeight", waterHeight); - document.set("lavaHeight", lavaHeight); - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - waterHeight = document.getInt("waterHeight"); - lavaHeight = document.getInt("lavaHeight"); - } + public static final int RANGE = 5; + + private final List floodedChunks = new ArrayList<>(); + + private int waterHeight = Integer.MAX_VALUE, + lavaHeight = 0; + + public TsunamiChallenge() { + super(MenuType.CHALLENGES, 1, 40, 4); + setCategory(SettingCategory.WORLD); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ICE, Message.forName("item-tsunami-challenge")); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-time-seconds-description").asArray(getValue() * 15); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 15); + } + + @Override + protected void onEnable() { + + if (waterHeight == Integer.MAX_VALUE) { + waterHeight = BukkitReflectionUtils.getMinHeight(ChallengeAPI.getGameWorld(Environment.NORMAL)); + } + bossbar.setContent((bossbar, player) -> { + World world = player.getWorld(); + Environment environment = world.getEnvironment(); + int height = environment == Environment.NORMAL ? waterHeight : lavaHeight; + if (height < (world.getMaxHeight() - 1)) + bossbar.setProgress(getProgress()); + + if (environment == Environment.NORMAL) { + bossbar.setColor(BarColor.BLUE); + bossbar.setTitle(Message.forName("bossbar-tsunami-water").asString(waterHeight)); + } else if (environment == Environment.NETHER) { + bossbar.setColor(BarColor.RED); + bossbar.setTitle(Message.forName("bossbar-tsunami-lava").asString(lavaHeight)); + } else { + bossbar.setVisible(false); + } + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Override + protected int getSecondsUntilNextActivation() { + return getValue() * 15; + } + + @Override + protected void handleCountdown() { + bossbar.update(); + } + + @Override + protected void onTimeActivation() { + restartTimer(); + + for (World world : ChallengeAPI.getGameWorlds()) { + if (!world.getPlayers().isEmpty()) { + if (world.getEnvironment() == Environment.NORMAL) { + if (waterHeight >= (world.getMaxHeight() - 1)) continue; + waterHeight++; + } else if (world.getEnvironment() == Environment.NETHER) { + if (lavaHeight >= (world.getMaxHeight() - 1)) continue; + lavaHeight++; + } + } + } + + List previouslyFlooded = new ArrayList<>(floodedChunks); + bossbar.update(); + floodedChunks.clear(); + for (Chunk chunk : getChunksToFlood()) { + floodChunk(chunk, !previouslyFlooded.contains(chunk)); + } + + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + private void onPlayerMove(@Nonnull PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo() == null) return; + + Chunk newChunk = event.getTo().getChunk(); + if (event.getFrom().getChunk() == newChunk) return; + + for (Chunk chunk : getChunksAroundChunk(newChunk)) { + floodChunk(chunk, true); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onTeleport(@Nonnull PlayerTeleportEvent event) { + if (ignorePlayer(event.getPlayer())) return; + if (!shouldExecuteEffect()) return; + if (event.getTo() == null) return; + + Chunk newChunk = event.getTo().getChunk(); + if (event.getFrom().getChunk() == newChunk) return; + + bossbar.update(); + + for (Chunk chunk : getChunksAroundChunk(newChunk)) { + floodChunk(chunk, true); + } + } + + @EventHandler + public void onChunkUnload(@Nonnull ChunkUnloadEvent event) { + floodedChunks.remove(event.getChunk()); + } + + private void floodChunk(@Nonnull Chunk chunk, boolean discovered) { + if (floodedChunks.contains(chunk)) return; + floodedChunks.add(chunk); + if (chunk.getWorld().getEnvironment() == Environment.THE_END) return; + + boolean overworld = chunk.getWorld().getEnvironment() == Environment.NORMAL; + int height = overworld ? waterHeight : lavaHeight; + floodChunk0(chunk, discovered ? null : height - 1, height, overworld, (delay, task) -> Bukkit.getScheduler().runTaskLater(plugin, task, delay)); + } + + private void floodChunk0(@Nonnull Chunk chunk, @Nullable Integer givenStartAt, int height, boolean overworld, @Nonnull BiConsumer executor) { + int startAt = givenStartAt != null ? Math.max(BukkitReflectionUtils.getMinHeight(chunk.getWorld()) + 1, givenStartAt) : BukkitReflectionUtils + .getMinHeight(chunk.getWorld()) + 1; + Map> blocksByDelay = new HashMap<>(); + Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y = startAt + 1; y <= height; y++) { + List blocks = blocksByDelay.computeIfAbsent(0, key -> new ArrayList<>(16)); + Block block = chunk.getBlock(x, y, z); + Material type = block.getType(); + if (type != Material.WATER && type != Material.LAVA && block.isPassable() || (overworld && type == Material.LAVA)) + blocks.add(block); + } + } + } + blocksByDelay.forEach((delay, blocks) -> { + executor.accept(delay, () -> { + for (Block block : blocks) { + block.setType(overworld ? Material.WATER : Material.LAVA, false); + } + }); + }); + }); + } + + private List getChunksToFlood() { + return new ListBuilder().fill(chunkListBuilder -> { + broadcastFiltered(player -> chunkListBuilder.addAllIfNotContains(getChunksAroundChunk(player.getLocation().getChunk()))); + }).build(); + } + + private List getChunksAroundChunk(@Nonnull Chunk origin) { + return new ListBuilder().fill(builder -> { + for (int x = -RANGE; x <= RANGE; x++) { + for (int z = -RANGE; z <= RANGE; z++) { + builder.addIfNotContains(origin.getWorld().getChunkAt(origin.getX() + x, origin.getZ() + z)); + } + } + }).build(); + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + document.set("waterHeight", waterHeight); + document.set("lavaHeight", lavaHeight); + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + waterHeight = document.getInt("waterHeight"); + lavaHeight = document.getInt("lavaHeight"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java index b5d281832..b8efd70c9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java @@ -18,39 +18,39 @@ public class DamageRuleSetting extends Setting { - private final List causes; - - private final String name; - private final ItemBuilder preset; - - public DamageRuleSetting(@Nonnull ItemBuilder preset, @Nonnull String name, @Nonnull DamageCause... causes) { - super(MenuType.DAMAGE, true); - this.causes = Arrays.asList(causes); - this.name = name; - this.preset = preset; - } - - @NotNull - @Override - public String getUniqueName() { - return super.getUniqueName() + name; - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return preset.clone().applyFormat(Message.forName("item-damage-rule-" + name).asItemDescription()); - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (ChallengeAPI.isWorldInUse()) return; - if (isEnabled()) return; - if (!(event.getEntity() instanceof Player)) return; - if (event.getCause() == DamageCause.VOID || event.getCause() == DamageCause.CUSTOM) - return; // Never ignore void or custom to prevent different issues - if (!causes.contains(event.getCause())) return; - event.setCancelled(true); - } + private final List causes; + + private final String name; + private final ItemBuilder preset; + + public DamageRuleSetting(@Nonnull ItemBuilder preset, @Nonnull String name, @Nonnull DamageCause... causes) { + super(MenuType.DAMAGE, true); + this.causes = Arrays.asList(causes); + this.name = name; + this.preset = preset; + } + + @NotNull + @Override + public String getUniqueName() { + return super.getUniqueName() + name; + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return preset.clone().applyFormat(Message.forName("item-damage-rule-" + name).asItemDescription()); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (ChallengeAPI.isWorldInUse()) return; + if (isEnabled()) return; + if (!(event.getEntity() instanceof Player)) return; + if (event.getCause() == DamageCause.VOID || event.getCause() == DamageCause.CUSTOM) + return; // Never ignore void or custom to prevent different issues + if (!causes.contains(event.getCause())) return; + event.setCancelled(true); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java index c02c60823..d7e86c3ec 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java @@ -29,97 +29,97 @@ @Since("2.1.0") public class AllAdvancementGoal extends PointsGoal { - private final List allAdvancements; - private final int advancementCount; - - public AllAdvancementGoal() { - setCategory(SettingCategory.FASTEST_TIME); - allAdvancements = new LinkedList<>(); - Bukkit.getServer().advancementIterator().forEachRemaining(advancement -> { - if (!advancement.getKey().toString().contains(":recipes/")) { - allAdvancements.add(advancement); - } - }); - advancementCount = allAdvancements.size(); - } - - @Override - protected void onEnable() { - updateAdvancements(); - scoreboard.setContent(GoalHelper.createScoreboard(() -> - getPoints(new AtomicInteger(), true), player -> { - return Collections.singletonList(Message.forName("all-advancements-goal").asString(advancementCount)); - })); - scoreboard.show(); - } - - @Override - protected void onDisable() { - scoreboard.hide(); - } - - @Override - public void getWinnersOnEnd(@NotNull List winners) { - broadcastFiltered(player -> { - if (hasWon(player)) { - winners.add(player); - } - }); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOOK, Message.forName("item-all-advancements-goal")); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onAdvancement(PlayerAdvancementDoneEvent event) { - if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - updateAdvancements(event.getPlayer()); - scoreboard.update(); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onJoin(PlayerJoinEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - updateAdvancements(event.getPlayer()); - scoreboard.update(); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onGamemodeChange(PlayerGameModeChangeEvent event) { - if (!shouldExecuteEffect()) return; - Bukkit.getScheduler().runTask(plugin, (Runnable) scoreboard::update); - } - - protected void updateAdvancements() { - broadcastFiltered(this::updateAdvancements); - } - - protected void updateAdvancements(@Nonnull Player player) { - int done = 0; - for (Advancement advancement : allAdvancements) { - AdvancementProgress progress = player.getAdvancementProgress(advancement); - if (progress.isDone()) { - done++; - } - } - setPoints(player.getUniqueId(), done); - checkForWinning(player); - } - - protected void checkForWinning(Player player) { - if (hasWon(player)) { - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - } - } - - protected boolean hasWon(@Nonnull Player player) { - return getPoints(player.getUniqueId()) >= advancementCount; - } + private final List allAdvancements; + private final int advancementCount; + + public AllAdvancementGoal() { + setCategory(SettingCategory.FASTEST_TIME); + allAdvancements = new LinkedList<>(); + Bukkit.getServer().advancementIterator().forEachRemaining(advancement -> { + if (!advancement.getKey().toString().contains(":recipes/")) { + allAdvancements.add(advancement); + } + }); + advancementCount = allAdvancements.size(); + } + + @Override + protected void onEnable() { + updateAdvancements(); + scoreboard.setContent(GoalHelper.createScoreboard(() -> + getPoints(new AtomicInteger(), true), player -> { + return Collections.singletonList(Message.forName("all-advancements-goal").asString(advancementCount)); + })); + scoreboard.show(); + } + + @Override + protected void onDisable() { + scoreboard.hide(); + } + + @Override + public void getWinnersOnEnd(@NotNull List winners) { + broadcastFiltered(player -> { + if (hasWon(player)) { + winners.add(player); + } + }); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BOOK, Message.forName("item-all-advancements-goal")); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onAdvancement(PlayerAdvancementDoneEvent event) { + if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + updateAdvancements(event.getPlayer()); + scoreboard.update(); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJoin(PlayerJoinEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + updateAdvancements(event.getPlayer()); + scoreboard.update(); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onGamemodeChange(PlayerGameModeChangeEvent event) { + if (!shouldExecuteEffect()) return; + Bukkit.getScheduler().runTask(plugin, (Runnable) scoreboard::update); + } + + protected void updateAdvancements() { + broadcastFiltered(this::updateAdvancements); + } + + protected void updateAdvancements(@Nonnull Player player) { + int done = 0; + for (Advancement advancement : allAdvancements) { + AdvancementProgress progress = player.getAdvancementProgress(advancement); + if (progress.isDone()) { + done++; + } + } + setPoints(player.getUniqueId(), done); + checkForWinning(player); + } + + protected void checkForWinning(Player player) { + if (hasWon(player)) { + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } + } + + protected boolean hasWon(@Nonnull Player player) { + return getPoints(player.getUniqueId()) >= advancementCount; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index 8ddbb8b79..5c86340c9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -2,7 +2,6 @@ import lombok.Getter; import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.anweisen.utilities.common.annotations.Since; import net.anweisen.utilities.common.collection.SeededRandomWrapper; import net.anweisen.utilities.common.config.Document; @@ -15,6 +14,7 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Bukkit; @@ -37,167 +37,167 @@ @Since("2.0") public class CollectAllItemsGoal extends SettingGoal implements SenderCommand { - @Getter - private final int totalItemsCount; - private SeededRandomWrapper random; - @Getter - private List allItemsToFind; - @Getter - private List itemsToFind; - @Getter - private Material currentItem; - - public CollectAllItemsGoal() { - random = new SeededRandomWrapper(); - reloadItemsToFind(); - totalItemsCount = itemsToFind.size(); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-all-items-goal")); - } - - private void reloadItemsToFind() { - allItemsToFind = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - allItemsToFind.removeIf(material -> !material.isItem()); - allItemsToFind.removeIf(material -> !ItemUtils.isObtainableInSurvival(material)); - Collections.shuffle(allItemsToFind, random); - itemsToFind = new ArrayList<>(allItemsToFind); - nextItem(); - - if (isEnabled()) - bossbar.update(); - } - - private void nextItem() { - if (itemsToFind.isEmpty()) { - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - return; - } - currentItem = itemsToFind.remove(0); - } - - @Override - protected void onEnable() { - bossbar.setContent((bossbar, player) -> { - if (currentItem == null) { - bossbar.setTitle(Message.forName("bossbar-all-items-finished").asString()); - return; - } - bossbar.setTitle(Message.forName("bossbar-all-items-current-max").asComponent( - getItemDisplayName(currentItem), - totalItemsCount - itemsToFind.size() + 1, - totalItemsCount)); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - if (!isEnabled()) { - Message.forName("challenge-disabled").send(sender, Prefix.CHALLENGES); - SoundSample.BASS_OFF.playIfPlayer(sender); - return; - } - if (currentItem == null) { - Message.forName("all-items-already-finished").send(sender, Prefix.CHALLENGES); - SoundSample.BASS_OFF.playIfPlayer(sender); - return; - } - - Message.forName("all-items-skipped").broadcast(Prefix.CHALLENGES, getItemDisplayName(currentItem)); - SoundSample.PLING.broadcast(); - nextItem(); - bossbar.update(); - - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onClick(@Nonnull PlayerInventoryClickEvent event) { - if (event.isCancelled()) return; - ItemStack item = event.getCurrentItem(); - if (item == null) return; - handleNewItem(item.getType(), event.getPlayer()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPickUp(@Nonnull PlayerPickupItemEvent event) { - Material material = event.getItem().getItemStack().getType(); - handleNewItem(material, event.getPlayer()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInteract(@Nonnull PlayerInteractEvent event) { - Bukkit.getScheduler().runTaskLater(plugin, () -> { - ItemStack item = event.getPlayer().getInventory().getItemInMainHand(); - Material material = item.getType(); - handleNewItem(material, event.getPlayer()); - }, 1); - } - - protected void handleNewItem(@Nullable Material material, @Nonnull Player player) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(player)) return; - if (currentItem != material) return; - Message.forName("all-items-found").broadcast(Prefix.CHALLENGES, getItemDisplayName(currentItem) , NameHelper.getName(player)); - SoundSample.PLING.broadcast(); - nextItem(); - bossbar.update(); - } - - @Override - public void getWinnersOnEnd(@Nonnull List winners) { - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - random = new SeededRandomWrapper(document.getLong("seed")); - reloadItemsToFind(); - - for (int i = 0; i < document.getInt("found"); i++) - nextItem(); - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - document.set("seed", random.getSeed()); - document.set("found", totalItemsCount - itemsToFind.size()); - } - - private String getItemDisplayName(@Nullable Material material) { - if (material == null) return "Unbekannt"; - - String name = material.name(); - - if (name.contains("SMITHING_TEMPLATE")) { - String prefix = name.replace("_SMITHING_TEMPLATE", ""); - String formattedPrefix = Arrays.stream(prefix.split("_")) - .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) - .collect(Collectors.joining(" ")); - - return formattedPrefix + " Smithing template"; - } - - if (name.endsWith("_BANNER_PATTERN")) { - String prefix = name.replace("_BANNER_PATTERN", ""); - String formattedPrefix = Arrays.stream(prefix.split("_")) - .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) - .collect(Collectors.joining(" ")); - - return formattedPrefix + " Banner Pattern"; - } - - return Arrays.stream(name.split("_")) - .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) - .collect(Collectors.joining(" ")); - } + @Getter + private final int totalItemsCount; + private SeededRandomWrapper random; + @Getter + private List allItemsToFind; + @Getter + private List itemsToFind; + @Getter + private Material currentItem; + + public CollectAllItemsGoal() { + random = new SeededRandomWrapper(); + reloadItemsToFind(); + totalItemsCount = itemsToFind.size(); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-all-items-goal")); + } + + private void reloadItemsToFind() { + allItemsToFind = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + allItemsToFind.removeIf(material -> !material.isItem()); + allItemsToFind.removeIf(material -> !ItemUtils.isObtainableInSurvival(material)); + Collections.shuffle(allItemsToFind, random); + itemsToFind = new ArrayList<>(allItemsToFind); + nextItem(); + + if (isEnabled()) + bossbar.update(); + } + + private void nextItem() { + if (itemsToFind.isEmpty()) { + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + return; + } + currentItem = itemsToFind.remove(0); + } + + @Override + protected void onEnable() { + bossbar.setContent((bossbar, player) -> { + if (currentItem == null) { + bossbar.setTitle(Message.forName("bossbar-all-items-finished").asString()); + return; + } + bossbar.setTitle(Message.forName("bossbar-all-items-current-max").asComponent( + getItemDisplayName(currentItem), + totalItemsCount - itemsToFind.size() + 1, + totalItemsCount)); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + if (!isEnabled()) { + Message.forName("challenge-disabled").send(sender, Prefix.CHALLENGES); + SoundSample.BASS_OFF.playIfPlayer(sender); + return; + } + if (currentItem == null) { + Message.forName("all-items-already-finished").send(sender, Prefix.CHALLENGES); + SoundSample.BASS_OFF.playIfPlayer(sender); + return; + } + + Message.forName("all-items-skipped").broadcast(Prefix.CHALLENGES, getItemDisplayName(currentItem)); + SoundSample.PLING.broadcast(); + nextItem(); + bossbar.update(); + + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onClick(@Nonnull PlayerInventoryClickEvent event) { + if (event.isCancelled()) return; + ItemStack item = event.getCurrentItem(); + if (item == null) return; + handleNewItem(item.getType(), event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPickUp(@Nonnull PlayerPickupItemEvent event) { + Material material = event.getItem().getItemStack().getType(); + handleNewItem(material, event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onInteract(@Nonnull PlayerInteractEvent event) { + Bukkit.getScheduler().runTaskLater(plugin, () -> { + ItemStack item = event.getPlayer().getInventory().getItemInMainHand(); + Material material = item.getType(); + handleNewItem(material, event.getPlayer()); + }, 1); + } + + protected void handleNewItem(@Nullable Material material, @Nonnull Player player) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(player)) return; + if (currentItem != material) return; + Message.forName("all-items-found").broadcast(Prefix.CHALLENGES, getItemDisplayName(currentItem), NameHelper.getName(player)); + SoundSample.PLING.broadcast(); + nextItem(); + bossbar.update(); + } + + @Override + public void getWinnersOnEnd(@Nonnull List winners) { + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + random = new SeededRandomWrapper(document.getLong("seed")); + reloadItemsToFind(); + + for (int i = 0; i < document.getInt("found"); i++) + nextItem(); + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + document.set("seed", random.getSeed()); + document.set("found", totalItemsCount - itemsToFind.size()); + } + + private String getItemDisplayName(@Nullable Material material) { + if (material == null) return "Unbekannt"; + + String name = material.name(); + + if (name.contains("SMITHING_TEMPLATE")) { + String prefix = name.replace("_SMITHING_TEMPLATE", ""); + String formattedPrefix = Arrays.stream(prefix.split("_")) + .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) + .collect(Collectors.joining(" ")); + + return formattedPrefix + " Smithing template"; + } + + if (name.endsWith("_BANNER_PATTERN")) { + String prefix = name.replace("_BANNER_PATTERN", ""); + String formattedPrefix = Arrays.stream(prefix.split("_")) + .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) + .collect(Collectors.joining(" ")); + + return formattedPrefix + " Banner Pattern"; + } + + return Arrays.stream(name.split("_")) + .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) + .collect(Collectors.joining(" ")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java index 99b1bec22..4e80c2757 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java @@ -16,26 +16,26 @@ @Since("2.1.2") public class CollectHorseAmorGoal extends ItemCollectionGoal { - public CollectHorseAmorGoal() { - super(); - setCategory(SettingCategory.FASTEST_TIME); - List targets = new ArrayList<>(Arrays.asList( - Material.DIAMOND_HORSE_ARMOR, - Material.GOLDEN_HORSE_ARMOR, - Material.IRON_HORSE_ARMOR - )); - - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { - targets.add(Material.LEATHER_HORSE_ARMOR); - } - - setTarget(targets.toArray(new Object[0])); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_HORSE_ARMOR, Message.forName("item-collect-horse-armor-goal")); - } + public CollectHorseAmorGoal() { + super(); + setCategory(SettingCategory.FASTEST_TIME); + List targets = new ArrayList<>(Arrays.asList( + Material.DIAMOND_HORSE_ARMOR, + Material.GOLDEN_HORSE_ARMOR, + Material.IRON_HORSE_ARMOR + )); + + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { + targets.add(Material.LEATHER_HORSE_ARMOR); + } + + setTarget(targets.toArray(new Object[0])); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIAMOND_HORSE_ARMOR, Message.forName("item-collect-horse-armor-goal")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java index 42f602a26..42cbc8f41 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java @@ -11,15 +11,15 @@ @Since("2.1.2") public class CollectIceBlocksGoal extends ItemCollectionGoal { - public CollectIceBlocksGoal() { - super(Material.ICE, Material.BLUE_ICE, Material.PACKED_ICE, Material.SNOW_BLOCK); - setCategory(SettingCategory.FASTEST_TIME); - } + public CollectIceBlocksGoal() { + super(Material.ICE, Material.BLUE_ICE, Material.PACKED_ICE, Material.SNOW_BLOCK); + setCategory(SettingCategory.FASTEST_TIME); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PACKED_ICE, Message.forName("item-collect-ice-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.PACKED_ICE, Message.forName("item-collect-ice-goal")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java index 6ced4873d..449d3d2e5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java @@ -17,31 +17,31 @@ public class CollectMostDeathsGoal extends CollectionGoal { - public CollectMostDeathsGoal() { - super(DamageCause.values()); - setCategory(SettingCategory.SCORE_POINTS); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.LAVA_BUCKET, Message.forName("item-most-deaths-goal")); - } - - @EventHandler - public void onDeath(@Nonnull PlayerDeathEvent event) { - if (!shouldExecuteEffect()) return; - - EntityDamageEvent lastCause = event.getEntity().getLastDamageCause(); - if (lastCause == null) return; - - DamageCause cause = lastCause.getCause(); - if (cause == DamageCause.CUSTOM) return; - - collect(event.getEntity(), cause, () -> { - Message.forName("death-collected").send(event.getEntity(), Prefix.CHALLENGES, StringUtils.getEnumName(cause)); - SoundSample.PLING.play(event.getEntity()); - }); - } + public CollectMostDeathsGoal() { + super(DamageCause.values()); + setCategory(SettingCategory.SCORE_POINTS); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.LAVA_BUCKET, Message.forName("item-most-deaths-goal")); + } + + @EventHandler + public void onDeath(@Nonnull PlayerDeathEvent event) { + if (!shouldExecuteEffect()) return; + + EntityDamageEvent lastCause = event.getEntity().getLastDamageCause(); + if (lastCause == null) return; + + DamageCause cause = lastCause.getCause(); + if (cause == DamageCause.CUSTOM) return; + + collect(event.getEntity(), cause, () -> { + Message.forName("death-collected").send(event.getEntity(), Prefix.CHALLENGES, StringUtils.getEnumName(cause)); + SoundSample.PLING.play(event.getEntity()); + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java index 1131174c3..a1acc29bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java @@ -16,27 +16,27 @@ @Since("2.0") public class CollectMostExpGoal extends PointsGoal { - public CollectMostExpGoal() { - super(); - setCategory(SettingCategory.SCORE_POINTS); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-most-xp-goal")); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onExpChange(@Nonnull PlayerExpChangeEvent event) { - if (!shouldExecuteEffect()) return; - collect(event.getPlayer(), event.getAmount()); - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { - if (!shouldExecuteEffect()) return; - event.setKeepLevel(true); - } + public CollectMostExpGoal() { + super(); + setCategory(SettingCategory.SCORE_POINTS); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-most-xp-goal")); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onExpChange(@Nonnull PlayerExpChangeEvent event) { + if (!shouldExecuteEffect()) return; + collect(event.getPlayer(), event.getAmount()); + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { + if (!shouldExecuteEffect()) return; + event.setKeepLevel(true); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java index 2583fdc7b..d9145b4c8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.CollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -20,45 +20,45 @@ public class CollectMostItemsGoal extends CollectionGoal { - public CollectMostItemsGoal() { - super(ExperimentalUtils.getMaterials()); - setCategory(SettingCategory.SCORE_POINTS); - } + public CollectMostItemsGoal() { + super(ExperimentalUtils.getMaterials()); + setCategory(SettingCategory.SCORE_POINTS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STICK, Message.forName("item-most-items-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.STICK, Message.forName("item-most-items-goal")); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPickUp(@Nonnull EntityPickupItemEvent event) { - if (!isEnabled()) return; - if (!(event.getEntity() instanceof Player)) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPickUp(@Nonnull EntityPickupItemEvent event) { + if (!isEnabled()) return; + if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - ItemStack item = event.getItem().getItemStack(); - handleNewItem(item.getType(), player); - } + Player player = (Player) event.getEntity(); + ItemStack item = event.getItem().getItemStack(); + handleNewItem(item.getType(), player); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onClick(@Nonnull InventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getWhoClicked() instanceof Player)) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onClick(@Nonnull InventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getWhoClicked() instanceof Player)) return; - Player player = (Player) event.getWhoClicked(); - ItemStack item = event.getCurrentItem(); - if (item == null) return; - if (!ItemUtils.isObtainableInSurvival(item.getType())) return; + Player player = (Player) event.getWhoClicked(); + ItemStack item = event.getCurrentItem(); + if (item == null) return; + if (!ItemUtils.isObtainableInSurvival(item.getType())) return; - handleNewItem(item.getType(), player); - } + handleNewItem(item.getType(), player); + } - protected void handleNewItem(@Nonnull Material material, @Nonnull Player player) { - collect(player, material, () -> { - Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); - SoundSample.PLING.play(player); - }); - } + protected void handleNewItem(@Nonnull Material material, @Nonnull Player player) { + collect(player, material, () -> { + Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); + SoundSample.PLING.play(player); + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java index dc326cc51..5fa0758ad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java @@ -16,25 +16,25 @@ @Since("2.1.2") public class CollectSwordsGoal extends ItemCollectionGoal { - public CollectSwordsGoal() { - setCategory(SettingCategory.FASTEST_TIME); - List targets = new ArrayList<>(Arrays.asList( - Material.WOODEN_SWORD, Material.STONE_SWORD, - Material.IRON_SWORD, Material.GOLDEN_SWORD, - Material.DIAMOND_SWORD - )); - - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_16)) { - targets.add(Material.NETHERITE_SWORD); - } - - setTarget(targets.toArray(new Object[0])); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_SWORD, Message.forName("item-collect-swords-goal")); - } + public CollectSwordsGoal() { + setCategory(SettingCategory.FASTEST_TIME); + List targets = new ArrayList<>(Arrays.asList( + Material.WOODEN_SWORD, Material.STONE_SWORD, + Material.IRON_SWORD, Material.GOLDEN_SWORD, + Material.DIAMOND_SWORD + )); + + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_16)) { + targets.add(Material.NETHERITE_SWORD); + } + + setTarget(targets.toArray(new Object[0])); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIAMOND_SWORD, Message.forName("item-collect-swords-goal")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java index aefe3adc8..2a5a98552 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java @@ -22,107 +22,107 @@ public class CollectWoodGoal extends SettingModifierCollectionGoal { - private static final boolean newNether = MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_16); - private static final int - OVERWORLD = 1, - NETHER = 2, - BOTH = 3; - - public CollectWoodGoal() { - super(1, newNether ? 3 : 1); - setCategory(SettingCategory.FASTEST_TIME); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_AXE, Message.forName("item-collect-wood-goal")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (!newNether) return DefaultItem.enabled(); - if (getValue() == OVERWORLD) - return DefaultItem.create(Material.OAK_LOG, Message.forName("item-collect-wood-goal-overworld")); - if (getValue() == NETHER) - return DefaultItem.create(Material.WARPED_STEM, Message.forName("item-collect-wood-goal-nether")); - return DefaultItem.create(Material.CRYING_OBSIDIAN, Message.forName("item-collect-wood-goal-both")); - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - if (!newNether && info.isLowerItemClick() && enabled) { - setEnabled(false); - SoundSample.playStatusSound(info.getPlayer(), enabled); - playStatusUpdateTitle(); - } else { - super.handleClick(info); - } - } - - @Override - protected void onEnable() { - super.onEnable(); - setTarget(getWoodMaterials()); - checkCollects(); - } - - @Override - protected void onValueChange() { - setTarget(getWoodMaterials()); - checkCollects(); - } - - @Nonnull - private Object[] getWoodMaterials() { - return new ListBuilder().fill(builder -> { - for (Material material : ExperimentalUtils.getMaterials()) { - if (isSearched(material)) - builder.add(material); - } - }).build().toArray(); - } - - private boolean isLog(@Nonnull Material material) { - return material.name().contains("LOG") && !material.name().contains("STRIPPED"); - } - - private boolean isNetherLog(@Nonnull Material material) { - return material == Material.WARPED_STEM || material == Material.CRIMSON_STEM; - } - - private boolean isSearched(@Nonnull Material material) { - return getValue() == OVERWORLD && isLog(material) || - getValue() == NETHER && isNetherLog(material) || - getValue() == BOTH && (isLog(material) || isNetherLog(material)); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPickupItem(@Nonnull PlayerPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - Material material = event.getItem().getItemStack().getType(); - Player player = event.getPlayer(); - handleCollect(player, material); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (event.isCancelled()) return; - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getHolder() != event.getPlayer()) return; - if (event.getCurrentItem() == null) return; - Player player = event.getPlayer(); - Material material = event.getCurrentItem().getType(); - handleCollect(player, material); - } - - private void handleCollect(@Nonnull Player player, @Nonnull Material material) { - collect(player, material, () -> { - Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); - SoundSample.PLING.play(player); - }); - } + private static final boolean newNether = MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_16); + private static final int + OVERWORLD = 1, + NETHER = 2, + BOTH = 3; + + public CollectWoodGoal() { + super(1, newNether ? 3 : 1); + setCategory(SettingCategory.FASTEST_TIME); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GOLDEN_AXE, Message.forName("item-collect-wood-goal")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (!newNether) return DefaultItem.enabled(); + if (getValue() == OVERWORLD) + return DefaultItem.create(Material.OAK_LOG, Message.forName("item-collect-wood-goal-overworld")); + if (getValue() == NETHER) + return DefaultItem.create(Material.WARPED_STEM, Message.forName("item-collect-wood-goal-nether")); + return DefaultItem.create(Material.CRYING_OBSIDIAN, Message.forName("item-collect-wood-goal-both")); + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + if (!newNether && info.isLowerItemClick() && enabled) { + setEnabled(false); + SoundSample.playStatusSound(info.getPlayer(), enabled); + playStatusUpdateTitle(); + } else { + super.handleClick(info); + } + } + + @Override + protected void onEnable() { + super.onEnable(); + setTarget(getWoodMaterials()); + checkCollects(); + } + + @Override + protected void onValueChange() { + setTarget(getWoodMaterials()); + checkCollects(); + } + + @Nonnull + private Object[] getWoodMaterials() { + return new ListBuilder().fill(builder -> { + for (Material material : ExperimentalUtils.getMaterials()) { + if (isSearched(material)) + builder.add(material); + } + }).build().toArray(); + } + + private boolean isLog(@Nonnull Material material) { + return material.name().contains("LOG") && !material.name().contains("STRIPPED"); + } + + private boolean isNetherLog(@Nonnull Material material) { + return material == Material.WARPED_STEM || material == Material.CRIMSON_STEM; + } + + private boolean isSearched(@Nonnull Material material) { + return getValue() == OVERWORLD && isLog(material) || + getValue() == NETHER && isNetherLog(material) || + getValue() == BOTH && (isLog(material) || isNetherLog(material)); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPickupItem(@Nonnull PlayerPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + Material material = event.getItem().getItemStack().getType(); + Player player = event.getPlayer(); + handleCollect(player, material); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (event.isCancelled()) return; + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getHolder() != event.getPlayer()) return; + if (event.getCurrentItem() == null) return; + Player player = event.getPlayer(); + Material material = event.getCurrentItem().getType(); + handleCollect(player, material); + } + + private void handleCollect(@Nonnull Player player, @Nonnull Material material) { + collect(player, material, () -> { + Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); + SoundSample.PLING.play(player); + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java index e28eb9813..6fbb0a0ca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java @@ -14,20 +14,20 @@ @RequireVersion(MinecraftVersion.V1_14) public class CollectWorkstationsGoal extends ItemCollectionGoal { - public CollectWorkstationsGoal() { - super( - Material.LECTERN, Material.COMPOSTER, Material.GRINDSTONE, Material.BLAST_FURNACE, - Material.SMOKER, Material.FLETCHING_TABLE, Material.CARTOGRAPHY_TABLE, - Material.BREWING_STAND, Material.SMITHING_TABLE, Material.CAULDRON, - Material.LOOM, Material.STONECUTTER, Material.BARREL - ); - setCategory(SettingCategory.FASTEST_TIME); - } + public CollectWorkstationsGoal() { + super( + Material.LECTERN, Material.COMPOSTER, Material.GRINDSTONE, Material.BLAST_FURNACE, + Material.SMOKER, Material.FLETCHING_TABLE, Material.CARTOGRAPHY_TABLE, + Material.BREWING_STAND, Material.SMITHING_TABLE, Material.CAULDRON, + Material.LOOM, Material.STONECUTTER, Material.BARREL + ); + setCategory(SettingCategory.FASTEST_TIME); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FLETCHING_TABLE, Message.forName("item-collect-workstations-item")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FLETCHING_TABLE, Message.forName("item-collect-workstations-item")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java index 8bac031bc..e90d6996e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java @@ -21,33 +21,33 @@ @Since("2.1.2") public class EatCakeGoal extends SettingGoal { - public EatCakeGoal() { - super(); - setCategory(SettingCategory.FASTEST_TIME); - } - - @Override - public void getWinnersOnEnd(@NotNull List winners) { - - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CAKE, Message.forName("item-eat-cake-goal")); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInteract(PlayerInteractEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getClickedBlock() == null) return; - if (event.getClickedBlock().getType() != Material.CAKE) return; - if (event.getPlayer().getFoodLevel() >= 20) return; - // Execute on next tick to prevent hunger bar not filling up - Bukkit.getScheduler().runTask(plugin, () -> { - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); - }); - } + public EatCakeGoal() { + super(); + setCategory(SettingCategory.FASTEST_TIME); + } + + @Override + public void getWinnersOnEnd(@NotNull List winners) { + + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CAKE, Message.forName("item-eat-cake-goal")); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onInteract(PlayerInteractEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getClickedBlock() == null) return; + if (event.getClickedBlock().getType() != Material.CAKE) return; + if (event.getPlayer().getFoodLevel() >= 20) return; + // Execute on next tick to prevent hunger bar not filling up + Bukkit.getScheduler().runTask(plugin, () -> { + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java index e61660347..3c6ce547b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java @@ -16,27 +16,27 @@ @Since("2.1.2") public class EatMostGoal extends PointsGoal { - public EatMostGoal() { - super(); - setCategory(SettingCategory.SCORE_POINTS); - } + public EatMostGoal() { + super(); + setCategory(SettingCategory.SCORE_POINTS); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COOKIE, Message.forName("item-eat-most-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.COOKIE, Message.forName("item-eat-most-goal")); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onItemConsume(FoodLevelChangeEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - if (ignorePlayer(((Player) event.getEntity()))) return; - int changedFoodLevel = event.getFoodLevel() - event.getEntity().getFoodLevel(); - if (changedFoodLevel > 0) { - addPoints(event.getEntity().getUniqueId(), changedFoodLevel); - Message.forName("points-change").send(event.getEntity(), Prefix.CHALLENGES, "+" + changedFoodLevel); - } - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onItemConsume(FoodLevelChangeEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + if (ignorePlayer(((Player) event.getEntity()))) return; + int changedFoodLevel = event.getFoodLevel() - event.getEntity().getFoodLevel(); + if (changedFoodLevel > 0) { + addPoints(event.getEntity().getUniqueId(), changedFoodLevel); + Message.forName("points-change").send(event.getEntity(), Prefix.CHALLENGES, "+" + changedFoodLevel); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java index 0a3d9b3ca..035471b55 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java @@ -11,15 +11,15 @@ @Since("2.1.1") public class FindElytraGoal extends FindItemGoal { - public FindElytraGoal() { - super(Material.ELYTRA); - setCategory(SettingCategory.FASTEST_TIME); - } + public FindElytraGoal() { + super(Material.ELYTRA); + setCategory(SettingCategory.FASTEST_TIME); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ELYTRA, Message.forName("item-find-elytra-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ELYTRA, Message.forName("item-find-elytra-goal")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java index 61e478d00..94644d28d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java @@ -23,27 +23,27 @@ @RequireVersion(MinecraftVersion.V1_16) public class FinishRaidGoal extends SettingGoal { - public FinishRaidGoal() { - super(); - setCategory(SettingCategory.FASTEST_TIME); - } - - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CROSSBOW, Message.forName("item-finish-raid-goal")); - } - - @Override - public void getWinnersOnEnd(@Nonnull List winners) { - } - - @EventHandler(priority = EventPriority.HIGH) - public void onRaidFinish(@Nonnull RaidFinishEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getRaid().getStatus() != RaidStatus.VICTORY) return; - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, event::getWinners); - } + public FinishRaidGoal() { + super(); + setCategory(SettingCategory.FASTEST_TIME); + } + + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CROSSBOW, Message.forName("item-finish-raid-goal")); + } + + @Override + public void getWinnersOnEnd(@Nonnull List winners) { + } + + @EventHandler(priority = EventPriority.HIGH) + public void onRaidFinish(@Nonnull RaidFinishEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getRaid().getStatus() != RaidStatus.VICTORY) return; + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, event::getWinners); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java index 622a512d9..b5dede66f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java @@ -19,35 +19,35 @@ @Since("2.0") public class FirstOneToDieGoal extends SettingGoal { - private Player winner; - - public FirstOneToDieGoal() { - super(); - setCategory(SettingCategory.FASTEST_TIME); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-first-one-to-die-goal")); - } - - @Override - public void getWinnersOnEnd(@Nonnull List winners) { - if (winner != null) - winners.add(winner); - } - - @Override - protected void onDisable() { - winner = null; - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDeath(@Nonnull PlayerDeathEvent event) { - if (!shouldExecuteEffect()) return; - winner = event.getEntity(); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - } + private Player winner; + + public FirstOneToDieGoal() { + super(); + setCategory(SettingCategory.FASTEST_TIME); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-first-one-to-die-goal")); + } + + @Override + public void getWinnersOnEnd(@Nonnull List winners) { + if (winner != null) + winners.add(winner); + } + + @Override + protected void onDisable() { + winner = null; + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDeath(@Nonnull PlayerDeathEvent event) { + if (!shouldExecuteEffect()) return; + winner = event.getEntity(); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index 1cff0e3ff..0474468bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -25,66 +25,66 @@ @Since("2.2.0") public class GetFullHealthGoal extends SettingModifierGoal { - public GetFullHealthGoal() { - super(MenuType.GOAL, 1, 20, 20); - setCategory(SettingCategory.FASTEST_TIME); - } + public GetFullHealthGoal() { + super(MenuType.GOAL, 1, 20, 20); + setCategory(SettingCategory.FASTEST_TIME); + } - @Override - protected void onEnable() { - broadcastFiltered(player -> { - player.setHealth(getValue()); - }); - } + @Override + protected void onEnable() { + broadcastFiltered(player -> { + player.setHealth(getValue()); + }); + } - @Override - protected void onValueChange() { - broadcastFiltered(player -> { - player.setHealth(getValue()); - }); - } + @Override + protected void onValueChange() { + broadcastFiltered(player -> { + player.setHealth(getValue()); + }); + } - @Override - public void getWinnersOnEnd(@NotNull List winners) { - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); - if (attribute != null) { - if (player.getHealth() >= attribute.getBaseValue()) { - winners.add(player); - } - } - } - } + @Override + public void getWinnersOnEnd(@NotNull List winners) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute != null) { + if (player.getHealth() >= attribute.getBaseValue()) { + winners.add(player); + } + } + } + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.AZURE_BLUET, Message.forName("item-get-full-health-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.AZURE_BLUET, Message.forName("item-get-full-health-goal")); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-start-description").asArray(getValue() / 2f); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-heart-start-description").asArray(getValue() / 2f); + } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onHealthChange(EntityRegainHealthEvent event) { - if (!(event.getEntity() instanceof Player)) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer((Player) event.getEntity())) return; - Bukkit.getScheduler().runTask(plugin, () -> { - AttributeInstance attribute = ((Player) event.getEntity()).getAttribute(AttributeWrapper.MAX_HEALTH); - if (attribute != null && ((Player) event.getEntity()).getHealth() >= attribute.getBaseValue()) { - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - } - }); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onHealthChange(EntityRegainHealthEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer((Player) event.getEntity())) return; + Bukkit.getScheduler().runTask(plugin, () -> { + AttributeInstance attribute = ((Player) event.getEntity()).getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute != null && ((Player) event.getEntity()).getHealth() >= attribute.getBaseValue()) { + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java index 02041d067..149be26d3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java @@ -14,20 +14,20 @@ @Since("2.0") public class KillAllBossesGoal extends KillMobsGoal { - public KillAllBossesGoal() { - super(Arrays.asList(EntityType.ENDER_DRAGON, EntityType.WITHER, EntityType.ELDER_GUARDIAN)); - setCategory(SettingCategory.KILL_ENTITY); - } + public KillAllBossesGoal() { + super(Arrays.asList(EntityType.ENDER_DRAGON, EntityType.WITHER, EntityType.ELDER_GUARDIAN)); + setCategory(SettingCategory.KILL_ENTITY); + } - @Override - public Message getBossbarMessage() { - return Message.forName("bossbar-kill-all-bosses"); - } + @Override + public Message getBossbarMessage() { + return Message.forName("bossbar-kill-all-bosses"); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_SWORD, Message.forName("item-all-bosses-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIAMOND_SWORD, Message.forName("item-all-bosses-goal")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java index 0d9206315..06c17811c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java @@ -17,20 +17,20 @@ @RequireVersion(MinecraftVersion.V1_19) public class KillAllBossesNewGoal extends KillMobsGoal { - public KillAllBossesNewGoal() { - super(Arrays.asList(EntityType.ENDER_DRAGON, EntityType.WITHER, EntityType.ELDER_GUARDIAN, EntityType.WARDEN)); - setCategory(SettingCategory.KILL_ENTITY); - } + public KillAllBossesNewGoal() { + super(Arrays.asList(EntityType.ENDER_DRAGON, EntityType.WITHER, EntityType.ELDER_GUARDIAN, EntityType.WARDEN)); + setCategory(SettingCategory.KILL_ENTITY); + } - @Override - public Message getBossbarMessage() { - return Message.forName("bossbar-kill-all-bosses"); - } + @Override + public Message getBossbarMessage() { + return Message.forName("bossbar-kill-all-bosses"); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.NETHERITE_SWORD, Message.forName("item-all-bosses-new-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.NETHERITE_SWORD, Message.forName("item-all-bosses-new-goal")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java index 989e47a8d..86c667581 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java @@ -16,30 +16,30 @@ @Since("2.1.3") public class KillAllMobsGoal extends KillMobsGoal { - public KillAllMobsGoal() { - super(getAllMobsToKill()); - setCategory(SettingCategory.KILL_ENTITY); - } - - static List getAllMobsToKill() { - LinkedList list = new LinkedList<>(Arrays.asList(EntityType.values())); - list.removeIf(type -> !type.isAlive()); - list.remove(EntityType.GIANT); - list.remove(EntityType.ILLUSIONER); - list.remove(EntityType.PLAYER); - list.remove(EntityType.ARMOR_STAND); - return list; - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOW, Message.forName("item-all-mobs-goal")); - } - - @Override - public Message getBossbarMessage() { - return Message.forName("bossbar-kill-all-mobs"); - } + public KillAllMobsGoal() { + super(getAllMobsToKill()); + setCategory(SettingCategory.KILL_ENTITY); + } + + static List getAllMobsToKill() { + LinkedList list = new LinkedList<>(Arrays.asList(EntityType.values())); + list.removeIf(type -> !type.isAlive()); + list.remove(EntityType.GIANT); + list.remove(EntityType.ILLUSIONER); + list.remove(EntityType.PLAYER); + list.remove(EntityType.ARMOR_STAND); + return list; + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BOW, Message.forName("item-all-mobs-goal")); + } + + @Override + public Message getBossbarMessage() { + return Message.forName("bossbar-kill-all-mobs"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java index 8e846d715..d8ae5cfcd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java @@ -18,41 +18,41 @@ @Since("2.1.3") public class KillAllMonsterGoal extends KillMobsGoal { - public KillAllMonsterGoal() { - super(getAllMobsToKill()); - setCategory(SettingCategory.KILL_ENTITY); - } - - static List getAllMobsToKill() { - LinkedList list = new LinkedList<>(Arrays.asList(EntityType.values())); - list.removeIf(type -> !type.isAlive()); - list.removeIf(type -> { - assert type.getEntityClass() != null; - return !Monster.class.isAssignableFrom(type.getEntityClass()); - }); - list.add(EntityType.PHANTOM); - list.add(EntityType.ENDER_DRAGON); - list.add(EntityType.SHULKER); - list.add(EntityType.GHAST); - list.add(EntityType.MAGMA_CUBE); - list.add(EntityType.SLIME); - list.remove(EntityType.GIANT); - list.remove(EntityType.ILLUSIONER); - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_16)) { - list.add(EntityType.HOGLIN); - } - return list; - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ARROW, Message.forName("item-all-monster-goal")); - } - - @Override - public Message getBossbarMessage() { - return Message.forName("bossbar-kill-all-monster"); - } + public KillAllMonsterGoal() { + super(getAllMobsToKill()); + setCategory(SettingCategory.KILL_ENTITY); + } + + static List getAllMobsToKill() { + LinkedList list = new LinkedList<>(Arrays.asList(EntityType.values())); + list.removeIf(type -> !type.isAlive()); + list.removeIf(type -> { + assert type.getEntityClass() != null; + return !Monster.class.isAssignableFrom(type.getEntityClass()); + }); + list.add(EntityType.PHANTOM); + list.add(EntityType.ENDER_DRAGON); + list.add(EntityType.SHULKER); + list.add(EntityType.GHAST); + list.add(EntityType.MAGMA_CUBE); + list.add(EntityType.SLIME); + list.remove(EntityType.GIANT); + list.remove(EntityType.ILLUSIONER); + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_16)) { + list.add(EntityType.HOGLIN); + } + return list; + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ARROW, Message.forName("item-all-monster-goal")); + } + + @Override + public Message getBossbarMessage() { + return Message.forName("bossbar-kill-all-monster"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java index 485f83260..02650f3b6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java @@ -15,21 +15,21 @@ @Since("2.0") public class KillElderGuardianGoal extends KillEntityGoal { - public KillElderGuardianGoal() { - super(EntityType.ELDER_GUARDIAN); - setCategory(SettingCategory.KILL_ENTITY); - } + public KillElderGuardianGoal() { + super(EntityType.ELDER_GUARDIAN); + setCategory(SettingCategory.KILL_ENTITY); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PRISMARINE_SHARD, Message.forName("item-elder-guardian-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.PRISMARINE_SHARD, Message.forName("item-elder-guardian-goal")); + } - @Nonnull - @Override - public SoundSample getStartSound() { - return new SoundSample().addSound(Sound.ENTITY_ELDER_GUARDIAN_CURSE, 1); - } + @Nonnull + @Override + public SoundSample getStartSound() { + return new SoundSample().addSound(Sound.ENTITY_ELDER_GUARDIAN_CURSE, 1); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java index 019320b33..1b1290707 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java @@ -14,22 +14,22 @@ public class KillEnderDragonGoal extends KillEntityGoal { - public KillEnderDragonGoal() { - super(EntityType.ENDER_DRAGON, Environment.THE_END, true); - setCategory(SettingCategory.KILL_ENTITY); - setOneWinner(false); - } + public KillEnderDragonGoal() { + super(EntityType.ENDER_DRAGON, Environment.THE_END, true); + setCategory(SettingCategory.KILL_ENTITY); + setOneWinner(false); + } - @Nullable - @Override - public SoundSample getWinSound() { - return null; - } + @Nullable + @Override + public SoundSample getWinSound() { + return null; + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DRAGON_EGG, Message.forName("item-dragon-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DRAGON_EGG, Message.forName("item-dragon-goal")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java index 377ab6dcd..d2d062dda 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java @@ -15,22 +15,22 @@ @Since("2.0") public class KillIronGolemGoal extends KillEntityGoal { - public KillIronGolemGoal() { - super(EntityType.IRON_GOLEM); - setCategory(SettingCategory.KILL_ENTITY); - this.killerNeeded = true; - } + public KillIronGolemGoal() { + super(EntityType.IRON_GOLEM); + setCategory(SettingCategory.KILL_ENTITY); + this.killerNeeded = true; + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.IRON_INGOT, Message.forName("item-iron-golem-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.IRON_INGOT, Message.forName("item-iron-golem-goal")); + } - @Nonnull - @Override - public SoundSample getStartSound() { - return new SoundSample().addSound(Sound.ENTITY_IRON_GOLEM_HURT, 1); - } + @Nonnull + @Override + public SoundSample getStartSound() { + return new SoundSample().addSound(Sound.ENTITY_IRON_GOLEM_HURT, 1); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java index 8295a2712..d45086267 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import javax.annotation.Nonnull; import net.anweisen.utilities.bukkit.utils.animation.SoundSample; import net.anweisen.utilities.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; @@ -11,25 +10,27 @@ import org.bukkit.Material; import org.bukkit.Sound; +import javax.annotation.Nonnull; + @Since("2.0") public class KillSnowGolemGoal extends KillEntityGoal { - public KillSnowGolemGoal() { - super(MinecraftNameWrapper.SNOW_GOLEM); - setCategory(SettingCategory.KILL_ENTITY); - this.killerNeeded = true; - } + public KillSnowGolemGoal() { + super(MinecraftNameWrapper.SNOW_GOLEM); + setCategory(SettingCategory.KILL_ENTITY); + this.killerNeeded = true; + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SNOWBALL, Message.forName("item-snow-golem-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SNOWBALL, Message.forName("item-snow-golem-goal")); + } - @Nonnull - @Override - public SoundSample getStartSound() { - return new SoundSample().addSound(Sound.ENTITY_SNOW_GOLEM_DEATH, 1); - } + @Nonnull + @Override + public SoundSample getStartSound() { + return new SoundSample().addSound(Sound.ENTITY_SNOW_GOLEM_DEATH, 1); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java index 68e989ae9..1059a1d3a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java @@ -18,21 +18,21 @@ @RequireVersion(MinecraftVersion.V1_19) public class KillWardenGoal extends KillEntityGoal { - public KillWardenGoal() { - super(EntityType.WARDEN); - setCategory(SettingCategory.KILL_ENTITY); - } + public KillWardenGoal() { + super(EntityType.WARDEN); + setCategory(SettingCategory.KILL_ENTITY); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ECHO_SHARD, Message.forName("item-warden-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ECHO_SHARD, Message.forName("item-warden-goal")); + } - @Nonnull - @Override - public SoundSample getStartSound() { - return new SoundSample().addSound(Sound.ENTITY_WARDEN_EMERGE, 0.2f); - } + @Nonnull + @Override + public SoundSample getStartSound() { + return new SoundSample().addSound(Sound.ENTITY_WARDEN_EMERGE, 0.2f); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java index 258886f2b..6bf8f41fc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java @@ -13,21 +13,21 @@ public class KillWitherGoal extends KillEntityGoal { - public KillWitherGoal() { - super(EntityType.WITHER); - setCategory(SettingCategory.KILL_ENTITY); - } + public KillWitherGoal() { + super(EntityType.WITHER); + setCategory(SettingCategory.KILL_ENTITY); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.NETHER_STAR, Message.forName("item-wither-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.NETHER_STAR, Message.forName("item-wither-goal")); + } - @Nonnull - @Override - public SoundSample getStartSound() { - return new SoundSample().addSound(Sound.ENTITY_WITHER_SPAWN, 1); - } + @Nonnull + @Override + public SoundSample getStartSound() { + return new SoundSample().addSound(Sound.ENTITY_WITHER_SPAWN, 1); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java index f4b1afab1..3aa89c5a3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java @@ -21,49 +21,49 @@ @Since("2.0") public class LastManStandingGoal extends SettingGoal { - private Player winner; + private Player winner; - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.IRON_HELMET, Message.forName("item-last-man-standing-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.IRON_HELMET, Message.forName("item-last-man-standing-goal")); + } - @Override - public void getWinnersOnEnd(@Nonnull List winners) { - determineWinner(); - if (winner != null) - winners.add(winner); - } + @Override + public void getWinnersOnEnd(@Nonnull List winners) { + determineWinner(); + if (winner != null) + winners.add(winner); + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { - if (!isEnabled()) return; - checkEnd(); - } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { + if (!isEnabled()) return; + checkEnd(); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onLeave(@Nonnull PlayerQuitEvent event) { - if (!isEnabled()) return; - checkEnd(); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onLeave(@Nonnull PlayerQuitEvent event) { + if (!isEnabled()) return; + checkEnd(); + } - protected void determineWinner() { - int playersLiving = 0; - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.getGameMode() == GameMode.SPECTATOR) continue; - playersLiving++; - winner = player; - } + protected void determineWinner() { + int playersLiving = 0; + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.getGameMode() == GameMode.SPECTATOR) continue; + playersLiving++; + winner = player; + } - if (playersLiving != 1) - winner = null; - } + if (playersLiving != 1) + winner = null; + } - protected void checkEnd() { - determineWinner(); - if (winner == null) return; - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - } + protected void checkEnd() { + determineWinner(); + if (winner == null) return; + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java index 3abeba17c..a834abae8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java @@ -13,15 +13,15 @@ @Since("2.1.0") public class MaxHeightGoal extends FirstPlayerAtHeightGoal { - public MaxHeightGoal() { - setCategory(SettingCategory.FASTEST_TIME); - setHeightToGetTo(ChallengeAPI.getGameWorld(Environment.NORMAL).getMaxHeight()); - } + public MaxHeightGoal() { + setCategory(SettingCategory.FASTEST_TIME); + setHeightToGetTo(ChallengeAPI.getGameWorld(Environment.NORMAL).getMaxHeight()); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FEATHER, Message.forName("item-max-height-goal").asItemDescription(getHeightToGetTo())); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FEATHER, Message.forName("item-max-height-goal").asItemDescription(getHeightToGetTo())); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java index fe2ae7e01..abe805f0d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java @@ -14,15 +14,15 @@ @Since("2.1.0") public class MinHeightGoal extends FirstPlayerAtHeightGoal { - public MinHeightGoal() { - setCategory(SettingCategory.FASTEST_TIME); - setHeightToGetTo(BukkitReflectionUtils.getMinHeight(ChallengeAPI.getGameWorld(Environment.NORMAL)) + 1); - } + public MinHeightGoal() { + setCategory(SettingCategory.FASTEST_TIME); + setHeightToGetTo(BukkitReflectionUtils.getMinHeight(ChallengeAPI.getGameWorld(Environment.NORMAL)) + 1); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BEDROCK, Message.forName("item-min-height-goal").asItemDescription(getHeightToGetTo())); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BEDROCK, Message.forName("item-min-height-goal").asItemDescription(getHeightToGetTo())); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java index df37703b3..09cfad354 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java @@ -13,22 +13,22 @@ public class MineMostBlocksGoal extends PointsGoal { - public MineMostBlocksGoal() { - super(); - setCategory(SettingCategory.SCORE_POINTS); - } + public MineMostBlocksGoal() { + super(); + setCategory(SettingCategory.SCORE_POINTS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-mine-most-blocks-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-mine-most-blocks-goal")); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (!isEnabled()) return; - if (event.getBlock().isPassable()) return; - collect(event.getPlayer()); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (!isEnabled()) return; + if (event.getBlock().isPassable()) return; + collect(event.getPlayer()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java index 8cc7975bf..98f0b326b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java @@ -21,63 +21,63 @@ @Since("2.0.2") public class MostEmeraldsGoal extends PointsGoal { - public MostEmeraldsGoal() { - super(); - setCategory(SettingCategory.SCORE_POINTS); - } + public MostEmeraldsGoal() { + super(); + setCategory(SettingCategory.SCORE_POINTS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.EMERALD, Message.forName("item-most-emeralds-goal")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.EMERALD, Message.forName("item-most-emeralds-goal")); + } - @Override - protected void onEnable() { - broadcastFiltered(this::updatePoints); - super.onEnable(); - } + @Override + protected void onEnable() { + broadcastFiltered(this::updatePoints); + super.onEnable(); + } - private void updatePoints(@Nonnull Player player) { - Bukkit.getScheduler().runTask(plugin, () -> { - int count = getEmeraldsCount(player); - setPoints(player.getUniqueId(), count); - }); - } + private void updatePoints(@Nonnull Player player) { + Bukkit.getScheduler().runTask(plugin, () -> { + int count = getEmeraldsCount(player); + setPoints(player.getUniqueId(), count); + }); + } - private int getEmeraldsCount(@Nonnull Player player) { - PlayerInventory inventory = player.getInventory(); - int count = 0; - for (ItemStack itemStack : inventory.getContents()) { - if (itemStack != null && itemStack.getType() == Material.EMERALD) - count += itemStack.getAmount(); - } - if (player.getItemOnCursor().getType() == Material.EMERALD) - count += player.getItemOnCursor().getAmount(); - return count; - } + private int getEmeraldsCount(@Nonnull Player player) { + PlayerInventory inventory = player.getInventory(); + int count = 0; + for (ItemStack itemStack : inventory.getContents()) { + if (itemStack != null && itemStack.getType() == Material.EMERALD) + count += itemStack.getAmount(); + } + if (player.getItemOnCursor().getType() == Material.EMERALD) + count += player.getItemOnCursor().getAmount(); + return count; + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUpdate(@Nonnull InventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getWhoClicked() instanceof Player)) return; - Player player = (Player) event.getWhoClicked(); - if (ignorePlayer(player)) return; - updatePoints(player); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onUpdate(@Nonnull InventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getWhoClicked() instanceof Player)) return; + Player player = (Player) event.getWhoClicked(); + if (ignorePlayer(player)) return; + updatePoints(player); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUpdate(@Nonnull PlayerPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - updatePoints(event.getPlayer()); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onUpdate(@Nonnull PlayerPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + updatePoints(event.getPlayer()); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUpdate(@Nonnull PlayerDropItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - updatePoints(event.getPlayer()); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onUpdate(@Nonnull PlayerDropItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + updatePoints(event.getPlayer()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java index 8d9f1cec1..8f1e96643 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java @@ -19,66 +19,66 @@ @Since("2.1.1") public class MostOresGoal extends PointsGoal { - public MostOresGoal() { - super(); - setCategory(SettingCategory.SCORE_POINTS); - } + public MostOresGoal() { + super(); + setCategory(SettingCategory.SCORE_POINTS); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COAL_ORE, Message.forName("item-most-ores-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.COAL_ORE, Message.forName("item-most-ores-goal")); + } - private int getPointsForOre(Material material) { - switch (material) { - case EMERALD_ORE: - case DEEPSLATE_EMERALD_ORE: - return 15; - case DIAMOND_ORE: - case DEEPSLATE_DIAMOND_ORE: - return 10; - case LAPIS_ORE: - case DEEPSLATE_LAPIS_ORE: - return 8; - case GOLD_ORE: - case DEEPSLATE_GOLD_ORE: - return 6; - case IRON_ORE: - case DEEPSLATE_IRON_ORE: - return 4; - case COAL_ORE: - case DEEPSLATE_COAL_ORE: - case REDSTONE_ORE: - case DEEPSLATE_REDSTONE_ORE: - return 2; - default: - return 0; - } - } + private int getPointsForOre(Material material) { + switch (material) { + case EMERALD_ORE: + case DEEPSLATE_EMERALD_ORE: + return 15; + case DIAMOND_ORE: + case DEEPSLATE_DIAMOND_ORE: + return 10; + case LAPIS_ORE: + case DEEPSLATE_LAPIS_ORE: + return 8; + case GOLD_ORE: + case DEEPSLATE_GOLD_ORE: + return 6; + case IRON_ORE: + case DEEPSLATE_IRON_ORE: + return 4; + case COAL_ORE: + case DEEPSLATE_COAL_ORE: + case REDSTONE_ORE: + case DEEPSLATE_REDSTONE_ORE: + return 2; + default: + return 0; + } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUpdate(@Nonnull BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - int points = getPointsForOre(event.getBlock().getType()); - if (points > 0) { - Message.forName("points-change").send(event.getPlayer(), Prefix.CHALLENGES, "+" + points); - SoundSample.PLING.play(event.getPlayer()); - addPoints(event.getPlayer().getUniqueId(), points); - } - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onUpdate(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + int points = getPointsForOre(event.getBlock().getType()); + if (points > 0) { + Message.forName("points-change").send(event.getPlayer(), Prefix.CHALLENGES, "+" + points); + SoundSample.PLING.play(event.getPlayer()); + addPoints(event.getPlayer().getUniqueId(), points); + } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUpdate(@Nonnull BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - int points = getPointsForOre(event.getBlock().getType()); - if (points > 0) { - SoundSample.BASS_OFF.play(event.getPlayer()); - Message.forName("points-change").send(event.getPlayer(), Prefix.CHALLENGES, "-" + points); - removePoints(event.getPlayer().getUniqueId(), points); - } - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onUpdate(@Nonnull BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + int points = getPointsForOre(event.getBlock().getType()); + if (points > 0) { + SoundSample.BASS_OFF.play(event.getPlayer()); + Message.forName("points-change").send(event.getPlayer(), Prefix.CHALLENGES, "-" + points); + removePoints(event.getPlayer().getUniqueId(), points); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java index c773eb0ad..27a6b402e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java @@ -18,8 +18,11 @@ import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; -import org.bukkit.*; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.Particle.DustOptions; +import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; @@ -35,137 +38,137 @@ @Since("2.1.0") public class RaceGoal extends SettingModifierGoal { - protected long seed = IRandom.create().getSeed(); - - private Location goal; - - public RaceGoal() { - super(MenuType.GOAL, 1, 30, 5); - setCategory(SettingCategory.FASTEST_TIME); - } - - @Override - public void getWinnersOnEnd(@NotNull List winners) { - } - - @Override - protected void onEnable() { - reloadGoalLocation(); - bossbar.setContent((bar, player) -> { - bar.setColor(BarColor.GREEN); - if (player.getWorld() == goal.getWorld()) { - - Location relativeGoal = goal.clone(); - relativeGoal.setY(player.getLocation().getY()); - relativeGoal.add(0.5, 0, 0.5); - int distance = (int) Math.round(player.getLocation().distance(relativeGoal)); - - bar.setTitle(Message.forName("bossbar-race-goal-info") - .asString(goal.getBlockX(), goal.getBlockZ(), distance)); - } else { - bar.setTitle(Message.forName("bossbar-race-goal") - .asString(goal.getBlockX(), goal.getBlockZ())); - } - - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - goal = null; - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-range-blocks").asString(getValue() * 100)); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-range-blocks-description").asArray(getValue() * 100); - } - - - @Override - protected void onValueChange() { - reloadGoalLocation(); - bossbar.update(); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STRUCTURE_VOID, Message.forName("item-race-goal")); - } - - @ScheduledTask(ticks = 20) - public void onSecond() { - if (goal == null) return; - bossbar.update(); - broadcast(player -> { - Location relativeGoal = goal.clone(); - relativeGoal.setY(player.getLocation().getY()); - relativeGoal.add(0.5, 0, 0.5); - ParticleUtils.drawLine(player, player.getLocation(), relativeGoal, MinecraftNameWrapper.REDSTONE_DUST, new DustOptions( - Color.LIME, 1), 1, 0.5, 50); - - if (player.getWorld() != goal.getWorld()) return; - if (player.getLocation().distance(relativeGoal) > 20) return; - ParticleUtils.spawnParticleCircleAroundRadius(Challenges.getInstance(), relativeGoal, - MinecraftNameWrapper.INSTANT_EFFECT, 0.75, 0.5); - }); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; - if (event.getTo().getWorld() != goal.getWorld()) return; - if (event.getTo() == null) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), goal)) { - Message.forName("race-goal-reached").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); - ParticleUtils.spawnParticleCircleAroundRadius(Challenges.getInstance(), event.getTo(), MinecraftNameWrapper.ENTITY_EFFECT, 0.75, 2); - } - } - - private void reloadGoalLocation() { - - World world = ChallengeAPI.getGameWorld(Environment.NORMAL); - int y = 999; - - IRandom iRandom = IRandom.create(seed); - // Some more calculations to prevent the result cords to always end with the same digits. - int max = getValue() * 100 - iRandom.nextInt(getValue() - getValue() / 2); - - int x = iRandom.nextInt(max * 2) - max; - int z = iRandom.nextInt(max * 2) - max; - goal = new Location(world, x, y, z); - } - - @Override - public void loadGameState(@NotNull Document document) { - if (!document.contains("seed")) { - seed = IRandom.create().getSeed(); - return; - } - - long seed = document.getLong("seed"); - if (this.seed == seed) return; - this.seed = seed; - - if (!isEnabled()) return; - reloadGoalLocation(); - bossbar.update(); - } - - @Override - public void writeGameState(@NotNull Document document) { - document.set("seed", seed); - } + protected long seed = IRandom.create().getSeed(); + + private Location goal; + + public RaceGoal() { + super(MenuType.GOAL, 1, 30, 5); + setCategory(SettingCategory.FASTEST_TIME); + } + + @Override + public void getWinnersOnEnd(@NotNull List winners) { + } + + @Override + protected void onEnable() { + reloadGoalLocation(); + bossbar.setContent((bar, player) -> { + bar.setColor(BarColor.GREEN); + if (player.getWorld() == goal.getWorld()) { + + Location relativeGoal = goal.clone(); + relativeGoal.setY(player.getLocation().getY()); + relativeGoal.add(0.5, 0, 0.5); + int distance = (int) Math.round(player.getLocation().distance(relativeGoal)); + + bar.setTitle(Message.forName("bossbar-race-goal-info") + .asString(goal.getBlockX(), goal.getBlockZ(), distance)); + } else { + bar.setTitle(Message.forName("bossbar-race-goal") + .asString(goal.getBlockX(), goal.getBlockZ())); + } + + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + goal = null; + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-range-blocks").asString(getValue() * 100)); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return Message.forName("item-range-blocks-description").asArray(getValue() * 100); + } + + + @Override + protected void onValueChange() { + reloadGoalLocation(); + bossbar.update(); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.STRUCTURE_VOID, Message.forName("item-race-goal")); + } + + @ScheduledTask(ticks = 20) + public void onSecond() { + if (goal == null) return; + bossbar.update(); + broadcast(player -> { + Location relativeGoal = goal.clone(); + relativeGoal.setY(player.getLocation().getY()); + relativeGoal.add(0.5, 0, 0.5); + ParticleUtils.drawLine(player, player.getLocation(), relativeGoal, MinecraftNameWrapper.REDSTONE_DUST, new DustOptions( + Color.LIME, 1), 1, 0.5, 50); + + if (player.getWorld() != goal.getWorld()) return; + if (player.getLocation().distance(relativeGoal) > 20) return; + ParticleUtils.spawnParticleCircleAroundRadius(Challenges.getInstance(), relativeGoal, + MinecraftNameWrapper.INSTANT_EFFECT, 0.75, 0.5); + }); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; + if (event.getTo().getWorld() != goal.getWorld()) return; + if (event.getTo() == null) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), goal)) { + Message.forName("race-goal-reached").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); + ParticleUtils.spawnParticleCircleAroundRadius(Challenges.getInstance(), event.getTo(), MinecraftNameWrapper.ENTITY_EFFECT, 0.75, 2); + } + } + + private void reloadGoalLocation() { + + World world = ChallengeAPI.getGameWorld(Environment.NORMAL); + int y = 999; + + IRandom iRandom = IRandom.create(seed); + // Some more calculations to prevent the result cords to always end with the same digits. + int max = getValue() * 100 - iRandom.nextInt(getValue() - getValue() / 2); + + int x = iRandom.nextInt(max * 2) - max; + int z = iRandom.nextInt(max * 2) - max; + goal = new Location(world, x, y, z); + } + + @Override + public void loadGameState(@NotNull Document document) { + if (!document.contains("seed")) { + seed = IRandom.create().getSeed(); + return; + } + + long seed = document.getLong("seed"); + if (this.seed == seed) return; + this.seed = seed; + + if (!isEnabled()) return; + reloadGoalLocation(); + bossbar.update(); + } + + @Override + public void writeGameState(@NotNull Document document) { + document.set("seed", seed); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java index 3eab72397..711414e17 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java @@ -36,249 +36,249 @@ public class ExtremeForceBattleGoal extends ForceBattleDisplayGoal> { - public ExtremeForceBattleGoal() { - super(Message.forName("menu-extreme-force-battle-goal-settings")); - - registerSetting("give-item", new BooleanSubSetting( - () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), - false - )); - registerSetting("give-block", new BooleanSubSetting( - () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-block-battle-goal-give-block")), - false - )); + public ExtremeForceBattleGoal() { + super(Message.forName("menu-extreme-force-battle-goal-settings")); + + registerSetting("give-item", new BooleanSubSetting( + () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), + false + )); + registerSetting("give-block", new BooleanSubSetting( + () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-block-battle-goal-give-block")), + false + )); + } + + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BOOK, Message.forName("item-extreme-force-battle-goal")); + } + + @Override + protected ForceTarget[] getTargetsPossibleToFind() { + //Currently not needed as the setRandomTarget logic of the ForceBattleGoal class is not used + return new ForceTarget[0]; + } + + @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) + public void checkTargets() { + for (Map.Entry> entry : currentTarget.entrySet()) { + UUID uuid = entry.getKey(); + ForceTarget target = entry.getValue(); + Player player = Bukkit.getPlayer(uuid); + if (player == null || ignorePlayer(player)) continue; + + if (target.check(player)) { + handleTargetFound(player); + } } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOOK, Message.forName("item-extreme-force-battle-goal")); + } + + @Override + public ForceTarget getTargetFromDocument(Document document, String path) { + Document targetDocument = document.getDocument(path); + String targetTypeString = targetDocument.getString("type"); + String value = targetDocument.getString("value"); + + TargetType targetType = TargetType.valueOf(targetTypeString); + return targetType.parse().apply(value); + } + + @Override + public List> getListFromDocument(Document document, String path) { + List targetDocuments = document.getDocumentList(path); + List> targets = new ArrayList<>(); + for (Document targetDocument : targetDocuments) { + String targetTypeString = targetDocument.getString("type"); + Object value = targetDocument.getObject("value"); + + TargetType targetType = TargetType.valueOf(targetTypeString); + targets.add(targetType.parse().apply(value)); } - - @Override - protected ForceTarget[] getTargetsPossibleToFind() { - //Currently not needed as the setRandomTarget logic of the ForceBattleGoal class is not used - return new ForceTarget[0]; + return targets; + } + + @Override + public void setTargetInDocument(Document document, String path, ForceTarget target) { + document.set(path, Document.create().set("type", target.getType().name()).set("value", target.getTargetSaveObject())); + } + + @Override + public void setFoundListInDocument(Document document, String path, List> targets) { + List documents = new ArrayList<>(); + for (ForceTarget forceTarget : targets) { + documents.add(Document.create().set("type", forceTarget.getType().name()).set("value", forceTarget.getTargetSaveObject())); } + document.set(path, documents); + } - @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) - public void checkTargets() { - for (Map.Entry> entry : currentTarget.entrySet()) { - UUID uuid = entry.getKey(); - ForceTarget target = entry.getValue(); - Player player = Bukkit.getPlayer(uuid); - if (player == null || ignorePlayer(player)) continue; - - if (target.check(player)) { - handleTargetFound(player); - } - } - } + @Override + protected Message getLeaderboardTitleMessage() { + return Message.forName("extreme-force-battle-leaderboard"); + } - @Override - public ForceTarget getTargetFromDocument(Document document, String path) { - Document targetDocument = document.getDocument(path); - String targetTypeString = targetDocument.getString("type"); - String value = targetDocument.getString("value"); + @Override + public void setRandomTarget(Player player) { + updateDisplayStand(player); - TargetType targetType = TargetType.valueOf(targetTypeString); - return targetType.parse().apply(value); - } + TargetType targetType = globalRandom.choose(TargetType.values()); + ForceTarget newTarget = targetType.getRandomTarget().apply(player); - @Override - public List> getListFromDocument(Document document, String path) { - List targetDocuments = document.getDocumentList(path); - List> targets = new ArrayList<>(); - for (Document targetDocument : targetDocuments) { - String targetTypeString = targetDocument.getString("type"); - Object value = targetDocument.getObject("value"); - - TargetType targetType = TargetType.valueOf(targetTypeString); - targets.add(targetType.parse().apply(value)); - } - return targets; + if (newTarget instanceof AdvancementTarget) { + AdvancementProgress progress = player.getAdvancementProgress(((AdvancementTarget) newTarget).getTarget()); + progress.getAwardedCriteria().forEach(progress::revokeCriteria); } - @Override - public void setTargetInDocument(Document document, String path, ForceTarget target) { - document.set(path, Document.create().set("type", target.getType().name()).set("value", target.getTargetSaveObject())); - } + currentTarget.put(player.getUniqueId(), newTarget); + getNewTargetMessage(newTarget) + .send(player, Prefix.CHALLENGES, getTargetMessageReplacement(newTarget)); + SoundSample.PLING.play(player); - @Override - public void setFoundListInDocument(Document document, String path, List> targets) { - List documents = new ArrayList<>(); - for (ForceTarget forceTarget : targets) { - documents.add(Document.create().set("type", forceTarget.getType().name()).set("value", forceTarget.getTargetSaveObject())); - } - document.set(path, documents); + if (scoreboard.isShown()) { + scoreboard.update(); } - @Override - protected Message getLeaderboardTitleMessage() { - return Message.forName("extreme-force-battle-leaderboard"); + } + + @Override + protected void setScoreboardContent() { + scoreboard.setContent((board, player) -> { + List ingamePlayers = ChallengeAPI.getIngamePlayers(); + int emptyLinesAvailable = 15 - ingamePlayers.size(); + + if (emptyLinesAvailable > 0) { + board.addLine(""); + emptyLinesAvailable--; + } + + for (int i = 0; i < ingamePlayers.size() && i < 15; i++) { + Player ingamePlayer = ingamePlayers.get(i); + ForceTarget target = currentTarget.get(ingamePlayer.getUniqueId()); + String display = target == null ? Message.forName("none").asString() : (target.getScoreboardDisplayMessage().asString(getTargetName(target))); + board.addLine(NameHelper.getName(ingamePlayer) + " §8» §e" + display); + } + + if (emptyLinesAvailable > 0) { + board.addLine(""); + } + }); + } + + @Override + protected boolean shouldRegisterDupedTargetsSetting() { + return false; + } + + @Override + public void handleJokerUse(Player player) { + ForceTarget target = currentTarget.get(player.getUniqueId()); + if (giveItemOnSkip() && target instanceof ItemTarget) { + ItemTarget itemTarget = (ItemTarget) target; + InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), itemTarget.getTarget()); + } else if (giveBlockOnSkip() && target instanceof BlockTarget) { + BlockTarget blockTarget = (BlockTarget) target; + InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), blockTarget.getTarget()); } - - @Override - public void setRandomTarget(Player player) { - updateDisplayStand(player); - - TargetType targetType = globalRandom.choose(TargetType.values()); - ForceTarget newTarget = targetType.getRandomTarget().apply(player); - - if (newTarget instanceof AdvancementTarget) { - AdvancementProgress progress = player.getAdvancementProgress(((AdvancementTarget) newTarget).getTarget()); - progress.getAwardedCriteria().forEach(progress::revokeCriteria); - } - - currentTarget.put(player.getUniqueId(), newTarget); - getNewTargetMessage(newTarget) - .send(player, Prefix.CHALLENGES, getTargetMessageReplacement(newTarget)); - SoundSample.PLING.play(player); - - if (scoreboard.isShown()) { - scoreboard.update(); - } - + super.handleJokerUse(player); + } + + public enum TargetType { + ITEM(object -> { + return new ItemTarget(Material.valueOf((String) object)); + }, player -> { + return new ItemTarget(globalRandom.choose(ItemTarget.getPossibleItems())); + }), + BLOCK(object -> { + return new BlockTarget(Material.valueOf((String) object)); + }, player -> { + return new BlockTarget(globalRandom.choose(BlockTarget.getPossibleBlocks())); + }), + HEIGHT(object -> { + return new HeightTarget(Integer.valueOf((String) object)); + }, player -> { + World world = ChallengeAPI.getGameWorld(World.Environment.NORMAL); + int height = globalRandom.range(BukkitReflectionUtils.getMinHeight(world), world.getMaxHeight()); + return new HeightTarget(height); + }), + MOB(object -> { + return new MobTarget(EntityType.valueOf((String) object)); + }, player -> { + return new MobTarget(globalRandom.choose(MobTarget.getPossibleMobs())); + }), + BIOME(object -> { + return new BiomeTarget(Biome.valueOf((String) object)); + }, player -> { + return new BiomeTarget(globalRandom.choose(BiomeTarget.getPossibleBiomes())); + }), + DAMAGE(object -> { + return new DamageTarget(Integer.valueOf((String) object)); + }, player -> { + return new DamageTarget(globalRandom.range(1, 19)); + }), + ADVANCEMENT(object -> { + return new AdvancementTarget(Bukkit.getAdvancement(Objects.requireNonNull(NamespacedKey.fromString((String) object)))); + }, player -> { + return new AdvancementTarget(globalRandom.choose(AdvancementTarget.getPossibleAdvancements())); + }), + POSITION(object -> { + Document document = (Document) object; + return new PositionTarget(document.getDouble("x"), document.getDouble("z")); + }, PositionTarget::new); + + private final Function> parseFunction; + private final Function> randomTargetFunction; + + TargetType(Function> parseFunction, Function> randomTargetFunction) { + this.parseFunction = parseFunction; + this.randomTargetFunction = randomTargetFunction; } - @Override - protected void setScoreboardContent() { - scoreboard.setContent((board, player) -> { - List ingamePlayers = ChallengeAPI.getIngamePlayers(); - int emptyLinesAvailable = 15 - ingamePlayers.size(); - - if (emptyLinesAvailable > 0) { - board.addLine(""); - emptyLinesAvailable--; - } - - for (int i = 0; i < ingamePlayers.size() && i < 15; i++) { - Player ingamePlayer = ingamePlayers.get(i); - ForceTarget target = currentTarget.get(ingamePlayer.getUniqueId()); - String display = target == null ? Message.forName("none").asString() : (target.getScoreboardDisplayMessage().asString(getTargetName(target))); - board.addLine(NameHelper.getName(ingamePlayer) + " §8» §e" + display); - } - - if (emptyLinesAvailable > 0) { - board.addLine(""); - } - }); + public Function> parse() { + return parseFunction; } - @Override - protected boolean shouldRegisterDupedTargetsSetting() { - return false; + public Function> getRandomTarget() { + return randomTargetFunction; } - - @Override - public void handleJokerUse(Player player) { - ForceTarget target = currentTarget.get(player.getUniqueId()); - if (giveItemOnSkip() && target instanceof ItemTarget) { - ItemTarget itemTarget = (ItemTarget) target; - InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), itemTarget.getTarget()); - } else if (giveBlockOnSkip() && target instanceof BlockTarget) { - BlockTarget blockTarget = (BlockTarget) target; - InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), blockTarget.getTarget()); - } - super.handleJokerUse(player); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onKill(@Nonnull EntityDeathEvent event) { + if (!shouldExecuteEffect()) return; + LivingEntity entity = event.getEntity(); + Player killer = entity.getKiller(); + if (killer == null) return; + if (ignorePlayer(killer)) return; + if (currentTarget.get(killer.getUniqueId()) == null) return; + if (currentTarget.get(killer.getUniqueId()) instanceof MobTarget) { + MobTarget target = (MobTarget) currentTarget.get(killer.getUniqueId()); + if (target.getTarget() != entity.getType()) return; + handleTargetFound(killer); } - - public enum TargetType { - ITEM(object -> { - return new ItemTarget(Material.valueOf((String) object)); - }, player -> { - return new ItemTarget(globalRandom.choose(ItemTarget.getPossibleItems())); - }), - BLOCK(object -> { - return new BlockTarget(Material.valueOf((String) object)); - }, player -> { - return new BlockTarget(globalRandom.choose(BlockTarget.getPossibleBlocks())); - }), - HEIGHT(object -> { - return new HeightTarget(Integer.valueOf((String) object)); - }, player -> { - World world = ChallengeAPI.getGameWorld(World.Environment.NORMAL); - int height = globalRandom.range(BukkitReflectionUtils.getMinHeight(world), world.getMaxHeight()); - return new HeightTarget(height); - }), - MOB(object -> { - return new MobTarget(EntityType.valueOf((String) object)); - }, player -> { - return new MobTarget(globalRandom.choose(MobTarget.getPossibleMobs())); - }), - BIOME(object -> { - return new BiomeTarget(Biome.valueOf((String) object)); - }, player -> { - return new BiomeTarget(globalRandom.choose(BiomeTarget.getPossibleBiomes())); - }), - DAMAGE(object -> { - return new DamageTarget(Integer.valueOf((String) object)); - }, player -> { - return new DamageTarget(globalRandom.range(1, 19)); - }), - ADVANCEMENT(object -> { - return new AdvancementTarget(Bukkit.getAdvancement(Objects.requireNonNull(NamespacedKey.fromString((String) object)))); - }, player -> { - return new AdvancementTarget(globalRandom.choose(AdvancementTarget.getPossibleAdvancements())); - }), - POSITION(object -> { - Document document = (Document) object; - return new PositionTarget(document.getDouble("x"), document.getDouble("z")); - }, PositionTarget::new); - - private final Function> parseFunction; - private final Function> randomTargetFunction; - - TargetType(Function> parseFunction, Function> randomTargetFunction) { - this.parseFunction = parseFunction; - this.randomTargetFunction = randomTargetFunction; - } - - public Function> parse() { - return parseFunction; - } - - public Function> getRandomTarget() { - return randomTargetFunction; - } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + if (currentTarget.get(player.getUniqueId()) == null) return; + if (currentTarget.get(player.getUniqueId()) instanceof DamageTarget) { + DamageTarget target = (DamageTarget) currentTarget.get(player.getUniqueId()); + int damage = (int) ChallengeHelper.getFinalDamage(event); + if (damage != target.getTarget()) return; + handleTargetFound(player); } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onKill(@Nonnull EntityDeathEvent event) { - if (!shouldExecuteEffect()) return; - LivingEntity entity = event.getEntity(); - Player killer = entity.getKiller(); - if (killer == null) return; - if (ignorePlayer(killer)) return; - if (currentTarget.get(killer.getUniqueId()) == null) return; - if (currentTarget.get(killer.getUniqueId()) instanceof MobTarget) { - MobTarget target = (MobTarget) currentTarget.get(killer.getUniqueId()); - if (target.getTarget() != entity.getType()) return; - handleTargetFound(killer); - } - } + private boolean giveItemOnSkip() { + return getSetting("give-item").getAsBoolean(); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - if (currentTarget.get(player.getUniqueId()) == null) return; - if (currentTarget.get(player.getUniqueId()) instanceof DamageTarget) { - DamageTarget target = (DamageTarget) currentTarget.get(player.getUniqueId()); - int damage = (int) ChallengeHelper.getFinalDamage(event); - if (damage != target.getTarget()) return; - handleTargetFound(player); - } - } - - private boolean giveItemOnSkip() { - return getSetting("give-item").getAsBoolean(); - } - - private boolean giveBlockOnSkip() { - return getSetting("give-block").getAsBoolean(); - } + private boolean giveBlockOnSkip() { + return getSetting("give-block").getAsBoolean(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java index 2a637edd4..9290b0d2b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java @@ -25,81 +25,81 @@ @Since("2.2.0") public class ForceAdvancementBattleGoal extends ForceBattleGoal { - public ForceAdvancementBattleGoal() { - super(Message.forName("menu-force-advancement-battle-goal-settings")); - } + public ForceAdvancementBattleGoal() { + super(Message.forName("menu-force-advancement-battle-goal-settings")); + } - private void resetAdvancementProgress(Player player, Advancement advancement) { - if (advancement == null) return; - AdvancementProgress progress = player.getAdvancementProgress(advancement); - progress.getAwardedCriteria().forEach(progress::revokeCriteria); - } + private void resetAdvancementProgress(Player player, Advancement advancement) { + if (advancement == null) return; + AdvancementProgress progress = player.getAdvancementProgress(advancement); + progress.getAwardedCriteria().forEach(progress::revokeCriteria); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-force-advancement-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-force-advancement-battle-goal")); + } - @Override - protected AdvancementTarget[] getTargetsPossibleToFind() { - List advancements = AdvancementTarget.getPossibleAdvancements(); - return advancements.stream().map(AdvancementTarget::new).toArray(AdvancementTarget[]::new); - } + @Override + protected AdvancementTarget[] getTargetsPossibleToFind() { + List advancements = AdvancementTarget.getPossibleAdvancements(); + return advancements.stream().map(AdvancementTarget::new).toArray(AdvancementTarget[]::new); + } - @Override - public AdvancementTarget getTargetFromDocument(Document document, String path) { - String advancementKey = document.getString(path); - try { - assert advancementKey != null; - NamespacedKey namespacedKey = BukkitReflectionUtils.fromString(advancementKey); - assert namespacedKey != null; - return new AdvancementTarget(Bukkit.getAdvancement(namespacedKey)); - } catch (Exception exception) { - // DON'T EXIST - } - return null; - } + @Override + public AdvancementTarget getTargetFromDocument(Document document, String path) { + String advancementKey = document.getString(path); + try { + assert advancementKey != null; + NamespacedKey namespacedKey = BukkitReflectionUtils.fromString(advancementKey); + assert namespacedKey != null; + return new AdvancementTarget(Bukkit.getAdvancement(namespacedKey)); + } catch (Exception exception) { + // DON'T EXIST + } + return null; + } - @Override - public List getListFromDocument(Document document, String path) { - List advancementKeys = document.getStringList(path); - List advancementTargets = new ArrayList<>(); - for (String advancementKey : advancementKeys) { - try { - advancementTargets.add(new AdvancementTarget(Bukkit.getAdvancement(Objects.requireNonNull(BukkitReflectionUtils.fromString(advancementKey))))); - } catch (Exception exception) { - // DON'T EXIST - } - } - return advancementTargets; - } + @Override + public List getListFromDocument(Document document, String path) { + List advancementKeys = document.getStringList(path); + List advancementTargets = new ArrayList<>(); + for (String advancementKey : advancementKeys) { + try { + advancementTargets.add(new AdvancementTarget(Bukkit.getAdvancement(Objects.requireNonNull(BukkitReflectionUtils.fromString(advancementKey))))); + } catch (Exception exception) { + // DON'T EXIST + } + } + return advancementTargets; + } - @Override - protected Message getLeaderboardTitleMessage() { - return Message.forName("force-advancement-battle-leaderboard"); - } + @Override + protected Message getLeaderboardTitleMessage() { + return Message.forName("force-advancement-battle-leaderboard"); + } - @Override - public void setRandomTarget(Player player) { - super.setRandomTarget(player); - resetAdvancementProgress(player, currentTarget.get(player.getUniqueId()).getTarget()); - } + @Override + public void setRandomTarget(Player player) { + super.setRandomTarget(player); + resetAdvancementProgress(player, currentTarget.get(player.getUniqueId()).getTarget()); + } - @EventHandler(priority = EventPriority.MONITOR) - public void onAdvancement(PlayerAdvancementDoneEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - Player player = event.getPlayer(); - if (event.getAdvancement() == currentTarget.get(player.getUniqueId()).getTarget()) { - handleTargetFound(player); - } - } + @EventHandler(priority = EventPriority.MONITOR) + public void onAdvancement(PlayerAdvancementDoneEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + Player player = event.getPlayer(); + if (event.getAdvancement() == currentTarget.get(player.getUniqueId()).getTarget()) { + handleTargetFound(player); + } + } - @Override - public void handleTargetFound(Player player) { - super.handleTargetFound(player); - Advancement advancement = currentTarget.get(player.getUniqueId()).getTarget(); - resetAdvancementProgress(player, advancement); - } + @Override + public void handleTargetFound(Player player) { + super.handleTargetFound(player); + Advancement advancement = currentTarget.get(player.getUniqueId()).getTarget(); + resetAdvancementProgress(player, advancement); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java index 680cf5fb5..3010f5a48 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java @@ -19,51 +19,51 @@ public class ForceBiomeBattleGoal extends ForceBattleGoal { - public ForceBiomeBattleGoal() { - super(Message.forName("menu-force-biome-battle-goal-settings")); - } + public ForceBiomeBattleGoal() { + super(Message.forName("menu-force-biome-battle-goal-settings")); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FILLED_MAP, Message.forName("item-force-biome-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FILLED_MAP, Message.forName("item-force-biome-battle-goal")); + } - @Override - protected BiomeTarget[] getTargetsPossibleToFind() { - List biomes = BiomeTarget.getPossibleBiomes(); - return biomes.stream().map(BiomeTarget::new).toArray(BiomeTarget[]::new); - } + @Override + protected BiomeTarget[] getTargetsPossibleToFind() { + List biomes = BiomeTarget.getPossibleBiomes(); + return biomes.stream().map(BiomeTarget::new).toArray(BiomeTarget[]::new); + } - @Override - public BiomeTarget getTargetFromDocument(Document document, String path) { - return new BiomeTarget(Registry.BIOME.get(NamespacedKey.minecraft(Objects.requireNonNull(document.getString(path)).toLowerCase()))); - } + @Override + public BiomeTarget getTargetFromDocument(Document document, String path) { + return new BiomeTarget(Registry.BIOME.get(NamespacedKey.minecraft(Objects.requireNonNull(document.getString(path)).toLowerCase()))); + } - @Override - public List getListFromDocument(Document document, String path) { - return document.getStringList(path).stream() - .map(biomeName -> new BiomeTarget( - Registry.BIOME.get(NamespacedKey.minecraft(biomeName.toLowerCase())) - )) - .collect(Collectors.toList()); - } + @Override + public List getListFromDocument(Document document, String path) { + return document.getStringList(path).stream() + .map(biomeName -> new BiomeTarget( + Registry.BIOME.get(NamespacedKey.minecraft(biomeName.toLowerCase())) + )) + .collect(Collectors.toList()); + } - @Override - protected Message getLeaderboardTitleMessage() { - return Message.forName("force-biome-battle-leaderboard"); - } + @Override + protected Message getLeaderboardTitleMessage() { + return Message.forName("force-biome-battle-leaderboard"); + } - @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) - public void checkBiomes() { - if (!shouldExecuteEffect()) return; - broadcastFiltered(player -> { - BiomeTarget target = currentTarget.get(player.getUniqueId()); - if (target != null && target.check(player)) { - handleTargetFound(player); - } - }); - } + @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) + public void checkBiomes() { + if (!shouldExecuteEffect()) return; + broadcastFiltered(player -> { + BiomeTarget target = currentTarget.get(player.getUniqueId()); + if (target != null && target.check(player)) { + handleTargetFound(player); + } + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java index 6b72f552d..1ecf964ab 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java @@ -19,63 +19,63 @@ @Since("2.2.0") public class ForceBlockBattleGoal extends ForceBattleDisplayGoal { - public ForceBlockBattleGoal() { - super(Message.forName("menu-force-block-battle-goal-settings")); + public ForceBlockBattleGoal() { + super(Message.forName("menu-force-block-battle-goal-settings")); - registerSetting("give-block", new BooleanSubSetting( - () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-block-battle-goal-give-block")), - false - )); - } + registerSetting("give-block", new BooleanSubSetting( + () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-block-battle-goal-give-block")), + false + )); + } - @Override - protected BlockTarget[] getTargetsPossibleToFind() { - List materials = BlockTarget.getPossibleBlocks(); - return materials.stream().map(BlockTarget::new).toArray(BlockTarget[]::new); - } + @Override + protected BlockTarget[] getTargetsPossibleToFind() { + List materials = BlockTarget.getPossibleBlocks(); + return materials.stream().map(BlockTarget::new).toArray(BlockTarget[]::new); + } - @Override - public BlockTarget getTargetFromDocument(Document document, String path) { - return new BlockTarget(document.getEnum(path, Material.class)); - } + @Override + public BlockTarget getTargetFromDocument(Document document, String path) { + return new BlockTarget(document.getEnum(path, Material.class)); + } - @Override - public List getListFromDocument(Document document, String path) { - return document.getEnumList(path, Material.class).stream().map(BlockTarget::new).collect(Collectors.toList()); - } + @Override + public List getListFromDocument(Document document, String path) { + return document.getEnumList(path, Material.class).stream().map(BlockTarget::new).collect(Collectors.toList()); + } - @Override - public Message getLeaderboardTitleMessage() { - return Message.forName("force-block-battle-leaderboard"); - } + @Override + public Message getLeaderboardTitleMessage() { + return Message.forName("force-block-battle-leaderboard"); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-force-block-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-force-block-battle-goal")); + } - @Override - public void handleJokerUse(Player player) { - super.handleJokerUse(player); - if (giveBlockOnSkip()) { - InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), currentTarget.get(player.getUniqueId()).getTarget()); - } + @Override + public void handleJokerUse(Player player) { + super.handleJokerUse(player); + if (giveBlockOnSkip()) { + InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), currentTarget.get(player.getUniqueId()).getTarget()); } + } - @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) - public void checkBlocks() { - if (!shouldExecuteEffect()) return; - broadcastFiltered(player -> { - BlockTarget target = currentTarget.get(player.getUniqueId()); - if (target != null && target.check(player)) { - handleTargetFound(player); - } - }); - } + @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) + public void checkBlocks() { + if (!shouldExecuteEffect()) return; + broadcastFiltered(player -> { + BlockTarget target = currentTarget.get(player.getUniqueId()); + if (target != null && target.check(player)) { + handleTargetFound(player); + } + }); + } - private boolean giveBlockOnSkip() { - return getSetting("give-block").getAsBoolean(); - } + private boolean giveBlockOnSkip() { + return getSetting("give-block").getAsBoolean(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java index e229b34ea..64896b11d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java @@ -19,57 +19,57 @@ public class ForceDamageBattleGoal extends ForceBattleGoal { - public ForceDamageBattleGoal() { - super(Message.forName("menu-force-damage-battle-goal-settings")); - } + public ForceDamageBattleGoal() { + super(Message.forName("menu-force-damage-battle-goal-settings")); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.TOTEM_OF_UNDYING, Message.forName("item-force-damage-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.TOTEM_OF_UNDYING, Message.forName("item-force-damage-battle-goal")); + } - @Override - protected DamageTarget[] getTargetsPossibleToFind() { - return new DamageTarget[0]; //Not used - } + @Override + protected DamageTarget[] getTargetsPossibleToFind() { + return new DamageTarget[0]; //Not used + } - @Override - protected DamageTarget getRandomTarget(Player player) { - return new DamageTarget(globalRandom.range(1, 19)); - } + @Override + protected DamageTarget getRandomTarget(Player player) { + return new DamageTarget(globalRandom.range(1, 19)); + } - @Override - public DamageTarget getTargetFromDocument(Document document, String path) { - return new DamageTarget(document.getInt(path)); - } + @Override + public DamageTarget getTargetFromDocument(Document document, String path) { + return new DamageTarget(document.getInt(path)); + } - @Override - public List getListFromDocument(Document document, String path) { - return document.getIntegerList(path).stream().map(DamageTarget::new).collect(Collectors.toList()); - } + @Override + public List getListFromDocument(Document document, String path) { + return document.getIntegerList(path).stream().map(DamageTarget::new).collect(Collectors.toList()); + } - @Override - protected Message getLeaderboardTitleMessage() { - return Message.forName("force-damage-battle-leaderboard"); - } + @Override + protected Message getLeaderboardTitleMessage() { + return Message.forName("force-damage-battle-leaderboard"); + } - @Override - protected boolean shouldRegisterDupedTargetsSetting() { - return false; - } + @Override + protected boolean shouldRegisterDupedTargetsSetting() { + return false; + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - if (currentTarget.get(player.getUniqueId()) == null) return; - DamageTarget target = currentTarget.get(player.getUniqueId()); - int damage = (int) ChallengeHelper.getFinalDamage(event); - if (damage != target.getTarget()) return; - handleTargetFound(player); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + if (currentTarget.get(player.getUniqueId()) == null) return; + DamageTarget target = currentTarget.get(player.getUniqueId()); + int damage = (int) ChallengeHelper.getFinalDamage(event); + if (damage != target.getTarget()) return; + handleTargetFound(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java index f72bdbf81..e454d07e0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java @@ -18,55 +18,55 @@ public class ForceHeightBattleGoal extends ForceBattleGoal { - public ForceHeightBattleGoal() { - super(Message.forName("menu-force-height-battle-goal-settings")); - } + public ForceHeightBattleGoal() { + super(Message.forName("menu-force-height-battle-goal-settings")); + } - @Override - protected HeightTarget[] getTargetsPossibleToFind() { - return new HeightTarget[0]; //Not used - } + @Override + protected HeightTarget[] getTargetsPossibleToFind() { + return new HeightTarget[0]; //Not used + } - @Override - protected HeightTarget getRandomTarget(Player player) { - World world = player.getWorld(); - return new HeightTarget(globalRandom.range(BukkitReflectionUtils.getMinHeight(world), world.getMaxHeight())); - } + @Override + protected HeightTarget getRandomTarget(Player player) { + World world = player.getWorld(); + return new HeightTarget(globalRandom.range(BukkitReflectionUtils.getMinHeight(world), world.getMaxHeight())); + } - @Override - public HeightTarget getTargetFromDocument(Document document, String path) { - return new HeightTarget(document.getInt(path)); - } + @Override + public HeightTarget getTargetFromDocument(Document document, String path) { + return new HeightTarget(document.getInt(path)); + } - @Override - public List getListFromDocument(Document document, String path) { - return document.getIntegerList(path).stream().map(HeightTarget::new).collect(Collectors.toList()); - } + @Override + public List getListFromDocument(Document document, String path) { + return document.getIntegerList(path).stream().map(HeightTarget::new).collect(Collectors.toList()); + } - @Override - protected Message getLeaderboardTitleMessage() { - return Message.forName("force-height-battle-leaderboard"); - } + @Override + protected Message getLeaderboardTitleMessage() { + return Message.forName("force-height-battle-leaderboard"); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.RABBIT_FOOT, Message.forName("item-force-height-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.RABBIT_FOOT, Message.forName("item-force-height-battle-goal")); + } - @Override - protected boolean shouldRegisterDupedTargetsSetting() { - return false; - } + @Override + protected boolean shouldRegisterDupedTargetsSetting() { + return false; + } - @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) - public void checkHeights() { - if (!shouldExecuteEffect()) return; - broadcastFiltered(player -> { - HeightTarget target = currentTarget.get(player.getUniqueId()); - if (target != null && target.check(player)) { - handleTargetFound(player); - } - }); - } + @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) + public void checkHeights() { + if (!shouldExecuteEffect()) return; + broadcastFiltered(player -> { + HeightTarget target = currentTarget.get(player.getUniqueId()); + if (target != null && target.check(player)) { + handleTargetFound(player); + } + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java index b74e60a7a..bec126bed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java @@ -21,76 +21,76 @@ @Since("2.1.3") public class ForceItemBattleGoal extends ForceBattleDisplayGoal { - public ForceItemBattleGoal() { - super(Message.forName("menu-force-item-battle-goal-settings")); + public ForceItemBattleGoal() { + super(Message.forName("menu-force-item-battle-goal-settings")); - registerSetting("give-item", new BooleanSubSetting( - () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), - false - )); - } + registerSetting("give-item", new BooleanSubSetting( + () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), + false + )); + } - @Override - protected ItemTarget[] getTargetsPossibleToFind() { - List materials = ItemTarget.getPossibleItems(); - return materials.stream().map(ItemTarget::new).toArray(ItemTarget[]::new); - } + @Override + protected ItemTarget[] getTargetsPossibleToFind() { + List materials = ItemTarget.getPossibleItems(); + return materials.stream().map(ItemTarget::new).toArray(ItemTarget[]::new); + } - @Override - public ItemTarget getTargetFromDocument(Document document, String path) { - return new ItemTarget(document.getEnum(path, Material.class)); - } + @Override + public ItemTarget getTargetFromDocument(Document document, String path) { + return new ItemTarget(document.getEnum(path, Material.class)); + } - @Override - public List getListFromDocument(Document document, String path) { - return document.getEnumList(path, Material.class).stream().map(ItemTarget::new).collect(Collectors.toList()); - } + @Override + public List getListFromDocument(Document document, String path) { + return document.getEnumList(path, Material.class).stream().map(ItemTarget::new).collect(Collectors.toList()); + } - @Override - public Message getLeaderboardTitleMessage() { - return Message.forName("force-item-battle-leaderboard"); - } + @Override + public Message getLeaderboardTitleMessage() { + return Message.forName("force-item-battle-leaderboard"); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ITEM_FRAME, Message.forName("item-force-item-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ITEM_FRAME, Message.forName("item-force-item-battle-goal")); + } - @Override - public void handleJokerUse(Player player) { - if (giveItemOnSkip()) { - InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), currentTarget.get(player.getUniqueId()).getTarget()); - } - super.handleJokerUse(player); - } + @Override + public void handleJokerUse(Player player) { + if (giveItemOnSkip()) { + InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), currentTarget.get(player.getUniqueId()).getTarget()); + } + super.handleJokerUse(player); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onClick(PlayerInventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getClickedInventory() == null) return; - if (event.getCurrentItem() == null) return; - Material material = currentTarget.get(event.getPlayer().getUniqueId()).getTarget(); - if (material == null) return; - if (material == event.getCurrentItem().getType()) { - handleTargetFound(event.getPlayer()); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onClick(PlayerInventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getClickedInventory() == null) return; + if (event.getCurrentItem() == null) return; + Material material = currentTarget.get(event.getPlayer().getUniqueId()).getTarget(); + if (material == null) return; + if (material == event.getCurrentItem().getType()) { + handleTargetFound(event.getPlayer()); + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPickup(PlayerPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - Material material = currentTarget.get(event.getPlayer().getUniqueId()).getTarget(); - if (material == null) return; - if (material == event.getItem().getItemStack().getType()) { - handleTargetFound(event.getPlayer()); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPickup(PlayerPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + Material material = currentTarget.get(event.getPlayer().getUniqueId()).getTarget(); + if (material == null) return; + if (material == event.getItem().getItemStack().getType()) { + handleTargetFound(event.getPlayer()); + } + } - private boolean giveItemOnSkip() { - return getSetting("give-item").getAsBoolean(); - } + private boolean giveItemOnSkip() { + return getSetting("give-item").getAsBoolean(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java index 542f64d5d..be2caa7ec 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java @@ -22,48 +22,48 @@ @Since("2.2.0") public class ForceMobBattleGoal extends ForceBattleDisplayGoal { - public ForceMobBattleGoal() { - super(Message.forName("menu-force-mob-battle-goal-settings")); - } + public ForceMobBattleGoal() { + super(Message.forName("menu-force-mob-battle-goal-settings")); + } - @Override - protected MobTarget[] getTargetsPossibleToFind() { - List entityTypes = MobTarget.getPossibleMobs(); - return entityTypes.stream().map(MobTarget::new).toArray(MobTarget[]::new); - } + @Override + protected MobTarget[] getTargetsPossibleToFind() { + List entityTypes = MobTarget.getPossibleMobs(); + return entityTypes.stream().map(MobTarget::new).toArray(MobTarget[]::new); + } - @Override - protected Message getLeaderboardTitleMessage() { - return Message.forName("force-mob-battle-leaderboard"); - } + @Override + protected Message getLeaderboardTitleMessage() { + return Message.forName("force-mob-battle-leaderboard"); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOW, Message.forName("item-force-mob-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BOW, Message.forName("item-force-mob-battle-goal")); + } - @Override - public MobTarget getTargetFromDocument(Document document, String path) { - return new MobTarget(document.getEnum(path, EntityType.class)); - } + @Override + public MobTarget getTargetFromDocument(Document document, String path) { + return new MobTarget(document.getEnum(path, EntityType.class)); + } - @Override - public List getListFromDocument(Document document, String path) { - return document.getEnumList(path, EntityType.class).stream().map(MobTarget::new).collect(Collectors.toList()); - } + @Override + public List getListFromDocument(Document document, String path) { + return document.getEnumList(path, EntityType.class).stream().map(MobTarget::new).collect(Collectors.toList()); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onKill(@Nonnull EntityDeathEvent event) { - if (!shouldExecuteEffect()) return; - LivingEntity entity = event.getEntity(); - Player killer = entity.getKiller(); - if (killer == null) return; - if (ignorePlayer(killer)) return; - if (currentTarget.get(killer.getUniqueId()) == null) return; - if (entity.getType() == currentTarget.get(killer.getUniqueId()).getTarget()) { - handleTargetFound(killer); - } - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onKill(@Nonnull EntityDeathEvent event) { + if (!shouldExecuteEffect()) return; + LivingEntity entity = event.getEntity(); + Player killer = entity.getKiller(); + if (killer == null) return; + if (ignorePlayer(killer)) return; + if (currentTarget.get(killer.getUniqueId()) == null) return; + if (entity.getType() == currentTarget.get(killer.getUniqueId()).getTarget()) { + handleTargetFound(killer); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java index a800dbff4..885f1ceda 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java @@ -15,69 +15,69 @@ import java.util.stream.Collectors; public class ForcePositionBattleGoal extends ForceBattleGoal { - public ForcePositionBattleGoal() { - super(Message.forName("menu-force-position-battle-goal-settings")); - registerSetting("radius", new NumberSubSetting( - () -> new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-position-battle-radius")), - value -> null, - value -> "§e" + (value * 100), - 1, - 100, - 15 - )); - } + public ForcePositionBattleGoal() { + super(Message.forName("menu-force-position-battle-goal-settings")); + registerSetting("radius", new NumberSubSetting( + () -> new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-position-battle-radius")), + value -> null, + value -> "§e" + (value * 100), + 1, + 100, + 15 + )); + } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-position-battle-goal")); - } + @NotNull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-position-battle-goal")); + } - @Override - protected PositionTarget[] getTargetsPossibleToFind() { - return new PositionTarget[0]; //Not used - } + @Override + protected PositionTarget[] getTargetsPossibleToFind() { + return new PositionTarget[0]; //Not used + } - @Override - protected PositionTarget getRandomTarget(Player player) { - return new PositionTarget(player, getRadius()); - } + @Override + protected PositionTarget getRandomTarget(Player player) { + return new PositionTarget(player, getRadius()); + } - @Override - public PositionTarget getTargetFromDocument(Document document, String path) { - return new PositionTarget( - document.getDocument(path).getDouble("x"), - document.getDocument(path).getDouble("z") - ); - } + @Override + public PositionTarget getTargetFromDocument(Document document, String path) { + return new PositionTarget( + document.getDocument(path).getDouble("x"), + document.getDocument(path).getDouble("z") + ); + } - @Override - public List getListFromDocument(Document document, String path) { - return document.getDocumentList(path).stream().map(doc -> new PositionTarget(doc.getDouble("x"), doc.getDouble("z"))).collect(Collectors.toList()); - } + @Override + public List getListFromDocument(Document document, String path) { + return document.getDocumentList(path).stream().map(doc -> new PositionTarget(doc.getDouble("x"), doc.getDouble("z"))).collect(Collectors.toList()); + } - @Override - protected Message getLeaderboardTitleMessage() { - return Message.forName("force-position-battle-leaderboard"); - } + @Override + protected Message getLeaderboardTitleMessage() { + return Message.forName("force-position-battle-leaderboard"); + } - @Override - protected boolean shouldRegisterDupedTargetsSetting() { - return false; - } + @Override + protected boolean shouldRegisterDupedTargetsSetting() { + return false; + } - @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) - public void checkPositions() { - if (!shouldExecuteEffect()) return; - broadcastFiltered(player -> { - PositionTarget target = currentTarget.get(player.getUniqueId()); - if (target != null && target.check(player)) { - handleTargetFound(player); - } - }); - } + @ScheduledTask(ticks = 5, async = false, timerPolicy = TimerPolicy.STARTED) + public void checkPositions() { + if (!shouldExecuteEffect()) return; + broadcastFiltered(player -> { + PositionTarget target = currentTarget.get(player.getUniqueId()); + if (target != null && target.check(player)) { + handleTargetFound(player); + } + }); + } - protected int getRadius() { - return getSetting("radius").getAsInt() * 100; - } + protected int getRadius() { + return getSetting("radius").getAsInt() * 100; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java index 62ebf3f97..2cc333635 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java @@ -12,59 +12,59 @@ public class AdvancementTarget extends ForceTarget { - public AdvancementTarget(Advancement target) { - super(target); - } + public AdvancementTarget(Advancement target) { + super(target); + } - @Override - public boolean check(Player player) { - return player.getAdvancementProgress(target).isDone(); - } + @Override + public boolean check(Player player) { + return player.getAdvancementProgress(target).isDone(); + } - public static List getPossibleAdvancements() { - List advancements = new ArrayList<>(); - Bukkit.getServer().advancementIterator().forEachRemaining(advancement -> { - String string = advancement.getKey().toString(); - if (!string.contains(":recipes/") && !string.endsWith("root")) { - advancements.add(advancement); - } - }); - return advancements; - } + public static List getPossibleAdvancements() { + List advancements = new ArrayList<>(); + Bukkit.getServer().advancementIterator().forEachRemaining(advancement -> { + String string = advancement.getKey().toString(); + if (!string.contains(":recipes/") && !string.endsWith("root")) { + advancements.add(advancement); + } + }); + return advancements; + } - @Override - public Object toMessage() { - return target; - } + @Override + public Object toMessage() { + return target; + } - @Override - public String getName() { - return BukkitStringUtils.getAdvancementTitle(target).toPlainText(); - } + @Override + public String getName() { + return BukkitStringUtils.getAdvancementTitle(target).toPlainText(); + } - @Override - public Message getNewTargetMessage() { - return Message.forName("force-advancement-battle-new-advancement"); - } + @Override + public Message getNewTargetMessage() { + return Message.forName("force-advancement-battle-new-advancement"); + } - @Override - public Message getCompletedMessage() { - return Message.forName("force-advancement-battle-completed"); - } + @Override + public Message getCompletedMessage() { + return Message.forName("force-advancement-battle-completed"); + } - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.ADVANCEMENT; - } + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.ADVANCEMENT; + } - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-advancement-target-display"); - } + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-advancement-target-display"); + } - @Override - public Object getTargetSaveObject() { - return target.getKey().toString(); - } + @Override + public Object getTargetSaveObject() { + return target.getKey().toString(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java index 11ba3212e..ddf3035f0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java @@ -12,50 +12,50 @@ public class BiomeTarget extends ForceTarget { - public BiomeTarget(Biome target) { - super(target); - } - - @Override - public boolean check(Player player) { - return player.getLocation().getBlock().getBiome() == target; - } - - public static List getPossibleBiomes() { - return Arrays.stream(Biome.values()) - .filter(biome -> !biome.name().contains("VOID")) - .filter(biome -> !biome.name().equals("CUSTOM")) - .collect(Collectors.toList()); - } - - @Override - public Object toMessage() { - return target; - } - - @Override - public String getName() { - return BukkitStringUtils.getBiomeName(target).toPlainText(); - } - - @Override - public Message getNewTargetMessage() { - return Message.forName("extreme-force-battle-new-biome"); - } - - @Override - public Message getCompletedMessage() { - return Message.forName("extreme-force-battle-found-biome"); - } - - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.BIOME; - } - - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-biome-target-display"); - } + public BiomeTarget(Biome target) { + super(target); + } + + @Override + public boolean check(Player player) { + return player.getLocation().getBlock().getBiome() == target; + } + + public static List getPossibleBiomes() { + return Arrays.stream(Biome.values()) + .filter(biome -> !biome.name().contains("VOID")) + .filter(biome -> !biome.name().equals("CUSTOM")) + .collect(Collectors.toList()); + } + + @Override + public Object toMessage() { + return target; + } + + @Override + public String getName() { + return BukkitStringUtils.getBiomeName(target).toPlainText(); + } + + @Override + public Message getNewTargetMessage() { + return Message.forName("extreme-force-battle-new-biome"); + } + + @Override + public Message getCompletedMessage() { + return Message.forName("extreme-force-battle-found-biome"); + } + + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.BIOME; + } + + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-biome-target-display"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java index 1728cbc6c..51ed23a66 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; +import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import org.bukkit.Material; @@ -15,54 +15,54 @@ public class BlockTarget extends ForceTarget { - public BlockTarget(Material target) { - super(target); - } + public BlockTarget(Material target) { + super(target); + } - @Override - public boolean check(Player player) { - return EntityUtils.isStandingOnBlock(player, target); - } + @Override + public boolean check(Player player) { + return EntityUtils.isStandingOnBlock(player, target); + } - public static List getPossibleBlocks() { - List materials = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - materials.removeIf(material -> !ItemUtils.blockIsAvailableInSurvival(material)); - return materials; - } + public static List getPossibleBlocks() { + List materials = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + materials.removeIf(material -> !ItemUtils.blockIsAvailableInSurvival(material)); + return materials; + } - @Override - public Object toMessage() { - return target; - } + @Override + public Object toMessage() { + return target; + } - @Override - public String getName() { - return BukkitStringUtils.getItemName(target).toPlainText(); - } + @Override + public String getName() { + return BukkitStringUtils.getItemName(target).toPlainText(); + } - @Override - public Message getNewTargetMessage() { - return Message.forName("force-block-battle-new-block"); - } + @Override + public Message getNewTargetMessage() { + return Message.forName("force-block-battle-new-block"); + } - @Override - public Message getCompletedMessage() { - return Message.forName("force-block-battle-found"); - } + @Override + public Message getCompletedMessage() { + return Message.forName("force-block-battle-found"); + } - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.BLOCK; - } + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.BLOCK; + } - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-block-target-display"); - } + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-block-target-display"); + } - @Override - public String toString() { - return target.name(); - } + @Override + public String toString() { + return target.name(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java index 2cc448a88..9ac2322ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java @@ -6,43 +6,43 @@ public class DamageTarget extends ForceTarget { - public DamageTarget(Integer target) { - super(target); - } - - @Override - public boolean check(Player player) { - return false; - } - - @Override - public Object toMessage() { - return (double) target / 2; - } - - @Override - public String getName() { - return String.valueOf((double) target / 2); - } - - @Override - public Message getNewTargetMessage() { - return Message.forName("extreme-force-battle-new-damage"); - } - - @Override - public Message getCompletedMessage() { - return Message.forName("extreme-force-battle-took-damage"); - } - - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.DAMAGE; - } - - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-damage-target-display"); - } + public DamageTarget(Integer target) { + super(target); + } + + @Override + public boolean check(Player player) { + return false; + } + + @Override + public Object toMessage() { + return (double) target / 2; + } + + @Override + public String getName() { + return String.valueOf((double) target / 2); + } + + @Override + public Message getNewTargetMessage() { + return Message.forName("extreme-force-battle-new-damage"); + } + + @Override + public Message getCompletedMessage() { + return Message.forName("extreme-force-battle-took-damage"); + } + + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.DAMAGE; + } + + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-damage-target-display"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java index 167bfbd0a..dfa948547 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java @@ -13,35 +13,41 @@ @Getter public abstract class ForceTarget { - protected final T target; + protected final T target; - protected ForceTarget(T target) { - this.target = target; - } + protected ForceTarget(T target) { + this.target = target; + } - public abstract boolean check(Player player); - public abstract Object toMessage(); - public abstract String getName(); - public abstract Message getNewTargetMessage(); - public abstract Message getCompletedMessage(); - public abstract ExtremeForceBattleGoal.TargetType getType(); - public abstract Message getScoreboardDisplayMessage(); - - @Override - public String toString() { - return target.toString(); - } + public abstract boolean check(Player player); - public void updateDisplayStand(@NotNull ArmorStand armorStand) { - if (target instanceof Material) { - Objects.requireNonNull(armorStand.getEquipment()).setHelmet(new ItemStack((Material) target)); - } else { - Objects.requireNonNull(armorStand.getEquipment()).setHelmet(null); - } - } + public abstract Object toMessage(); + + public abstract String getName(); + + public abstract Message getNewTargetMessage(); - public Object getTargetSaveObject() { - return target.toString(); + public abstract Message getCompletedMessage(); + + public abstract ExtremeForceBattleGoal.TargetType getType(); + + public abstract Message getScoreboardDisplayMessage(); + + @Override + public String toString() { + return target.toString(); + } + + public void updateDisplayStand(@NotNull ArmorStand armorStand) { + if (target instanceof Material) { + Objects.requireNonNull(armorStand.getEquipment()).setHelmet(new ItemStack((Material) target)); + } else { + Objects.requireNonNull(armorStand.getEquipment()).setHelmet(null); } + } + + public Object getTargetSaveObject() { + return target.toString(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java index 30f913054..efd616946 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java @@ -6,43 +6,43 @@ public class HeightTarget extends ForceTarget { - public HeightTarget(Integer target) { - super(target); - } - - @Override - public boolean check(Player player) { - return player.getLocation().getBlockY() == target; - } - - @Override - public Object toMessage() { - return target; - } - - @Override - public String getName() { - return target.toString(); - } - - @Override - public Message getNewTargetMessage() { - return Message.forName("extreme-force-battle-new-height"); - } - - @Override - public Message getCompletedMessage() { - return Message.forName("extreme-force-battle-reached-height"); - } - - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.HEIGHT; - } - - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-height-target-display"); - } + public HeightTarget(Integer target) { + super(target); + } + + @Override + public boolean check(Player player) { + return player.getLocation().getBlockY() == target; + } + + @Override + public Object toMessage() { + return target; + } + + @Override + public String getName() { + return target.toString(); + } + + @Override + public Message getNewTargetMessage() { + return Message.forName("extreme-force-battle-new-height"); + } + + @Override + public Message getCompletedMessage() { + return Message.forName("extreme-force-battle-reached-height"); + } + + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.HEIGHT; + } + + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-height-target-display"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java index c8a6c9ca3..5b2b1d526 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; +import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -14,55 +14,55 @@ public class ItemTarget extends ForceTarget { - public ItemTarget(Material target) { - super(target); - } + public ItemTarget(Material target) { + super(target); + } - @Override - public boolean check(Player player) { - return player.getInventory().contains(target); - } + @Override + public boolean check(Player player) { + return player.getInventory().contains(target); + } - public static List getPossibleItems() { - List materials = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - materials.removeIf(material -> !material.isItem()); - materials.removeIf(material -> !ItemUtils.isObtainableInSurvival(material)); - return materials; - } + public static List getPossibleItems() { + List materials = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + materials.removeIf(material -> !material.isItem()); + materials.removeIf(material -> !ItemUtils.isObtainableInSurvival(material)); + return materials; + } - @Override - public Object toMessage() { - return target; - } + @Override + public Object toMessage() { + return target; + } - @Override - public String getName() { - return BukkitStringUtils.getItemName(target).toPlainText(); - } + @Override + public String getName() { + return BukkitStringUtils.getItemName(target).toPlainText(); + } - @Override - public Message getNewTargetMessage() { - return Message.forName("force-item-battle-new-item"); - } + @Override + public Message getNewTargetMessage() { + return Message.forName("force-item-battle-new-item"); + } - @Override - public Message getCompletedMessage() { - return Message.forName("force-item-battle-found"); - } + @Override + public Message getCompletedMessage() { + return Message.forName("force-item-battle-found"); + } - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.ITEM; - } + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.ITEM; + } - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-item-target-display"); - } + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-item-target-display"); + } - @Override - public String toString() { - return target.name(); - } + @Override + public String toString() { + return target.name(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java index c333e8307..ba9f60a2c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java @@ -19,62 +19,62 @@ public class MobTarget extends ForceTarget { - public MobTarget(EntityType target) { - super(target); - } + public MobTarget(EntityType target) { + super(target); + } - @Override - public boolean check(Player player) { - return false; - } + @Override + public boolean check(Player player) { + return false; + } - public static List getPossibleMobs() { - List entityTypes = new ArrayList<>(Arrays.asList(EntityType.values())); - entityTypes.removeIf(entityType -> !entityType.isSpawnable()); - entityTypes.removeIf(entityType -> !entityType.isAlive()); - Utils.removeEnums(entityTypes, "ILLUSIONER", "ARMOR_STAND", "ZOMBIE_HORSE", "GIANT"); + public static List getPossibleMobs() { + List entityTypes = new ArrayList<>(Arrays.asList(EntityType.values())); + entityTypes.removeIf(entityType -> !entityType.isSpawnable()); + entityTypes.removeIf(entityType -> !entityType.isAlive()); + Utils.removeEnums(entityTypes, "ILLUSIONER", "ARMOR_STAND", "ZOMBIE_HORSE", "GIANT"); - return entityTypes; - } + return entityTypes; + } - @Override - public Object toMessage() { - return target; - } + @Override + public Object toMessage() { + return target; + } - @Override - public String getName() { - return BukkitStringUtils.getEntityName(target).toPlainText(); - } + @Override + public String getName() { + return BukkitStringUtils.getEntityName(target).toPlainText(); + } - @Override - public Message getNewTargetMessage() { - return Message.forName("force-mob-battle-new-mob"); - } + @Override + public Message getNewTargetMessage() { + return Message.forName("force-mob-battle-new-mob"); + } - @Override - public Message getCompletedMessage() { - return Message.forName("force-mob-battle-killed"); - } + @Override + public Message getCompletedMessage() { + return Message.forName("force-mob-battle-killed"); + } - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.MOB; - } + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.MOB; + } - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-mob-target-display"); - } + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-mob-target-display"); + } - @Override - public void updateDisplayStand(@NotNull ArmorStand armorStand) { - Material spawnEgg = EntityUtils.getSpawnEgg(target); - if (spawnEgg == null) { - Objects.requireNonNull(armorStand.getEquipment()).setHelmet(null); - } else { - Objects.requireNonNull(armorStand.getEquipment()).setHelmet(new ItemStack(spawnEgg)); - } + @Override + public void updateDisplayStand(@NotNull ArmorStand armorStand) { + Material spawnEgg = EntityUtils.getSpawnEgg(target); + if (spawnEgg == null) { + Objects.requireNonNull(armorStand.getEquipment()).setHelmet(null); + } else { + Objects.requireNonNull(armorStand.getEquipment()).setHelmet(new ItemStack(spawnEgg)); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java index dae98fc12..7d5012c5a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java @@ -10,61 +10,61 @@ public class PositionTarget extends ForceTarget> { - public PositionTarget(double x, double z) { - super(Tuple.of(x, z)); - } + public PositionTarget(double x, double z) { + super(Tuple.of(x, z)); + } - public PositionTarget(Player player, int radius) { - super(Tuple.of( - player.getLocation().getBlockX() + (double) IRandom.singleton().range(-radius, radius), - player.getLocation().getBlockZ() + (double) IRandom.singleton().range(-radius, radius) - )); - } + public PositionTarget(Player player, int radius) { + super(Tuple.of( + player.getLocation().getBlockX() + (double) IRandom.singleton().range(-radius, radius), + player.getLocation().getBlockZ() + (double) IRandom.singleton().range(-radius, radius) + )); + } - public PositionTarget(Player player) { - this(player, 1500); - } + public PositionTarget(Player player) { + this(player, 1500); + } - @Override - public boolean check(Player player) { - Location playerLocation = player.getLocation().clone(); - playerLocation.setY(0); - Location targetLocation = new Location(playerLocation.getWorld(), target.getFirst(), 0, target.getSecond()); - return playerLocation.distance(targetLocation) < 5; - } + @Override + public boolean check(Player player) { + Location playerLocation = player.getLocation().clone(); + playerLocation.setY(0); + Location targetLocation = new Location(playerLocation.getWorld(), target.getFirst(), 0, target.getSecond()); + return playerLocation.distance(targetLocation) < 5; + } - @Override - public Object toMessage() { - return getName(); - } + @Override + public Object toMessage() { + return getName(); + } - @Override - public String getName() { - return Message.forName("extreme-force-battle-position").asString(target.getFirst(), target.getSecond()); - } + @Override + public String getName() { + return Message.forName("extreme-force-battle-position").asString(target.getFirst(), target.getSecond()); + } - @Override - public Message getNewTargetMessage() { - return Message.forName("extreme-force-battle-new-position"); - } + @Override + public Message getNewTargetMessage() { + return Message.forName("extreme-force-battle-new-position"); + } - @Override - public Message getCompletedMessage() { - return Message.forName("extreme-force-battle-reached-position"); - } + @Override + public Message getCompletedMessage() { + return Message.forName("extreme-force-battle-reached-position"); + } - @Override - public ExtremeForceBattleGoal.TargetType getType() { - return ExtremeForceBattleGoal.TargetType.POSITION; - } + @Override + public ExtremeForceBattleGoal.TargetType getType() { + return ExtremeForceBattleGoal.TargetType.POSITION; + } - @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-position-target-display"); - } + @Override + public Message getScoreboardDisplayMessage() { + return Message.forName("force-battle-position-target-display"); + } - @Override - public Object getTargetSaveObject() { - return Document.create().set("x", target.getFirst()).set("z", target.getSecond()); - } + @Override + public Object getTargetSaveObject() { + return Document.create().set("x", target.getFirst()).set("z", target.getSecond()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java index 2305b84e0..a09668c43 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java @@ -22,83 +22,83 @@ public class BlockMaterialSetting extends Setting { - private final String name; - private final ItemBuilder preset; - private final Object[] replacements; - private final Material[] materials; - - public BlockMaterialSetting(@Nonnull String name, @Nonnull ItemBuilder preset, @Nonnull Object[] replacements, @Nonnull Material... materials) { - super(MenuType.ITEMS, true); - this.name = name; - this.preset = preset; - this.replacements = replacements; - this.materials = materials; - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return preset.clone().applyFormat(Message.forName(name).asItemDescription(replacements)); - } - - private boolean blockMaterial(Material material) { - return Arrays.asList(materials).contains(material); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerInteract(@Nonnull PlayerInteractEvent event) { - if (isEnabled()) return; - if (ChallengeAPI.isWorldInUse()) return; - if (ignorePlayer(event.getPlayer())) return; - if (!blockMaterial(event.getMaterial())) { - if (event.getClickedBlock() == null) return; - if (!blockMaterial(event.getClickedBlock().getType())) return; - event.setCancelled(true); - return; - } - event.setCancelled(true); - - dropMaterial(event.getPlayer().getLocation(), event.getPlayer().getInventory()); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - if (isEnabled()) return; - if (ignorePlayer(event.getPlayer())) return; - if (ChallengeAPI.isWorldInUse()) return; - if (event.getCurrentItem() == null) return; - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getHolder() != event.getPlayer()) return; - if (!blockMaterial(event.getCurrentItem().getType())) return; - event.setCancelled(true); - - dropMaterial(event.getPlayer().getLocation(), event.getClickedInventory()); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerPickupItem(@Nonnull PlayerPickupItemEvent event) { - if (isEnabled()) return; - if (ignorePlayer(event.getPlayer())) return; - if (ChallengeAPI.isWorldInUse()) return; - if (!blockMaterial(event.getItem().getItemStack().getType())) return; - event.setCancelled(true); - } - - public void dropMaterial(@Nonnull Location location, @Nonnull Inventory inventory) { - for (int slot = 0; slot < inventory.getSize(); slot++) { - ItemStack item = inventory.getItem(slot); - if (item == null) continue; - if (!blockMaterial(item.getType())) continue; - InventoryUtils.dropItemByPlayer(location, item); - inventory.setItem(slot, null); - } - - } - - @NotNull - @Override - public String getUniqueName() { - return "blockmaterial" + materials[0].name().toLowerCase(); - } + private final String name; + private final ItemBuilder preset; + private final Object[] replacements; + private final Material[] materials; + + public BlockMaterialSetting(@Nonnull String name, @Nonnull ItemBuilder preset, @Nonnull Object[] replacements, @Nonnull Material... materials) { + super(MenuType.ITEMS, true); + this.name = name; + this.preset = preset; + this.replacements = replacements; + this.materials = materials; + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return preset.clone().applyFormat(Message.forName(name).asItemDescription(replacements)); + } + + private boolean blockMaterial(Material material) { + return Arrays.asList(materials).contains(material); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerInteract(@Nonnull PlayerInteractEvent event) { + if (isEnabled()) return; + if (ChallengeAPI.isWorldInUse()) return; + if (ignorePlayer(event.getPlayer())) return; + if (!blockMaterial(event.getMaterial())) { + if (event.getClickedBlock() == null) return; + if (!blockMaterial(event.getClickedBlock().getType())) return; + event.setCancelled(true); + return; + } + event.setCancelled(true); + + dropMaterial(event.getPlayer().getLocation(), event.getPlayer().getInventory()); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + if (isEnabled()) return; + if (ignorePlayer(event.getPlayer())) return; + if (ChallengeAPI.isWorldInUse()) return; + if (event.getCurrentItem() == null) return; + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getHolder() != event.getPlayer()) return; + if (!blockMaterial(event.getCurrentItem().getType())) return; + event.setCancelled(true); + + dropMaterial(event.getPlayer().getLocation(), event.getClickedInventory()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerPickupItem(@Nonnull PlayerPickupItemEvent event) { + if (isEnabled()) return; + if (ignorePlayer(event.getPlayer())) return; + if (ChallengeAPI.isWorldInUse()) return; + if (!blockMaterial(event.getItem().getItemStack().getType())) return; + event.setCancelled(true); + } + + public void dropMaterial(@Nonnull Location location, @Nonnull Inventory inventory) { + for (int slot = 0; slot < inventory.getSize(); slot++) { + ItemStack item = inventory.getItem(slot); + if (item == null) continue; + if (!blockMaterial(item.getType())) continue; + InventoryUtils.dropItemByPlayer(location, item); + inventory.setItem(slot, null); + } + + } + + @NotNull + @Override + public String getUniqueName() { + return "blockmaterial" + materials[0].name().toLowerCase(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java index ffbdb9309..34bed85b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java @@ -29,137 +29,137 @@ public class BackpackSetting extends SettingModifier implements PlayerCommand { - public static final int SHARED = 1, - PLAYER = 2; - - private final int size; - private final Map backpacks = new HashMap<>(); - private final Inventory sharedBackpack; - - public BackpackSetting() { - super(MenuType.SETTINGS, 1, 2, SHARED); - size = Math.max(Math.min(ChallengeConfigHelper.getSettingsDocument().getInt("backpack-size") * 9, 6 * 9), 9); - sharedBackpack = createInventory("§5Team Backpack"); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CHEST, Message.forName("item-backpack-setting")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (getValue() == SHARED) - return DefaultItem.create(Material.ENDER_CHEST, Message.forName("item-backpack-setting-team")); - return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("item-backpack-setting-player")); - } - - - @Override - public void playValueChangeTitle() { - switch (getValue()) { - case SHARED: - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-backpack-setting-team")); - break; - case PLAYER: - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-backpack-setting-player")); - break; - default: - ChallengeHelper.playToggleChallengeTitle(this, false); - } - } - - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) { - if (ChallengeAPI.isPaused()) { - Message.forName("timer-not-started").send(player, Prefix.BACKPACK); - SoundSample.BASS_OFF.play(player); - return; - } - - if (!isEnabled()) { - Message.forName("backpacks-disabled").send(player, Prefix.BACKPACK); - SoundSample.BASS_OFF.play(player); - return; - } - - if (getValue() == SHARED || getValue() == PLAYER) { - Message.forName("backpack-opened").send(player, Prefix.BACKPACK, getValue() == SHARED ? "§5Team Backpack" : "§6Player Backpack"); - player.openInventory(getCurrentBackpack(player)); - SoundSample.OPEN.play(player); - } else { - Message.forName("backpacks-disabled").send(player, Prefix.BACKPACK); - SoundSample.BASS_OFF.play(player); - } - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - - loadChecked(document, "shared", sharedBackpack); - - Document players = document.getDocument("players"); - for (String key : players.keys()) { - loadChecked(players, key, backpacks.computeIfAbsent(UUID.fromString(key), k -> createInventory("§6Backpack"))); - } - - } - - protected void loadChecked(@Nonnull Document document, @Nonnull String key, @Nonnull Inventory inventory) { - - if (document.isDocument(key)) { - loadLegacy(document.getDocument(key), inventory); - } else { - try { - String value = document.getString(key); - if (value == null) return; - BukkitSerialization.fromBase64(inventory, value); - } catch (IOException exception) { - Challenges.getInstance().getLogger().error("", exception); - } - } - - } - - protected void loadLegacy(@Nonnull Document document, @Nonnull Inventory inventory) { - - for (String key : document.keys()) { - try { - int index = Integer.parseInt(key); - ItemStack item = document.getSerializable(key, ItemStack.class); - inventory.setItem(index, item); - } catch (Exception ignored) { - } - } - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - - write(document, "shared", sharedBackpack); - - Document players = document.getDocument("players"); - backpacks.forEach((uuid, inventory) -> { - write(players, uuid.toString(), inventory); - }); - } - - protected void write(@Nonnull Document document, @Nonnull String key, @Nonnull Inventory inventory) { - document.set(key, BukkitSerialization.toBase64(inventory)); - } - - @Nonnull - protected Inventory createInventory(@Nonnull String title) { - return Bukkit.createInventory(null, size, InventoryTitleManager.getTitle(title)); - } - - @Nonnull - protected Inventory getCurrentBackpack(@Nonnull Player player) { - return (getValue() == SHARED) ? sharedBackpack : backpacks.computeIfAbsent(player.getUniqueId(), key -> createInventory("§6Backpack")); - } + public static final int SHARED = 1, + PLAYER = 2; + + private final int size; + private final Map backpacks = new HashMap<>(); + private final Inventory sharedBackpack; + + public BackpackSetting() { + super(MenuType.SETTINGS, 1, 2, SHARED); + size = Math.max(Math.min(ChallengeConfigHelper.getSettingsDocument().getInt("backpack-size") * 9, 6 * 9), 9); + sharedBackpack = createInventory("§5Team Backpack"); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CHEST, Message.forName("item-backpack-setting")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (getValue() == SHARED) + return DefaultItem.create(Material.ENDER_CHEST, Message.forName("item-backpack-setting-team")); + return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("item-backpack-setting-player")); + } + + + @Override + public void playValueChangeTitle() { + switch (getValue()) { + case SHARED: + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-backpack-setting-team")); + break; + case PLAYER: + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-backpack-setting-player")); + break; + default: + ChallengeHelper.playToggleChallengeTitle(this, false); + } + } + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) { + if (ChallengeAPI.isPaused()) { + Message.forName("timer-not-started").send(player, Prefix.BACKPACK); + SoundSample.BASS_OFF.play(player); + return; + } + + if (!isEnabled()) { + Message.forName("backpacks-disabled").send(player, Prefix.BACKPACK); + SoundSample.BASS_OFF.play(player); + return; + } + + if (getValue() == SHARED || getValue() == PLAYER) { + Message.forName("backpack-opened").send(player, Prefix.BACKPACK, getValue() == SHARED ? "§5Team Backpack" : "§6Player Backpack"); + player.openInventory(getCurrentBackpack(player)); + SoundSample.OPEN.play(player); + } else { + Message.forName("backpacks-disabled").send(player, Prefix.BACKPACK); + SoundSample.BASS_OFF.play(player); + } + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + + loadChecked(document, "shared", sharedBackpack); + + Document players = document.getDocument("players"); + for (String key : players.keys()) { + loadChecked(players, key, backpacks.computeIfAbsent(UUID.fromString(key), k -> createInventory("§6Backpack"))); + } + + } + + protected void loadChecked(@Nonnull Document document, @Nonnull String key, @Nonnull Inventory inventory) { + + if (document.isDocument(key)) { + loadLegacy(document.getDocument(key), inventory); + } else { + try { + String value = document.getString(key); + if (value == null) return; + BukkitSerialization.fromBase64(inventory, value); + } catch (IOException exception) { + Challenges.getInstance().getLogger().error("", exception); + } + } + + } + + protected void loadLegacy(@Nonnull Document document, @Nonnull Inventory inventory) { + + for (String key : document.keys()) { + try { + int index = Integer.parseInt(key); + ItemStack item = document.getSerializable(key, ItemStack.class); + inventory.setItem(index, item); + } catch (Exception ignored) { + } + } + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + + write(document, "shared", sharedBackpack); + + Document players = document.getDocument("players"); + backpacks.forEach((uuid, inventory) -> { + write(players, uuid.toString(), inventory); + }); + } + + protected void write(@Nonnull Document document, @Nonnull String key, @Nonnull Inventory inventory) { + document.set(key, BukkitSerialization.toBase64(inventory)); + } + + @Nonnull + protected Inventory createInventory(@Nonnull String title) { + return Bukkit.createInventory(null, size, InventoryTitleManager.getTitle(title)); + } + + @Nonnull + protected Inventory getCurrentBackpack(@Nonnull Player player) { + return (getValue() == SHARED) ? sharedBackpack : backpacks.computeIfAbsent(player.getUniqueId(), key -> createInventory("§6Backpack")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java index afdd615d3..bc31d6d29 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java @@ -19,15 +19,15 @@ @RequireVersion(MinecraftVersion.V1_16) public class BastionSpawnSetting extends NetherPortalSpawnSetting { - public BastionSpawnSetting() { - super(MenuType.SETTINGS, StructureType.BASTION_REMNANT, "unable-to-find-bastion", - Arrays.stream(ExperimentalUtils.getMaterials()).filter(material -> material.name().contains("BASALT")).collect(Collectors.toList())); - } + public BastionSpawnSetting() { + super(MenuType.SETTINGS, StructureType.BASTION_REMNANT, "unable-to-find-bastion", + Arrays.stream(ExperimentalUtils.getMaterials()).filter(material -> material.name().contains("BASALT")).collect(Collectors.toList())); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.POLISHED_BLACKSTONE_BRICKS, Message.forName("item-bastion-spawn-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.POLISHED_BLACKSTONE_BRICKS, Message.forName("item-bastion-spawn-setting")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java index ccfd47482..dc5e9aea1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java @@ -1,7 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.anweisen.utilities.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; @@ -11,6 +10,7 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.Utils; @@ -33,201 +33,201 @@ @Since("2.0") public class CutCleanSetting extends MenuSetting { - public CutCleanSetting() { - super(MenuType.SETTINGS, Message.forName("menu-cut-clean-setting-settings")); - registerSetting("iron->iron_ingot", - new ConvertDropSubSetting(() -> new ItemBuilder(Material.IRON_INGOT, Message.forName("item-cut-clean-iron-setting")), true, - Material.IRON_INGOT, "IRON_ORE", "DEEPSLATE_IRON_ORE")); - registerSetting("gold->gold_ingot", - new ConvertDropSubSetting(() -> new ItemBuilder(Material.GOLD_INGOT, Message.forName("item-cut-clean-gold-setting")), true, - Material.GOLD_INGOT, "GOLD_ORE", "DEEPSLATE_GOLD_ORE")); - registerSetting("coal->torch", - new ConvertDropSubSetting(() -> new ItemBuilder(Material.COAL, Message.forName("item-cut-clean-coal-setting")), false, - Material.TORCH, "COAL_ORE", "DEEPSLATE_COAL_ORE")); - registerSetting("gravel->flint", - new ConvertDropSubSetting(() -> new ItemBuilder(Material.FLINT, Message.forName("item-cut-clean-flint-setting")), false, - Material.FLINT, "GRAVEL")); - registerSetting("ore->veins", - new BreakOreVeinsSubSetting(() -> new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-cut-clean-vein-setting")), 1, 10)); - registerSetting("items->inventory", - new DirectIntoInventorySubSetting(() -> new ItemBuilder(Material.CHEST, Message.forName("item-cut-clean-inventory-setting")))); - registerSetting("row->cooked", - new CookFoodSubSetting(() -> new ItemBuilder(Material.COOKED_BEEF, Message.forName("item-cut-clean-food-setting")), true)); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.IRON_AXE, Message.forName("item-cut-clean-setting")); - } - - protected boolean directIntoInventory() { - return getSetting("items->inventory").getAsBoolean(); - } - - private class DirectIntoInventorySubSetting extends BooleanSubSetting { - - public DirectIntoInventorySubSetting(@Nonnull Supplier item) { - super(item); - } - - @Nonnull - @Override - public BooleanSubSetting setEnabled(boolean enabled) { - return super.setEnabled(enabled); - } - - } - - private class ConvertDropSubSetting extends BooleanSubSetting { - - protected final Material[] from; - protected final Material to; - - public ConvertDropSubSetting(@Nonnull Supplier item, boolean enabledByDefault, - @Nonnull Material to, @Nonnull String... from) { - super(item, enabledByDefault); - - List materials = new ArrayList<>(); - for (String s : from) { - Material material = Utils.getMaterial(s); - if (material != null) { - materials.add(material); - } - } - - this.from = materials.toArray(new Material[0]); - this.to = to; - } - - @Override - public void onEnable() { - if (from == null) return; - for (Material material : from) { - Challenges.getInstance().getBlockDropManager().setCustomDrops(material, to, DropPriority.CUT_CLEAN); - } - } - - @Override - public void onDisable() { - if (from == null) return; - for (Material material : from) { - Challenges.getInstance().getBlockDropManager().resetCustomDrop(material, DropPriority.CUT_CLEAN); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (!directIntoInventory()) return; - if (!event.isDropItems()) return; - Material type = event.getBlock().getType(); - - for (Material material : from) { - if (type != material) continue; - List customDrops = Challenges.getInstance().getBlockDropManager().getCustomDrops(event.getBlock().getType()); - if (customDrops.isEmpty()) return; - event.setDropItems(false); - customDrops.forEach(drop -> InventoryUtils.dropOrGiveItem(event.getPlayer().getInventory(), event.getBlock().getLocation(), drop)); - } - - } - - } - - private class BreakOreVeinsSubSetting extends NumberAndBooleanSubSetting { - - public BreakOreVeinsSubSetting(@Nonnull Supplier item, int min, int max) { - super(item, min, max); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - ItemStack itemInMainHand = event.getPlayer().getInventory().getItemInMainHand(); - if (!canBeBroken(event.getBlock(), itemInMainHand)) return; - if (!event.getBlock().getType().name().contains("ORE")) return; - - breakBlockVein(event.getPlayer(), event.getBlock(), itemInMainHand); - } - - private void breakBlockVein(@Nonnull Player player, @Nonnull Block block, @Nonnull ItemStack tool) { - Material material = block.getType(); - - List allBlocks = new ArrayList<>(); - List nextBlocks = new ArrayList<>(); - nextBlocks.add(block); - - for (int i = 0; i < getValue(); i++) { - - if (nextBlocks.isEmpty()) break; - - List lastBlocks = new ArrayList<>(nextBlocks); - nextBlocks.clear(); - - for (Block currentMiddleBlock : lastBlocks) { - for (Block sideBlock : BlockUtils.getBlocksAroundBlock(currentMiddleBlock)) { - if (sideBlock.getType() == material && sideBlock != block && !allBlocks.contains(sideBlock) && allBlocks.size() < getValue()) { - allBlocks.add(sideBlock); - nextBlocks.add(sideBlock); - } - } - } - } - - AtomicInteger index = new AtomicInteger(); - Bukkit.getScheduler().runTaskTimer(plugin, timer -> { - - SoundSample.LOW_PLOP.play(player); - for (int i = 0; i < 2; i++) { - - if (index.get() >= allBlocks.size()) { - timer.cancel(); - return; - } - - Block currentBlock = allBlocks.get(index.get()); - if (currentBlock.getType() == material) { - ChallengeHelper.breakBlock(currentBlock, tool, player.getInventory()); - } - - index.getAndIncrement(); - } - }, 0, 2); - - } - - private boolean canBeBroken(@Nonnull Block block, @Nonnull ItemStack tool) { - return !block.getDrops(tool).isEmpty(); - } - - @Nonnull - @Override - public ItemBuilder getSettingsItem() { - return getAsBoolean() ? DefaultItem.value(getValue(), "§7Max Vein Size: §e") : DefaultItem.disabled(); - } + public CutCleanSetting() { + super(MenuType.SETTINGS, Message.forName("menu-cut-clean-setting-settings")); + registerSetting("iron->iron_ingot", + new ConvertDropSubSetting(() -> new ItemBuilder(Material.IRON_INGOT, Message.forName("item-cut-clean-iron-setting")), true, + Material.IRON_INGOT, "IRON_ORE", "DEEPSLATE_IRON_ORE")); + registerSetting("gold->gold_ingot", + new ConvertDropSubSetting(() -> new ItemBuilder(Material.GOLD_INGOT, Message.forName("item-cut-clean-gold-setting")), true, + Material.GOLD_INGOT, "GOLD_ORE", "DEEPSLATE_GOLD_ORE")); + registerSetting("coal->torch", + new ConvertDropSubSetting(() -> new ItemBuilder(Material.COAL, Message.forName("item-cut-clean-coal-setting")), false, + Material.TORCH, "COAL_ORE", "DEEPSLATE_COAL_ORE")); + registerSetting("gravel->flint", + new ConvertDropSubSetting(() -> new ItemBuilder(Material.FLINT, Message.forName("item-cut-clean-flint-setting")), false, + Material.FLINT, "GRAVEL")); + registerSetting("ore->veins", + new BreakOreVeinsSubSetting(() -> new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-cut-clean-vein-setting")), 1, 10)); + registerSetting("items->inventory", + new DirectIntoInventorySubSetting(() -> new ItemBuilder(Material.CHEST, Message.forName("item-cut-clean-inventory-setting")))); + registerSetting("row->cooked", + new CookFoodSubSetting(() -> new ItemBuilder(Material.COOKED_BEEF, Message.forName("item-cut-clean-food-setting")), true)); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.IRON_AXE, Message.forName("item-cut-clean-setting")); + } + + protected boolean directIntoInventory() { + return getSetting("items->inventory").getAsBoolean(); + } + + private class DirectIntoInventorySubSetting extends BooleanSubSetting { + + public DirectIntoInventorySubSetting(@Nonnull Supplier item) { + super(item); + } + + @Nonnull + @Override + public BooleanSubSetting setEnabled(boolean enabled) { + return super.setEnabled(enabled); + } + + } + + private class ConvertDropSubSetting extends BooleanSubSetting { + + protected final Material[] from; + protected final Material to; + + public ConvertDropSubSetting(@Nonnull Supplier item, boolean enabledByDefault, + @Nonnull Material to, @Nonnull String... from) { + super(item, enabledByDefault); + + List materials = new ArrayList<>(); + for (String s : from) { + Material material = Utils.getMaterial(s); + if (material != null) { + materials.add(material); + } + } + + this.from = materials.toArray(new Material[0]); + this.to = to; + } + + @Override + public void onEnable() { + if (from == null) return; + for (Material material : from) { + Challenges.getInstance().getBlockDropManager().setCustomDrops(material, to, DropPriority.CUT_CLEAN); + } + } + + @Override + public void onDisable() { + if (from == null) return; + for (Material material : from) { + Challenges.getInstance().getBlockDropManager().resetCustomDrop(material, DropPriority.CUT_CLEAN); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (!directIntoInventory()) return; + if (!event.isDropItems()) return; + Material type = event.getBlock().getType(); + + for (Material material : from) { + if (type != material) continue; + List customDrops = Challenges.getInstance().getBlockDropManager().getCustomDrops(event.getBlock().getType()); + if (customDrops.isEmpty()) return; + event.setDropItems(false); + customDrops.forEach(drop -> InventoryUtils.dropOrGiveItem(event.getPlayer().getInventory(), event.getBlock().getLocation(), drop)); + } + + } + + } + + private class BreakOreVeinsSubSetting extends NumberAndBooleanSubSetting { + + public BreakOreVeinsSubSetting(@Nonnull Supplier item, int min, int max) { + super(item, min, max); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + ItemStack itemInMainHand = event.getPlayer().getInventory().getItemInMainHand(); + if (!canBeBroken(event.getBlock(), itemInMainHand)) return; + if (!event.getBlock().getType().name().contains("ORE")) return; + + breakBlockVein(event.getPlayer(), event.getBlock(), itemInMainHand); + } + + private void breakBlockVein(@Nonnull Player player, @Nonnull Block block, @Nonnull ItemStack tool) { + Material material = block.getType(); + + List allBlocks = new ArrayList<>(); + List nextBlocks = new ArrayList<>(); + nextBlocks.add(block); + + for (int i = 0; i < getValue(); i++) { + + if (nextBlocks.isEmpty()) break; + + List lastBlocks = new ArrayList<>(nextBlocks); + nextBlocks.clear(); + + for (Block currentMiddleBlock : lastBlocks) { + for (Block sideBlock : BlockUtils.getBlocksAroundBlock(currentMiddleBlock)) { + if (sideBlock.getType() == material && sideBlock != block && !allBlocks.contains(sideBlock) && allBlocks.size() < getValue()) { + allBlocks.add(sideBlock); + nextBlocks.add(sideBlock); + } + } + } + } + + AtomicInteger index = new AtomicInteger(); + Bukkit.getScheduler().runTaskTimer(plugin, timer -> { + + SoundSample.LOW_PLOP.play(player); + for (int i = 0; i < 2; i++) { + + if (index.get() >= allBlocks.size()) { + timer.cancel(); + return; + } + + Block currentBlock = allBlocks.get(index.get()); + if (currentBlock.getType() == material) { + ChallengeHelper.breakBlock(currentBlock, tool, player.getInventory()); + } + + index.getAndIncrement(); + } + }, 0, 2); + + } + + private boolean canBeBroken(@Nonnull Block block, @Nonnull ItemStack tool) { + return !block.getDrops(tool).isEmpty(); + } + + @Nonnull + @Override + public ItemBuilder getSettingsItem() { + return getAsBoolean() ? DefaultItem.value(getValue(), "§7Max Vein Size: §e") : DefaultItem.disabled(); + } - } - - private class CookFoodSubSetting extends BooleanSubSetting { + } + + private class CookFoodSubSetting extends BooleanSubSetting { - public CookFoodSubSetting(@Nonnull Supplier item, boolean enabledByDefault) { - super(item, enabledByDefault); - } + public CookFoodSubSetting(@Nonnull Supplier item, boolean enabledByDefault) { + super(item, enabledByDefault); + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityKill(@Nonnull EntityDeathEvent event) { - if (!isEnabled()) return; - event.getDrops().replaceAll(item -> new ItemBuilder(ItemUtils.convertFoodToCookedFood(item.getType())).amount(item.getAmount()).build()); + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityKill(@Nonnull EntityDeathEvent event) { + if (!isEnabled()) return; + event.getDrops().replaceAll(item -> new ItemBuilder(ItemUtils.convertFoodToCookedFood(item.getType())).amount(item.getAmount()).build()); - Player killer = event.getEntity().getKiller(); - if (killer != null && directIntoInventory()) { - event.getDrops().forEach(itemStack -> InventoryUtils.dropOrGiveItem(killer.getInventory(), killer.getLocation(), itemStack)); - event.getDrops().clear(); - } + Player killer = event.getEntity().getKiller(); + if (killer != null && directIntoInventory()) { + event.getDrops().forEach(itemStack -> InventoryUtils.dropOrGiveItem(killer.getInventory(), killer.getLocation(), itemStack)); + event.getDrops().clear(); + } - } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java index 43405e86d..8e029ac56 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java @@ -25,62 +25,62 @@ public class DamageDisplaySetting extends Setting { - public DamageDisplaySetting() { - super(MenuType.SETTINGS, true); - } + public DamageDisplaySetting() { + super(MenuType.SETTINGS, true); + } - public static String getCause(@Nonnull EntityDamageEvent event) { + public static String getCause(@Nonnull EntityDamageEvent event) { - if (event.getCause() == DamageCause.CUSTOM) return Message.forName("undefined").asString(); - String cause = StringUtils.getEnumName(event.getCause()); + if (event.getCause() == DamageCause.CUSTOM) return Message.forName("undefined").asString(); + String cause = StringUtils.getEnumName(event.getCause()); - if (event instanceof EntityDamageByEntityEvent) { + if (event instanceof EntityDamageByEntityEvent) { - EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) event; - if (damageEvent.getDamager() instanceof Player) { - Player damager = (Player) damageEvent.getDamager(); - cause += " §8(§7" + NameHelper.getName(damager) + "§8)"; - } else if (damageEvent.getDamager() instanceof Projectile) { - Projectile projectile = (Projectile) damageEvent.getDamager(); - cause = StringUtils.getEnumName(projectile.getType()); - String damager = ""; - ProjectileSource shooter = projectile.getShooter(); - if (shooter instanceof Entity) { - Entity entity = (Entity) shooter; - if (entity instanceof Player) { - Player playerDamager = (Player) entity; - damager = NameHelper.getName(playerDamager); - } else { - damager = StringUtils.getEnumName(entity.getType()); - } - } + EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) event; + if (damageEvent.getDamager() instanceof Player) { + Player damager = (Player) damageEvent.getDamager(); + cause += " §8(§7" + NameHelper.getName(damager) + "§8)"; + } else if (damageEvent.getDamager() instanceof Projectile) { + Projectile projectile = (Projectile) damageEvent.getDamager(); + cause = StringUtils.getEnumName(projectile.getType()); + String damager = ""; + ProjectileSource shooter = projectile.getShooter(); + if (shooter instanceof Entity) { + Entity entity = (Entity) shooter; + if (entity instanceof Player) { + Player playerDamager = (Player) entity; + damager = NameHelper.getName(playerDamager); + } else { + damager = StringUtils.getEnumName(entity.getType()); + } + } - if (!cause.contains(damager)) - cause += " §8(§7" + damager + "§8)"; - } else { - String damager = StringUtils.getEnumName(damageEvent.getDamager().getType()); - if (!cause.contains(damager)) - cause += " §8(§7" + damager + "§8)"; - } - } - return cause; - } + if (!cause.contains(damager)) + cause += " §8(§7" + damager + "§8)"; + } else { + String damager = StringUtils.getEnumName(damageEvent.getDamager().getType()); + if (!cause.contains(damager)) + cause += " §8(§7" + damager + "§8)"; + } + } + return cause; + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (ChallengeAPI.isPaused() || event.getCause() == DamageCause.CUSTOM || !isEnabled()) - return; - if (!(event.getEntity() instanceof Player)) return; - if (ChallengeHelper.finalDamageIsNull(event)) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (ChallengeAPI.isPaused() || event.getCause() == DamageCause.CUSTOM || !isEnabled()) + return; + if (!(event.getEntity() instanceof Player)) return; + if (ChallengeHelper.finalDamageIsNull(event)) return; - double damage = event.getFinalDamage(); - String damageDisplay = damage >= 1000 ? "∞" : Display.HEARTS.formatChat(damage); - Message.forName("player-damage-display").broadcast(Prefix.DAMAGE, NameHelper.getName((Player) event.getEntity()), damageDisplay, getCause(event)); - } + double damage = event.getFinalDamage(); + String damageDisplay = damage >= 1000 ? "∞" : Display.HEARTS.formatChat(damage); + Message.forName("player-damage-display").broadcast(Prefix.DAMAGE, NameHelper.getName((Player) event.getEntity()), damageDisplay, getCause(event)); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COMMAND_BLOCK, Message.forName("item-damage-display-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.COMMAND_BLOCK, Message.forName("item-damage-display-setting")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java index bae4e3b93..2841569f9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java @@ -16,31 +16,31 @@ public class DamageMultiplierModifier extends Modifier { - public DamageMultiplierModifier() { - super(MenuType.SETTINGS, 10); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-damage-setting")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.value(getValue()).appendName("x"); - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (!(event.getEntity() instanceof Player)) return; - event.setDamage(event.getDamage() * getValue()); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() + "x"); - } + public DamageMultiplierModifier() { + super(MenuType.SETTINGS, 10); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-damage-setting")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + return DefaultItem.value(getValue()).appendName("x"); + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + event.setDamage(event.getDamage() * getValue()); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, getValue() + "x"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java index 39e646b59..96feb5592 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java @@ -22,73 +22,73 @@ public class DeathMessageSetting extends Modifier { - public static final int ENABLED = 2, - VANILLA = 3; + public static final int ENABLED = 2, + VANILLA = 3; - private boolean hide; + private boolean hide; - public DeathMessageSetting() { - super(MenuType.SETTINGS, 1, 3, 2); - } + public DeathMessageSetting() { + super(MenuType.SETTINGS, 1, 3, 2); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOW, Message.forName("item-death-message-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BOW, Message.forName("item-death-message-setting")); + } - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - switch (getValue()) { - default: - return DefaultItem.disabled(); - case ENABLED: - return DefaultItem.enabled(); - case VANILLA: - return DefaultItem.create(MinecraftNameWrapper.SIGN, Message.forName("item-death-message-setting-vanilla")); - } - } + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + switch (getValue()) { + default: + return DefaultItem.disabled(); + case ENABLED: + return DefaultItem.enabled(); + case VANILLA: + return DefaultItem.create(MinecraftNameWrapper.SIGN, Message.forName("item-death-message-setting-vanilla")); + } + } - @Override - public void playValueChangeTitle() { - switch (getValue()) { - case ENABLED: - ChallengeHelper.playToggleChallengeTitle(this, true); - return; - case VANILLA: - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-death-message-setting-vanilla")); - return; - default: - ChallengeHelper.playToggleChallengeTitle(this, false); - } - } + @Override + public void playValueChangeTitle() { + switch (getValue()) { + case ENABLED: + ChallengeHelper.playToggleChallengeTitle(this, true); + return; + case VANILLA: + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-death-message-setting-vanilla")); + return; + default: + ChallengeHelper.playToggleChallengeTitle(this, false); + } + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onDeath(@Nonnull PlayerDeathEvent event) { - event.setDeathMessage(null); - if (hide) return; + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onDeath(@Nonnull PlayerDeathEvent event) { + event.setDeathMessage(null); + if (hide) return; - String original = event.getDeathMessage(); - Player entity = event.getEntity(); - switch (getValue()) { - case ENABLED: - EntityDamageEvent cause = entity.getLastDamageCause(); - if (cause != null && cause.getCause() != DamageCause.CUSTOM) { - Message.forName("death-message-cause").broadcast(Prefix.CHALLENGES, NameHelper.getName(entity), DamageDisplaySetting.getCause(cause)); - } else { - Message.forName("death-message").broadcast(Prefix.CHALLENGES, NameHelper.getName(entity)); - } - return; - case VANILLA: - if (original != null) { - Bukkit.broadcastMessage(Prefix.CHALLENGES + "§7" + original); - } - } - } + String original = event.getDeathMessage(); + Player entity = event.getEntity(); + switch (getValue()) { + case ENABLED: + EntityDamageEvent cause = entity.getLastDamageCause(); + if (cause != null && cause.getCause() != DamageCause.CUSTOM) { + Message.forName("death-message-cause").broadcast(Prefix.CHALLENGES, NameHelper.getName(entity), DamageDisplaySetting.getCause(cause)); + } else { + Message.forName("death-message").broadcast(Prefix.CHALLENGES, NameHelper.getName(entity)); + } + return; + case VANILLA: + if (original != null) { + Bukkit.broadcastMessage(Prefix.CHALLENGES + "§7" + original); + } + } + } - public void setHideMessagesTemporarily(boolean hide) { - this.hide = hide; - } + public void setHideMessagesTemporarily(boolean hide) { + this.hide = hide; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java index 19337ecd6..6f5c14d5f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java @@ -17,29 +17,29 @@ @Since("2.0") public class DeathPositionSetting extends Setting { - private static final String POSITION_PREFIX = "death-"; + private static final String POSITION_PREFIX = "death-"; - public DeathPositionSetting() { - super(MenuType.SETTINGS); - } + public DeathPositionSetting() { + super(MenuType.SETTINGS); + } - @EventHandler(priority = EventPriority.LOWEST) - public void onDeath(@Nonnull PlayerDeathEvent event) { - if (!shouldExecuteEffect()) return; + @EventHandler(priority = EventPriority.LOWEST) + public void onDeath(@Nonnull PlayerDeathEvent event) { + if (!shouldExecuteEffect()) return; - int index = 1; - while (AbstractChallenge.getFirstInstance(PositionSetting.class).containsPosition(POSITION_PREFIX + index)) - index++; + int index = 1; + while (AbstractChallenge.getFirstInstance(PositionSetting.class).containsPosition(POSITION_PREFIX + index)) + index++; - Player player = event.getEntity(); - player.performCommand("pos " + POSITION_PREFIX + index); + Player player = event.getEntity(); + player.performCommand("pos " + POSITION_PREFIX + index); - } + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MUSIC_DISC_11, Message.forName("item-death-position-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.MUSIC_DISC_11, Message.forName("item-death-position-setting")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java index 0ae530df8..55c7a7a51 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java @@ -32,138 +32,138 @@ public class DifficultySetting extends Modifier implements SenderCommand, TabCompleter { - public DifficultySetting() { - super(MenuType.SETTINGS, 0, 3, 2); - } - - @Override - protected void onValueChange() { - setDifficulty(getDifficultyByValue(getValue())); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GLISTERING_MELON_SLICE, Message.forName("item-difficulty-setting")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - switch (getValue()) { - case 0: - return DefaultItem.create(Material.LIME_DYE, getDifficultyName()); - case 1: - return DefaultItem.create(MinecraftNameWrapper.GREEN_DYE, getDifficultyName()); - case 2: - return DefaultItem.create(Material.ORANGE_DYE, getDifficultyName()); - default: - return DefaultItem.create(MinecraftNameWrapper.RED_DYE, getDifficultyName()); - } - } - - private String getDifficultyName() { - return getDifficultyComponent().toLegacyText(); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getDifficultyName()); - } - - private void setDifficulty(Difficulty difficulty) { - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "minecraft:difficulty " + difficulty.name().toLowerCase()); - for (World world : Bukkit.getWorlds()) { - world.setDifficulty(difficulty); - } - } - - @Nonnull - private Difficulty getCurrentDifficulty() { - return Bukkit.getWorlds().isEmpty() ? Difficulty.NORMAL : ChallengeAPI.getGameWorld(Environment.NORMAL) - .getDifficulty(); - } - - @Nonnull - private Difficulty getDifficultyByValue(int value) { - Difficulty difficulty = Difficulty.values()[value]; - return difficulty == null ? Difficulty.NORMAL : difficulty; - } - - @Override - public void loadSettings(@Nonnull Document document) { - if (!document.contains("value")) - setValue(getCurrentDifficulty().ordinal()); - - super.loadSettings(document); - } - - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - - if (args.length == 0) { - Message.forName("command-difficulty-current").send(sender, Prefix.CHALLENGES, getDifficultyComponent()); - return; - } - - int difficulty = getDifficultyValue(args[0]); - if (difficulty == -1) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "difficulty "); - return; - } - - setValue(difficulty); - Message.forName("command-difficulty-change").broadcast(Prefix.CHALLENGES, getDifficultyComponent()); - - } - - private BaseComponent getDifficultyComponent() { - TranslatableComponent name = BukkitStringUtils.getDifficultyName(getDifficultyByValue(getValue())); - switch (getValue()) { - case 0: - name.setColor(ChatColor.GREEN); - break; - case 1: - name.setColor(ChatColor.DARK_GREEN); - break; - case 2: - name.setColor(ChatColor.GOLD); - break; - default: - name.setColor(ChatColor.RED); - break; - } - return name; - } - - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String alias, @Nonnull String[] args) { - if (args.length > 1) return new ArrayList<>(); - return Arrays.asList("peaceful", "easy", "normal", "hard"); - } - - private int getDifficultyValue(@Nonnull String input) { - - switch (input.toLowerCase()) { - case "peaceful": - return 0; - case "easy": - return 1; - case "normal": - return 2; - case "hard": - return 3; - } - - try { - int value = Integer.parseInt(input); - if (value < 0 || value > 3) return -1; - return value; - } catch (Exception ex) { - return -1; - } - - } + public DifficultySetting() { + super(MenuType.SETTINGS, 0, 3, 2); + } + + @Override + protected void onValueChange() { + setDifficulty(getDifficultyByValue(getValue())); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GLISTERING_MELON_SLICE, Message.forName("item-difficulty-setting")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + switch (getValue()) { + case 0: + return DefaultItem.create(Material.LIME_DYE, getDifficultyName()); + case 1: + return DefaultItem.create(MinecraftNameWrapper.GREEN_DYE, getDifficultyName()); + case 2: + return DefaultItem.create(Material.ORANGE_DYE, getDifficultyName()); + default: + return DefaultItem.create(MinecraftNameWrapper.RED_DYE, getDifficultyName()); + } + } + + private String getDifficultyName() { + return getDifficultyComponent().toLegacyText(); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, getDifficultyName()); + } + + private void setDifficulty(Difficulty difficulty) { + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "minecraft:difficulty " + difficulty.name().toLowerCase()); + for (World world : Bukkit.getWorlds()) { + world.setDifficulty(difficulty); + } + } + + @Nonnull + private Difficulty getCurrentDifficulty() { + return Bukkit.getWorlds().isEmpty() ? Difficulty.NORMAL : ChallengeAPI.getGameWorld(Environment.NORMAL) + .getDifficulty(); + } + + @Nonnull + private Difficulty getDifficultyByValue(int value) { + Difficulty difficulty = Difficulty.values()[value]; + return difficulty == null ? Difficulty.NORMAL : difficulty; + } + + @Override + public void loadSettings(@Nonnull Document document) { + if (!document.contains("value")) + setValue(getCurrentDifficulty().ordinal()); + + super.loadSettings(document); + } + + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + + if (args.length == 0) { + Message.forName("command-difficulty-current").send(sender, Prefix.CHALLENGES, getDifficultyComponent()); + return; + } + + int difficulty = getDifficultyValue(args[0]); + if (difficulty == -1) { + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "difficulty "); + return; + } + + setValue(difficulty); + Message.forName("command-difficulty-change").broadcast(Prefix.CHALLENGES, getDifficultyComponent()); + + } + + private BaseComponent getDifficultyComponent() { + TranslatableComponent name = BukkitStringUtils.getDifficultyName(getDifficultyByValue(getValue())); + switch (getValue()) { + case 0: + name.setColor(ChatColor.GREEN); + break; + case 1: + name.setColor(ChatColor.DARK_GREEN); + break; + case 2: + name.setColor(ChatColor.GOLD); + break; + default: + name.setColor(ChatColor.RED); + break; + } + return name; + } + + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String alias, @Nonnull String[] args) { + if (args.length > 1) return new ArrayList<>(); + return Arrays.asList("peaceful", "easy", "normal", "hard"); + } + + private int getDifficultyValue(@Nonnull String input) { + + switch (input.toLowerCase()) { + case "peaceful": + return 0; + case "easy": + return 1; + case "normal": + return 2; + case "hard": + return 3; + } + + try { + int value = Integer.parseInt(input); + if (value < 0 || value > 3) return -1; + return value; + } catch (Exception ex) { + return -1; + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java index 80a8c9ef7..659aaeec7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java @@ -16,25 +16,25 @@ @Since("2.0") public class EnderChestCommandSetting extends Setting implements PlayerCommand { - public EnderChestCommandSetting() { - super(MenuType.SETTINGS); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENDER_CHEST, Message.forName("item-enderchest-command-setting")); - } - - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - if (!isEnabled() || ChallengeAPI.isWorldInUse()) { - Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); - return; - } - - player.openInventory(player.getEnderChest()); - Message.forName("command-enderchest-open").send(player, Prefix.CHALLENGES); - } + public EnderChestCommandSetting() { + super(MenuType.SETTINGS); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ENDER_CHEST, Message.forName("item-enderchest-command-setting")); + } + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + if (!isEnabled() || ChallengeAPI.isWorldInUse()) { + Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); + return; + } + + player.openInventory(player.getEnderChest()); + Message.forName("command-enderchest-open").send(player, Prefix.CHALLENGES); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java index 846d5f120..748011a2d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java @@ -13,14 +13,14 @@ @Since("2.0") public class FortressSpawnSetting extends NetherPortalSpawnSetting { - public FortressSpawnSetting() { - super(MenuType.SETTINGS, StructureType.NETHER_FORTRESS, "unable-to-find-fortress", Material.NETHER_BRICKS); - } + public FortressSpawnSetting() { + super(MenuType.SETTINGS, StructureType.NETHER_FORTRESS, "unable-to-find-fortress", Material.NETHER_BRICKS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.NETHER_BRICK_STAIRS, Message.forName("item-fortress-spawn-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.NETHER_BRICK_STAIRS, Message.forName("item-fortress-spawn-setting")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java index 3349bcb63..55176e6ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import javax.annotation.Nonnull; - import net.anweisen.utilities.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; @@ -14,81 +12,79 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.scoreboard.DisplaySlot; -import org.bukkit.scoreboard.Objective; -import org.bukkit.scoreboard.RenderType; -import org.bukkit.scoreboard.Scoreboard; -import org.bukkit.scoreboard.ScoreboardManager; +import org.bukkit.scoreboard.*; + +import javax.annotation.Nonnull; @Since("2.0") public class HealthDisplaySetting extends Setting { - public static final String OBJECTIVE_NAME = "health_display"; - - public HealthDisplaySetting() { - super(MenuType.SETTINGS, true); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.RED_STAINED_GLASS, Message.forName("item-health-display-setting")); - } - - @Override - protected void onEnable() { - Bukkit.getOnlinePlayers().forEach(this::show); - } - - @Override - protected void onDisable() { - Bukkit.getOnlinePlayers().forEach(this::hide); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onJoin(@Nonnull PlayerJoinEvent event) { - if (isEnabled()) { - show(event.getPlayer()); - } else { - hide(event.getPlayer()); - } - } - - private void show(@Nonnull Player player) { - Scoreboard scoreboard = player.getScoreboard(); - ScoreboardManager manager = Bukkit.getScoreboardManager(); - if (manager == null) return; - if (player.getScoreboard() == manager.getMainScoreboard()) - player.setScoreboard(scoreboard = manager.getNewScoreboard()); - - Objective objective = scoreboard.getObjective(OBJECTIVE_NAME); - if (objective == null) - objective = scoreboard.registerNewObjective(OBJECTIVE_NAME, "health", OBJECTIVE_NAME); - // Criteria interface only available since 1.20 - - objective.setDisplaySlot(DisplaySlot.PLAYER_LIST); - - try { - objective.setRenderType(RenderType.HEARTS); - } catch (Exception ex) { - Challenges.getInstance().getLogger().severe("Tablist Health could not be updated. You are using an outdated version of spigot."); - // In some versions of spigot RenderType does not exist - } - - } - - private void hide(@Nonnull Player player) { - - Scoreboard scoreboard = player.getScoreboard(); - Objective objective = scoreboard.getObjective(OBJECTIVE_NAME); - if (objective == null) return; - - try { - objective.unregister(); - } catch (Exception ex) { - Challenges.getInstance().getLogger().severe("Error while unregistering tablist hearts objective"); - } - - } + public static final String OBJECTIVE_NAME = "health_display"; + + public HealthDisplaySetting() { + super(MenuType.SETTINGS, true); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.RED_STAINED_GLASS, Message.forName("item-health-display-setting")); + } + + @Override + protected void onEnable() { + Bukkit.getOnlinePlayers().forEach(this::show); + } + + @Override + protected void onDisable() { + Bukkit.getOnlinePlayers().forEach(this::hide); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onJoin(@Nonnull PlayerJoinEvent event) { + if (isEnabled()) { + show(event.getPlayer()); + } else { + hide(event.getPlayer()); + } + } + + private void show(@Nonnull Player player) { + Scoreboard scoreboard = player.getScoreboard(); + ScoreboardManager manager = Bukkit.getScoreboardManager(); + if (manager == null) return; + if (player.getScoreboard() == manager.getMainScoreboard()) + player.setScoreboard(scoreboard = manager.getNewScoreboard()); + + Objective objective = scoreboard.getObjective(OBJECTIVE_NAME); + if (objective == null) + objective = scoreboard.registerNewObjective(OBJECTIVE_NAME, "health", OBJECTIVE_NAME); + // Criteria interface only available since 1.20 + + objective.setDisplaySlot(DisplaySlot.PLAYER_LIST); + + try { + objective.setRenderType(RenderType.HEARTS); + } catch (Exception ex) { + Challenges.getInstance().getLogger().severe("Tablist Health could not be updated. You are using an outdated version of spigot."); + // In some versions of spigot RenderType does not exist + } + + } + + private void hide(@Nonnull Player player) { + + Scoreboard scoreboard = player.getScoreboard(); + Objective objective = scoreboard.getObjective(OBJECTIVE_NAME); + if (objective == null) return; + + try { + objective.unregister(); + } catch (Exception ex) { + Challenges.getInstance().getLogger().severe("Error while unregistering tablist hearts objective"); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java index e050cbcb2..fa6eb8e24 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java @@ -18,51 +18,51 @@ @Since("2.0") public class ImmediateRespawnSetting extends Setting { - private boolean respawnWithEvent; + private boolean respawnWithEvent; - public ImmediateRespawnSetting() { - super(MenuType.SETTINGS); - } + public ImmediateRespawnSetting() { + super(MenuType.SETTINGS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_APPLE, Message.forName("item-immediate-respawn-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GOLDEN_APPLE, Message.forName("item-immediate-respawn-setting")); + } - @Override - protected void onEnable() { - if (respawnWithEvent) { - return; - } - try { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.DO_IMMEDIATE_RESPAWN, true); - } - } catch (NoSuchFieldError ignored) { - respawnWithEvent = true; - } - } + @Override + protected void onEnable() { + if (respawnWithEvent) { + return; + } + try { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.DO_IMMEDIATE_RESPAWN, true); + } + } catch (NoSuchFieldError ignored) { + respawnWithEvent = true; + } + } - @Override - protected void onDisable() { - if (respawnWithEvent) { - return; - } - try { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.DO_IMMEDIATE_RESPAWN, false); - } - } catch (NoSuchFieldError ignored) { - } - } + @Override + protected void onDisable() { + if (respawnWithEvent) { + return; + } + try { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.DO_IMMEDIATE_RESPAWN, false); + } + } catch (NoSuchFieldError ignored) { + } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { - if (!isEnabled()) return; - if (!respawnWithEvent) return; - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> event.getEntity().spigot().respawn(), 1); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { + if (!isEnabled()) return; + if (!respawnWithEvent) return; + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> event.getEntity().spigot().respawn(), 1); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java index 3bb1c7b54..dac4723cd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java @@ -13,27 +13,27 @@ public class KeepInventorySetting extends Setting { - public KeepInventorySetting() { - super(MenuType.SETTINGS); - } + public KeepInventorySetting() { + super(MenuType.SETTINGS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENDER_EYE, Message.forName("item-keep-inventory-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ENDER_EYE, Message.forName("item-keep-inventory-setting")); + } - @Override - protected void onEnable() { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.KEEP_INVENTORY, true); - } - } + @Override + protected void onEnable() { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.KEEP_INVENTORY, true); + } + } - @Override - protected void onDisable() { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.KEEP_INVENTORY, false); - } - } + @Override + protected void onDisable() { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.KEEP_INVENTORY, false); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java index ea526cc68..f91ef2290 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java @@ -9,6 +9,7 @@ import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; + import javax.annotation.Nonnull; import java.util.Objects; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index 0b380bb82..f460ecd9d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import javax.annotation.Nonnull; import net.anweisen.utilities.bukkit.utils.item.MaterialWrapper; import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; import net.anweisen.utilities.common.config.Document; @@ -18,103 +17,105 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.jetbrains.annotations.NotNull; +import javax.annotation.Nonnull; + public class MaxHealthSetting extends Modifier { - /** - * Offset that can be used to modify the max health for specific players with other challenges. - * Is saved within the gamestate so it resets with a world reset. - * Saves the data with the uuid as string as the key and with an integer which defines the offset - * The health offset for every player is saved with the key "all" - */ - private Document valueOffset = new GsonDocument(); - - public MaxHealthSetting() { - super(MenuType.SETTINGS, 1, 200 * 2, 20); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(MaterialWrapper.RED_DYE, Message.forName("item-max-health-setting")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.value(getValue(), "§e").appendName(" §7HP §8(§e" + (getValue() / 2f) + " §c❤§8)"); - } - - @Override - public void writeGameState(@NotNull Document document) { - super.writeGameState(document); - document.set("offset", valueOffset); - } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - valueOffset = document.contains("offset") ? document.getDocument("offset") : new GsonDocument(); - onValueChange(); - } - - @Override - public void onValueChange() { - broadcast(this::updateHealth); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - - @EventHandler - public void onJoin(@Nonnull PlayerJoinEvent event) { - updateHealth(event.getPlayer()); - } - - private void updateHealth(Player player) { - AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); - if (attribute == null) - return; // This should never happen because its a generic attribute, but just in case - int newMaxHealth = getMaxHealth(player); - double oldMaxHealth = attribute.getBaseValue(); - - if (newMaxHealth <= 0) { - ChallengeHelper.kill(player); - valueOffset.remove(player.getUniqueId().toString()); - return; - } - - if (oldMaxHealth != newMaxHealth) { - attribute.setBaseValue(newMaxHealth); - - if (oldMaxHealth < newMaxHealth) { - double oldHealth = player.getHealth(); - double newHealth = oldHealth + (newMaxHealth - oldMaxHealth); - player.setHealth(Math.min(Math.max(newHealth, 0), newMaxHealth)); - } - if (MinecraftVersion.current().isNewerThan(MinecraftVersion.V1_19)) { - player.sendHealthUpdate(); - } - // TODO: Versions lower than 1.19 need to update health via nms - } - } - - public int getMaxHealth(Player player) { - String key = player.getUniqueId().toString(); - return getValue() + valueOffset.getInt("all") + valueOffset.getInt(key); - } - - public void addHealth(int health) { - valueOffset.set("all", valueOffset.getInt("all") + health); - onValueChange(); - } - - public void addHealth(Player player, int health) { - String key = player.getUniqueId().toString(); - valueOffset.set(key, valueOffset.getInt(key) + health); - updateHealth(player); - } + /** + * Offset that can be used to modify the max health for specific players with other challenges. + * Is saved within the gamestate so it resets with a world reset. + * Saves the data with the uuid as string as the key and with an integer which defines the offset + * The health offset for every player is saved with the key "all" + */ + private Document valueOffset = new GsonDocument(); + + public MaxHealthSetting() { + super(MenuType.SETTINGS, 1, 200 * 2, 20); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(MaterialWrapper.RED_DYE, Message.forName("item-max-health-setting")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + return DefaultItem.value(getValue(), "§e").appendName(" §7HP §8(§e" + (getValue() / 2f) + " §c❤§8)"); + } + + @Override + public void writeGameState(@NotNull Document document) { + super.writeGameState(document); + document.set("offset", valueOffset); + } + + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + valueOffset = document.contains("offset") ? document.getDocument("offset") : new GsonDocument(); + onValueChange(); + } + + @Override + public void onValueChange() { + broadcast(this::updateHealth); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + } + + @EventHandler + public void onJoin(@Nonnull PlayerJoinEvent event) { + updateHealth(event.getPlayer()); + } + + private void updateHealth(Player player) { + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) + return; // This should never happen because its a generic attribute, but just in case + int newMaxHealth = getMaxHealth(player); + double oldMaxHealth = attribute.getBaseValue(); + + if (newMaxHealth <= 0) { + ChallengeHelper.kill(player); + valueOffset.remove(player.getUniqueId().toString()); + return; + } + + if (oldMaxHealth != newMaxHealth) { + attribute.setBaseValue(newMaxHealth); + + if (oldMaxHealth < newMaxHealth) { + double oldHealth = player.getHealth(); + double newHealth = oldHealth + (newMaxHealth - oldMaxHealth); + player.setHealth(Math.min(Math.max(newHealth, 0), newMaxHealth)); + } + if (MinecraftVersion.current().isNewerThan(MinecraftVersion.V1_19)) { + player.sendHealthUpdate(); + } + // TODO: Versions lower than 1.19 need to update health via nms + } + } + + public int getMaxHealth(Player player) { + String key = player.getUniqueId().toString(); + return getValue() + valueOffset.getInt("all") + valueOffset.getInt(key); + } + + public void addHealth(int health) { + valueOffset.set("all", valueOffset.getInt("all") + health); + onValueChange(); + } + + public void addHealth(Player player, int health) { + String key = player.getUniqueId().toString(); + valueOffset.set(key, valueOffset.getInt(key) + health); + updateHealth(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java index 95e75720d..1a6180b08 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java @@ -13,27 +13,27 @@ public class MobGriefingSetting extends Setting { - public MobGriefingSetting() { - super(MenuType.SETTINGS); - } + public MobGriefingSetting() { + super(MenuType.SETTINGS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CREEPER_HEAD, Message.forName("item-mob-griefing-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.CREEPER_HEAD, Message.forName("item-mob-griefing-setting")); + } - @Override - protected void onEnable() { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.MOB_GRIEFING, false); - } + @Override + protected void onEnable() { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.MOB_GRIEFING, false); } + } - @Override - protected void onDisable() { - for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.MOB_GRIEFING, true); - } + @Override + protected void onDisable() { + for (World world : Bukkit.getWorlds()) { + world.setGameRule(GameRule.MOB_GRIEFING, true); } -} \ No newline at end of file + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java index f74da9f48..7ac0f95a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java @@ -16,23 +16,23 @@ public class NoHitDelaySetting extends Setting { - public NoHitDelaySetting() { - super(MenuType.SETTINGS); - } + public NoHitDelaySetting() { + super(MenuType.SETTINGS); + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onDamageByEntity(@Nonnull EntityDamageEvent event) { - if (!(event.getEntity() instanceof LivingEntity)) return; - if (!shouldExecuteEffect()) return; - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { - ((LivingEntity) event.getEntity()).setNoDamageTicks(0); - }, 1); - } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onDamageByEntity(@Nonnull EntityDamageEvent event) { + if (!(event.getEntity() instanceof LivingEntity)) return; + if (!shouldExecuteEffect()) return; + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { + ((LivingEntity) event.getEntity()).setNoDamageTicks(0); + }, 1); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FEATHER, Message.forName("item-no-hit-delay-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FEATHER, Message.forName("item-no-hit-delay-setting")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java index a3a5ef966..a7e2ced01 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java @@ -13,32 +13,32 @@ public class NoHungerSetting extends Setting { - public NoHungerSetting() { - super(MenuType.SETTINGS); - } - - @Override - protected void onEnable() { - broadcastFiltered(this::feedPlayer); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BREAD, Message.forName("no-hunger-setting")); - } - - @EventHandler(ignoreCancelled = true) - public void onHunger(@Nonnull FoodLevelChangeEvent event) { - if (!(event.getEntity() instanceof Player)) return; - if (!shouldExecuteEffect()) return; - feedPlayer(((Player) event.getEntity())); - event.setCancelled(true); - } - - private void feedPlayer(@Nonnull Player player) { - player.setFoodLevel(20); - player.setSaturation(20); - } + public NoHungerSetting() { + super(MenuType.SETTINGS); + } + + @Override + protected void onEnable() { + broadcastFiltered(this::feedPlayer); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BREAD, Message.forName("no-hunger-setting")); + } + + @EventHandler(ignoreCancelled = true) + public void onHunger(@Nonnull FoodLevelChangeEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!shouldExecuteEffect()) return; + feedPlayer(((Player) event.getEntity())); + event.setCancelled(true); + } + + private void feedPlayer(@Nonnull Player player) { + player.setFoodLevel(20); + player.setSaturation(20); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java index 0a7565208..3c57403c8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java @@ -12,23 +12,23 @@ public class NoItemDamageSetting extends Setting { - public NoItemDamageSetting() { - super(MenuType.SETTINGS); - } - - @EventHandler - public void onItemDamage(PlayerItemDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - - event.setCancelled(true); - event.getPlayer().updateInventory(); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ANVIL, Message.forName("item-no-item-damage-setting")); - } + public NoItemDamageSetting() { + super(MenuType.SETTINGS); + } + + @EventHandler + public void onItemDamage(PlayerItemDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + + event.setCancelled(true); + event.getPlayer().updateInventory(); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.ANVIL, Message.forName("item-no-item-damage-setting")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java index 66e998142..0e0b09421 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java @@ -20,44 +20,44 @@ @Since("2.0") public class NoOffhandSetting extends Setting { - public NoOffhandSetting() { - super(MenuType.SETTINGS); - } - - @Override - protected void onEnable() { - for (Player player : Bukkit.getOnlinePlayers()) { - ItemStack itemInOffHand = player.getInventory().getItemInOffHand(); - if (itemInOffHand.getType() == Material.AIR) return; - player.getWorld().dropItemNaturally(player.getLocation(), itemInOffHand); - player.getInventory().setItemInOffHand(null); - player.updateInventory(); - } - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SHIELD, Message.forName("item-no-offhand-setting")); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerSwapHandItems(PlayerSwapHandItemsEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onInventoryClick(InventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getWhoClicked() instanceof Player)) return; - Player player = (Player) event.getWhoClicked(); - if (ignorePlayer(player)) return; - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getType() != InventoryType.PLAYER) return; - if (event.getSlot() != 40) return; - event.setCancelled(true); - } + public NoOffhandSetting() { + super(MenuType.SETTINGS); + } + + @Override + protected void onEnable() { + for (Player player : Bukkit.getOnlinePlayers()) { + ItemStack itemInOffHand = player.getInventory().getItemInOffHand(); + if (itemInOffHand.getType() == Material.AIR) return; + player.getWorld().dropItemNaturally(player.getLocation(), itemInOffHand); + player.getInventory().setItemInOffHand(null); + player.updateInventory(); + } + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.SHIELD, Message.forName("item-no-offhand-setting")); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerSwapHandItems(PlayerSwapHandItemsEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onInventoryClick(InventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getWhoClicked() instanceof Player)) return; + Player player = (Player) event.getWhoClicked(); + if (ignorePlayer(player)) return; + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getType() != InventoryType.PLAYER) return; + if (event.getSlot() != 40) return; + event.setCancelled(true); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java index 0b756d43d..3fa5c2747 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java @@ -21,55 +21,55 @@ @Since("2.0") public class OldPvPSetting extends Setting { - public static final double DISABLED = 32, NORMAL = 4; // Values copied from BackToTheRoots + public static final double DISABLED = 32, NORMAL = 4; // Values copied from BackToTheRoots - public OldPvPSetting() { - super(MenuType.SETTINGS); - } + public OldPvPSetting() { + super(MenuType.SETTINGS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.IRON_SWORD, Message.forName("item-old-pvp-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.IRON_SWORD, Message.forName("item-old-pvp-setting")); + } - @Override - protected void onDisable() { - broadcast(player -> setAttackSpeed(player, NORMAL)); - } + @Override + protected void onDisable() { + broadcast(player -> setAttackSpeed(player, NORMAL)); + } - @Override - protected void onEnable() { - broadcast(player -> setAttackSpeed(player, DISABLED)); - } + @Override + protected void onEnable() { + broadcast(player -> setAttackSpeed(player, DISABLED)); + } - @EventHandler - public void onChangeWorldEvent(@Nonnull PlayerChangedWorldEvent event) { - if (!isEnabled()) return; - setAttackSpeed(event.getPlayer(), DISABLED); - } + @EventHandler + public void onChangeWorldEvent(@Nonnull PlayerChangedWorldEvent event) { + if (!isEnabled()) return; + setAttackSpeed(event.getPlayer(), DISABLED); + } - @EventHandler - public void onJoin(@Nonnull PlayerJoinEvent event) { - if (!isEnabled()) return; - setAttackSpeed(event.getPlayer(), DISABLED); - } + @EventHandler + public void onJoin(@Nonnull PlayerJoinEvent event) { + if (!isEnabled()) return; + setAttackSpeed(event.getPlayer(), DISABLED); + } - @EventHandler - public void onQuit(@Nonnull PlayerQuitEvent event) { - setAttackSpeed(event.getPlayer(), NORMAL); - } + @EventHandler + public void onQuit(@Nonnull PlayerQuitEvent event) { + setAttackSpeed(event.getPlayer(), NORMAL); + } - @EventHandler - public void onSweepDamage(@Nonnull EntityDamageEvent event) { - if (!isEnabled()) return; - if (event.getCause() != DamageCause.ENTITY_SWEEP_ATTACK) return; - event.setCancelled(true); - } + @EventHandler + public void onSweepDamage(@Nonnull EntityDamageEvent event) { + if (!isEnabled()) return; + if (event.getCause() != DamageCause.ENTITY_SWEEP_ATTACK) return; + event.setCancelled(true); + } - protected void setAttackSpeed(@Nonnull Player player, double value) { - AttributeInstance attribute = player.getAttribute(AttributeWrapper.ATTACK_SPEED); - if (attribute == null) return; - attribute.setBaseValue(value); - } + protected void setAttackSpeed(@Nonnull Player player, double value) { + AttributeInstance attribute = player.getAttribute(AttributeWrapper.ATTACK_SPEED); + if (attribute == null) return; + attribute.setBaseValue(value); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java index 8ab6ef1a2..5daa22b3d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java @@ -17,35 +17,35 @@ public class OneTeamLifeSetting extends Setting { - private boolean isKilling = false; - - public OneTeamLifeSetting() { - super(MenuType.SETTINGS, true); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FIRE_CHARGE, Message.forName("item-one-life-setting")); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDeath(@Nonnull PlayerDeathEvent event) { - if (!shouldExecuteEffect()) return; - if (isKilling) return; - - Bukkit.getScheduler().runTask(plugin, () -> { - AbstractChallenge.getFirstInstance(DeathMessageSetting.class).setHideMessagesTemporarily(isKilling = true); - for (Player player : Bukkit.getOnlinePlayers()) { - if (player == event.getEntity()) continue; - if (ignorePlayer(player)) continue; - ChallengeHelper.kill(player); - } - - AbstractChallenge.getFirstInstance(RespawnSetting.class).checkAllPlayersDead(); - AbstractChallenge.getFirstInstance(DeathMessageSetting.class).setHideMessagesTemporarily(isKilling = false); - }); - - } + private boolean isKilling = false; + + public OneTeamLifeSetting() { + super(MenuType.SETTINGS, true); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.FIRE_CHARGE, Message.forName("item-one-life-setting")); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDeath(@Nonnull PlayerDeathEvent event) { + if (!shouldExecuteEffect()) return; + if (isKilling) return; + + Bukkit.getScheduler().runTask(plugin, () -> { + AbstractChallenge.getFirstInstance(DeathMessageSetting.class).setHideMessagesTemporarily(isKilling = true); + for (Player player : Bukkit.getOnlinePlayers()) { + if (player == event.getEntity()) continue; + if (ignorePlayer(player)) continue; + ChallengeHelper.kill(player); + } + + AbstractChallenge.getFirstInstance(RespawnSetting.class).checkAllPlayersDead(); + AbstractChallenge.getFirstInstance(DeathMessageSetting.class).setHideMessagesTemporarily(isKilling = false); + }); + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java index cc8fbad1f..2d2a688b6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java @@ -18,40 +18,40 @@ public class PlayerGlowSetting extends Setting { - public PlayerGlowSetting() { - super(MenuType.SETTINGS); - } - - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GLASS_BOTTLE, Message.forName("item-glow-setting")); - } - - @Override - protected void onEnable() { - updateEffects(); - } - - @Override - protected void onDisable() { - updateEffects(); - } - - @TimerTask(status = {TimerStatus.PAUSED, TimerStatus.RUNNING}, async = false) - @ScheduledTask(ticks = 50, async = false, timerPolicy = TimerPolicy.ALWAYS) - public void updateEffects() { - if (!shouldExecuteEffect()) { - broadcast(player -> player.removePotionEffect(PotionEffectType.GLOWING)); - return; - } - broadcast(player -> player.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, Integer.MAX_VALUE, 1, true, false, false))); - } - - @EventHandler - public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { - updateEffects(); - } + public PlayerGlowSetting() { + super(MenuType.SETTINGS); + } + + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.GLASS_BOTTLE, Message.forName("item-glow-setting")); + } + + @Override + protected void onEnable() { + updateEffects(); + } + + @Override + protected void onDisable() { + updateEffects(); + } + + @TimerTask(status = {TimerStatus.PAUSED, TimerStatus.RUNNING}, async = false) + @ScheduledTask(ticks = 50, async = false, timerPolicy = TimerPolicy.ALWAYS) + public void updateEffects() { + if (!shouldExecuteEffect()) { + broadcast(player -> player.removePotionEffect(PotionEffectType.GLOWING)); + return; + } + broadcast(player -> player.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, Integer.MAX_VALUE, 1, true, false, false))); + } + + @EventHandler + public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { + updateEffects(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java index f9c8b9cd3..98529fca2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java @@ -31,282 +31,282 @@ public class PositionSetting extends Setting implements PlayerCommand, TabCompleter { - private final Map positions = new HashMap<>(); - private final boolean particleLines; - - public PositionSetting() { - super(MenuType.SETTINGS, true); - particleLines = ChallengeConfigHelper.getSettingsDocument().getBoolean("position-particle-lines"); - Challenges.getInstance().registerCommand(new DelPosCommand(), "delposition"); - Challenges.getInstance().registerCommand(new SetPosCommand(), "setposition"); - } - - public static Environment getWorldEnvironment(@Nonnull String name) { - switch (name.toLowerCase()) { - default: - return null; - case "overworld": - return Environment.NORMAL; - case "nether": - return Environment.NETHER; - case "end": - return Environment.THE_END; - } - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BLUE_BANNER, Message.forName("item-position-setting")); - } - - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) { - if (!isEnabled()) { - Message.forName("positions-disabled").send(player, Prefix.POSITION); - SoundSample.BASS_OFF.play(player); - return; - } - - if (args.length == 0) { - if (positions.entrySet().stream().noneMatch(entry -> player.getWorld() == entry.getValue().getWorld())) { - Message.forName("no-positions").send(player, Prefix.POSITION, "position "); - return; - } - - positions.entrySet().stream() - .filter(entry -> player.getWorld() == entry.getValue().getWorld()) - .sorted(Comparator.>comparingDouble(entry -> entry.getValue().distance(player.getLocation())).reversed()) - .forEach(entry -> { - - Location location = entry.getValue(); - Message.forName("position").send(player, Prefix.POSITION, location.getBlockX(), location.getBlockY(), location.getBlockZ(), getWorldName(location), entry.getKey(), (int) location.distance(player.getLocation())); - }); - } else if (args.length == 1) { - String name = args[0].toLowerCase(); - Location position = positions.get(name); - if (position != null) { - if (position.getWorld() != player.getLocation().getWorld()) { - Message.forName("position-other-world").send(player, Prefix.POSITION, getWorldName(position)); - SoundSample.BASS_OFF.play(player); - return; - } - Message.forName("position").send(player, Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, (int) position.distance(player.getLocation())); - playParticleLine(player, position); - } else if (ChallengeAPI.isPaused()) { - Message.forName("timer-not-started").send(player, Prefix.POSITION); - SoundSample.BASS_OFF.play(player); - } else { - positions.put(name, position = player.getLocation()); - Message.forName("position-set").broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, NameHelper.getName(player)); - SoundSample.BASS_ON.play(player); - broadcastParticleLine(position); - } - - } else { - Message.forName("syntax").send(player, Prefix.POSITION, "position [name]"); - } - } - - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String alias, @Nonnull String[] args) { - if (args.length > 1) return new ArrayList<>(); - return Utils.filterRecommendations(args[0], positions.keySet().toArray(new String[0])); - } - - public String getWorldName(@Nonnull Location location) { - if (location.getWorld() == null) return "?"; - switch (location.getWorld().getEnvironment()) { - default: - return "Overworld"; - case NETHER: - return "Nether"; - case THE_END: - return "End"; - } - } - - public boolean containsPosition(@Nonnull String name) { - return positions.containsKey(name); - } - - private void broadcastParticleLine(@Nonnull Location location) { - broadcast(player -> playParticleLine(player, location)); - } - - private void playParticleLine(@Nonnull Player player, @Nonnull Location position) { - if (!particleLines) return; - if (player.getWorld() != position.getWorld()) return; - - // Defining target location to - Location target = position.clone().add(0, 0.3, 0); - - final int[] current = {0}; - Bukkit.getScheduler().runTaskTimer(plugin, task -> { - current[0]++; - if (current[0] >= 10) task.cancel(); - ParticleUtils.drawLine(player, player.getLocation(), target, - MinecraftNameWrapper.REDSTONE_DUST, new DustOptions(Color.LIME, 1), 1, 0.5, 50); - }, 0, 10); - } - - @Override - public void loadGameState(@Nonnull Document document) { - positions.clear(); - for (String name : document.keys()) { - positions.put(name, document.getSerializable(name, Location.class)); - } - } - - @Override - public void writeGameState(@Nonnull Document document) { - for (String key : document.keys()) { - document.remove(key); - } - positions.forEach(document::set); - } - - public class DelPosCommand implements PlayerCommand, TabCompleter { - - @Override - public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { - if (!isEnabled()) { - Message.forName("positions-disabled").send(player, Prefix.POSITION); - SoundSample.BASS_OFF.play(player); - return; - } - if (!ChallengeAPI.isStarted()) { - Message.forName("timer-not-started").send(player, Prefix.POSITION); - SoundSample.BASS_OFF.play(player); - return; - } - - if (args.length == 0) { - if (positions.isEmpty()) { - Message.forName("no-positions-global").send(player, Prefix.POSITION, "position "); - return; - } - - positions.entrySet().stream() - .sorted(Comparator.>comparingDouble(entry -> entry.getValue().distance(player.getLocation())).reversed()) - .forEach(entry -> { - Location location = entry.getValue(); - Message.forName("position").send(player, Prefix.POSITION, location.getBlockX(), location.getBlockY(), location.getBlockZ(), getWorldName(location), entry.getKey(), (int) location.distance(player.getLocation())); - }); - } else if (args.length == 1) { - String name = args[0].toLowerCase(); - Location position = positions.get(name); - if (position != null) { - positions.remove(name); - Message.forName("position-deleted").broadcast(Prefix.POSITION, - position.getBlockX(), position.getBlockY(), position.getBlockZ(), - getWorldName(position), name, NameHelper.getName(player)); - } else { - Message.forName("position-not-exists").send(player, Prefix.POSITION); - } - - } else { - Message.forName("syntax").send(player, Prefix.POSITION, "delposition "); - } - - } - - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { - if (args.length > 1) return new ArrayList<>(); - return Utils.filterRecommendations(args[0], positions.keySet().toArray(new String[0])); - } - - } - - public class SetPosCommand implements PlayerCommand, TabCompleter { - - @Override - public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { - if (!isEnabled()) { - Message.forName("positions-disabled").send(player, Prefix.POSITION); - SoundSample.BASS_OFF.play(player); - return; - } - if (!ChallengeAPI.isStarted()) { - Message.forName("timer-not-started").send(player, Prefix.POSITION); - SoundSample.BASS_OFF.play(player); - return; - } - - if (args.length < 5) { - Message.forName("syntax").send(player, Prefix.POSITION, "setposition "); - return; - } - - String name = args[0].toLowerCase(); - - if (positions.containsKey(name)) { - Message.forName("position-already-exists").send(player, Prefix.POSITION, name); - return; - } - - String worldName = args[1]; - String x = args[2]; - String y = args[3]; - String z = args[4]; - - try { - Environment environment = getWorldEnvironment(worldName); - World world = ChallengeAPI.getGameWorld(environment); - if (world == null) throw new IllegalArgumentException(); - double doubleX = Double.parseDouble(x); - double doubleY = Double.parseDouble(y); - double doubleZ = Double.parseDouble(z); - - Location position = new Location(world, doubleX, doubleY, doubleZ); - positions.put(name, position); - Message.forName("position-set") - .broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), - position.getBlockZ(), getWorldName(position), name, NameHelper.getName(player)); - SoundSample.BASS_ON.play(player); - broadcastParticleLine(position); - - } catch (Exception exception) { - Message.forName("syntax").send(player, Prefix.POSITION, "setposition "); - } - - } - - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { - if (!(sender instanceof Player)) return new LinkedList<>(); - Player player = (Player) sender; - if (args.length > 5) return new LinkedList<>(); - - if (args.length > 2) { - int arg = args.length - 2; - - double cord; - Location location = player.getLocation(); - switch (arg) { - case 1: - cord = location.getBlockX() + 0.5; - break; - case 2: - cord = location.getBlockY(); - break; - default: - cord = location.getBlockZ() + 0.5; - } - - return Collections.singletonList(String.valueOf(cord)); - - } else if (args.length > 1) { - return Arrays.asList("Overworld", "Nether", "End"); - } - - return new LinkedList<>(); - } - - } + private final Map positions = new HashMap<>(); + private final boolean particleLines; + + public PositionSetting() { + super(MenuType.SETTINGS, true); + particleLines = ChallengeConfigHelper.getSettingsDocument().getBoolean("position-particle-lines"); + Challenges.getInstance().registerCommand(new DelPosCommand(), "delposition"); + Challenges.getInstance().registerCommand(new SetPosCommand(), "setposition"); + } + + public static Environment getWorldEnvironment(@Nonnull String name) { + switch (name.toLowerCase()) { + default: + return null; + case "overworld": + return Environment.NORMAL; + case "nether": + return Environment.NETHER; + case "end": + return Environment.THE_END; + } + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BLUE_BANNER, Message.forName("item-position-setting")); + } + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) { + if (!isEnabled()) { + Message.forName("positions-disabled").send(player, Prefix.POSITION); + SoundSample.BASS_OFF.play(player); + return; + } + + if (args.length == 0) { + if (positions.entrySet().stream().noneMatch(entry -> player.getWorld() == entry.getValue().getWorld())) { + Message.forName("no-positions").send(player, Prefix.POSITION, "position "); + return; + } + + positions.entrySet().stream() + .filter(entry -> player.getWorld() == entry.getValue().getWorld()) + .sorted(Comparator.>comparingDouble(entry -> entry.getValue().distance(player.getLocation())).reversed()) + .forEach(entry -> { + + Location location = entry.getValue(); + Message.forName("position").send(player, Prefix.POSITION, location.getBlockX(), location.getBlockY(), location.getBlockZ(), getWorldName(location), entry.getKey(), (int) location.distance(player.getLocation())); + }); + } else if (args.length == 1) { + String name = args[0].toLowerCase(); + Location position = positions.get(name); + if (position != null) { + if (position.getWorld() != player.getLocation().getWorld()) { + Message.forName("position-other-world").send(player, Prefix.POSITION, getWorldName(position)); + SoundSample.BASS_OFF.play(player); + return; + } + Message.forName("position").send(player, Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, (int) position.distance(player.getLocation())); + playParticleLine(player, position); + } else if (ChallengeAPI.isPaused()) { + Message.forName("timer-not-started").send(player, Prefix.POSITION); + SoundSample.BASS_OFF.play(player); + } else { + positions.put(name, position = player.getLocation()); + Message.forName("position-set").broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, NameHelper.getName(player)); + SoundSample.BASS_ON.play(player); + broadcastParticleLine(position); + } + + } else { + Message.forName("syntax").send(player, Prefix.POSITION, "position [name]"); + } + } + + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String alias, @Nonnull String[] args) { + if (args.length > 1) return new ArrayList<>(); + return Utils.filterRecommendations(args[0], positions.keySet().toArray(new String[0])); + } + + public String getWorldName(@Nonnull Location location) { + if (location.getWorld() == null) return "?"; + switch (location.getWorld().getEnvironment()) { + default: + return "Overworld"; + case NETHER: + return "Nether"; + case THE_END: + return "End"; + } + } + + public boolean containsPosition(@Nonnull String name) { + return positions.containsKey(name); + } + + private void broadcastParticleLine(@Nonnull Location location) { + broadcast(player -> playParticleLine(player, location)); + } + + private void playParticleLine(@Nonnull Player player, @Nonnull Location position) { + if (!particleLines) return; + if (player.getWorld() != position.getWorld()) return; + + // Defining target location to + Location target = position.clone().add(0, 0.3, 0); + + final int[] current = {0}; + Bukkit.getScheduler().runTaskTimer(plugin, task -> { + current[0]++; + if (current[0] >= 10) task.cancel(); + ParticleUtils.drawLine(player, player.getLocation(), target, + MinecraftNameWrapper.REDSTONE_DUST, new DustOptions(Color.LIME, 1), 1, 0.5, 50); + }, 0, 10); + } + + @Override + public void loadGameState(@Nonnull Document document) { + positions.clear(); + for (String name : document.keys()) { + positions.put(name, document.getSerializable(name, Location.class)); + } + } + + @Override + public void writeGameState(@Nonnull Document document) { + for (String key : document.keys()) { + document.remove(key); + } + positions.forEach(document::set); + } + + public class DelPosCommand implements PlayerCommand, TabCompleter { + + @Override + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { + if (!isEnabled()) { + Message.forName("positions-disabled").send(player, Prefix.POSITION); + SoundSample.BASS_OFF.play(player); + return; + } + if (!ChallengeAPI.isStarted()) { + Message.forName("timer-not-started").send(player, Prefix.POSITION); + SoundSample.BASS_OFF.play(player); + return; + } + + if (args.length == 0) { + if (positions.isEmpty()) { + Message.forName("no-positions-global").send(player, Prefix.POSITION, "position "); + return; + } + + positions.entrySet().stream() + .sorted(Comparator.>comparingDouble(entry -> entry.getValue().distance(player.getLocation())).reversed()) + .forEach(entry -> { + Location location = entry.getValue(); + Message.forName("position").send(player, Prefix.POSITION, location.getBlockX(), location.getBlockY(), location.getBlockZ(), getWorldName(location), entry.getKey(), (int) location.distance(player.getLocation())); + }); + } else if (args.length == 1) { + String name = args[0].toLowerCase(); + Location position = positions.get(name); + if (position != null) { + positions.remove(name); + Message.forName("position-deleted").broadcast(Prefix.POSITION, + position.getBlockX(), position.getBlockY(), position.getBlockZ(), + getWorldName(position), name, NameHelper.getName(player)); + } else { + Message.forName("position-not-exists").send(player, Prefix.POSITION); + } + + } else { + Message.forName("syntax").send(player, Prefix.POSITION, "delposition "); + } + + } + + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { + if (args.length > 1) return new ArrayList<>(); + return Utils.filterRecommendations(args[0], positions.keySet().toArray(new String[0])); + } + + } + + public class SetPosCommand implements PlayerCommand, TabCompleter { + + @Override + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { + if (!isEnabled()) { + Message.forName("positions-disabled").send(player, Prefix.POSITION); + SoundSample.BASS_OFF.play(player); + return; + } + if (!ChallengeAPI.isStarted()) { + Message.forName("timer-not-started").send(player, Prefix.POSITION); + SoundSample.BASS_OFF.play(player); + return; + } + + if (args.length < 5) { + Message.forName("syntax").send(player, Prefix.POSITION, "setposition "); + return; + } + + String name = args[0].toLowerCase(); + + if (positions.containsKey(name)) { + Message.forName("position-already-exists").send(player, Prefix.POSITION, name); + return; + } + + String worldName = args[1]; + String x = args[2]; + String y = args[3]; + String z = args[4]; + + try { + Environment environment = getWorldEnvironment(worldName); + World world = ChallengeAPI.getGameWorld(environment); + if (world == null) throw new IllegalArgumentException(); + double doubleX = Double.parseDouble(x); + double doubleY = Double.parseDouble(y); + double doubleZ = Double.parseDouble(z); + + Location position = new Location(world, doubleX, doubleY, doubleZ); + positions.put(name, position); + Message.forName("position-set") + .broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), + position.getBlockZ(), getWorldName(position), name, NameHelper.getName(player)); + SoundSample.BASS_ON.play(player); + broadcastParticleLine(position); + + } catch (Exception exception) { + Message.forName("syntax").send(player, Prefix.POSITION, "setposition "); + } + + } + + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { + if (!(sender instanceof Player)) return new LinkedList<>(); + Player player = (Player) sender; + if (args.length > 5) return new LinkedList<>(); + + if (args.length > 2) { + int arg = args.length - 2; + + double cord; + Location location = player.getLocation(); + switch (arg) { + case 1: + cord = location.getBlockX() + 0.5; + break; + case 2: + cord = location.getBlockY(); + break; + default: + cord = location.getBlockZ() + 0.5; + } + + return Collections.singletonList(String.valueOf(cord)); + + } else if (args.length > 1) { + return Arrays.asList("Overworld", "Nether", "End"); + } + + return new LinkedList<>(); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java index 2c6a9e9db..16f50d30a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java @@ -16,42 +16,42 @@ public class PregameMovementSetting extends Setting { - public PregameMovementSetting() { - super(MenuType.SETTINGS, true); - } - - @EventHandler - public void onMove(@Nonnull PlayerMoveEvent event) { - if (ChallengeAPI.isStarted() || isEnabled()) return; - if (event.getPlayer().getGameMode() == GameMode.SPECTATOR || event.getPlayer().getGameMode() == GameMode.CREATIVE) - return; - - Location to = event.getTo(); - if (to == null) return; - if (BlockUtils.isSameLocationIgnoreHeight(event.getFrom(), to)) return; - - Location target = event.getFrom().clone(); - target.setY(target.getBlockY()); - findNearestBlock(target); - target.add(0, 1, 0); - - target.setPitch(to.getPitch()); - target.setYaw(to.getYaw()); - target.setDirection(to.getDirection()); - event.setTo(target); - - Message.forName("title-pregame-movement-setting").sendTitleInstant(event.getPlayer()); - } - - private void findNearestBlock(@Nonnull Location location) { - for (; location.getBlockY() > 0 && location.getBlock().isPassable(); location.subtract(0, 1, 0)) - ; - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PISTON, Message.forName("pregame-movement-setting")); - } + public PregameMovementSetting() { + super(MenuType.SETTINGS, true); + } + + @EventHandler + public void onMove(@Nonnull PlayerMoveEvent event) { + if (ChallengeAPI.isStarted() || isEnabled()) return; + if (event.getPlayer().getGameMode() == GameMode.SPECTATOR || event.getPlayer().getGameMode() == GameMode.CREATIVE) + return; + + Location to = event.getTo(); + if (to == null) return; + if (BlockUtils.isSameLocationIgnoreHeight(event.getFrom(), to)) return; + + Location target = event.getFrom().clone(); + target.setY(target.getBlockY()); + findNearestBlock(target); + target.add(0, 1, 0); + + target.setPitch(to.getPitch()); + target.setYaw(to.getYaw()); + target.setDirection(to.getDirection()); + event.setTo(target); + + Message.forName("title-pregame-movement-setting").sendTitleInstant(event.getPlayer()); + } + + private void findNearestBlock(@Nonnull Location location) { + for (; location.getBlockY() > 0 && location.getBlock().isPassable(); location.subtract(0, 1, 0)) + ; + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.PISTON, Message.forName("pregame-movement-setting")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java index 2a6180473..5e301e89f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java @@ -13,21 +13,21 @@ public class PvPSetting extends Setting { - public PvPSetting() { - super(MenuType.SETTINGS, true); - } + public PvPSetting() { + super(MenuType.SETTINGS, true); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-pvp-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-pvp-setting")); + } - @EventHandler - public void onDamage(@Nonnull EntityDamageByPlayerEvent event) { - if (isEnabled()) return; - if (!(event.getEntity() instanceof Player)) return; - event.setCancelled(true); - } + @EventHandler + public void onDamage(@Nonnull EntityDamageByPlayerEvent event) { + if (isEnabled()) return; + if (!(event.getEntity() instanceof Player)) return; + event.setCancelled(true); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java index 7402eb235..c4a3b67b0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java @@ -19,53 +19,53 @@ public class RegenerationSetting extends Modifier { - public RegenerationSetting() { - super(MenuType.SETTINGS, 1, 3, 2); - } + public RegenerationSetting() { + super(MenuType.SETTINGS, 1, 3, 2); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new PotionBuilder(Material.POTION, Message.forName("item-regeneration-setting")).color(Color.RED); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new PotionBuilder(Material.POTION, Message.forName("item-regeneration-setting")).color(Color.RED); + } - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (getValue() == 1) { - return DefaultItem.disabled(); - } else if (getValue() == 2) { - return DefaultItem.enabled(); - } - return DefaultItem.create(Material.ORANGE_DYE, Message.forName("item-regeneration-setting-not_natural")); - } + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (getValue() == 1) { + return DefaultItem.disabled(); + } else if (getValue() == 2) { + return DefaultItem.enabled(); + } + return DefaultItem.create(Material.ORANGE_DYE, Message.forName("item-regeneration-setting-not_natural")); + } - @Override - public void playValueChangeTitle() { - if (getValue() == 1) { - ChallengeHelper.playToggleChallengeTitle(this, false); - return; - } - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 2 ? Message.forName("enabled") : Message.forName("item-regeneration-setting-not_natural")); - } + @Override + public void playValueChangeTitle() { + if (getValue() == 1) { + ChallengeHelper.playToggleChallengeTitle(this, false); + return; + } + ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 2 ? Message.forName("enabled") : Message.forName("item-regeneration-setting-not_natural")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityRegainHealth(EntityRegainHealthEvent event) { - if (!(event.getEntity() instanceof Player)) return; + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityRegainHealth(EntityRegainHealthEvent event) { + if (!(event.getEntity() instanceof Player)) return; - if (getValue() == 1) { - event.setAmount(0); - event.setCancelled(true); - return; - } + if (getValue() == 1) { + event.setAmount(0); + event.setCancelled(true); + return; + } - if (getValue() == 3) { - if (event.getRegainReason() == RegainReason.SATIATED || event.getRegainReason() == RegainReason.REGEN) { - event.setAmount(0); - event.setCancelled(true); - } - } + if (getValue() == 3) { + if (event.getRegainReason() == RegainReason.SATIATED || event.getRegainReason() == RegainReason.REGEN) { + event.setAmount(0); + event.setCancelled(true); + } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java index b2c320340..635874ed7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import javax.annotation.Nonnull; import net.anweisen.utilities.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; @@ -22,54 +19,58 @@ import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerRespawnEvent; +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + public class RespawnSetting extends Setting { - private final Map locationsBeforeRespawn = new ConcurrentHashMap<>(); + private final Map locationsBeforeRespawn = new ConcurrentHashMap<>(); - public RespawnSetting() { - super(MenuType.SETTINGS); - } + public RespawnSetting() { + super(MenuType.SETTINGS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.RED_BED, Message.forName("item-respawn-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.RED_BED, Message.forName("item-respawn-setting")); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { - Player player = event.getEntity(); - if (isEnabled()) { - SoundSample.DEATH.play(player); - } else { - locationsBeforeRespawn.put(player, player.getLocation()); - player.setGameMode(GameMode.SPECTATOR); + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { + Player player = event.getEntity(); + if (isEnabled()) { + SoundSample.DEATH.play(player); + } else { + locationsBeforeRespawn.put(player, player.getLocation()); + player.setGameMode(GameMode.SPECTATOR); - if (ChallengeAPI.isStarted()) - checkAllPlayersDead(); - } + if (ChallengeAPI.isStarted()) + checkAllPlayersDead(); + } - ParticleUtils.spawnUpGoingParticleCircle(Challenges.getInstance(), player.getLocation(), - MinecraftNameWrapper.WITCH_EFFECT, 17, 1, 2); - } + ParticleUtils.spawnUpGoingParticleCircle(Challenges.getInstance(), player.getLocation(), + MinecraftNameWrapper.WITCH_EFFECT, 17, 1, 2); + } - public void checkAllPlayersDead() { - int playersAlive = ChallengeAPI.getIngamePlayers().size(); - if (playersAlive == 0) { - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_FAILED); - } - } + public void checkAllPlayersDead() { + int playersAlive = ChallengeAPI.getIngamePlayers().size(); + if (playersAlive == 0) { + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_FAILED); + } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onRespawn(@Nonnull PlayerRespawnEvent event) { - if (isEnabled()) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onRespawn(@Nonnull PlayerRespawnEvent event) { + if (isEnabled()) return; - Player player = event.getPlayer(); - Location locationBeforeRespawn = locationsBeforeRespawn.remove(player); - if (locationBeforeRespawn == null) return; - if (locationBeforeRespawn.getY() < 0) - return; // If the player dies in the void (y <= 0), we dont want him to spawn there, he would die again - event.setRespawnLocation(locationBeforeRespawn); - } + Player player = event.getPlayer(); + Location locationBeforeRespawn = locationsBeforeRespawn.remove(player); + if (locationBeforeRespawn == null) return; + if (locationBeforeRespawn.getY() < 0) + return; // If the player dies in the void (y <= 0), we dont want him to spawn there, he would die again + event.setRespawnLocation(locationBeforeRespawn); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java index 9d60a6687..3627347ee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java @@ -28,135 +28,135 @@ @Since("2.0") public class SlotLimitSetting extends Modifier { - public SlotLimitSetting() { - super(MenuType.SETTINGS, 1, 36, 36); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BARRIER, Message.forName("item-slot-limit-setting")); - } - - @Override - protected void onValueChange() { - update(); - } - - @TimerTask(status = { TimerStatus.RUNNING }) - public void updateDelayed() { - Bukkit.getScheduler().runTaskLater(plugin, this::update, 1); - } - - @TimerTask(status = { TimerStatus.PAUSED }, async = false) - public void update() { - Bukkit.getOnlinePlayers().forEach(this::updateSlots); - } - - private void updateSlots(@Nonnull Player player) { - for (int i = 0; i < 36; i++) { - if (ignorePlayer(player)) { - unBlockSlot(player, i); - continue; - } - if (isBlocked(i) && ChallengeAPI.isStarted()) { - blockSlot(player, i); - } else { - unBlockSlot(player, i); - } - } - } - - private boolean isBlocked(int slot) { - if (slot > 35) return false; - - int value = getValue() - 1; - - if (slot >= 9 && slot <= 17) { - slot += 9 * 2; - } else if (slot >= 27) { - slot -= 9 * 2; - } - - return slot > value; - } - - private void blockSlot(@Nonnull Player player, int slot) { - if (ignorePlayer(player)) return; - - ItemStack item = player.getInventory().getItem(slot); - if (item != null && !item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { - if (!Bukkit.isPrimaryThread()) { - Bukkit.getScheduler().runTask(plugin, () -> { - player.getWorld().dropItemNaturally(player.getLocation(), item); - }); - } else { - player.getWorld().dropItemNaturally(player.getLocation(), item); - } - } - player.getInventory().setItem(slot, ItemBuilder.BLOCKED_ITEM); - } - - private void unBlockSlot(@Nonnull Player player, int slot) { - ItemStack item = player.getInventory().getItem(slot); - if (item != null && item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { - player.getInventory().setItem(slot, null); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getType() != InventoryType.PLAYER) return; - if (isBlocked(event.getSlot())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (!event.getItemDrop().getItemStack().isSimilar(ItemBuilder.BLOCKED_ITEM)) return; - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onClick(@Nonnull BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (!event.getItemInHand().isSimilar(ItemBuilder.BLOCKED_ITEM)) return; - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSwapItem(@Nonnull PlayerSwapHandItemsEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - - if (event.getMainHandItem() != null && event.getMainHandItem().isSimilar(ItemBuilder.BLOCKED_ITEM)) { - event.setCancelled(true); - } else if (event.getOffHandItem() != null && event.getOffHandItem().isSimilar(ItemBuilder.BLOCKED_ITEM)) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { - event.getDrops().removeIf(itemStack -> itemStack.isSimilar(ItemBuilder.BLOCKED_ITEM)); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onRespawn(PlayerRespawnEvent event) { - updateSlots(event.getPlayer()); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerIgnoreStatusChange(PlayerIgnoreStatusChangeEvent event) { - Bukkit.getScheduler().runTask(plugin, () -> { - updateSlots(event.getPlayer()); - }); - } + public SlotLimitSetting() { + super(MenuType.SETTINGS, 1, 36, 36); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.BARRIER, Message.forName("item-slot-limit-setting")); + } + + @Override + protected void onValueChange() { + update(); + } + + @TimerTask(status = {TimerStatus.RUNNING}) + public void updateDelayed() { + Bukkit.getScheduler().runTaskLater(plugin, this::update, 1); + } + + @TimerTask(status = {TimerStatus.PAUSED}, async = false) + public void update() { + Bukkit.getOnlinePlayers().forEach(this::updateSlots); + } + + private void updateSlots(@Nonnull Player player) { + for (int i = 0; i < 36; i++) { + if (ignorePlayer(player)) { + unBlockSlot(player, i); + continue; + } + if (isBlocked(i) && ChallengeAPI.isStarted()) { + blockSlot(player, i); + } else { + unBlockSlot(player, i); + } + } + } + + private boolean isBlocked(int slot) { + if (slot > 35) return false; + + int value = getValue() - 1; + + if (slot >= 9 && slot <= 17) { + slot += 9 * 2; + } else if (slot >= 27) { + slot -= 9 * 2; + } + + return slot > value; + } + + private void blockSlot(@Nonnull Player player, int slot) { + if (ignorePlayer(player)) return; + + ItemStack item = player.getInventory().getItem(slot); + if (item != null && !item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { + if (!Bukkit.isPrimaryThread()) { + Bukkit.getScheduler().runTask(plugin, () -> { + player.getWorld().dropItemNaturally(player.getLocation(), item); + }); + } else { + player.getWorld().dropItemNaturally(player.getLocation(), item); + } + } + player.getInventory().setItem(slot, ItemBuilder.BLOCKED_ITEM); + } + + private void unBlockSlot(@Nonnull Player player, int slot) { + ItemStack item = player.getInventory().getItem(slot); + if (item != null && item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { + player.getInventory().setItem(slot, null); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getType() != InventoryType.PLAYER) return; + if (isBlocked(event.getSlot())) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (!event.getItemDrop().getItemStack().isSimilar(ItemBuilder.BLOCKED_ITEM)) return; + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onClick(@Nonnull BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (!event.getItemInHand().isSimilar(ItemBuilder.BLOCKED_ITEM)) return; + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onSwapItem(@Nonnull PlayerSwapHandItemsEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + + if (event.getMainHandItem() != null && event.getMainHandItem().isSimilar(ItemBuilder.BLOCKED_ITEM)) { + event.setCancelled(true); + } else if (event.getOffHandItem() != null && event.getOffHandItem().isSimilar(ItemBuilder.BLOCKED_ITEM)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { + event.getDrops().removeIf(itemStack -> itemStack.isSimilar(ItemBuilder.BLOCKED_ITEM)); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onRespawn(PlayerRespawnEvent event) { + updateSlots(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerIgnoreStatusChange(PlayerIgnoreStatusChangeEvent event) { + Bukkit.getScheduler().runTask(plugin, () -> { + updateSlots(event.getPlayer()); + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java index 0ecda9701..60e150200 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import javax.annotation.Nonnull; import net.anweisen.utilities.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -15,35 +14,37 @@ import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.potion.PotionEffect; +import javax.annotation.Nonnull; + public class SoupSetting extends Setting { - public SoupSetting() { - super(MenuType.SETTINGS); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MUSHROOM_STEW, Message.forName("item-soup-setting")); - } - - @EventHandler - public void onInteract(PlayerInteractEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) - return; - if (event.getItem() == null) return; - if (event.getItem().getType() != Material.MUSHROOM_STEW) return; - - Player player = event.getPlayer(); - if (player.getGameMode() == GameMode.CREATIVE) return; - if (player.getHealth() == player.getMaxHealth()) return; - - player.addPotionEffect(new PotionEffect(MinecraftNameWrapper.INSTANT_HEALTH, 1, 1)); - player.getInventory().setItemInMainHand(new ItemBuilder(Material.BOWL).build()); - player.updateInventory(); - SoundSample.EAT.play(player); - - } + public SoupSetting() { + super(MenuType.SETTINGS); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.MUSHROOM_STEW, Message.forName("item-soup-setting")); + } + + @EventHandler + public void onInteract(PlayerInteractEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) + return; + if (event.getItem() == null) return; + if (event.getItem().getType() != Material.MUSHROOM_STEW) return; + + Player player = event.getPlayer(); + if (player.getGameMode() == GameMode.CREATIVE) return; + if (player.getHealth() == player.getMaxHealth()) return; + + player.addPotionEffect(new PotionEffect(MinecraftNameWrapper.INSTANT_HEALTH, 1, 1)); + player.getInventory().setItemInMainHand(new ItemBuilder(Material.BOWL).build()); + player.updateInventory(); + SoundSample.EAT.play(player); + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index 9f9c4669e..4333b5525 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -23,84 +23,84 @@ public class SplitHealthSetting extends Setting { - public SplitHealthSetting() { - super(MenuType.SETTINGS); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new PotionBuilder(Material.TIPPED_ARROW, Message.forName("item-split-health-setting")).color(Color.RED); - } - - @Override - protected void onEnable() { - setHealth(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityRegainHealth(@Nonnull EntityRegainHealthEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - - Bukkit.getScheduler().runTaskLater(plugin, () -> setHealth(player, null), 1); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDamage(EntityDamageEvent event) { - if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (ignorePlayer(player)) return; - - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> setHealth(player, event), 1); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onJoin(@Nonnull PlayerJoinEvent event) { - if (ignorePlayer(event.getPlayer())) return; - setHealth(); - } - - /** - * Calls {@link SplitHealthSetting#setHealth(Player, EntityDamageEvent)} for the player with the lowest health - */ - private void setHealth() { - Player player = null; - - for (Player currentPlayer : Bukkit.getOnlinePlayers()) { - if (player == null || player.getHealth() > currentPlayer.getHealth()) { - player = currentPlayer; - } - - } - if (player == null) return; - setHealth(player, null); - } - - public void setHealth(@Nonnull Player player, @Nullable EntityDamageEvent damageEvent) { - if (!shouldExecuteEffect()) return; - - for (Player currentPlayer : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(currentPlayer)) continue; - if (currentPlayer.equals(player)) continue; - - double health = player.getHealth(); - AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); - if (attribute == null) return; - if (health > attribute.getValue()) { - health = attribute.getValue(); - } - - if (health <= 0 && damageEvent != null) { - currentPlayer.setLastDamageCause(damageEvent); - } - - currentPlayer.setHealth(health); - } - - } + public SplitHealthSetting() { + super(MenuType.SETTINGS); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new PotionBuilder(Material.TIPPED_ARROW, Message.forName("item-split-health-setting")).color(Color.RED); + } + + @Override + protected void onEnable() { + setHealth(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityRegainHealth(@Nonnull EntityRegainHealthEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + + Bukkit.getScheduler().runTaskLater(plugin, () -> setHealth(player, null), 1); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDamage(EntityDamageEvent event) { + if (!shouldExecuteEffect()) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (ignorePlayer(player)) return; + + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> setHealth(player, event), 1); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJoin(@Nonnull PlayerJoinEvent event) { + if (ignorePlayer(event.getPlayer())) return; + setHealth(); + } + + /** + * Calls {@link SplitHealthSetting#setHealth(Player, EntityDamageEvent)} for the player with the lowest health + */ + private void setHealth() { + Player player = null; + + for (Player currentPlayer : Bukkit.getOnlinePlayers()) { + if (player == null || player.getHealth() > currentPlayer.getHealth()) { + player = currentPlayer; + } + + } + if (player == null) return; + setHealth(player, null); + } + + public void setHealth(@Nonnull Player player, @Nullable EntityDamageEvent damageEvent) { + if (!shouldExecuteEffect()) return; + + for (Player currentPlayer : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(currentPlayer)) continue; + if (currentPlayer.equals(player)) continue; + + double health = player.getHealth(); + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) return; + if (health > attribute.getValue()) { + health = attribute.getValue(); + } + + if (health <= 0 && damageEvent != null) { + currentPlayer.setLastDamageCause(damageEvent); + } + + currentPlayer.setHealth(health); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java index 0d2235a39..36e89c03c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java @@ -25,121 +25,121 @@ public class TimberSetting extends SettingModifier { - public static final int LOGS_LEAVES = 2; - - - public TimberSetting() { - super(MenuType.SETTINGS, 2); - } - - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_AXE, Message.forName("item-timber-setting")); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - if (getValue() == LOGS_LEAVES) - return DefaultItem.create(Material.OAK_LEAVES, Message.forName("item-timber-setting-logs-and-leaves")); - return DefaultItem.create(Material.OAK_LOG, Message.forName("item-timber-setting-logs")); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == LOGS_LEAVES ? Message.forName("item-timber-setting-logs-and-leaves") : Message.forName("item-timber-setting-logs")); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBreak(@Nonnull BlockBreakEvent event) { - if (!shouldExecuteEffect()) return; - if (!isLog(event.getBlock().getType())) return; - - List treeBlocks = getAllTreeBlocks(event.getBlock(), getValue() == LOGS_LEAVES); - ItemStack item = event.getPlayer().getInventory().getItemInMainHand(); - - final int[] index = {0}; - - boolean damageItem = !Objects.requireNonNull(item.getItemMeta()).isUnbreakable() && !AbstractChallenge.getFirstInstance(NoItemDamageSetting.class).isEnabled(); - - Bukkit.getScheduler().runTaskTimer(plugin, timer -> { - for (int i = 0; i < 2 && !treeBlocks.isEmpty(); i++) { - Block block = treeBlocks.get(index[0]); - breakBlock(block, item, damageItem); - - index[0]++; - if (index[0] >= treeBlocks.size()) { - timer.cancel(); - return; - } - } - }, 0, 1); - - } - - private void breakBlock(@Nonnull Block block, @Nonnull ItemStack item, boolean damageItem) { - if (isLog(block.getType())) { - ChallengeHelper.breakBlock(block, item); - if (damageItem) { - ItemUtils.damageItem(item); - } - } else if (isLeaves(block.getType())) { - ChallengeHelper.breakBlock(block, item); - } - } - - private List getAllTreeBlocks(@Nonnull Block block, boolean leaves) { - List allBlocks = new ArrayList<>(); - - List currentBlocks = new ArrayList<>(); - currentBlocks.add(block); - - for (int i = 0; i < 8; i++) { - - ArrayList lastBlocks = new ArrayList<>(currentBlocks); - currentBlocks.clear(); - - for (Block currentBlock : lastBlocks) { - for (Block blockAround : BlockUtils.getBlocksAroundBlock(currentBlock)) { - if (BukkitReflectionUtils.isAir(blockAround.getType())) continue; - if (allBlocks.contains(blockAround)) continue; - - if (currentBlock.getType() == blockAround.getType() || (leaves && isLeaveMaterial(currentBlock.getType(), blockAround.getType()))) { - allBlocks.add(blockAround); - currentBlocks.add(blockAround); - } - } - } - - if (currentBlocks.isEmpty()) - break; - - } - - return allBlocks; - } - - private boolean isLog(Material material) { - String name = material.name(); - return name.contains("LOG") || name.contains("STEM"); - } - - private boolean isLeaves(Material material) { - return material.name().endsWith("LEAVES") || material.name().endsWith("WART_BLOCK"); - } - - public boolean isLeaveMaterial(@Nonnull Material logMaterial, @Nonnull Material leaveMaterial) { - // Exceptions like nether wood - if (logMaterial.name().equals("CRIMSON_STEM")) - return leaveMaterial.name().equals("NETHER_WART_BLOCK") || leaveMaterial.name().equals("SHROOMLIGHT"); - if (logMaterial.name().equals("WARPED_STEM")) - return leaveMaterial.name().equals("WARPED_WART_BLOCK") || leaveMaterial.name().equals("SHROOMLIGHT"); - - int firstUnderscore = logMaterial.name().indexOf("_"); - if (firstUnderscore == -1) return false; - String logPrefix = logMaterial.name().substring(0, firstUnderscore); - return leaveMaterial.name().startsWith(logPrefix) && leaveMaterial.name().endsWith("LEAVES"); - } + public static final int LOGS_LEAVES = 2; + + + public TimberSetting() { + super(MenuType.SETTINGS, 2); + } + + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.DIAMOND_AXE, Message.forName("item-timber-setting")); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + if (getValue() == LOGS_LEAVES) + return DefaultItem.create(Material.OAK_LEAVES, Message.forName("item-timber-setting-logs-and-leaves")); + return DefaultItem.create(Material.OAK_LOG, Message.forName("item-timber-setting-logs")); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == LOGS_LEAVES ? Message.forName("item-timber-setting-logs-and-leaves") : Message.forName("item-timber-setting-logs")); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBreak(@Nonnull BlockBreakEvent event) { + if (!shouldExecuteEffect()) return; + if (!isLog(event.getBlock().getType())) return; + + List treeBlocks = getAllTreeBlocks(event.getBlock(), getValue() == LOGS_LEAVES); + ItemStack item = event.getPlayer().getInventory().getItemInMainHand(); + + final int[] index = {0}; + + boolean damageItem = !Objects.requireNonNull(item.getItemMeta()).isUnbreakable() && !AbstractChallenge.getFirstInstance(NoItemDamageSetting.class).isEnabled(); + + Bukkit.getScheduler().runTaskTimer(plugin, timer -> { + for (int i = 0; i < 2 && !treeBlocks.isEmpty(); i++) { + Block block = treeBlocks.get(index[0]); + breakBlock(block, item, damageItem); + + index[0]++; + if (index[0] >= treeBlocks.size()) { + timer.cancel(); + return; + } + } + }, 0, 1); + + } + + private void breakBlock(@Nonnull Block block, @Nonnull ItemStack item, boolean damageItem) { + if (isLog(block.getType())) { + ChallengeHelper.breakBlock(block, item); + if (damageItem) { + ItemUtils.damageItem(item); + } + } else if (isLeaves(block.getType())) { + ChallengeHelper.breakBlock(block, item); + } + } + + private List getAllTreeBlocks(@Nonnull Block block, boolean leaves) { + List allBlocks = new ArrayList<>(); + + List currentBlocks = new ArrayList<>(); + currentBlocks.add(block); + + for (int i = 0; i < 8; i++) { + + ArrayList lastBlocks = new ArrayList<>(currentBlocks); + currentBlocks.clear(); + + for (Block currentBlock : lastBlocks) { + for (Block blockAround : BlockUtils.getBlocksAroundBlock(currentBlock)) { + if (BukkitReflectionUtils.isAir(blockAround.getType())) continue; + if (allBlocks.contains(blockAround)) continue; + + if (currentBlock.getType() == blockAround.getType() || (leaves && isLeaveMaterial(currentBlock.getType(), blockAround.getType()))) { + allBlocks.add(blockAround); + currentBlocks.add(blockAround); + } + } + } + + if (currentBlocks.isEmpty()) + break; + + } + + return allBlocks; + } + + private boolean isLog(Material material) { + String name = material.name(); + return name.contains("LOG") || name.contains("STEM"); + } + + private boolean isLeaves(Material material) { + return material.name().endsWith("LEAVES") || material.name().endsWith("WART_BLOCK"); + } + + public boolean isLeaveMaterial(@Nonnull Material logMaterial, @Nonnull Material leaveMaterial) { + // Exceptions like nether wood + if (logMaterial.name().equals("CRIMSON_STEM")) + return leaveMaterial.name().equals("NETHER_WART_BLOCK") || leaveMaterial.name().equals("SHROOMLIGHT"); + if (logMaterial.name().equals("WARPED_STEM")) + return leaveMaterial.name().equals("WARPED_WART_BLOCK") || leaveMaterial.name().equals("SHROOMLIGHT"); + + int firstUnderscore = logMaterial.name().indexOf("_"); + if (firstUnderscore == -1) return false; + String logPrefix = logMaterial.name().substring(0, firstUnderscore); + return leaveMaterial.name().startsWith(logPrefix) && leaveMaterial.name().endsWith("LEAVES"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java index 9483e70a1..0d5e1a187 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java @@ -18,58 +18,58 @@ public class TopCommandSetting extends Setting implements PlayerCommand { - public TopCommandSetting() { - super(MenuType.SETTINGS); - } + public TopCommandSetting() { + super(MenuType.SETTINGS); + } - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) { - if (!isEnabled()) { - Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); - SoundSample.BASS_OFF.play(player); - return; - } + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) { + if (!isEnabled()) { + Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); + SoundSample.BASS_OFF.play(player); + return; + } - World world = player.getWorld(); - Environment environment = world.getEnvironment(); - Location playerLocation = player.getLocation(); - if (environment == Environment.NORMAL) { - Message.forName("top-to-surface").send(player, Prefix.CHALLENGES); + World world = player.getWorld(); + Environment environment = world.getEnvironment(); + Location playerLocation = player.getLocation(); + if (environment == Environment.NORMAL) { + Message.forName("top-to-surface").send(player, Prefix.CHALLENGES); - Location location = player.getWorld().getHighestBlockAt(playerLocation).getLocation().add(0.5, 1, 0.5); - location.setYaw(playerLocation.getYaw()); - location.setPitch(playerLocation.getPitch()); - player.setFallDistance(0); - player.teleport(location); + Location location = player.getWorld().getHighestBlockAt(playerLocation).getLocation().add(0.5, 1, 0.5); + location.setYaw(playerLocation.getYaw()); + location.setPitch(playerLocation.getPitch()); + player.setFallDistance(0); + player.teleport(location); - } else { - Message.forName("top-to-overworld").send(player, Prefix.CHALLENGES); + } else { + Message.forName("top-to-overworld").send(player, Prefix.CHALLENGES); - if (environment == Environment.NETHER) { - Location location = playerLocation.clone(); - world = ChallengeAPI.getGameWorld(Environment.NORMAL); - location.setWorld(world); - location.multiply(8); - location = world.getHighestBlockAt(location).getLocation().add(0.5, 1, 0.5); - player.setFallDistance(0); - player.teleport(location); - } else { - world = ChallengeAPI.getGameWorld(Environment.NORMAL); - Location location = player.getBedSpawnLocation(); - if (location == null) location = world.getSpawnLocation(); - player.setFallDistance(0); - player.teleport(location); - } + if (environment == Environment.NETHER) { + Location location = playerLocation.clone(); + world = ChallengeAPI.getGameWorld(Environment.NORMAL); + location.setWorld(world); + location.multiply(8); + location = world.getHighestBlockAt(location).getLocation().add(0.5, 1, 0.5); + player.setFallDistance(0); + player.teleport(location); + } else { + world = ChallengeAPI.getGameWorld(Environment.NORMAL); + Location location = player.getBedSpawnLocation(); + if (location == null) location = world.getSpawnLocation(); + player.setFallDistance(0); + player.teleport(location); + } - } - SoundSample.TELEPORT.play(player); + } + SoundSample.TELEPORT.play(player); - } + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MAGENTA_GLAZED_TERRACOTTA, Message.forName("top-command-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.MAGENTA_GLAZED_TERRACOTTA, Message.forName("top-command-setting")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java index f441a1429..2199b8451 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java @@ -16,21 +16,21 @@ @Since("2.0") public class TotemSaveDeathSetting extends Setting { - public TotemSaveDeathSetting() { - super(MenuType.SETTINGS); - } + public TotemSaveDeathSetting() { + super(MenuType.SETTINGS); + } - @Nonnull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.TOTEM_OF_UNDYING, Message.forName("item-totem-save-setting")); - } + @Nonnull + @Override + public ItemBuilder createDisplayItem() { + return new ItemBuilder(Material.TOTEM_OF_UNDYING, Message.forName("item-totem-save-setting")); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityResurrect(@Nonnull EntityResurrectEvent event) { - if (ChallengeHelper.isInInstantKill() && !isEnabled()) { - event.setCancelled(true); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityResurrect(@Nonnull EntityResurrectEvent event) { + if (ChallengeHelper.isInInstantKill() && !isEnabled()) { + event.setCancelled(true); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java index a2ae004e7..b96458fd0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java @@ -15,86 +15,86 @@ public class EmptyChallenge implements IChallenge { - private final MenuType menuType; + private final MenuType menuType; - public EmptyChallenge(@Nonnull MenuType menuType) { - this.menuType = menuType; - } + public EmptyChallenge(@Nonnull MenuType menuType) { + this.menuType = menuType; + } - @Override - public boolean isEnabled() { - return false; - } + @Override + public boolean isEnabled() { + return false; + } - @Override - public void restoreDefaults() { + @Override + public void restoreDefaults() { - } + } - @Override - public void handleShutdown() { + @Override + public void handleShutdown() { - } + } - @NotNull - @Override - public String getUniqueGamestateName() { - return getUniqueName(); - } + @NotNull + @Override + public String getUniqueGamestateName() { + return getUniqueName(); + } - @NotNull - @Override - public String getUniqueName() { - return "empty"; - } + @NotNull + @Override + public String getUniqueName() { + return "empty"; + } - @NotNull - @Override - public MenuType getType() { - return menuType; - } + @NotNull + @Override + public MenuType getType() { + return menuType; + } - @Nullable - @Override - public SettingCategory getCategory() { - return null; - } + @Nullable + @Override + public SettingCategory getCategory() { + return null; + } - @NotNull - @Override - public ItemStack getDisplayItem() { - return new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, "§0").build(); - } + @NotNull + @Override + public ItemStack getDisplayItem() { + return new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, "§0").build(); + } - @NotNull - @Override - public ItemStack getSettingsItem() { - return new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, "§0").build(); - } + @NotNull + @Override + public ItemStack getSettingsItem() { + return new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, "§0").build(); + } - @Override - public void handleClick(@NotNull ChallengeMenuClickInfo info) { - SoundSample.CLICK.play(info.getPlayer()); - } + @Override + public void handleClick(@NotNull ChallengeMenuClickInfo info) { + SoundSample.CLICK.play(info.getPlayer()); + } - @Override - public void writeSettings(@NotNull Document document) { + @Override + public void writeSettings(@NotNull Document document) { - } + } - @Override - public void loadSettings(@NotNull Document document) { + @Override + public void loadSettings(@NotNull Document document) { - } + } - @Override - public void writeGameState(@NotNull Document document) { + @Override + public void writeGameState(@NotNull Document document) { - } + } - @Override - public void loadGameState(@NotNull Document document) { + @Override + public void loadGameState(@NotNull Document document) { - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java index 7679a2c08..708f9e99e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java @@ -13,66 +13,66 @@ public interface IChallenge extends GamestateSaveable { - /** - * Returns if this challenge is enabled. - * This value is used in checks and policies like {@link net.codingarea.challenges.plugin.management.scheduler.policy.ChallengeStatusPolicy} which are used for tasks. - * If this challenge does not have clear boolean value, you may always return {@code true} - * - * @return if this challenge is enabled - */ - boolean isEnabled(); + /** + * Returns if this challenge is enabled. + * This value is used in checks and policies like {@link net.codingarea.challenges.plugin.management.scheduler.policy.ChallengeStatusPolicy} which are used for tasks. + * If this challenge does not have clear boolean value, you may always return {@code true} + * + * @return if this challenge is enabled + */ + boolean isEnabled(); - /** - * Restores the default settings of this challenge. - * This will be executed when the /config reset command is executed. - * - * @see ChallengeManager#restoreDefaults() - */ - void restoreDefaults(); + /** + * Restores the default settings of this challenge. + * This will be executed when the /config reset command is executed. + * + * @see ChallengeManager#restoreDefaults() + */ + void restoreDefaults(); - /** - * This method will be executed when the challenges plugin is being disabled. - * This will occur when the server is shutdown or reloaded. - * This method is intended for removing temporarily content or calling disable logic. - * - * @see ChallengeManager#shutdownChallenges() - */ - void handleShutdown(); + /** + * This method will be executed when the challenges plugin is being disabled. + * This will occur when the server is shutdown or reloaded. + * This method is intended for removing temporarily content or calling disable logic. + * + * @see ChallengeManager#shutdownChallenges() + */ + void handleShutdown(); - /** - * Returns the internal name of this challenges. - * This name will be used for saving and assigning the right settings or gamestate. - * If multiple instances of class are registered, they must not return the same value. - * Multiple challenges should not have the same name. - * - * @return the internal name of this challenge - */ - @Nonnull - String getUniqueName(); + /** + * Returns the internal name of this challenges. + * This name will be used for saving and assigning the right settings or gamestate. + * If multiple instances of class are registered, they must not return the same value. + * Multiple challenges should not have the same name. + * + * @return the internal name of this challenge + */ + @Nonnull + String getUniqueName(); - /** - * This challenge will be displayed in the menu for the given {@link MenuType}. - * This has to always return the same value. - * If {@link MenuType#isUsable()} is {@code false}, an {@link IllegalArgumentException} will be thrown when registering this challenge. - * - * @return the target menu for the challenge - */ - @Nonnull - MenuType getType(); + /** + * This challenge will be displayed in the menu for the given {@link MenuType}. + * This has to always return the same value. + * If {@link MenuType#isUsable()} is {@code false}, an {@link IllegalArgumentException} will be thrown when registering this challenge. + * + * @return the target menu for the challenge + */ + @Nonnull + MenuType getType(); - @Nullable - SettingCategory getCategory(); + @Nullable + SettingCategory getCategory(); - @Nonnull - ItemStack getDisplayItem(); + @Nonnull + ItemStack getDisplayItem(); - @Nonnull - ItemStack getSettingsItem(); + @Nonnull + ItemStack getSettingsItem(); - void handleClick(@Nonnull ChallengeMenuClickInfo info); + void handleClick(@Nonnull ChallengeMenuClickInfo info); - void writeSettings(@Nonnull Document document); + void writeSettings(@Nonnull Document document); - void loadSettings(@Nonnull Document document); + void loadSettings(@Nonnull Document document); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java index 66d438d2d..c3943a7a4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java @@ -12,39 +12,39 @@ public interface IGoal extends IChallenge { - /** - * Enabled / disabled this goal. - * This must call {@link ChallengeManager#setCurrentGoal(IGoal)} with - * {@code this} if {@code enabled} is {@code true} or {@code null} if {@code enabled} is {@code false} and this goal is the current. - * This can be checked by comparing {@link ChallengeManager#getCurrentGoal()} to {@code this}. - * You may just call {@link GoalHelper#handleSetEnabled(IGoal, boolean)} with {@code this}, {@code enabled} - */ - void setEnabled(boolean enabled); - - /** - * This sound will be played when the timer is started and the plugin setting "enable-specific-start-sounds" is enabled. - * If not the standard sound will be played. - * - * @return the sound to play - */ - @Nonnull - SoundSample getStartSound(); - - /** - * This sound will be played when the challenge is won and the plugin setting "enabled-win-sounds" is enabled. - * If this returns {@code null} no sound will be played. - * - * @return the sound to play - */ - @Nullable - SoundSample getWinSound(); - - /** - * This method will be called, when the challenges are being ended with a winnable cause ({@link ChallengeEndCause#isWinnable()}) and when there is no player supplier given in order to determine the winner of this challenge run. - * If no players are added to the winners list, the {@link ChallengeEndCause#getNoWinnerMessage()} will be shown instead of the {@link ChallengeEndCause#getWinnerMessage()}. - * - * @param winners the list to which the winners should be added - */ - void getWinnersOnEnd(@Nonnull List winners); + /** + * Enabled / disabled this goal. + * This must call {@link ChallengeManager#setCurrentGoal(IGoal)} with + * {@code this} if {@code enabled} is {@code true} or {@code null} if {@code enabled} is {@code false} and this goal is the current. + * This can be checked by comparing {@link ChallengeManager#getCurrentGoal()} to {@code this}. + * You may just call {@link GoalHelper#handleSetEnabled(IGoal, boolean)} with {@code this}, {@code enabled} + */ + void setEnabled(boolean enabled); + + /** + * This sound will be played when the timer is started and the plugin setting "enable-specific-start-sounds" is enabled. + * If not the standard sound will be played. + * + * @return the sound to play + */ + @Nonnull + SoundSample getStartSound(); + + /** + * This sound will be played when the challenge is won and the plugin setting "enabled-win-sounds" is enabled. + * If this returns {@code null} no sound will be played. + * + * @return the sound to play + */ + @Nullable + SoundSample getWinSound(); + + /** + * This method will be called, when the challenges are being ended with a winnable cause ({@link ChallengeEndCause#isWinnable()}) and when there is no player supplier given in order to determine the winner of this challenge run. + * If no players are added to the winners list, the {@link ChallengeEndCause#getNoWinnerMessage()} will be shown instead of the {@link ChallengeEndCause#getWinnerMessage()}. + * + * @param winners the list to which the winners should be added + */ + void getWinnersOnEnd(@Nonnull List winners); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java index 928f4c13c..8f1a6be8b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java @@ -4,17 +4,17 @@ public interface IModifier { - @Nonnegative - int getValue(); + @Nonnegative + int getValue(); - void setValue(int value); + void setValue(int value); - @Nonnegative - int getMinValue(); + @Nonnegative + int getMinValue(); - @Nonnegative - int getMaxValue(); + @Nonnegative + int getMaxValue(); - void playValueChangeTitle(); + void playValueChangeTitle(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java index ca222f168..929fd8e19 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java @@ -30,188 +30,188 @@ public abstract class AbstractChallenge implements IChallenge, Listener { - protected static final Challenges plugin = Challenges.getInstance(); - protected static final IRandom globalRandom = IRandom.create(); + protected static final Challenges plugin = Challenges.getInstance(); + protected static final IRandom globalRandom = IRandom.create(); - private static final Map, AbstractChallenge> firstInstanceByClass = new HashMap<>(); - @Getter + private static final Map, AbstractChallenge> firstInstanceByClass = new HashMap<>(); + @Getter private static final boolean ignoreCreativePlayers, ignoreSpectatorPlayers; - static { - Document ignoreDocument = Challenges.getInstance().getConfigDocument().getDocument("ignore-players"); - ignoreCreativePlayers = ignoreDocument.getBoolean("creative"); - ignoreSpectatorPlayers = ignoreDocument.getBoolean("spectator"); - } + static { + Document ignoreDocument = Challenges.getInstance().getConfigDocument().getDocument("ignore-players"); + ignoreCreativePlayers = ignoreDocument.getBoolean("creative"); + ignoreSpectatorPlayers = ignoreDocument.getBoolean("spectator"); + } - protected final MenuType menu; - @Getter + protected final MenuType menu; + @Getter protected final ChallengeBossBar bossbar = new ChallengeBossBar(); - @Getter + @Getter protected final ChallengeScoreboard scoreboard = new ChallengeScoreboard(); - @Setter - protected SettingCategory category; - private String name; - private ItemStack cachedDisplayItem; - - public AbstractChallenge(@Nonnull MenuType menu) { - this.menu = menu; - firstInstanceByClass.put(this.getClass(), this); - } - - @Nonnull - public static C getFirstInstance(@Nonnull Class classOfChallenge) { - return classOfChallenge.cast(firstInstanceByClass.get(classOfChallenge)); - } - - public static void broadcast(@Nonnull Consumer action) { - Bukkit.getOnlinePlayers().forEach(action); - } - - public static void broadcastFiltered(@Nonnull Consumer action) { - for (Player player : Bukkit.getOnlinePlayers()) { - if (ignorePlayer(player)) continue; - action.accept(player); - } - } - - public static void broadcastIgnored(@Nonnull Consumer action) { - for (Player player : Bukkit.getOnlinePlayers()) { - if (!ignorePlayer(player)) continue; - action.accept(player); - } - } - - @CheckReturnValue - public static boolean ignorePlayer(@Nonnull Player player) { - return ignoreGameMode(player.getGameMode()); - } - - @CheckReturnValue - public static boolean ignoreGameMode(@Nonnull GameMode gameMode) { - return (isIgnoreSpectatorPlayers() && gameMode == GameMode.SPECTATOR) || (isIgnoreCreativePlayers() && gameMode == GameMode.CREATIVE); - } + @Setter + protected SettingCategory category; + private String name; + private ItemStack cachedDisplayItem; + + public AbstractChallenge(@Nonnull MenuType menu) { + this.menu = menu; + firstInstanceByClass.put(this.getClass(), this); + } + + @Nonnull + public static C getFirstInstance(@Nonnull Class classOfChallenge) { + return classOfChallenge.cast(firstInstanceByClass.get(classOfChallenge)); + } + + public static void broadcast(@Nonnull Consumer action) { + Bukkit.getOnlinePlayers().forEach(action); + } + + public static void broadcastFiltered(@Nonnull Consumer action) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (ignorePlayer(player)) continue; + action.accept(player); + } + } + + public static void broadcastIgnored(@Nonnull Consumer action) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (!ignorePlayer(player)) continue; + action.accept(player); + } + } + + @CheckReturnValue + public static boolean ignorePlayer(@Nonnull Player player) { + return ignoreGameMode(player.getGameMode()); + } + + @CheckReturnValue + public static boolean ignoreGameMode(@Nonnull GameMode gameMode) { + return (isIgnoreSpectatorPlayers() && gameMode == GameMode.SPECTATOR) || (isIgnoreCreativePlayers() && gameMode == GameMode.CREATIVE); + } + + @Nonnull + @Override + public final MenuType getType() { + return menu; + } + + @Override + public SettingCategory getCategory() { + return category; + } + + protected final void updateItems() { + ChallengeHelper.updateItems(this); + } + + @Nonnull + @Override + public ItemStack getDisplayItem() { + if (cachedDisplayItem != null) return cachedDisplayItem.clone(); + cachedDisplayItem = createDisplayItem().build(); + return cachedDisplayItem.clone(); + } + + @Nonnull + @Override + public ItemStack getSettingsItem() { + ItemBuilder item = createSettingsItem(); + String[] description = getSettingsDescription(); + if (description != null && isEnabled()) { + item.appendLore(" "); + item.appendLore(description); + } + + return item.build(); + } + + @Nullable + protected String[] getSettingsDescription() { + return null; + } + + @Nonnull + public abstract ItemBuilder createDisplayItem(); + + @Nonnull + public abstract ItemBuilder createSettingsItem(); + + @Nonnull + @Override + public String getUniqueGamestateName() { + return getUniqueName(); + } + + @Nonnull + @Override + public String getUniqueName() { + return name != null ? name : (name = getClass().getSimpleName().toLowerCase() + .replace("setting", "") + .replace("challenge", "") + .replace("modifier", "") + .replace("goal", "") + ); + } + + @Override + public void handleShutdown() { + } + + @Override + public void writeGameState(@Nonnull Document document) { + } + + @Override + public void loadGameState(@Nonnull Document document) { + } + + @Override + public void writeSettings(@Nonnull Document document) { + } + + @Override + public void loadSettings(@Nonnull Document document) { + } + + @CheckReturnValue + protected boolean shouldExecuteEffect() { + return isEnabled() && ChallengeAPI.isStarted() && !ChallengeAPI.isWorldInUse(); + } + + /** + * @deprecated Use {@link ChallengeHelper#kill(Player)} + */ + @Deprecated + @DeprecatedSince("2.1.0") + public void kill(@Nonnull Player player) { + ChallengeHelper.kill(player); + } + + /** + * @deprecated Use {@link ChallengeHelper#kill(Player, int)} + */ + @Deprecated + @DeprecatedSince("2.1.0") + public void kill(@Nonnull Player player, int delay) { + ChallengeHelper.kill(player, delay); + + } + + @Nonnull + protected final Document getGameStateData() { + return plugin.getConfigManager().getGamestateConfig().getDocument(this.getUniqueGamestateName()); + } + + @Nonnull + protected final Document getPlayerData(@Nonnull UUID player) { + return getGameStateData().getDocument("player").getDocument(player.toString()); + } @Nonnull - @Override - public final MenuType getType() { - return menu; - } - - @Override - public SettingCategory getCategory() { - return category; - } - - protected final void updateItems() { - ChallengeHelper.updateItems(this); - } - - @Nonnull - @Override - public ItemStack getDisplayItem() { - if (cachedDisplayItem != null) return cachedDisplayItem.clone(); - cachedDisplayItem = createDisplayItem().build(); - return cachedDisplayItem.clone(); - } - - @Nonnull - @Override - public ItemStack getSettingsItem() { - ItemBuilder item = createSettingsItem(); - String[] description = getSettingsDescription(); - if (description != null && isEnabled()) { - item.appendLore(" "); - item.appendLore(description); - } - - return item.build(); - } - - @Nullable - protected String[] getSettingsDescription() { - return null; - } - - @Nonnull - public abstract ItemBuilder createDisplayItem(); - - @Nonnull - public abstract ItemBuilder createSettingsItem(); - - @Nonnull - @Override - public String getUniqueGamestateName() { - return getUniqueName(); - } - - @Nonnull - @Override - public String getUniqueName() { - return name != null ? name : (name = getClass().getSimpleName().toLowerCase() - .replace("setting", "") - .replace("challenge", "") - .replace("modifier", "") - .replace("goal", "") - ); - } - - @Override - public void handleShutdown() { - } - - @Override - public void writeGameState(@Nonnull Document document) { - } - - @Override - public void loadGameState(@Nonnull Document document) { - } - - @Override - public void writeSettings(@Nonnull Document document) { - } - - @Override - public void loadSettings(@Nonnull Document document) { - } - - @CheckReturnValue - protected boolean shouldExecuteEffect() { - return isEnabled() && ChallengeAPI.isStarted() && !ChallengeAPI.isWorldInUse(); - } - - /** - * @deprecated Use {@link ChallengeHelper#kill(Player)} - */ - @Deprecated - @DeprecatedSince("2.1.0") - public void kill(@Nonnull Player player) { - ChallengeHelper.kill(player); - } - - /** - * @deprecated Use {@link ChallengeHelper#kill(Player, int)} - */ - @Deprecated - @DeprecatedSince("2.1.0") - public void kill(@Nonnull Player player, int delay) { - ChallengeHelper.kill(player, delay); - - } - - @Nonnull - protected final Document getGameStateData() { - return plugin.getConfigManager().getGamestateConfig().getDocument(this.getUniqueGamestateName()); - } - - @Nonnull - protected final Document getPlayerData(@Nonnull UUID player) { - return getGameStateData().getDocument("player").getDocument(player.toString()); - } - - @Nonnull - protected final Document getPlayerData(@Nonnull Player player) { - return getPlayerData(player.getUniqueId()); - } + protected final Document getPlayerData(@Nonnull Player player) { + return getPlayerData(player.getUniqueId()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java index e35e8bab3..65ab3cde8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java @@ -14,87 +14,87 @@ @Setter public abstract class AbstractForceChallenge extends TimedChallenge { - public static final int WAITING = 0, - COUNTDOWN = 1; - - private int state = WAITING; - - public AbstractForceChallenge(@Nonnull MenuType menu) { - super(menu, false); - } - - public AbstractForceChallenge(@Nonnull MenuType menu, int max) { - super(menu, max, false); - } - - public AbstractForceChallenge(@Nonnull MenuType menu, int min, int max) { - super(menu, min, max, false); - } - - public AbstractForceChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue, false); - } - - @Override - protected void onTimeActivation() { - switch (state) { - case WAITING: - state = COUNTDOWN; - chooseForcing(); - restartTimer(getForcingTime()); - SoundSample.BASS_ON.broadcast(); - bossbar.update(); - break; - case COUNTDOWN: - state = WAITING; - restartTimer(); - handleCountdownEnd(); - bossbar.update(); - break; - } - } - - protected final void endForcing() { - state = WAITING; - restartTimer(); - bossbar.update(); - } - - protected abstract void handleCountdownEnd(); - - @Override - protected void handleCountdown() { - bossbar.update(); - } - - @Override - protected void onEnable() { - bossbar.setContent(setupBossbar()); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - if (document.isEmpty()) { - state = WAITING; - } - } - - protected abstract void chooseForcing(); - - protected abstract int getForcingTime(); - - @Nonnull - protected abstract BiConsumer setupBossbar(); - - public final int getState() { - return state; - } + public static final int WAITING = 0, + COUNTDOWN = 1; + + private int state = WAITING; + + public AbstractForceChallenge(@Nonnull MenuType menu) { + super(menu, false); + } + + public AbstractForceChallenge(@Nonnull MenuType menu, int max) { + super(menu, max, false); + } + + public AbstractForceChallenge(@Nonnull MenuType menu, int min, int max) { + super(menu, min, max, false); + } + + public AbstractForceChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { + super(menu, min, max, defaultValue, false); + } + + @Override + protected void onTimeActivation() { + switch (state) { + case WAITING: + state = COUNTDOWN; + chooseForcing(); + restartTimer(getForcingTime()); + SoundSample.BASS_ON.broadcast(); + bossbar.update(); + break; + case COUNTDOWN: + state = WAITING; + restartTimer(); + handleCountdownEnd(); + bossbar.update(); + break; + } + } + + protected final void endForcing() { + state = WAITING; + restartTimer(); + bossbar.update(); + } + + protected abstract void handleCountdownEnd(); + + @Override + protected void handleCountdown() { + bossbar.update(); + } + + @Override + protected void onEnable() { + bossbar.setContent(setupBossbar()); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + if (document.isEmpty()) { + state = WAITING; + } + } + + protected abstract void chooseForcing(); + + protected abstract int getForcingTime(); + + @Nonnull + protected abstract BiConsumer setupBossbar(); + + public final int getState() { + return state; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java index c43553aa2..3e155e5a3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java @@ -17,112 +17,112 @@ public abstract class CollectionGoal extends SettingGoal { - private final Map> collections = new HashMap<>(); - protected Object[] target; - - public CollectionGoal(@Nonnull Object[] target) { - super(); - this.target = target; - } - - public CollectionGoal(boolean enabledByDefault, @Nonnull Object[] target) { - super(enabledByDefault); - this.target = target; - } - - @Override - protected void onEnable() { - scoreboard.setContent(GoalHelper.createScoreboard(() -> getPoints(new AtomicInteger(), true))); - scoreboard.show(); - } - - @Override - protected void onDisable() { - scoreboard.hide(); - } - - @Override - public void getWinnersOnEnd(@Nonnull List winners) { - AtomicInteger mostPoints = new AtomicInteger(); - Map points = getPoints(mostPoints, false); - if (mostPoints.get() == 0) return; // Nobody won, nobody has anything - - for (Entry entry : points.entrySet()) { - if (entry.getValue() != mostPoints.get()) continue; - winners.add(entry.getKey()); - } - } - - @Nonnull - @CheckReturnValue - protected Map getPoints(@Nonnull AtomicInteger mostPoints, boolean zeros) { - return GoalHelper.createPointsFromValues(mostPoints, collections, (uuid, strings) -> getCollectionFiltered(uuid).size(), zeros); - } - - protected void collect(@Nonnull Player player, @Nonnull Object item, @Nonnull Runnable success) { - if (ignorePlayer(player)) return; - List collection = getCollectionRaw(player.getUniqueId()); - if (collection.contains(item.toString())) return; - if (!Arrays.asList(target).contains(item)) return; - collection.add(item.toString()); - success.run(); - checkCollects(); - } - - protected List getCollectionFiltered(@Nonnull UUID uuid) { - List targetStringList = Arrays.stream(target).map(Object::toString).collect(Collectors.toList()); - return collections.computeIfAbsent(uuid, key -> new ArrayList<>()).stream().filter(targetStringList::contains).collect(Collectors.toList()); - } - - protected List getCollectionRaw(@Nonnull UUID uuid) { - return collections.computeIfAbsent(uuid, key -> new ArrayList<>()); - } - - protected void checkCollects() { - scoreboard.update(); - for (Player player : Bukkit.getOnlinePlayers()) { - checkCollects(getCollectionFiltered(player.getUniqueId())); - } - } - - protected void checkCollects(@Nonnull List collection) { - if (collection.size() >= target.length) - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - - collections.clear(); - Document scores = document.getDocument("scores"); - for (String key : scores.keys()) { - try { - UUID uuid = UUID.fromString(key); - List collection = scores.getStringList(key); - collections.put(uuid, collection); - } catch (Exception ex) { - Logger.error("Could not load scores for {}", key); - } - } - - if (scoreboard.isShown()) { - scoreboard.update(); - } - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - - Document scores = document.getDocument("scores"); - collections.forEach((uuid, collection) -> { - scores.set(uuid.toString(), collection); - }); - } - - protected void setTarget(@Nonnull Object... target) { - this.target = target; - } + private final Map> collections = new HashMap<>(); + protected Object[] target; + + public CollectionGoal(@Nonnull Object[] target) { + super(); + this.target = target; + } + + public CollectionGoal(boolean enabledByDefault, @Nonnull Object[] target) { + super(enabledByDefault); + this.target = target; + } + + @Override + protected void onEnable() { + scoreboard.setContent(GoalHelper.createScoreboard(() -> getPoints(new AtomicInteger(), true))); + scoreboard.show(); + } + + @Override + protected void onDisable() { + scoreboard.hide(); + } + + @Override + public void getWinnersOnEnd(@Nonnull List winners) { + AtomicInteger mostPoints = new AtomicInteger(); + Map points = getPoints(mostPoints, false); + if (mostPoints.get() == 0) return; // Nobody won, nobody has anything + + for (Entry entry : points.entrySet()) { + if (entry.getValue() != mostPoints.get()) continue; + winners.add(entry.getKey()); + } + } + + @Nonnull + @CheckReturnValue + protected Map getPoints(@Nonnull AtomicInteger mostPoints, boolean zeros) { + return GoalHelper.createPointsFromValues(mostPoints, collections, (uuid, strings) -> getCollectionFiltered(uuid).size(), zeros); + } + + protected void collect(@Nonnull Player player, @Nonnull Object item, @Nonnull Runnable success) { + if (ignorePlayer(player)) return; + List collection = getCollectionRaw(player.getUniqueId()); + if (collection.contains(item.toString())) return; + if (!Arrays.asList(target).contains(item)) return; + collection.add(item.toString()); + success.run(); + checkCollects(); + } + + protected List getCollectionFiltered(@Nonnull UUID uuid) { + List targetStringList = Arrays.stream(target).map(Object::toString).collect(Collectors.toList()); + return collections.computeIfAbsent(uuid, key -> new ArrayList<>()).stream().filter(targetStringList::contains).collect(Collectors.toList()); + } + + protected List getCollectionRaw(@Nonnull UUID uuid) { + return collections.computeIfAbsent(uuid, key -> new ArrayList<>()); + } + + protected void checkCollects() { + scoreboard.update(); + for (Player player : Bukkit.getOnlinePlayers()) { + checkCollects(getCollectionFiltered(player.getUniqueId())); + } + } + + protected void checkCollects(@Nonnull List collection) { + if (collection.size() >= target.length) + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + + collections.clear(); + Document scores = document.getDocument("scores"); + for (String key : scores.keys()) { + try { + UUID uuid = UUID.fromString(key); + List collection = scores.getStringList(key); + collections.put(uuid, collection); + } catch (Exception ex) { + Logger.error("Could not load scores for {}", key); + } + } + + if (scoreboard.isShown()) { + scoreboard.update(); + } + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + + Document scores = document.getDocument("scores"); + collections.forEach((uuid, collection) -> { + scores.set(uuid.toString(), collection); + }); + } + + protected void setTarget(@Nonnull Object... target) { + this.target = target; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java index 3ed7971dd..24c3742b1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java @@ -10,38 +10,38 @@ public abstract class CompletableForceChallenge extends AbstractForceChallenge { - public CompletableForceChallenge(@Nonnull MenuType menu) { - super(menu); - } - - public CompletableForceChallenge(@Nonnull MenuType menu, int max) { - super(menu, max); - } - - public CompletableForceChallenge(@Nonnull MenuType menu, int min, int max) { - super(menu, min, max); - } - - public CompletableForceChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue); - } - - @Override - protected final void handleCountdownEnd() { - broadcastFailedMessage(); - endForcing(); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_FAILED); - } - - protected final void completeForcing(@Nonnull Player player) { - if (getState() != COUNTDOWN) return; - broadcastSuccessMessage(player); - endForcing(); - SoundSample.LEVEL_UP.broadcast(); - } - - protected abstract void broadcastFailedMessage(); - - protected abstract void broadcastSuccessMessage(@Nonnull Player player); + public CompletableForceChallenge(@Nonnull MenuType menu) { + super(menu); + } + + public CompletableForceChallenge(@Nonnull MenuType menu, int max) { + super(menu, max); + } + + public CompletableForceChallenge(@Nonnull MenuType menu, int min, int max) { + super(menu, min, max); + } + + public CompletableForceChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { + super(menu, min, max, defaultValue); + } + + @Override + protected final void handleCountdownEnd() { + broadcastFailedMessage(); + endForcing(); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_FAILED); + } + + protected final void completeForcing(@Nonnull Player player) { + if (getState() != COUNTDOWN) return; + broadcastSuccessMessage(player); + endForcing(); + SoundSample.LEVEL_UP.broadcast(); + } + + protected abstract void broadcastFailedMessage(); + + protected abstract void broadcastSuccessMessage(@Nonnull Player player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java index 7a8b496b4..721c5a343 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java @@ -13,53 +13,53 @@ public abstract class EndingForceChallenge extends AbstractForceChallenge { - public EndingForceChallenge(@Nonnull MenuType menu) { - super(menu); - } + public EndingForceChallenge(@Nonnull MenuType menu) { + super(menu); + } - public EndingForceChallenge(@Nonnull MenuType menu, int max) { - super(menu, max); - } + public EndingForceChallenge(@Nonnull MenuType menu, int max) { + super(menu, max); + } - public EndingForceChallenge(@Nonnull MenuType menu, int min, int max) { - super(menu, min, max); - } + public EndingForceChallenge(@Nonnull MenuType menu, int min, int max) { + super(menu, min, max); + } - public EndingForceChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue); - } + public EndingForceChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { + super(menu, min, max, defaultValue); + } - @Override - protected final void handleCountdownEnd() { - checkAllPlayers(); - } + @Override + protected final void handleCountdownEnd() { + checkAllPlayers(); + } - private void checkAllPlayers() { - List failed = new ArrayList<>(); - for (Player player : Bukkit.getOnlinePlayers()) { - if (!ignorePlayer(player) && isFailing(player)) { - broadcastFailedMessage(player); - failed.add(player); - } - } - if (!failed.isEmpty()) { - killFailedPlayers(failed); - return; - } + private void checkAllPlayers() { + List failed = new ArrayList<>(); + for (Player player : Bukkit.getOnlinePlayers()) { + if (!ignorePlayer(player) && isFailing(player)) { + broadcastFailedMessage(player); + failed.add(player); + } + } + if (!failed.isEmpty()) { + killFailedPlayers(failed); + return; + } - broadcastSuccessMessage(); - SoundSample.LEVEL_UP.broadcast(); - } + broadcastSuccessMessage(); + SoundSample.LEVEL_UP.broadcast(); + } - private void killFailedPlayers(@Nonnull Iterable failed) { - if (!ChallengeAPI.isStarted()) return; - failed.forEach(ChallengeHelper::kill); - } + private void killFailedPlayers(@Nonnull Iterable failed) { + if (!ChallengeAPI.isStarted()) return; + failed.forEach(ChallengeHelper::kill); + } - protected abstract boolean isFailing(@Nonnull Player player); + protected abstract boolean isFailing(@Nonnull Player player); - protected abstract void broadcastFailedMessage(@Nonnull Player player); + protected abstract void broadcastFailedMessage(@Nonnull Player player); - protected abstract void broadcastSuccessMessage(); + protected abstract void broadcastSuccessMessage(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java index 92e48a424..da5e8ffba 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java @@ -17,37 +17,37 @@ public abstract class FindItemGoal extends SettingGoal { - private final Material searchedItem; - - public FindItemGoal(Material searchedItem) { - this.searchedItem = searchedItem; - } - - @Override - public void getWinnersOnEnd(@NotNull List winners) { - - } - - private void checkItem(ItemStack itemStack, @Nonnull Player player) { - if (itemStack == null) return; - if (itemStack.getType() != searchedItem) return; - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(player)); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPickup(PlayerPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - checkItem(event.getItem().getItemStack(), event.getPlayer()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInventoryClick(PlayerInventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getHolder() != event.getPlayer()) return; - checkItem(event.getCurrentItem(), event.getPlayer()); - } + private final Material searchedItem; + + public FindItemGoal(Material searchedItem) { + this.searchedItem = searchedItem; + } + + @Override + public void getWinnersOnEnd(@NotNull List winners) { + + } + + private void checkItem(ItemStack itemStack, @Nonnull Player player) { + if (itemStack == null) return; + if (itemStack.getType() != searchedItem) return; + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(player)); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPickup(PlayerPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + checkItem(event.getItem().getItemStack(), event.getPlayer()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onInventoryClick(PlayerInventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getHolder() != event.getPlayer()) return; + checkItem(event.getCurrentItem(), event.getPlayer()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java index 153913c7b..3db44282e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java @@ -18,39 +18,39 @@ @Getter public abstract class FirstPlayerAtHeightGoal extends SettingGoal { - private int heightToGetTo; - - @Override - protected void onEnable() { - bossbar.setContent((bar, player) -> { - bar.setTitle(Message.forName("bossbar-first-at-height-goal").asString(getHeightToGetTo())); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @Override - public void getWinnersOnEnd(@NotNull List winners) { - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getTo() == null) return; - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getTo().getBlockY() == event.getFrom().getBlockY()) return; - if (event.getTo().getBlockY() == heightToGetTo) { - Message.forName("height-reached").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), getHeightToGetTo()); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); - } - } - - protected void setHeightToGetTo(int heightToGetTo) { - this.heightToGetTo = heightToGetTo; - } + private int heightToGetTo; + + @Override + protected void onEnable() { + bossbar.setContent((bar, player) -> { + bar.setTitle(Message.forName("bossbar-first-at-height-goal").asString(getHeightToGetTo())); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @Override + public void getWinnersOnEnd(@NotNull List winners) { + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + if (event.getTo() == null) return; + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getTo().getBlockY() == event.getFrom().getBlockY()) return; + if (event.getTo().getBlockY() == heightToGetTo) { + Message.forName("height-reached").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), getHeightToGetTo()); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); + } + } + + protected void setHeightToGetTo(int heightToGetTo) { + this.heightToGetTo = heightToGetTo; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java index aeb3455cb..694afe425 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java @@ -21,103 +21,103 @@ public abstract class ForceBattleDisplayGoal> extends ForceBattleGoal { - private Map displayStands; - - public ForceBattleDisplayGoal(@NotNull Message title) { - super(title); - } - - @Override - protected void onEnable() { - displayStands = new HashMap<>(); - broadcastFiltered(this::updateDisplayStand); - super.onEnable(); - } - - @Override - protected void onDisable() { - super.onDisable(); - displayStands.values().forEach(Entity::remove); - displayStands = null; - } - - public void updateDisplayStand(Player player) { - ArmorStand armorStand = displayStands.computeIfAbsent(player, player1 -> { - World world = player1.getWorld(); - ArmorStand entity = (ArmorStand) world - .spawnEntity(player1.getLocation().clone().add(0, 2, 0), EntityType.ARMOR_STAND); - entity.setVisible(false); - entity.setInvulnerable(true); - entity.setGravity(false); - entity.setMarker(true); - entity.setSilent(true); - entity.setSmall(true); - return entity; - }); - armorStand.setVelocity(player.getVelocity().clone().multiply(2)); - armorStand.teleport(player.getLocation().clone().add(0, 2, 0)); - - handleDisplayStandUpdate(player, armorStand); + private Map displayStands; + + public ForceBattleDisplayGoal(@NotNull Message title) { + super(title); + } + + @Override + protected void onEnable() { + displayStands = new HashMap<>(); + broadcastFiltered(this::updateDisplayStand); + super.onEnable(); + } + + @Override + protected void onDisable() { + super.onDisable(); + displayStands.values().forEach(Entity::remove); + displayStands = null; + } + + public void updateDisplayStand(Player player) { + ArmorStand armorStand = displayStands.computeIfAbsent(player, player1 -> { + World world = player1.getWorld(); + ArmorStand entity = (ArmorStand) world + .spawnEntity(player1.getLocation().clone().add(0, 2, 0), EntityType.ARMOR_STAND); + entity.setVisible(false); + entity.setInvulnerable(true); + entity.setGravity(false); + entity.setMarker(true); + entity.setSilent(true); + entity.setSmall(true); + return entity; + }); + armorStand.setVelocity(player.getVelocity().clone().multiply(2)); + armorStand.teleport(player.getLocation().clone().add(0, 2, 0)); + + handleDisplayStandUpdate(player, armorStand); + } + + public void handleDisplayStandUpdate(@NotNull Player player, @NotNull ArmorStand armorStand) { + if (currentTarget.containsKey(player.getUniqueId())) { + currentTarget.get(player.getUniqueId()).updateDisplayStand(armorStand); + } else if (Objects.requireNonNull(armorStand.getEquipment()).getHelmet() != null) { + armorStand.getEquipment().setHelmet(null); } + } - public void handleDisplayStandUpdate(@NotNull Player player, @NotNull ArmorStand armorStand) { - if (currentTarget.containsKey(player.getUniqueId())) { - currentTarget.get(player.getUniqueId()).updateDisplayStand(armorStand); - } else if (Objects.requireNonNull(armorStand.getEquipment()).getHelmet() != null) { - armorStand.getEquipment().setHelmet(null); - } + @Override + public void loadGameState(@NotNull Document document) { + super.loadGameState(document); + if (isEnabled()) { + broadcastFiltered(this::updateDisplayStand); } - - @Override - public void loadGameState(@NotNull Document document) { - super.loadGameState(document); - if (isEnabled()) { - broadcastFiltered(this::updateDisplayStand); - } + } + + @Override + public void setRandomTarget(Player player) { + super.setRandomTarget(player); + updateDisplayStand(player); + } + + @EventHandler(ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + updateDisplayStand(event.getPlayer()); + } + + @EventHandler + public void onStatusChange(PlayerIgnoreStatusChangeEvent event) { + if (!shouldExecuteEffect()) return; + if (event.isNotIgnored()) { + setRandomTargetIfCurrentlyNone(event.getPlayer()); + updateDisplayStand(event.getPlayer()); + } else { + ArmorStand stand = displayStands.remove(event.getPlayer()); + if (stand != null) { + stand.remove(); + } } + } - @Override - public void setRandomTarget(Player player) { - super.setRandomTarget(player); - updateDisplayStand(player); + @Override + public void onTick() { + super.onTick(); + for (Player player : displayStands.keySet()) { + updateDisplayStand(player); } - - @EventHandler(ignoreCancelled = true) - public void onTeleport(PlayerTeleportEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - updateDisplayStand(event.getPlayer()); - } - - @EventHandler - public void onStatusChange(PlayerIgnoreStatusChangeEvent event) { - if (!shouldExecuteEffect()) return; - if (event.isNotIgnored()) { - setRandomTargetIfCurrentlyNone(event.getPlayer()); - updateDisplayStand(event.getPlayer()); - } else { - ArmorStand stand = displayStands.remove(event.getPlayer()); - if (stand != null) { - stand.remove(); - } - } - } - - @Override - public void onTick() { - super.onTick(); - for (Player player : displayStands.keySet()) { - updateDisplayStand(player); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onQuit(PlayerQuitEvent event) { - if (!shouldExecuteEffect()) return; - ArmorStand stand = displayStands.remove(event.getPlayer()); - if (stand != null) { - stand.remove(); - } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onQuit(PlayerQuitEvent event) { + if (!shouldExecuteEffect()) return; + ArmorStand stand = displayStands.remove(event.getPlayer()); + if (stand != null) { + stand.remove(); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java index d12c792b7..8aa1b47ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java @@ -39,412 +39,412 @@ public abstract class ForceBattleGoal> extends MenuGoal { - protected final Map jokerUsed = new HashMap<>(); - protected final Map> foundTargets = new HashMap<>(); - protected final Map currentTarget = new HashMap<>(); - protected T[] targetsPossibleToFind; - private ItemStack jokerItem; - - public ForceBattleGoal(@NotNull Message title) { - super(MenuType.GOAL, title); - setCategory(SettingCategory.FORCE_BATTLE); - - registerSetting("jokers", new NumberSubSetting( - () -> new ItemBuilder(Material.BARRIER, Message.forName("item-force-battle-goal-jokers")), - value -> null, - value -> "§e" + value, - 1, - 32, - 5 - )); - registerSetting("showScoreboard", new BooleanSubSetting( - () -> new ItemBuilder(Material.BOOK, Message.forName("item-force-battle-show-scoreboard")), - true - )); - if (shouldRegisterDupedTargetsSetting()) { - registerSetting("dupedTargets", new BooleanSubSetting( - () -> new ItemBuilder(Material.PAPER, Message.forName("item-force-battle-duped-targets")), - true - )); - } - } - - @Override - protected void onEnable() { - jokerItem = new ItemBuilder(Material.BARRIER, "§cJoker").build(); - - targetsPossibleToFind = getTargetsPossibleToFind(); - - broadcastFiltered(this::updateJokersInInventory); - broadcastFiltered(this::setRandomTargetIfCurrentlyNone); - - setScoreboardContent(); - if (showScoreboard()) { - scoreboard.show(); - } - } - - @Override - protected void onDisable() { - if (jokerItem == null) return; // Disable through plugin disable - broadcastFiltered(this::updateJokersInInventory); - jokerItem = null; - scoreboard.hide(); - targetsPossibleToFind = null; - } - - protected abstract T[] getTargetsPossibleToFind(); - - private void updateJokersInInventory(Player player) { - PlayerInventory inventory = player.getInventory(); - boolean enabled = isEnabled() && ChallengeAPI.isStarted(); - int usableJokers = getUsableJokers(player.getUniqueId()); - - int jokersInInventory = 0; - - LinkedList itemStacks = new LinkedList<>(Arrays.asList(inventory.getContents())); - itemStacks.add(player.getItemOnCursor()); - for (ItemStack itemStack : itemStacks) { - if (jokerItem.isSimilar(itemStack)) { - if (enabled) { - jokersInInventory += itemStack.getAmount(); - if (jokersInInventory >= usableJokers) { - int jokersToSubtract = jokersInInventory - usableJokers; - jokersInInventory -= jokersToSubtract; - itemStack.setAmount(itemStack.getAmount() - jokersToSubtract); - } - } else { - inventory.removeItem(itemStack); - } - } - - } - - if (enabled) { - if (jokersInInventory < usableJokers) { - ItemStack clone = jokerItem.clone(); - clone.setAmount(usableJokers - jokersInInventory); - InventoryUtils.dropOrGiveItem(inventory, player.getLocation(), clone); - } - } - - } - - @Override - public void loadGameState(@NotNull Document document) { - this.jokerUsed.clear(); - this.currentTarget.clear(); - this.foundTargets.clear(); - - List players = document.getDocumentList("players"); - for (Document player : players) { - UUID uuid = player.getUUID("uuid"); - - T currentTarget = getTargetFromDocument(player, "currentTarget"); - - if (currentTarget != null) { - this.currentTarget.put(uuid, currentTarget); - } - List foundItems = getListFromDocument(player, "foundTargets"); - this.foundTargets.put(uuid, foundItems); - - int jokerUsed = player.getInt("jokerUsed"); - this.jokerUsed.put(uuid, jokerUsed); - } - - if (isEnabled()) { - if (ChallengeAPI.isStarted()) { - broadcastFiltered(this::setRandomTargetIfCurrentlyNone); - } - scoreboard.update(); - broadcastFiltered(this::updateJokersInInventory); - } - } - - @Override - public void writeGameState(@NotNull Document document) { - List playersDocuments = new LinkedList<>(); - for (Map.Entry entry : currentTarget.entrySet()) { - List foundItems = this.foundTargets.get(entry.getKey()); - int jokerUsed = this.jokerUsed.getOrDefault(entry.getKey(), 0); - GsonDocument playerDocument = new GsonDocument(); - playerDocument.set("uuid", entry.getKey()); - setTargetInDocument(playerDocument, "currentTarget", entry.getValue()); - if (foundItems != null) { - setFoundListInDocument(playerDocument, "foundTargets", foundItems); - } - playerDocument.set("jokerUsed", jokerUsed); - playersDocuments.add(playerDocument); - } - - document.set("players", playersDocuments); - } - - public void setTargetInDocument(Document document, String path, T target) { - document.set(path, target.getTargetSaveObject()); - } - - public void setFoundListInDocument(Document document, String path, List targets) { - document.set(path, targets.stream().map(ForceTarget::getTargetSaveObject).collect(Collectors.toList())); - } - - public abstract T getTargetFromDocument(Document document, String path); - - public abstract List getListFromDocument(Document document, String path); - - public void setRandomTargetIfCurrentlyNone(Player player) { - if (currentTarget.containsKey(player.getUniqueId())) { - return; - } - setRandomTarget(player); - } - - public void setRandomTarget(Player player) { - T target = getRandomTarget(player); - - if (target != null) { - currentTarget.put(player.getUniqueId(), target); - getNewTargetMessage(target) - .send(player, Prefix.CHALLENGES, getTargetMessageReplacement(target)); - SoundSample.PLING.play(player); - } else { - currentTarget.remove(player.getUniqueId()); - SoundSample.BASS_OFF.play(player); - } - scoreboard.update(); - - } - - protected T getRandomTarget(Player player) { - LinkedList list = new LinkedList<>(Arrays.asList(targetsPossibleToFind)); - if (!getSetting("dupedTargets").getAsBoolean()) { - list.removeAll(foundTargets.getOrDefault(player.getUniqueId(), new LinkedList<>())); - } - if (!list.isEmpty()) { - return globalRandom.choose(list); - } - return null; - } - - protected Message getNewTargetMessage(T newTarget) { - return newTarget.getNewTargetMessage(); - } - - protected Message getTargetCompletedMessage(T target) { - return target.getCompletedMessage(); - } - - public void handleTargetFound(Player player) { - T foundTarget = currentTarget.get(player.getUniqueId()); - if (foundTarget != null) { - List list = foundTargets - .computeIfAbsent(player.getUniqueId(), uuid -> new LinkedList<>()); - list.add(foundTarget); - getTargetCompletedMessage(foundTarget).send(player, Prefix.CHALLENGES, getTargetMessageReplacement(foundTarget)); - } - setRandomTarget(player); - } - - public Object getTargetMessageReplacement(T target) { - return target.toMessage(); - } - - public String getTargetName(T target) { - return target.getName(); - } - - @Override - public void getWinnersOnEnd(@NotNull List winners) { - - Bukkit.getScheduler().runTask(plugin, () -> { - int place = 0; - int placeValue = -1; - - List>> list = foundTargets.entrySet().stream() - .sorted(Comparator.comparingInt(value -> value.getValue().size())) - .collect(Collectors.toList()); - Collections.reverse(list); - - getLeaderboardTitleMessage().broadcast(Prefix.CHALLENGES); - - for (Map.Entry> entry : list) { - if (entry.getValue().size() != placeValue) { - place++; - placeValue = entry.getValue().size(); - } - UUID uuid = entry.getKey(); - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); - ChatColor color = getPlaceColor(place); - Message.forName("force-battle-leaderboard-entry") - .broadcast(Prefix.CHALLENGES, color, place, NameHelper.getName(offlinePlayer), entry.getValue().size()); - } - - }); - - } - - public void sendResult(@NotNull Player player) { - Bukkit.getScheduler().runTask(plugin, () -> { - int place = 0; - int placeValue = -1; - - List>> list = foundTargets.entrySet().stream() - .sorted(Comparator.comparingInt(value -> value.getValue().size())) - .collect(Collectors.toList()); - Collections.reverse(list); - - getLeaderboardTitleMessage().broadcast(Prefix.CHALLENGES); - - for (Map.Entry> entry : list) { - if (entry.getValue().size() != placeValue) { - place++; - placeValue = entry.getValue().size(); - } - UUID uuid = entry.getKey(); - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); - ChatColor color = getPlaceColor(place); - Message.forName("force-battle-leaderboard-entry") - .send(player, Prefix.CHALLENGES, color, place, NameHelper.getName(offlinePlayer), entry.getValue().size()); - } - - }); - } - - protected abstract Message getLeaderboardTitleMessage(); - - protected ChatColor getPlaceColor(int place) { - switch (place) { - case 1: - return ChatColor.GOLD; - case 2: - return ChatColor.YELLOW; - case 3: - return ChatColor.RED; - default: - return ChatColor.GRAY; - } - } - - private int getUsableJokers(UUID uuid) { - return Math.max(0, getJokers() - jokerUsed.getOrDefault(uuid, 0)); - } - - public void handleJokerUse(Player player) { - if (currentTarget.get(player.getUniqueId()) == null) { - setRandomTargetIfCurrentlyNone(player); - return; - } - int jokerUsed = this.jokerUsed.getOrDefault(player.getUniqueId(), 0); - jokerUsed++; - this.jokerUsed.put(player.getUniqueId(), jokerUsed); - handleTargetFound(player); - updateJokersInInventory(player); - } - - protected void setScoreboardContent() { - scoreboard.setContent((board, player) -> { - List ingamePlayers = ChallengeAPI.getIngamePlayers(); - int emptyLinesAvailable = 15 - ingamePlayers.size(); - - if (emptyLinesAvailable > 0) { - board.addLine(""); - emptyLinesAvailable--; - } - - for (int i = 0; i < ingamePlayers.size() && i < 15; i++) { - Player ingamePlayer = ingamePlayers.get(i); - T target = currentTarget.get(ingamePlayer.getUniqueId()); - String display = target == null ? Message.forName("none").asString() : getTargetName(target); - board.addLine(NameHelper.getName(ingamePlayer) + " §8» §e" + display); - } - - if (emptyLinesAvailable > 0) { - board.addLine(""); - } - }); - } - - @TimerTask(status = TimerStatus.RUNNING, async = false) - public void onStart() { - broadcastFiltered(this::setRandomTargetIfCurrentlyNone); - broadcastFiltered(this::updateJokersInInventory); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onJoin(PlayerJoinEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - setRandomTargetIfCurrentlyNone(event.getPlayer()); - updateJokersInInventory(event.getPlayer()); - } - - @ScheduledTask(ticks = 1, async = false, timerPolicy = TimerPolicy.ALWAYS) - public void onTick() { - if (!isEnabled()) return; - - if (!scoreboard.isShown() && showScoreboard()) { - scoreboard.show(); - } else if (scoreboard.isShown() && !showScoreboard()) { - scoreboard.hide(); - } - broadcastFiltered(this::updateJokersInInventory); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onInteract(PlayerInteractEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (event.getAction() != Action.RIGHT_CLICK_AIR - && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; - if (jokerItem.isSimilar(event.getItem())) { - handleJokerUse(event.getPlayer()); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDropItem(PlayerDropItemEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (jokerItem.isSimilar(event.getItemDrop().getItemStack())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDeath(PlayerDeathEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getEntity())) return; - event.getDrops().removeIf(itemStack -> jokerItem.isSimilar(itemStack)); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onRespawn(PlayerRespawnEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - Bukkit.getScheduler().runTask(plugin, () -> { - updateJokersInInventory(event.getPlayer()); - }); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlace(BlockPlaceEvent event) { - if (!shouldExecuteEffect()) return; - if (ignorePlayer(event.getPlayer())) return; - if (jokerItem.isSimilar(event.getItemInHand())) { - event.setCancelled(true); - } - } - - private int getJokers() { - return getSetting("jokers").getAsInt(); - } - - private boolean showScoreboard() { - return getSetting("showScoreboard").getAsBoolean(); - } - - protected boolean shouldRegisterDupedTargetsSetting() { - return true; - } + protected final Map jokerUsed = new HashMap<>(); + protected final Map> foundTargets = new HashMap<>(); + protected final Map currentTarget = new HashMap<>(); + protected T[] targetsPossibleToFind; + private ItemStack jokerItem; + + public ForceBattleGoal(@NotNull Message title) { + super(MenuType.GOAL, title); + setCategory(SettingCategory.FORCE_BATTLE); + + registerSetting("jokers", new NumberSubSetting( + () -> new ItemBuilder(Material.BARRIER, Message.forName("item-force-battle-goal-jokers")), + value -> null, + value -> "§e" + value, + 1, + 32, + 5 + )); + registerSetting("showScoreboard", new BooleanSubSetting( + () -> new ItemBuilder(Material.BOOK, Message.forName("item-force-battle-show-scoreboard")), + true + )); + if (shouldRegisterDupedTargetsSetting()) { + registerSetting("dupedTargets", new BooleanSubSetting( + () -> new ItemBuilder(Material.PAPER, Message.forName("item-force-battle-duped-targets")), + true + )); + } + } + + @Override + protected void onEnable() { + jokerItem = new ItemBuilder(Material.BARRIER, "§cJoker").build(); + + targetsPossibleToFind = getTargetsPossibleToFind(); + + broadcastFiltered(this::updateJokersInInventory); + broadcastFiltered(this::setRandomTargetIfCurrentlyNone); + + setScoreboardContent(); + if (showScoreboard()) { + scoreboard.show(); + } + } + + @Override + protected void onDisable() { + if (jokerItem == null) return; // Disable through plugin disable + broadcastFiltered(this::updateJokersInInventory); + jokerItem = null; + scoreboard.hide(); + targetsPossibleToFind = null; + } + + protected abstract T[] getTargetsPossibleToFind(); + + private void updateJokersInInventory(Player player) { + PlayerInventory inventory = player.getInventory(); + boolean enabled = isEnabled() && ChallengeAPI.isStarted(); + int usableJokers = getUsableJokers(player.getUniqueId()); + + int jokersInInventory = 0; + + LinkedList itemStacks = new LinkedList<>(Arrays.asList(inventory.getContents())); + itemStacks.add(player.getItemOnCursor()); + for (ItemStack itemStack : itemStacks) { + if (jokerItem.isSimilar(itemStack)) { + if (enabled) { + jokersInInventory += itemStack.getAmount(); + if (jokersInInventory >= usableJokers) { + int jokersToSubtract = jokersInInventory - usableJokers; + jokersInInventory -= jokersToSubtract; + itemStack.setAmount(itemStack.getAmount() - jokersToSubtract); + } + } else { + inventory.removeItem(itemStack); + } + } + + } + + if (enabled) { + if (jokersInInventory < usableJokers) { + ItemStack clone = jokerItem.clone(); + clone.setAmount(usableJokers - jokersInInventory); + InventoryUtils.dropOrGiveItem(inventory, player.getLocation(), clone); + } + } + + } + + @Override + public void loadGameState(@NotNull Document document) { + this.jokerUsed.clear(); + this.currentTarget.clear(); + this.foundTargets.clear(); + + List players = document.getDocumentList("players"); + for (Document player : players) { + UUID uuid = player.getUUID("uuid"); + + T currentTarget = getTargetFromDocument(player, "currentTarget"); + + if (currentTarget != null) { + this.currentTarget.put(uuid, currentTarget); + } + List foundItems = getListFromDocument(player, "foundTargets"); + this.foundTargets.put(uuid, foundItems); + + int jokerUsed = player.getInt("jokerUsed"); + this.jokerUsed.put(uuid, jokerUsed); + } + + if (isEnabled()) { + if (ChallengeAPI.isStarted()) { + broadcastFiltered(this::setRandomTargetIfCurrentlyNone); + } + scoreboard.update(); + broadcastFiltered(this::updateJokersInInventory); + } + } + + @Override + public void writeGameState(@NotNull Document document) { + List playersDocuments = new LinkedList<>(); + for (Map.Entry entry : currentTarget.entrySet()) { + List foundItems = this.foundTargets.get(entry.getKey()); + int jokerUsed = this.jokerUsed.getOrDefault(entry.getKey(), 0); + GsonDocument playerDocument = new GsonDocument(); + playerDocument.set("uuid", entry.getKey()); + setTargetInDocument(playerDocument, "currentTarget", entry.getValue()); + if (foundItems != null) { + setFoundListInDocument(playerDocument, "foundTargets", foundItems); + } + playerDocument.set("jokerUsed", jokerUsed); + playersDocuments.add(playerDocument); + } + + document.set("players", playersDocuments); + } + + public void setTargetInDocument(Document document, String path, T target) { + document.set(path, target.getTargetSaveObject()); + } + + public void setFoundListInDocument(Document document, String path, List targets) { + document.set(path, targets.stream().map(ForceTarget::getTargetSaveObject).collect(Collectors.toList())); + } + + public abstract T getTargetFromDocument(Document document, String path); + + public abstract List getListFromDocument(Document document, String path); + + public void setRandomTargetIfCurrentlyNone(Player player) { + if (currentTarget.containsKey(player.getUniqueId())) { + return; + } + setRandomTarget(player); + } + + public void setRandomTarget(Player player) { + T target = getRandomTarget(player); + + if (target != null) { + currentTarget.put(player.getUniqueId(), target); + getNewTargetMessage(target) + .send(player, Prefix.CHALLENGES, getTargetMessageReplacement(target)); + SoundSample.PLING.play(player); + } else { + currentTarget.remove(player.getUniqueId()); + SoundSample.BASS_OFF.play(player); + } + scoreboard.update(); + + } + + protected T getRandomTarget(Player player) { + LinkedList list = new LinkedList<>(Arrays.asList(targetsPossibleToFind)); + if (!getSetting("dupedTargets").getAsBoolean()) { + list.removeAll(foundTargets.getOrDefault(player.getUniqueId(), new LinkedList<>())); + } + if (!list.isEmpty()) { + return globalRandom.choose(list); + } + return null; + } + + protected Message getNewTargetMessage(T newTarget) { + return newTarget.getNewTargetMessage(); + } + + protected Message getTargetCompletedMessage(T target) { + return target.getCompletedMessage(); + } + + public void handleTargetFound(Player player) { + T foundTarget = currentTarget.get(player.getUniqueId()); + if (foundTarget != null) { + List list = foundTargets + .computeIfAbsent(player.getUniqueId(), uuid -> new LinkedList<>()); + list.add(foundTarget); + getTargetCompletedMessage(foundTarget).send(player, Prefix.CHALLENGES, getTargetMessageReplacement(foundTarget)); + } + setRandomTarget(player); + } + + public Object getTargetMessageReplacement(T target) { + return target.toMessage(); + } + + public String getTargetName(T target) { + return target.getName(); + } + + @Override + public void getWinnersOnEnd(@NotNull List winners) { + + Bukkit.getScheduler().runTask(plugin, () -> { + int place = 0; + int placeValue = -1; + + List>> list = foundTargets.entrySet().stream() + .sorted(Comparator.comparingInt(value -> value.getValue().size())) + .collect(Collectors.toList()); + Collections.reverse(list); + + getLeaderboardTitleMessage().broadcast(Prefix.CHALLENGES); + + for (Map.Entry> entry : list) { + if (entry.getValue().size() != placeValue) { + place++; + placeValue = entry.getValue().size(); + } + UUID uuid = entry.getKey(); + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); + ChatColor color = getPlaceColor(place); + Message.forName("force-battle-leaderboard-entry") + .broadcast(Prefix.CHALLENGES, color, place, NameHelper.getName(offlinePlayer), entry.getValue().size()); + } + + }); + + } + + public void sendResult(@NotNull Player player) { + Bukkit.getScheduler().runTask(plugin, () -> { + int place = 0; + int placeValue = -1; + + List>> list = foundTargets.entrySet().stream() + .sorted(Comparator.comparingInt(value -> value.getValue().size())) + .collect(Collectors.toList()); + Collections.reverse(list); + + getLeaderboardTitleMessage().broadcast(Prefix.CHALLENGES); + + for (Map.Entry> entry : list) { + if (entry.getValue().size() != placeValue) { + place++; + placeValue = entry.getValue().size(); + } + UUID uuid = entry.getKey(); + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); + ChatColor color = getPlaceColor(place); + Message.forName("force-battle-leaderboard-entry") + .send(player, Prefix.CHALLENGES, color, place, NameHelper.getName(offlinePlayer), entry.getValue().size()); + } + + }); + } + + protected abstract Message getLeaderboardTitleMessage(); + + protected ChatColor getPlaceColor(int place) { + switch (place) { + case 1: + return ChatColor.GOLD; + case 2: + return ChatColor.YELLOW; + case 3: + return ChatColor.RED; + default: + return ChatColor.GRAY; + } + } + + private int getUsableJokers(UUID uuid) { + return Math.max(0, getJokers() - jokerUsed.getOrDefault(uuid, 0)); + } + + public void handleJokerUse(Player player) { + if (currentTarget.get(player.getUniqueId()) == null) { + setRandomTargetIfCurrentlyNone(player); + return; + } + int jokerUsed = this.jokerUsed.getOrDefault(player.getUniqueId(), 0); + jokerUsed++; + this.jokerUsed.put(player.getUniqueId(), jokerUsed); + handleTargetFound(player); + updateJokersInInventory(player); + } + + protected void setScoreboardContent() { + scoreboard.setContent((board, player) -> { + List ingamePlayers = ChallengeAPI.getIngamePlayers(); + int emptyLinesAvailable = 15 - ingamePlayers.size(); + + if (emptyLinesAvailable > 0) { + board.addLine(""); + emptyLinesAvailable--; + } + + for (int i = 0; i < ingamePlayers.size() && i < 15; i++) { + Player ingamePlayer = ingamePlayers.get(i); + T target = currentTarget.get(ingamePlayer.getUniqueId()); + String display = target == null ? Message.forName("none").asString() : getTargetName(target); + board.addLine(NameHelper.getName(ingamePlayer) + " §8» §e" + display); + } + + if (emptyLinesAvailable > 0) { + board.addLine(""); + } + }); + } + + @TimerTask(status = TimerStatus.RUNNING, async = false) + public void onStart() { + broadcastFiltered(this::setRandomTargetIfCurrentlyNone); + broadcastFiltered(this::updateJokersInInventory); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJoin(PlayerJoinEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + setRandomTargetIfCurrentlyNone(event.getPlayer()); + updateJokersInInventory(event.getPlayer()); + } + + @ScheduledTask(ticks = 1, async = false, timerPolicy = TimerPolicy.ALWAYS) + public void onTick() { + if (!isEnabled()) return; + + if (!scoreboard.isShown() && showScoreboard()) { + scoreboard.show(); + } else if (scoreboard.isShown() && !showScoreboard()) { + scoreboard.hide(); + } + broadcastFiltered(this::updateJokersInInventory); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onInteract(PlayerInteractEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (event.getAction() != Action.RIGHT_CLICK_AIR + && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (jokerItem.isSimilar(event.getItem())) { + handleJokerUse(event.getPlayer()); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDropItem(PlayerDropItemEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (jokerItem.isSimilar(event.getItemDrop().getItemStack())) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onDeath(PlayerDeathEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getEntity())) return; + event.getDrops().removeIf(itemStack -> jokerItem.isSimilar(itemStack)); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onRespawn(PlayerRespawnEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + Bukkit.getScheduler().runTask(plugin, () -> { + updateJokersInInventory(event.getPlayer()); + }); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlace(BlockPlaceEvent event) { + if (!shouldExecuteEffect()) return; + if (ignorePlayer(event.getPlayer())) return; + if (jokerItem.isSimilar(event.getItemInHand())) { + event.setCancelled(true); + } + } + + private int getJokers() { + return getSetting("jokers").getAsInt(); + } + + private boolean showScoreboard() { + return getSetting("showScoreboard").getAsBoolean(); + } + + protected boolean shouldRegisterDupedTargetsSetting() { + return true; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java index 04b5d1838..163829a2a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import javax.annotation.Nonnull; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -13,31 +12,33 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; +import javax.annotation.Nonnull; + public abstract class HydraChallenge extends Setting { - public HydraChallenge(@Nonnull MenuType menu) { - super(menu); - } + public HydraChallenge(@Nonnull MenuType menu) { + super(menu); + } - public HydraChallenge(@Nonnull MenuType menu, boolean enabledByDefault) { - super(menu, enabledByDefault); - } + public HydraChallenge(@Nonnull MenuType menu, boolean enabledByDefault) { + super(menu, enabledByDefault); + } - public abstract int getNewMobsCount(@Nonnull EntityType entityType); + public abstract int getNewMobsCount(@Nonnull EntityType entityType); - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityDamageByEntity(@Nonnull EntityDeathByPlayerEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getEntity() instanceof EnderDragon || event.getEntity() instanceof Player) return; - if (ChallengeHelper.ignoreDamager(event.getKiller())) return; + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityDamageByEntity(@Nonnull EntityDeathByPlayerEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getEntity() instanceof EnderDragon || event.getEntity() instanceof Player) return; + if (ChallengeHelper.ignoreDamager(event.getKiller())) return; - int mobsCount = getNewMobsCount(event.getEntityType()); + int mobsCount = getNewMobsCount(event.getEntityType()); - for (int i = 0; i < mobsCount; i++) { - event.getEntity().getWorld().spawnEntity(event.getEntity().getLocation(), event.getEntityType()); - } - ParticleUtils.spawnUpGoingParticleCircle(Challenges.getInstance(), event.getEntity().getLocation(), - MinecraftNameWrapper.ENTITY_EFFECT, 2, 17, 1); - } + for (int i = 0; i < mobsCount; i++) { + event.getEntity().getWorld().spawnEntity(event.getEntity().getLocation(), event.getEntityType()); + } + ParticleUtils.spawnUpGoingParticleCircle(Challenges.getInstance(), event.getEntity().getLocation(), + MinecraftNameWrapper.ENTITY_EFFECT, 2, 17, 1); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java index 95faee5b8..301d87772 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java @@ -18,46 +18,46 @@ public abstract class ItemCollectionGoal extends CollectionGoal { - public ItemCollectionGoal(@NotNull Material... target) { - super(target); - } - - public ItemCollectionGoal(boolean enabledByDefault, @NotNull Material... target) { - super(enabledByDefault, target); - } - - protected void handleCollect(@Nonnull Player player, @Nonnull Material material) { - collect(player, material, () -> { - Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); - SoundSample.PLING.play(player); - }); - } - - @Override - protected void onEnable() { - scoreboard.setContent(GoalHelper.createScoreboard(() -> getPoints(new AtomicInteger(), true), - player -> Collections.singletonList(Message.forName("items-to-collect").asString(target.length)))); - scoreboard.show(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPickupItem(@Nonnull PlayerPickupItemEvent event) { - if (!shouldExecuteEffect()) return; - Material material = event.getItem().getItemStack().getType(); - Player player = event.getPlayer(); - handleCollect(player, material); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - if (!shouldExecuteEffect()) return; - if (event.isCancelled()) return; - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getHolder() != event.getPlayer()) return; - if (event.getCurrentItem() == null) return; - Player player = event.getPlayer(); - Material material = event.getCurrentItem().getType(); - handleCollect(player, material); - } + public ItemCollectionGoal(@NotNull Material... target) { + super(target); + } + + public ItemCollectionGoal(boolean enabledByDefault, @NotNull Material... target) { + super(enabledByDefault, target); + } + + protected void handleCollect(@Nonnull Player player, @Nonnull Material material) { + collect(player, material, () -> { + Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); + SoundSample.PLING.play(player); + }); + } + + @Override + protected void onEnable() { + scoreboard.setContent(GoalHelper.createScoreboard(() -> getPoints(new AtomicInteger(), true), + player -> Collections.singletonList(Message.forName("items-to-collect").asString(target.length)))); + scoreboard.show(); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPickupItem(@Nonnull PlayerPickupItemEvent event) { + if (!shouldExecuteEffect()) return; + Material material = event.getItem().getItemStack().getType(); + Player player = event.getPlayer(); + handleCollect(player, material); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + if (!shouldExecuteEffect()) return; + if (event.isCancelled()) return; + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getHolder() != event.getPlayer()) return; + if (event.getCurrentItem() == null) return; + Player player = event.getPlayer(); + Material material = event.getCurrentItem().getType(); + handleCollect(player, material); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java index 218a068fe..3a70470bd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java @@ -16,50 +16,50 @@ public abstract class KillEntityGoal extends SettingGoal { - protected final EntityType entity; - protected final Environment environment; - @Setter + protected final EntityType entity; + protected final Environment environment; + @Setter protected boolean oneWinner = true; - protected boolean killerNeeded = false; - protected Player winner; + protected boolean killerNeeded = false; + protected Player winner; - public KillEntityGoal(@Nonnull EntityType entity) { - this(entity, false); - } + public KillEntityGoal(@Nonnull EntityType entity) { + this(entity, false); + } - public KillEntityGoal(@Nonnull EntityType entity, boolean enabledByDefault) { - this(entity, null, enabledByDefault); - } + public KillEntityGoal(@Nonnull EntityType entity, boolean enabledByDefault) { + this(entity, null, enabledByDefault); + } - public KillEntityGoal(EntityType entity, Environment world) { - this(entity, world, false); - } + public KillEntityGoal(EntityType entity, Environment world) { + this(entity, world, false); + } - public KillEntityGoal(EntityType entity, Environment world, boolean enabledByDefault) { - super(enabledByDefault); - this.entity = entity; - this.environment = world; - } + public KillEntityGoal(EntityType entity, Environment world, boolean enabledByDefault) { + super(enabledByDefault); + this.entity = entity; + this.environment = world; + } - @Override - public void getWinnersOnEnd(@Nonnull List winners) { - if (oneWinner && winner != null) winners.add(winner); - } + @Override + public void getWinnersOnEnd(@Nonnull List winners) { + if (oneWinner && winner != null) winners.add(winner); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onKill(@Nonnull EntityDeathEvent event) { - if (!isEnabled() || !ChallengeAPI.isStarted()) return; - LivingEntity entity = event.getEntity(); - if (entity.getType() != this.entity) return; - if (environment != null && event.getEntity().getWorld().getEnvironment() != environment) - return; - if (oneWinner) { - winner = event.getEntity().getKiller(); - if (killerNeeded && winner == null) { - return; - } - } - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onKill(@Nonnull EntityDeathEvent event) { + if (!isEnabled() || !ChallengeAPI.isStarted()) return; + LivingEntity entity = event.getEntity(); + if (entity.getType() != this.entity) return; + if (environment != null && event.getEntity().getWorld().getEnvironment() != environment) + return; + if (oneWinner) { + winner = event.getEntity().getKiller(); + if (killerNeeded && winner == null) { + return; + } + } + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java index 8cd2371a7..6b772881a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java @@ -19,83 +19,83 @@ public abstract class KillMobsGoal extends SettingGoal { - protected static List entitiesKilled; - - protected final List entitiesToKill; - - public KillMobsGoal(List entitiesKilled) { - this.entitiesToKill = entitiesKilled; - resetEntitiesToKill(); - } - - public abstract Message getBossbarMessage(); - - private void resetEntitiesToKill() { - entitiesKilled = new LinkedList<>(); - } - - @Override - public void getWinnersOnEnd(@NotNull List winners) { - - } - - @Override - protected void onEnable() { - bossbar.setContent((bar, player) -> { - float i = 1 - ((float) getEntitiesLeftToKill().size() / (float) entitiesToKill.size()); - bar.setProgress(i); - bar.setColor(BarColor.GREEN); - bar.setTitle(getBossbarMessage().asString(getEntitiesKilled().size(), entitiesToKill.size())); - }); - bossbar.show(); - } - - @Override - protected void onDisable() { - bossbar.hide(); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDeath(@Nonnull EntityDeathEvent event) { - if (!shouldExecuteEffect()) return; - if (event.getEntityType() != EntityType.WITHER && event.getEntityType() != EntityType.ENDER_DRAGON && event.getEntityType() != EntityType.ELDER_GUARDIAN) { - if (event.getEntity().getKiller() == null) return; - } - if (entitiesKilled.contains(event.getEntityType())) return; - entitiesKilled.add(event.getEntityType()); - if (entitiesToKill.contains(event.getEntityType())) { - Message.forName("mob-kill").broadcast(Prefix.CHALLENGES, event.getEntityType(), getEntitiesKilled().size(), entitiesToKill.size()); - bossbar.update(); - if (!getEntitiesLeftToKill().isEmpty()) return; - resetEntitiesToKill(); - ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); - } - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - - document.set("entities", entitiesKilled); - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - - entitiesKilled = document.getEnumList("entities", EntityType.class); - } - - public List getEntitiesKilled() { - LinkedList entityTypes = new LinkedList<>(entitiesKilled); - entityTypes.removeIf(type -> !entitiesToKill.contains(type)); - return entityTypes; - } - - public List getEntitiesLeftToKill() { - LinkedList entityTypes = new LinkedList<>(entitiesToKill); - entityTypes.removeAll(entitiesKilled); - return entityTypes; - } + protected static List entitiesKilled; + + protected final List entitiesToKill; + + public KillMobsGoal(List entitiesKilled) { + this.entitiesToKill = entitiesKilled; + resetEntitiesToKill(); + } + + public abstract Message getBossbarMessage(); + + private void resetEntitiesToKill() { + entitiesKilled = new LinkedList<>(); + } + + @Override + public void getWinnersOnEnd(@NotNull List winners) { + + } + + @Override + protected void onEnable() { + bossbar.setContent((bar, player) -> { + float i = 1 - ((float) getEntitiesLeftToKill().size() / (float) entitiesToKill.size()); + bar.setProgress(i); + bar.setColor(BarColor.GREEN); + bar.setTitle(getBossbarMessage().asString(getEntitiesKilled().size(), entitiesToKill.size())); + }); + bossbar.show(); + } + + @Override + protected void onDisable() { + bossbar.hide(); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDeath(@Nonnull EntityDeathEvent event) { + if (!shouldExecuteEffect()) return; + if (event.getEntityType() != EntityType.WITHER && event.getEntityType() != EntityType.ENDER_DRAGON && event.getEntityType() != EntityType.ELDER_GUARDIAN) { + if (event.getEntity().getKiller() == null) return; + } + if (entitiesKilled.contains(event.getEntityType())) return; + entitiesKilled.add(event.getEntityType()); + if (entitiesToKill.contains(event.getEntityType())) { + Message.forName("mob-kill").broadcast(Prefix.CHALLENGES, event.getEntityType(), getEntitiesKilled().size(), entitiesToKill.size()); + bossbar.update(); + if (!getEntitiesLeftToKill().isEmpty()) return; + resetEntitiesToKill(); + ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); + } + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + + document.set("entities", entitiesKilled); + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + + entitiesKilled = document.getEnumList("entities", EntityType.class); + } + + public List getEntitiesKilled() { + LinkedList entityTypes = new LinkedList<>(entitiesKilled); + entityTypes.removeIf(type -> !entitiesToKill.contains(type)); + return entityTypes; + } + + public List getEntitiesLeftToKill() { + LinkedList entityTypes = new LinkedList<>(entitiesToKill); + entityTypes.removeAll(entitiesKilled); + return entityTypes; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java index cf18fb51d..34a101526 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java @@ -11,26 +11,26 @@ import javax.annotation.Nullable; public abstract class MenuGoal extends MenuSetting implements IGoal { - public MenuGoal(@NotNull MenuType menu, @NotNull Message title) { - super(menu, title); - } + public MenuGoal(@NotNull MenuType menu, @NotNull Message title) { + super(menu, title); + } - @Override - public final void setEnabled(boolean enabled) { - if (isEnabled() == enabled) return; - GoalHelper.handleSetEnabled(this, enabled); - super.setEnabled(enabled); - } + @Override + public final void setEnabled(boolean enabled) { + if (isEnabled() == enabled) return; + GoalHelper.handleSetEnabled(this, enabled); + super.setEnabled(enabled); + } - @Nonnull - @Override - public SoundSample getStartSound() { - return SoundSample.DRAGON_BREATH; - } + @Nonnull + @Override + public SoundSample getStartSound() { + return SoundSample.DRAGON_BREATH; + } - @Nullable - @Override - public SoundSample getWinSound() { - return SoundSample.WIN; - } + @Nullable + @Override + public SoundSample getWinSound() { + return SoundSample.WIN; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java index 4b7427825..cee709060 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java @@ -31,598 +31,598 @@ public abstract class MenuSetting extends Setting { - private final Map settings = new LinkedHashMap<>(); - private final List inventories = new ArrayList<>(); - private final Message title; - - public MenuSetting(@Nonnull MenuType menu, @Nonnull Message title) { - super(menu); - this.title = title; - } - - @Nonnull - public static int[] getSlots(int amount) { - switch (amount) { - default: - return new int[0]; - case 1: - return new int[]{13}; - case 2: - return new int[]{12, 14}; - case 3: - return new int[]{11, 13, 15}; - case 4: - return new int[]{10, 12, 14, 16}; - } - } - - protected final void generateInventories() { - - inventories.clear(); - - int maxRowLength = 4; - int page = 0; - int index = 0; - - Collection settings = this.settings.values(); - - int pagesTotal = settings.size() / maxRowLength; - if (settings.size() % maxRowLength != 0) pagesTotal++; - - for (SubSetting setting : settings) { - - if (index >= maxRowLength) { - index = 0; - createNewInventory(++page, pagesTotal); - } else if (inventories.isEmpty()) { - createNewInventory(page, pagesTotal); - } - - int added = page * maxRowLength + index; - int left = settings.size() - added; - int fitOnThisPage = index + left; - if (fitOnThisPage > 4) fitOnThisPage = 4; - - int[] slots = getSlots(fitOnThisPage); - - int displaySlot = slots[index]; - - setting.setPage(page); - setting.setSlot(displaySlot); - setting.updateItems(); - - index++; - - } - - InventoryUtils.setNavigationItemsToInventory(inventories, SettingsMenuGenerator.NAVIGATION_SLOTS, true); - - } - - @Nonnull - private Inventory createNewInventory(int page, int pagesAmount) { - Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, SettingsMenuGenerator.SIZE, InventoryTitleManager.getMenuSettingTitle(getType(), title.asString(), page, pagesAmount > 1)); - InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); - inventories.add(inventory); - return inventory; - } - - protected final void registerSetting(@Nonnull String name, @Nonnull SubSetting setting) { - if (name.equals("enabled")) throw new IllegalArgumentException(); - settings.put(name, setting); - Challenges.getInstance().registerListener(setting); - } - - public final SubSetting getSetting(@Nonnull String name) { - return settings.get(name); - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - if (info.isUpperItemClick()) { - super.handleClick(info); - } else if (isEnabled() && !info.isRightClick()) { - openMenu(info); - } else { - super.handleClick(info); - } - } - - private void openMenu(@Nonnull ChallengeMenuClickInfo event) { - MenuPosition position = MenuPosition.get(event.getPlayer()); - if (position == null) position = new EmptyMenuPosition(); - Inventory inventory = event.getInventory(); - SoundSample.CLICK.play(event.getPlayer()); - open(event.getPlayer(), inventory, position, 0); - } - - private void open(@Nonnull Player player, @Nonnull Inventory inventory, @Nonnull MenuPosition position, int page) { - if (inventories.isEmpty()) generateInventories(); - if (inventories.isEmpty()) { - SoundSample.BASS_OFF.play(player); - return; - } - if (page >= inventories.size()) page = inventories.size() - 1; - Inventory menu = inventories.get(page); - MenuPosition.set(player, new SettingMenuPosition(position, inventory, page)); - player.openInventory(menu); - } - - @Nonnull - @Override - public final ItemBuilder createSettingsItem() { - return isEnabled() ? DefaultItem.customize() : DefaultItem.disabled(); - } - - @Override - public void writeSettings(@Nonnull Document document) { - document.set("enabled", isEnabled()); - for (Entry entry : settings.entrySet()) { - Document subDocument = document.getDocument(entry.getKey()); - entry.getValue().writeSettings(subDocument); - } - } - - @Override - public void loadSettings(@Nonnull Document document) { - setEnabled(document.getBoolean("enabled")); - for (Entry entry : settings.entrySet()) { - if (!document.contains(entry.getKey())) continue; - Document subDocument = document.getDocument(entry.getKey()); - entry.getValue().loadSettings(subDocument); - } - } - - @Override - public void restoreDefaults() { - super.restoreDefaults(); - settings.values().forEach(SubSetting::restoreDefaults); - } - - public abstract class SubSetting implements Listener { - - private int page = -1, slot = -1; - - private void setPage(int page) { - this.page = page; - } - - private void setSlot(int slot) { - this.slot = slot; - } - - public final void updateItems() { - if (inventories.isEmpty()) return; // Menu not generated yet, nothing to update here - if (page == -1 || slot == -1) return; // Invalid slots, menu not generated yet - - Inventory inventory = inventories.get(page); - - inventory.setItem(slot, getDisplayItem().hideAttributes().build()); - inventory.setItem(slot + 9, buildSettingsItem()); - } - - @Nonnull - private ItemStack buildSettingsItem() { - ItemBuilder item = getSettingsItem(); - String[] description = getSettingsDescription(); - if (description != null && isEnabled()) { - item.appendLore(" "); - item.appendLore(description); - } - - return item.build(); - } - - @Nonnull - public abstract ItemBuilder getDisplayItem(); - - @Nonnull - public abstract ItemBuilder getSettingsItem(); - - @Nullable - protected abstract String[] getSettingsDescription(); - - public boolean isEnabled() { - return MenuSetting.this.isEnabled() && getAsBoolean(); - } - - public abstract int getAsInt(); - - public abstract boolean getAsBoolean(); - - public abstract void restoreDefaults(); - - public abstract void loadSettings(@Nonnull Document document); - - public abstract void writeSettings(@Nonnull Document document); - - public abstract void handleClick(@Nonnull ChallengeMenuClickInfo info); - - } - - public class BooleanSubSetting extends SubSetting { - - private final Supplier item; - private final Supplier description; - private final boolean enabledByDefault; - private boolean enabled; - - public BooleanSubSetting(@Nonnull Supplier item) { - this(item, () -> null); - } - - public BooleanSubSetting(@Nonnull Supplier item, boolean enabledByDefault) { - this(item, () -> null, enabledByDefault); - } - - public BooleanSubSetting(@Nonnull Supplier item, @Nonnull Supplier description) { - this(item, description, false); - } - - public BooleanSubSetting(@Nonnull Supplier item, @Nonnull Supplier description, boolean enabledByDefault) { - this.item = item; - this.description = description; - this.enabledByDefault = enabledByDefault; - this.setEnabled(enabledByDefault); - } + private final Map settings = new LinkedHashMap<>(); + private final List inventories = new ArrayList<>(); + private final Message title; + + public MenuSetting(@Nonnull MenuType menu, @Nonnull Message title) { + super(menu); + this.title = title; + } + + @Nonnull + public static int[] getSlots(int amount) { + switch (amount) { + default: + return new int[0]; + case 1: + return new int[]{13}; + case 2: + return new int[]{12, 14}; + case 3: + return new int[]{11, 13, 15}; + case 4: + return new int[]{10, 12, 14, 16}; + } + } + + protected final void generateInventories() { + + inventories.clear(); + + int maxRowLength = 4; + int page = 0; + int index = 0; + + Collection settings = this.settings.values(); + + int pagesTotal = settings.size() / maxRowLength; + if (settings.size() % maxRowLength != 0) pagesTotal++; + + for (SubSetting setting : settings) { + + if (index >= maxRowLength) { + index = 0; + createNewInventory(++page, pagesTotal); + } else if (inventories.isEmpty()) { + createNewInventory(page, pagesTotal); + } + + int added = page * maxRowLength + index; + int left = settings.size() - added; + int fitOnThisPage = index + left; + if (fitOnThisPage > 4) fitOnThisPage = 4; + + int[] slots = getSlots(fitOnThisPage); + + int displaySlot = slots[index]; + + setting.setPage(page); + setting.setSlot(displaySlot); + setting.updateItems(); + + index++; + + } + + InventoryUtils.setNavigationItemsToInventory(inventories, SettingsMenuGenerator.NAVIGATION_SLOTS, true); + + } + + @Nonnull + private Inventory createNewInventory(int page, int pagesAmount) { + Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, SettingsMenuGenerator.SIZE, InventoryTitleManager.getMenuSettingTitle(getType(), title.asString(), page, pagesAmount > 1)); + InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); + inventories.add(inventory); + return inventory; + } + + protected final void registerSetting(@Nonnull String name, @Nonnull SubSetting setting) { + if (name.equals("enabled")) throw new IllegalArgumentException(); + settings.put(name, setting); + Challenges.getInstance().registerListener(setting); + } + + public final SubSetting getSetting(@Nonnull String name) { + return settings.get(name); + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + if (info.isUpperItemClick()) { + super.handleClick(info); + } else if (isEnabled() && !info.isRightClick()) { + openMenu(info); + } else { + super.handleClick(info); + } + } + + private void openMenu(@Nonnull ChallengeMenuClickInfo event) { + MenuPosition position = MenuPosition.get(event.getPlayer()); + if (position == null) position = new EmptyMenuPosition(); + Inventory inventory = event.getInventory(); + SoundSample.CLICK.play(event.getPlayer()); + open(event.getPlayer(), inventory, position, 0); + } + + private void open(@Nonnull Player player, @Nonnull Inventory inventory, @Nonnull MenuPosition position, int page) { + if (inventories.isEmpty()) generateInventories(); + if (inventories.isEmpty()) { + SoundSample.BASS_OFF.play(player); + return; + } + if (page >= inventories.size()) page = inventories.size() - 1; + Inventory menu = inventories.get(page); + MenuPosition.set(player, new SettingMenuPosition(position, inventory, page)); + player.openInventory(menu); + } + + @Nonnull + @Override + public final ItemBuilder createSettingsItem() { + return isEnabled() ? DefaultItem.customize() : DefaultItem.disabled(); + } + + @Override + public void writeSettings(@Nonnull Document document) { + document.set("enabled", isEnabled()); + for (Entry entry : settings.entrySet()) { + Document subDocument = document.getDocument(entry.getKey()); + entry.getValue().writeSettings(subDocument); + } + } + + @Override + public void loadSettings(@Nonnull Document document) { + setEnabled(document.getBoolean("enabled")); + for (Entry entry : settings.entrySet()) { + if (!document.contains(entry.getKey())) continue; + Document subDocument = document.getDocument(entry.getKey()); + entry.getValue().loadSettings(subDocument); + } + } + + @Override + public void restoreDefaults() { + super.restoreDefaults(); + settings.values().forEach(SubSetting::restoreDefaults); + } + + public abstract class SubSetting implements Listener { + + private int page = -1, slot = -1; + + private void setPage(int page) { + this.page = page; + } + + private void setSlot(int slot) { + this.slot = slot; + } + + public final void updateItems() { + if (inventories.isEmpty()) return; // Menu not generated yet, nothing to update here + if (page == -1 || slot == -1) return; // Invalid slots, menu not generated yet + + Inventory inventory = inventories.get(page); + + inventory.setItem(slot, getDisplayItem().hideAttributes().build()); + inventory.setItem(slot + 9, buildSettingsItem()); + } + + @Nonnull + private ItemStack buildSettingsItem() { + ItemBuilder item = getSettingsItem(); + String[] description = getSettingsDescription(); + if (description != null && isEnabled()) { + item.appendLore(" "); + item.appendLore(description); + } + + return item.build(); + } + + @Nonnull + public abstract ItemBuilder getDisplayItem(); + + @Nonnull + public abstract ItemBuilder getSettingsItem(); + + @Nullable + protected abstract String[] getSettingsDescription(); + + public boolean isEnabled() { + return MenuSetting.this.isEnabled() && getAsBoolean(); + } + + public abstract int getAsInt(); + + public abstract boolean getAsBoolean(); + + public abstract void restoreDefaults(); + + public abstract void loadSettings(@Nonnull Document document); + + public abstract void writeSettings(@Nonnull Document document); + + public abstract void handleClick(@Nonnull ChallengeMenuClickInfo info); + + } + + public class BooleanSubSetting extends SubSetting { + + private final Supplier item; + private final Supplier description; + private final boolean enabledByDefault; + private boolean enabled; + + public BooleanSubSetting(@Nonnull Supplier item) { + this(item, () -> null); + } + + public BooleanSubSetting(@Nonnull Supplier item, boolean enabledByDefault) { + this(item, () -> null, enabledByDefault); + } + + public BooleanSubSetting(@Nonnull Supplier item, @Nonnull Supplier description) { + this(item, description, false); + } + + public BooleanSubSetting(@Nonnull Supplier item, @Nonnull Supplier description, boolean enabledByDefault) { + this.item = item; + this.description = description; + this.enabledByDefault = enabledByDefault; + this.setEnabled(enabledByDefault); + } - @Nonnull - @Override - public ItemBuilder getDisplayItem() { - return item.get(); - } + @Nonnull + @Override + public ItemBuilder getDisplayItem() { + return item.get(); + } - @Nonnull - @Override - public ItemBuilder getSettingsItem() { - return DefaultItem.status(enabled); - } + @Nonnull + @Override + public ItemBuilder getSettingsItem() { + return DefaultItem.status(enabled); + } - @Nullable - @Override - protected String[] getSettingsDescription() { - return description.get(); - } + @Nullable + @Override + protected String[] getSettingsDescription() { + return description.get(); + } - @Override - public int getAsInt() { - return enabled ? 1 : 0; - } + @Override + public int getAsInt() { + return enabled ? 1 : 0; + } - @Override - public boolean getAsBoolean() { - return enabled; - } + @Override + public boolean getAsBoolean() { + return enabled; + } - @Override - public void restoreDefaults() { - this.setEnabled(enabledByDefault); - } + @Override + public void restoreDefaults() { + this.setEnabled(enabledByDefault); + } - @Nonnull - public BooleanSubSetting setEnabled(boolean enabled) { - if (this.enabled == enabled) return this; - this.enabled = enabled; + @Nonnull + public BooleanSubSetting setEnabled(boolean enabled) { + if (this.enabled == enabled) return this; + this.enabled = enabled; - if (enabled) this.onEnable(); - else this.onDisable(); + if (enabled) this.onEnable(); + else this.onDisable(); - this.updateItems(); - return this; - } + this.updateItems(); + return this; + } - @Override - public final void handleClick(@Nonnull ChallengeMenuClickInfo info) { - this.setEnabled(!enabled); - SoundSample.playStatusSound(info.getPlayer(), enabled); - } + @Override + public final void handleClick(@Nonnull ChallengeMenuClickInfo info) { + this.setEnabled(!enabled); + SoundSample.playStatusSound(info.getPlayer(), enabled); + } - @Override - public void loadSettings(@Nonnull Document document) { - this.setEnabled(document.getBoolean("enabled")); - } + @Override + public void loadSettings(@Nonnull Document document) { + this.setEnabled(document.getBoolean("enabled")); + } - @Override - public void writeSettings(@Nonnull Document document) { - document.set("enabled", enabled); - } + @Override + public void writeSettings(@Nonnull Document document) { + document.set("enabled", enabled); + } - protected void onEnable() { - } + protected void onEnable() { + } - protected void onDisable() { - } - - } - - public class NumberSubSetting extends SubSetting { - - private final Supplier item; - private final Function description; - private final Function name; - private final int max, min; - private final int defaultValue; - @Getter + protected void onDisable() { + } + + } + + public class NumberSubSetting extends SubSetting { + + private final Supplier item; + private final Function description; + private final Function name; + private final int max, min; + private final int defaultValue; + @Getter private int value; - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name) { - this(item, description, name, 64); - } - - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int max) { - this(item, description, name, max, 1); - } - - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max) { - this(item, description, name, min, max, min); - } - - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max, int defaultValue) { - if (max <= min) throw new IllegalArgumentException("max <= min"); - if (min < 0) throw new IllegalArgumentException("min < 0"); - if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); - if (defaultValue < min) throw new IllegalArgumentException("defaultValue < min"); - this.value = defaultValue; - this.defaultValue = defaultValue; - this.max = max; - this.min = min; - this.item = item; - this.description = description; - this.name = name; - } - - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description) { - this(item, description, null, 64, 1); - } - - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, int max) { - this(item, description, null, max, 1); - } - - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max) { - this(item, description, null, min, max, min); - } - - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max, int defaultValue) { - this(item, description, null, min, max, defaultValue); - } - - public NumberSubSetting(@Nonnull Supplier item) { - this(item, value -> null); - } - - public NumberSubSetting(@Nonnull Supplier item, int max) { - this(item, value -> null, max); - } - - public NumberSubSetting(@Nonnull Supplier item, int min, int max) { - this(item, value -> null, min, max); - } - - public NumberSubSetting(@Nonnull Supplier item, int min, int max, int defaultValue) { - this(item, value -> null, min, max, defaultValue); - } - - @Nonnull - @Override - public ItemBuilder getDisplayItem() { - return item.get(); - } - - @Nonnull - @Override - public ItemBuilder getSettingsItem() { - if (name != null) - return DefaultItem.create(Material.STONE_BUTTON, name.apply(getValue())).amount(getValue()); - - return DefaultItem.value(value); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return description.apply(getValue()); - } - - @Override - public void restoreDefaults() { - this.setValue(defaultValue); - } + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name) { + this(item, description, name, 64); + } + + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int max) { + this(item, description, name, max, 1); + } + + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max) { + this(item, description, name, min, max, min); + } + + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max, int defaultValue) { + if (max <= min) throw new IllegalArgumentException("max <= min"); + if (min < 0) throw new IllegalArgumentException("min < 0"); + if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); + if (defaultValue < min) throw new IllegalArgumentException("defaultValue < min"); + this.value = defaultValue; + this.defaultValue = defaultValue; + this.max = max; + this.min = min; + this.item = item; + this.description = description; + this.name = name; + } + + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description) { + this(item, description, null, 64, 1); + } + + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, int max) { + this(item, description, null, max, 1); + } + + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max) { + this(item, description, null, min, max, min); + } + + public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max, int defaultValue) { + this(item, description, null, min, max, defaultValue); + } + + public NumberSubSetting(@Nonnull Supplier item) { + this(item, value -> null); + } + + public NumberSubSetting(@Nonnull Supplier item, int max) { + this(item, value -> null, max); + } + + public NumberSubSetting(@Nonnull Supplier item, int min, int max) { + this(item, value -> null, min, max); + } + + public NumberSubSetting(@Nonnull Supplier item, int min, int max, int defaultValue) { + this(item, value -> null, min, max, defaultValue); + } + + @Nonnull + @Override + public ItemBuilder getDisplayItem() { + return item.get(); + } + + @Nonnull + @Override + public ItemBuilder getSettingsItem() { + if (name != null) + return DefaultItem.create(Material.STONE_BUTTON, name.apply(getValue())).amount(getValue()); + + return DefaultItem.value(value); + } + + @Nullable + @Override + protected String[] getSettingsDescription() { + return description.apply(getValue()); + } + + @Override + public void restoreDefaults() { + this.setValue(defaultValue); + } public void setValue(int value) { - if (this.value == value) return; - this.value = value; - - updateItems(); - onValueChange(); - } - - @Override - public int getAsInt() { - return value; - } - - @Override - public boolean getAsBoolean() { - return value > 0; - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - int amount = info.isShiftClick() ? 10 : 1; - int newValue = value; - if (info.isRightClick()) { - newValue -= amount; - } else { - newValue += amount; - } - - if (newValue > max) - newValue = min; - if (newValue < min) - newValue = max; - - this.setValue(newValue); - SoundSample.CLICK.play(info.getPlayer()); - } - - @Override - public void loadSettings(@Nonnull Document document) { - this.setValue(document.getInt("value")); - } - - @Override - public void writeSettings(@Nonnull Document document) { - document.set("value", value); - } - - protected void onValueChange() { - } - - } - - public class NumberAndBooleanSubSetting extends NumberSubSetting { - - private final boolean enabledByDefault = false; // Implement in future - private boolean enabled; - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name) { - super(item, description, name); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int max) { - super(item, description, name, max); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max) { - super(item, description, name, min, max); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max, int defaultValue) { - super(item, description, name, min, max, defaultValue); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description) { - super(item, description); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, int max) { - super(item, description, max); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max) { - super(item, description, min, max); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max, int defaultValue) { - super(item, description, min, max, defaultValue); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item) { - super(item); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, int max) { - super(item, max); - } - - public NumberAndBooleanSubSetting(@Nonnull Supplier item, int min, int max) { - super(item, min, max); - } - - @Override - public void restoreDefaults() { - super.restoreDefaults(); - this.setEnabled(enabledByDefault); - } - - public void setEnabled(boolean enabled) { - if (this.enabled == enabled) return; - this.enabled = enabled; - - if (enabled) this.onEnable(); - else this.onDisable(); - - this.updateItems(); - } - - @Override - public boolean getAsBoolean() { - return enabled; - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - if (info.isUpperItemClick() || !enabled) { - this.setEnabled(!enabled); - SoundSample.playStatusSound(info.getPlayer(), enabled); - } else { - super.handleClick(info); - } - } - - @Override - public void loadSettings(@Nonnull Document document) { - super.loadSettings(document); - this.setEnabled(document.getBoolean("enabled")); - } - - @Override - public void writeSettings(@Nonnull Document document) { - super.writeSettings(document); - document.set("enabled", enabled); - } - - protected void onEnable() { - } - - protected void onDisable() { - } - - } - - private final class SettingMenuPosition implements MenuPosition { - - private final MenuPosition before; - private final Inventory inventoryBefore; - private final int page; - - public SettingMenuPosition(@Nonnull MenuPosition before, @Nonnull Inventory inventoryBefore, int page) { - this.before = before; - this.inventoryBefore = inventoryBefore; - this.page = page; - } - - @Override - public void handleClick(@Nonnull MenuClickInfo info) { - - if (info.getSlot() == SettingsMenuGenerator.NAVIGATION_SLOTS[0]) { - if (page == 0) { - MenuPosition.set(info.getPlayer(), before); - info.getPlayer().openInventory(inventoryBefore); - } else { - open(info.getPlayer(), inventoryBefore, before, page - 1); - } - SoundSample.CLICK.play(info.getPlayer()); - return; - } else if (info.getSlot() == SettingsMenuGenerator.NAVIGATION_SLOTS[1]) { - open(info.getPlayer(), inventoryBefore, before, page + 1); - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - for (SubSetting setting : settings.values()) { - if (setting.page != page) continue; - if (info.getSlot() != setting.slot && info.getSlot() != setting.slot + 9) continue; - - setting.handleClick(new ChallengeMenuClickInfo(info, info.getSlot() == setting.slot)); - return; - } - - SoundSample.CLICK.play(info.getPlayer()); - - } - - } + if (this.value == value) return; + this.value = value; + + updateItems(); + onValueChange(); + } + + @Override + public int getAsInt() { + return value; + } + + @Override + public boolean getAsBoolean() { + return value > 0; + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + int amount = info.isShiftClick() ? 10 : 1; + int newValue = value; + if (info.isRightClick()) { + newValue -= amount; + } else { + newValue += amount; + } + + if (newValue > max) + newValue = min; + if (newValue < min) + newValue = max; + + this.setValue(newValue); + SoundSample.CLICK.play(info.getPlayer()); + } + + @Override + public void loadSettings(@Nonnull Document document) { + this.setValue(document.getInt("value")); + } + + @Override + public void writeSettings(@Nonnull Document document) { + document.set("value", value); + } + + protected void onValueChange() { + } + + } + + public class NumberAndBooleanSubSetting extends NumberSubSetting { + + private final boolean enabledByDefault = false; // Implement in future + private boolean enabled; + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name) { + super(item, description, name); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int max) { + super(item, description, name, max); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max) { + super(item, description, name, min, max); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max, int defaultValue) { + super(item, description, name, min, max, defaultValue); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description) { + super(item, description); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, int max) { + super(item, description, max); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max) { + super(item, description, min, max); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max, int defaultValue) { + super(item, description, min, max, defaultValue); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item) { + super(item); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, int max) { + super(item, max); + } + + public NumberAndBooleanSubSetting(@Nonnull Supplier item, int min, int max) { + super(item, min, max); + } + + @Override + public void restoreDefaults() { + super.restoreDefaults(); + this.setEnabled(enabledByDefault); + } + + public void setEnabled(boolean enabled) { + if (this.enabled == enabled) return; + this.enabled = enabled; + + if (enabled) this.onEnable(); + else this.onDisable(); + + this.updateItems(); + } + + @Override + public boolean getAsBoolean() { + return enabled; + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + if (info.isUpperItemClick() || !enabled) { + this.setEnabled(!enabled); + SoundSample.playStatusSound(info.getPlayer(), enabled); + } else { + super.handleClick(info); + } + } + + @Override + public void loadSettings(@Nonnull Document document) { + super.loadSettings(document); + this.setEnabled(document.getBoolean("enabled")); + } + + @Override + public void writeSettings(@Nonnull Document document) { + super.writeSettings(document); + document.set("enabled", enabled); + } + + protected void onEnable() { + } + + protected void onDisable() { + } + + } + + private final class SettingMenuPosition implements MenuPosition { + + private final MenuPosition before; + private final Inventory inventoryBefore; + private final int page; + + public SettingMenuPosition(@Nonnull MenuPosition before, @Nonnull Inventory inventoryBefore, int page) { + this.before = before; + this.inventoryBefore = inventoryBefore; + this.page = page; + } + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + + if (info.getSlot() == SettingsMenuGenerator.NAVIGATION_SLOTS[0]) { + if (page == 0) { + MenuPosition.set(info.getPlayer(), before); + info.getPlayer().openInventory(inventoryBefore); + } else { + open(info.getPlayer(), inventoryBefore, before, page - 1); + } + SoundSample.CLICK.play(info.getPlayer()); + return; + } else if (info.getSlot() == SettingsMenuGenerator.NAVIGATION_SLOTS[1]) { + open(info.getPlayer(), inventoryBefore, before, page + 1); + SoundSample.CLICK.play(info.getPlayer()); + return; + } + + for (SubSetting setting : settings.values()) { + if (setting.page != page) continue; + if (info.getSlot() != setting.slot && info.getSlot() != setting.slot + 9) continue; + + setting.handleClick(new ChallengeMenuClickInfo(info, info.getSlot() == setting.slot)); + return; + } + + SoundSample.CLICK.play(info.getPlayer()); + + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java index a9091053d..1c7edca94 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java @@ -14,104 +14,104 @@ public abstract class Modifier extends AbstractChallenge implements IModifier { - private final int max, min; - private final int defaultValue; - private int value; - - public Modifier(@Nonnull MenuType menu) { - this(menu, 64); - } - - public Modifier(@Nonnull MenuType menu, int max) { - this(menu, 1, max); - } - - public Modifier(@Nonnull MenuType menu, int min, int max) { - this(menu, min, max, min); - } - - public Modifier(@Nonnull MenuType menu, int min, int max, int defaultValue) { - super(menu); - if (max < min) throw new IllegalArgumentException("max < min"); - if (min < 0) throw new IllegalArgumentException("min < 0"); - if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); - if (defaultValue < min) throw new IllegalArgumentException("defaultValue < min"); - this.max = max; - this.min = min; - this.value = defaultValue; - this.defaultValue = defaultValue; - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.value(value); - } - - @Override - public void restoreDefaults() { - setValue(defaultValue); - } - - @Override - @Nonnegative - public final int getValue() { - return value; - } - - @Override - public void setValue(int value) { - if (value > max) throw new IllegalArgumentException("value > max"); - if (value < min) throw new IllegalArgumentException("value < min"); - this.value = value; - - try { - if (isEnabled()) onValueChange(); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Error while modifying value of Setting {}", getClass().getSimpleName(), exception); - } - - updateItems(); - } - - @Override - @Nonnegative - public final int getMaxValue() { - return max; - } - - @Override - @Nonnegative - public final int getMinValue() { - return min; - } - - @Override - public boolean isEnabled() { - return true; - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - ChallengeHelper.handleModifierClick(info, this); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this); - } - - protected void onValueChange() { - } - - @Override - public void loadSettings(@Nonnull Document document) { - setValue(document.getInt("value", value)); - } - - @Override - public void writeSettings(@Nonnull Document document) { - document.set("value", value); - } + private final int max, min; + private final int defaultValue; + private int value; + + public Modifier(@Nonnull MenuType menu) { + this(menu, 64); + } + + public Modifier(@Nonnull MenuType menu, int max) { + this(menu, 1, max); + } + + public Modifier(@Nonnull MenuType menu, int min, int max) { + this(menu, min, max, min); + } + + public Modifier(@Nonnull MenuType menu, int min, int max, int defaultValue) { + super(menu); + if (max < min) throw new IllegalArgumentException("max < min"); + if (min < 0) throw new IllegalArgumentException("min < 0"); + if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); + if (defaultValue < min) throw new IllegalArgumentException("defaultValue < min"); + this.max = max; + this.min = min; + this.value = defaultValue; + this.defaultValue = defaultValue; + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + return DefaultItem.value(value); + } + + @Override + public void restoreDefaults() { + setValue(defaultValue); + } + + @Override + @Nonnegative + public final int getValue() { + return value; + } + + @Override + public void setValue(int value) { + if (value > max) throw new IllegalArgumentException("value > max"); + if (value < min) throw new IllegalArgumentException("value < min"); + this.value = value; + + try { + if (isEnabled()) onValueChange(); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Error while modifying value of Setting {}", getClass().getSimpleName(), exception); + } + + updateItems(); + } + + @Override + @Nonnegative + public final int getMaxValue() { + return max; + } + + @Override + @Nonnegative + public final int getMinValue() { + return min; + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + ChallengeHelper.handleModifierClick(info, this); + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this); + } + + protected void onValueChange() { + } + + @Override + public void loadSettings(@Nonnull Document document) { + setValue(document.getInt("value", value)); + } + + @Override + public void writeSettings(@Nonnull Document document) { + document.set("value", value); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java index b9a9e3276..4a71765d2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; import net.anweisen.utilities.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -9,97 +8,96 @@ import javax.annotation.Nonnegative; import javax.annotation.Nonnull; -import javax.annotation.Nullable; public abstract class ModifierCollectionGoal extends CollectionGoal implements IModifier { - private final int max, min; - private final int defaultValue; - private int value; - - public ModifierCollectionGoal(int min, int max, @Nonnull Object[] target) { - this(min, max, min, target); - } - - public ModifierCollectionGoal(int min, int max, int defaultValue, @Nonnull Object[] target) { - super(target); - if (max < min) throw new IllegalArgumentException("max < min"); - if (min < 0) throw new IllegalArgumentException("min < 0"); - if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); - if (defaultValue < min) throw new IllegalArgumentException("defaultValue < min"); - this.max = max; - this.min = min; - this.value = defaultValue; - this.defaultValue = defaultValue; - } - - @Override - public void restoreDefaults() { - setValue(defaultValue); - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - ChallengeHelper.handleModifierClick(info, this); - } - - @Override - public boolean isEnabled() { - return true; - } - - @Override - public void setEnabled(boolean enabled) { - if (isEnabled() == enabled) return; - GoalHelper.handleSetEnabled(this, enabled); - super.setEnabled(enabled); - } - - @Override - @Nonnegative - public final int getValue() { - return value; - } - - @Override - public void setValue(int value) { - if (value > max) throw new IllegalArgumentException("value > max"); - if (value < min) throw new IllegalArgumentException("value < min"); - this.value = value; - - if (isEnabled()) onValueChange(); - - updateItems(); - } - - @Override - @Nonnegative - public final int getMaxValue() { - return max; - } - - @Override - @Nonnegative - public final int getMinValue() { - return min; - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, this); - } - - protected void onValueChange() { - } - - @Override - public void loadSettings(@Nonnull Document document) { - setValue(document.getInt("value", value)); - } - - @Override - public void writeSettings(@Nonnull Document document) { - document.set("value", value); - } + private final int max, min; + private final int defaultValue; + private int value; + + public ModifierCollectionGoal(int min, int max, @Nonnull Object[] target) { + this(min, max, min, target); + } + + public ModifierCollectionGoal(int min, int max, int defaultValue, @Nonnull Object[] target) { + super(target); + if (max < min) throw new IllegalArgumentException("max < min"); + if (min < 0) throw new IllegalArgumentException("min < 0"); + if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); + if (defaultValue < min) throw new IllegalArgumentException("defaultValue < min"); + this.max = max; + this.min = min; + this.value = defaultValue; + this.defaultValue = defaultValue; + } + + @Override + public void restoreDefaults() { + setValue(defaultValue); + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + ChallengeHelper.handleModifierClick(info, this); + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public void setEnabled(boolean enabled) { + if (isEnabled() == enabled) return; + GoalHelper.handleSetEnabled(this, enabled); + super.setEnabled(enabled); + } + + @Override + @Nonnegative + public final int getValue() { + return value; + } + + @Override + public void setValue(int value) { + if (value > max) throw new IllegalArgumentException("value > max"); + if (value < min) throw new IllegalArgumentException("value < min"); + this.value = value; + + if (isEnabled()) onValueChange(); + + updateItems(); + } + + @Override + @Nonnegative + public final int getMaxValue() { + return max; + } + + @Override + @Nonnegative + public final int getMinValue() { + return min; + } + + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, this); + } + + protected void onValueChange() { + } + + @Override + public void loadSettings(@Nonnull Document document) { + setValue(document.getInt("value", value)); + } + + @Override + public void writeSettings(@Nonnull Document document) { + document.set("value", value); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java index a10551f4e..33b52d8a5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java @@ -20,179 +20,179 @@ public abstract class NetherPortalSpawnSetting extends OneEnabledSetting { - private static final String id = "netherportal_handle"; - - private final Map netherPortalsByOverworldPortals = new HashMap<>(); - private final StructureType structureType; - private final Collection groundMaterial; - private final String unableToFindMessage; - - public NetherPortalSpawnSetting(@Nonnull MenuType menu, @Nonnull StructureType structureType, @Nonnull String unableToFindMessage, @Nonnull Material... groundMaterial) { - super(menu, id); - this.structureType = structureType; - this.unableToFindMessage = unableToFindMessage; - this.groundMaterial = Arrays.asList(groundMaterial); - } - - public NetherPortalSpawnSetting(@Nonnull MenuType menu, @Nonnull StructureType structureType, @Nonnull String unableToFindMessage, @Nonnull Collection groundMaterial) { - super(menu, id); - this.structureType = structureType; - this.unableToFindMessage = unableToFindMessage; - this.groundMaterial = groundMaterial; - } - - @EventHandler - public void onNetherPortal(@Nonnull PlayerTeleportEvent event) { - if (!isEnabled()) return; - if (event.getCause() != TeleportCause.NETHER_PORTAL) return; - if (event.getTo() == null) return; - if (event.getTo().getWorld() == null) return; - - if (event.getTo().getWorld().getEnvironment() == Environment.NETHER) { - - World world = event.getTo().getWorld(); - Location location = getNetherPortal(event.getFrom(), world); - if (location == null) { - Message.forName(unableToFindMessage).send(event.getPlayer(), Prefix.CHALLENGES); - return; - } - - buildPortal(location); - event.setTo(location.clone().add(1, 0, 0.5)); // Middle of portal - - } else if (event.getTo().getWorld().getEnvironment() == Environment.NORMAL) { - Location location = getOverworldPortal(event.getFrom()); - if (location == null) return; - event.setTo(location.clone().add(1, 0, 0.5)); // Middle of portal - } - } - - @Nullable - private Location getNetherPortal(@Nonnull Location overworldPortal, @Nonnull World nether) { - - // Look if the current portal was used before - for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { - if (overworldPortal.distance(entry.getKey()) < 10) - return entry.getValue(); - } - - // Find next structure - Location structure = nether.locateNearestStructure(new Location(nether, 0, 100, 0), structureType, 10000, false); - if (structure == null) return null; - - // Look if there's already a portal to this structure - for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { - if (structure.distance(entry.getValue()) < 100) - return entry.getValue(); - } - - Location target = findNearestStructurePart(structure.clone()); - netherPortalsByOverworldPortals.put(overworldPortal, target); - return target; - - } - - @Nullable - private Location getOverworldPortal(@Nonnull Location netherPortal) { - for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { - if (netherPortal.distance(entry.getValue()) < 100) - return entry.getKey(); - } - return null; - } - - - @Nullable - private Location findNearestStructurePart(@Nonnull Location structure) { - - Chunk chunk = structure.getChunk(); - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - - Location location = chunk.getBlock(x, 100, z).getLocation(); // Structures wont be above y=100 - while (location.getBlockY() > 30) { // Structures wont be below y=30 - location.subtract(0, 1, 0); - if (groundMaterial.contains(location.getBlock().getType())) - return location.add(0, 1, 0); - } - - } - } - - return null; - - } - - private void buildPortal(@Nonnull Location origin) { - - // Floor - origin.clone().add(-1, -1, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(0, -1, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(1, -1, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(2, -1, 0).getBlock().setType(Material.OBSIDIAN); - - // Above - origin.clone().add(-1, 3, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(0, 3, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(1, 3, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(2, 3, 0).getBlock().setType(Material.OBSIDIAN); - - // Wall left - origin.clone().add(-1, 0, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(-1, 1, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(-1, 2, 0).getBlock().setType(Material.OBSIDIAN); - - // Wall right - origin.clone().add(2, 0, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(2, 1, 0).getBlock().setType(Material.OBSIDIAN); - origin.clone().add(2, 2, 0).getBlock().setType(Material.OBSIDIAN); - - // Fill portal - origin.clone().add(0, 0, 0).getBlock().setType(Material.NETHER_PORTAL); - origin.clone().add(1, 0, 0).getBlock().setType(Material.NETHER_PORTAL); - origin.clone().add(0, 1, 0).getBlock().setType(Material.NETHER_PORTAL); - origin.clone().add(1, 1, 0).getBlock().setType(Material.NETHER_PORTAL); - origin.clone().add(0, 2, 0).getBlock().setType(Material.NETHER_PORTAL); - origin.clone().add(1, 2, 0).getBlock().setType(Material.NETHER_PORTAL); - - // Free some place around - for (int x = -1; x <= 2; x++) { - for (int y = 0; y <= 3; y++) { - origin.clone().add(x, y, 1).getBlock().setType(Material.AIR); - origin.clone().add(x, y, 2).getBlock().setType(Material.AIR); - origin.clone().add(x, y, -1).getBlock().setType(Material.AIR); - origin.clone().add(x, y, -2).getBlock().setType(Material.AIR); - } - } - - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - - Document portals = document.getDocument("portals"); - for (String key : portals.keys()) { - Document portal = portals.getDocument(key); - Location from = portal.getSerializable("portal", Location.class); - Location to = portal.getSerializable("target", Location.class); - - if (from == null || to == null) continue; - netherPortalsByOverworldPortals.put(from, to); - } - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - - int index = 0; - Document portals = document.getDocument("portals"); - for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { - Document portal = portals.getDocument(String.valueOf(index)); - portal.set("portal", entry.getKey()); - portal.set("target", entry.getValue()); - } - } + private static final String id = "netherportal_handle"; + + private final Map netherPortalsByOverworldPortals = new HashMap<>(); + private final StructureType structureType; + private final Collection groundMaterial; + private final String unableToFindMessage; + + public NetherPortalSpawnSetting(@Nonnull MenuType menu, @Nonnull StructureType structureType, @Nonnull String unableToFindMessage, @Nonnull Material... groundMaterial) { + super(menu, id); + this.structureType = structureType; + this.unableToFindMessage = unableToFindMessage; + this.groundMaterial = Arrays.asList(groundMaterial); + } + + public NetherPortalSpawnSetting(@Nonnull MenuType menu, @Nonnull StructureType structureType, @Nonnull String unableToFindMessage, @Nonnull Collection groundMaterial) { + super(menu, id); + this.structureType = structureType; + this.unableToFindMessage = unableToFindMessage; + this.groundMaterial = groundMaterial; + } + + @EventHandler + public void onNetherPortal(@Nonnull PlayerTeleportEvent event) { + if (!isEnabled()) return; + if (event.getCause() != TeleportCause.NETHER_PORTAL) return; + if (event.getTo() == null) return; + if (event.getTo().getWorld() == null) return; + + if (event.getTo().getWorld().getEnvironment() == Environment.NETHER) { + + World world = event.getTo().getWorld(); + Location location = getNetherPortal(event.getFrom(), world); + if (location == null) { + Message.forName(unableToFindMessage).send(event.getPlayer(), Prefix.CHALLENGES); + return; + } + + buildPortal(location); + event.setTo(location.clone().add(1, 0, 0.5)); // Middle of portal + + } else if (event.getTo().getWorld().getEnvironment() == Environment.NORMAL) { + Location location = getOverworldPortal(event.getFrom()); + if (location == null) return; + event.setTo(location.clone().add(1, 0, 0.5)); // Middle of portal + } + } + + @Nullable + private Location getNetherPortal(@Nonnull Location overworldPortal, @Nonnull World nether) { + + // Look if the current portal was used before + for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { + if (overworldPortal.distance(entry.getKey()) < 10) + return entry.getValue(); + } + + // Find next structure + Location structure = nether.locateNearestStructure(new Location(nether, 0, 100, 0), structureType, 10000, false); + if (structure == null) return null; + + // Look if there's already a portal to this structure + for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { + if (structure.distance(entry.getValue()) < 100) + return entry.getValue(); + } + + Location target = findNearestStructurePart(structure.clone()); + netherPortalsByOverworldPortals.put(overworldPortal, target); + return target; + + } + + @Nullable + private Location getOverworldPortal(@Nonnull Location netherPortal) { + for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { + if (netherPortal.distance(entry.getValue()) < 100) + return entry.getKey(); + } + return null; + } + + + @Nullable + private Location findNearestStructurePart(@Nonnull Location structure) { + + Chunk chunk = structure.getChunk(); + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + + Location location = chunk.getBlock(x, 100, z).getLocation(); // Structures wont be above y=100 + while (location.getBlockY() > 30) { // Structures wont be below y=30 + location.subtract(0, 1, 0); + if (groundMaterial.contains(location.getBlock().getType())) + return location.add(0, 1, 0); + } + + } + } + + return null; + + } + + private void buildPortal(@Nonnull Location origin) { + + // Floor + origin.clone().add(-1, -1, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(0, -1, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(1, -1, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(2, -1, 0).getBlock().setType(Material.OBSIDIAN); + + // Above + origin.clone().add(-1, 3, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(0, 3, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(1, 3, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(2, 3, 0).getBlock().setType(Material.OBSIDIAN); + + // Wall left + origin.clone().add(-1, 0, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(-1, 1, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(-1, 2, 0).getBlock().setType(Material.OBSIDIAN); + + // Wall right + origin.clone().add(2, 0, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(2, 1, 0).getBlock().setType(Material.OBSIDIAN); + origin.clone().add(2, 2, 0).getBlock().setType(Material.OBSIDIAN); + + // Fill portal + origin.clone().add(0, 0, 0).getBlock().setType(Material.NETHER_PORTAL); + origin.clone().add(1, 0, 0).getBlock().setType(Material.NETHER_PORTAL); + origin.clone().add(0, 1, 0).getBlock().setType(Material.NETHER_PORTAL); + origin.clone().add(1, 1, 0).getBlock().setType(Material.NETHER_PORTAL); + origin.clone().add(0, 2, 0).getBlock().setType(Material.NETHER_PORTAL); + origin.clone().add(1, 2, 0).getBlock().setType(Material.NETHER_PORTAL); + + // Free some place around + for (int x = -1; x <= 2; x++) { + for (int y = 0; y <= 3; y++) { + origin.clone().add(x, y, 1).getBlock().setType(Material.AIR); + origin.clone().add(x, y, 2).getBlock().setType(Material.AIR); + origin.clone().add(x, y, -1).getBlock().setType(Material.AIR); + origin.clone().add(x, y, -2).getBlock().setType(Material.AIR); + } + } + + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + + Document portals = document.getDocument("portals"); + for (String key : portals.keys()) { + Document portal = portals.getDocument(key); + Location from = portal.getSerializable("portal", Location.class); + Location to = portal.getSerializable("target", Location.class); + + if (from == null || to == null) continue; + netherPortalsByOverworldPortals.put(from, to); + } + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + + int index = 0; + Document portals = document.getDocument("portals"); + for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { + Document portal = portals.getDocument(String.valueOf(index)); + portal.set("portal", entry.getKey()); + portal.set("target", entry.getValue()); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java index ebd7ba918..9bf18459d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java @@ -7,32 +7,32 @@ public abstract class OneEnabledSetting extends Setting { - private final String typeId; - - public OneEnabledSetting(@Nonnull MenuType menu, @Nonnull String typeId) { - super(menu); - this.typeId = typeId; - } - - public OneEnabledSetting(@Nonnull MenuType menu, boolean enabledByDefault, @Nonnull String typeId) { - super(menu, enabledByDefault); - this.typeId = typeId; - } - - - @Override - public void setEnabled(boolean enabled) { - super.setEnabled(enabled); - if (isEnabled()) disableOthers(); - } - - protected final void disableOthers() { - Challenges.getInstance().getChallengeManager().getChallenges().stream() - .filter(challenge -> challenge != this) - .filter(challenge -> challenge instanceof OneEnabledSetting) - .map(challenge -> (OneEnabledSetting) challenge) - .filter(setting -> setting.typeId.equals(typeId)) - .forEach(setting -> setting.setEnabled(false)); - } + private final String typeId; + + public OneEnabledSetting(@Nonnull MenuType menu, @Nonnull String typeId) { + super(menu); + this.typeId = typeId; + } + + public OneEnabledSetting(@Nonnull MenuType menu, boolean enabledByDefault, @Nonnull String typeId) { + super(menu, enabledByDefault); + this.typeId = typeId; + } + + + @Override + public void setEnabled(boolean enabled) { + super.setEnabled(enabled); + if (isEnabled()) disableOthers(); + } + + protected final void disableOthers() { + Challenges.getInstance().getChallengeManager().getChallenges().stream() + .filter(challenge -> challenge != this) + .filter(challenge -> challenge instanceof OneEnabledSetting) + .map(challenge -> (OneEnabledSetting) challenge) + .filter(setting -> setting.typeId.equals(typeId)) + .forEach(setting -> setting.setEnabled(false)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java index 2ee5d22f0..d37d3abc7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java @@ -15,92 +15,92 @@ public abstract class PointsGoal extends SettingGoal { - private final Map points = new HashMap<>(); - - public PointsGoal() { - super(); - } - - public PointsGoal(boolean enabledByDefault) { - super(enabledByDefault); - } - - @Override - protected void onEnable() { - super.onEnable(); - scoreboard.setContent(GoalHelper.createScoreboard(() -> getPoints(new AtomicInteger(), true))); - scoreboard.show(); - } - - @Override - protected void onDisable() { - super.onDisable(); - scoreboard.hide(); - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - - Document scores = document.getDocument("scores"); - for (String key : scores.keys()) { - try { - UUID uuid = UUID.fromString(key); - int value = scores.getInt(key); - points.put(uuid, value); - } catch (Exception ex) { - Logger.error("Could not load scores for {}", key); - } - } - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - - Document scores = document.getDocument("scores"); - points.forEach((uuid, points) -> scores.set(uuid.toString(), points)); - } - - @Override - public void getWinnersOnEnd(@Nonnull List winners) { - GoalHelper.getWinnersOnEnd(winners, getPoints(new AtomicInteger(), false)); - } - - @Nonnull - @CheckReturnValue - protected Map getPoints(@Nonnull AtomicInteger mostPoints, boolean zeros) { - return GoalHelper.createPointsFromValues(mostPoints, points, (uuid, integer) -> integer, zeros); - } - - protected void collect(@Nonnull Player player) { - collect(player, 1); - } - - protected void collect(@Nonnull Player player, int amount) { - points.compute(player.getUniqueId(), (uuid, points) -> points == null ? amount : points + amount); - scoreboard.update(); - } - - protected void setPoints(@Nonnull UUID uuid, int amount) { - points.put(uuid, amount); - scoreboard.update(); - } - - protected void addPoints(@Nonnull UUID uuid, int amount) { - points.put(uuid, getPoints(uuid) + amount); - scoreboard.update(); - } - - protected void removePoints(@Nonnull UUID uuid, int amount) { - points.put(uuid, getPoints(uuid) - amount); - scoreboard.update(); - } - - @CheckReturnValue - protected int getPoints(@Nonnull UUID uuid) { - Integer points = this.points.get(uuid); - return points == null ? 0 : points; - } + private final Map points = new HashMap<>(); + + public PointsGoal() { + super(); + } + + public PointsGoal(boolean enabledByDefault) { + super(enabledByDefault); + } + + @Override + protected void onEnable() { + super.onEnable(); + scoreboard.setContent(GoalHelper.createScoreboard(() -> getPoints(new AtomicInteger(), true))); + scoreboard.show(); + } + + @Override + protected void onDisable() { + super.onDisable(); + scoreboard.hide(); + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + + Document scores = document.getDocument("scores"); + for (String key : scores.keys()) { + try { + UUID uuid = UUID.fromString(key); + int value = scores.getInt(key); + points.put(uuid, value); + } catch (Exception ex) { + Logger.error("Could not load scores for {}", key); + } + } + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + + Document scores = document.getDocument("scores"); + points.forEach((uuid, points) -> scores.set(uuid.toString(), points)); + } + + @Override + public void getWinnersOnEnd(@Nonnull List winners) { + GoalHelper.getWinnersOnEnd(winners, getPoints(new AtomicInteger(), false)); + } + + @Nonnull + @CheckReturnValue + protected Map getPoints(@Nonnull AtomicInteger mostPoints, boolean zeros) { + return GoalHelper.createPointsFromValues(mostPoints, points, (uuid, integer) -> integer, zeros); + } + + protected void collect(@Nonnull Player player) { + collect(player, 1); + } + + protected void collect(@Nonnull Player player, int amount) { + points.compute(player.getUniqueId(), (uuid, points) -> points == null ? amount : points + amount); + scoreboard.update(); + } + + protected void setPoints(@Nonnull UUID uuid, int amount) { + points.put(uuid, amount); + scoreboard.update(); + } + + protected void addPoints(@Nonnull UUID uuid, int amount) { + points.put(uuid, getPoints(uuid) + amount); + scoreboard.update(); + } + + protected void removePoints(@Nonnull UUID uuid, int amount) { + points.put(uuid, getPoints(uuid) - amount); + scoreboard.update(); + } + + @CheckReturnValue + protected int getPoints(@Nonnull UUID uuid) { + Integer points = this.points.get(uuid); + return points == null ? 0 : points; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java index 3c9b8ebb6..f625256b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java @@ -10,52 +10,52 @@ public abstract class RandomizerSetting extends Setting { - protected IRandom random = IRandom.create(); - - public RandomizerSetting(@Nonnull MenuType menu) { - super(menu); - setCategory(SettingCategory.RANDOMIZER); - } - - public RandomizerSetting(@Nonnull MenuType menu, boolean enabledByDefault) { - super(menu, enabledByDefault); - setCategory(SettingCategory.RANDOMIZER); - } - - protected abstract void reloadRandomization(); - - protected int getMatches(int pairs, int matchesRemaining) { - if ((pairs * 3) <= matchesRemaining - 3) return 3; - if ((pairs * 2) <= matchesRemaining - 2) return 2; - return 1; - } - - @Override - protected void onEnable() { - reloadRandomization(); - } - - @Override - public void loadGameState(@Nonnull Document document) { - super.loadGameState(document); - if (!document.contains("seed")) { - random = new SeededRandomWrapper(); - return; - } - - long seed = document.getLong("seed"); - if (seed == random.getSeed()) return; - - random = IRandom.create(seed); - - if (!isEnabled()) return; - reloadRandomization(); - } - - @Override - public void writeGameState(@Nonnull Document document) { - super.writeGameState(document); - document.set("seed", random.getSeed()); - } + protected IRandom random = IRandom.create(); + + public RandomizerSetting(@Nonnull MenuType menu) { + super(menu); + setCategory(SettingCategory.RANDOMIZER); + } + + public RandomizerSetting(@Nonnull MenuType menu, boolean enabledByDefault) { + super(menu, enabledByDefault); + setCategory(SettingCategory.RANDOMIZER); + } + + protected abstract void reloadRandomization(); + + protected int getMatches(int pairs, int matchesRemaining) { + if ((pairs * 3) <= matchesRemaining - 3) return 3; + if ((pairs * 2) <= matchesRemaining - 2) return 2; + return 1; + } + + @Override + protected void onEnable() { + reloadRandomization(); + } + + @Override + public void loadGameState(@Nonnull Document document) { + super.loadGameState(document); + if (!document.contains("seed")) { + random = new SeededRandomWrapper(); + return; + } + + long seed = document.getLong("seed"); + if (seed == random.getSeed()) return; + + random = IRandom.create(seed); + + if (!isEnabled()) return; + reloadRandomization(); + } + + @Override + public void writeGameState(@Nonnull Document document) { + super.writeGameState(document); + document.set("seed", random.getSeed()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java index 0f74a1501..33804057c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java @@ -14,82 +14,82 @@ public abstract class Setting extends AbstractChallenge { - private final boolean enabledByDefault; - protected boolean enabled; - - public Setting(@Nonnull MenuType menu) { - this(menu, false); - } - - public Setting(@Nonnull MenuType menu, boolean enabledByDefault) { - super(menu); - this.enabledByDefault = enabledByDefault; - setEnabled(enabledByDefault); - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - setEnabled(!enabled); - SoundSample.playStatusSound(info.getPlayer(), enabled); - playStatusUpdateTitle(); - } - - @Override - public void restoreDefaults() { - setEnabled(enabledByDefault); - } - - public void playStatusUpdateTitle() { - ChallengeHelper.playToggleChallengeTitle(this); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.status(enabled); - } - - protected void onEnable() { - } - - protected void onDisable() { - } - - @Override - public void handleShutdown() { - super.handleShutdown(); - - if (isEnabled()) - onDisable(); - } - - @Override - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - if (this.enabled == enabled) return; - this.enabled = enabled; - - try { - if (enabled) onEnable(); - else onDisable(); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Error while {} Setting {}", enabled ? "enabling" : "disabling", getClass().getSimpleName(), exception); - } - - updateItems(); - } - - @Override - public void loadSettings(@Nonnull Document document) { - setEnabled(document.getBoolean("enabled", enabled)); - } - - @Override - public void writeSettings(@Nonnull Document document) { - document.set("enabled", enabled); - } + private final boolean enabledByDefault; + protected boolean enabled; + + public Setting(@Nonnull MenuType menu) { + this(menu, false); + } + + public Setting(@Nonnull MenuType menu, boolean enabledByDefault) { + super(menu); + this.enabledByDefault = enabledByDefault; + setEnabled(enabledByDefault); + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + setEnabled(!enabled); + SoundSample.playStatusSound(info.getPlayer(), enabled); + playStatusUpdateTitle(); + } + + @Override + public void restoreDefaults() { + setEnabled(enabledByDefault); + } + + public void playStatusUpdateTitle() { + ChallengeHelper.playToggleChallengeTitle(this); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + return DefaultItem.status(enabled); + } + + protected void onEnable() { + } + + protected void onDisable() { + } + + @Override + public void handleShutdown() { + super.handleShutdown(); + + if (isEnabled()) + onDisable(); + } + + @Override + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + if (this.enabled == enabled) return; + this.enabled = enabled; + + try { + if (enabled) onEnable(); + else onDisable(); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Error while {} Setting {}", enabled ? "enabling" : "disabling", getClass().getSimpleName(), exception); + } + + updateItems(); + } + + @Override + public void loadSettings(@Nonnull Document document) { + setEnabled(document.getBoolean("enabled", enabled)); + } + + @Override + public void writeSettings(@Nonnull Document document) { + document.set("enabled", enabled); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java index 606ddb68d..d969538ca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java @@ -10,30 +10,30 @@ public abstract class SettingGoal extends Setting implements IGoal { - public SettingGoal() { - super(MenuType.GOAL); - } - - public SettingGoal(boolean enabledByDefault) { - super(MenuType.GOAL, enabledByDefault); - } - - @Nonnull - public SoundSample getStartSound() { - return SoundSample.DRAGON_BREATH; - } - - @Nullable - @Override - public SoundSample getWinSound() { - return SoundSample.WIN; - } - - @Override - public void setEnabled(boolean enabled) { - if (isEnabled() == enabled) return; - GoalHelper.handleSetEnabled(this, enabled); - super.setEnabled(enabled); - } + public SettingGoal() { + super(MenuType.GOAL); + } + + public SettingGoal(boolean enabledByDefault) { + super(MenuType.GOAL, enabledByDefault); + } + + @Nonnull + public SoundSample getStartSound() { + return SoundSample.DRAGON_BREATH; + } + + @Nullable + @Override + public SoundSample getWinSound() { + return SoundSample.WIN; + } + + @Override + public void setEnabled(boolean enabled) { + if (isEnabled() == enabled) return; + GoalHelper.handleSetEnabled(this, enabled); + super.setEnabled(enabled); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java index 644839adc..59c5c6f4b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java @@ -13,94 +13,94 @@ public abstract class SettingModifier extends Modifier { - private boolean enabled; - - public SettingModifier(@Nonnull MenuType menu) { - super(menu); - } - - public SettingModifier(@Nonnull MenuType menu, int max) { - super(menu, max); - } - - public SettingModifier(@Nonnull MenuType menu, int min, int max) { - super(menu, min, max); - } - - public SettingModifier(@Nonnull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue); - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - if (info.isUpperItemClick() || !enabled) { - setEnabled(!enabled); - SoundSample.playStatusSound(info.getPlayer(), enabled); - playStatusUpdateTitle(); - } else { - super.handleClick(info); - } - } - - @Override - public void restoreDefaults() { - super.restoreDefaults(); - setEnabled(false); - } - - @Nonnull - @Override - public ItemStack getSettingsItem() { - return isEnabled() ? super.getSettingsItem() : DefaultItem.disabled().build(); - } - - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.enabled().amount(getValue()); - } - - @Override - public final boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - if (this.enabled == enabled) return; - this.enabled = enabled; - - if (enabled) onEnable(); - else onDisable(); - - updateItems(); - } - - public void playStatusUpdateTitle() { - ChallengeHelper.playToggleChallengeTitle(this); - } - - protected void onEnable() { - } - - protected void onDisable() { - } - - @Override - public void handleShutdown() { - super.handleShutdown(); - onDisable(); - } - - @Override - public void writeSettings(@Nonnull Document document) { - super.writeSettings(document); - document.set("enabled", enabled); - } - - @Override - public void loadSettings(@Nonnull Document document) { - super.loadSettings(document); - setEnabled(document.getBoolean("enabled")); - } + private boolean enabled; + + public SettingModifier(@Nonnull MenuType menu) { + super(menu); + } + + public SettingModifier(@Nonnull MenuType menu, int max) { + super(menu, max); + } + + public SettingModifier(@Nonnull MenuType menu, int min, int max) { + super(menu, min, max); + } + + public SettingModifier(@Nonnull MenuType menu, int min, int max, int defaultValue) { + super(menu, min, max, defaultValue); + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + if (info.isUpperItemClick() || !enabled) { + setEnabled(!enabled); + SoundSample.playStatusSound(info.getPlayer(), enabled); + playStatusUpdateTitle(); + } else { + super.handleClick(info); + } + } + + @Override + public void restoreDefaults() { + super.restoreDefaults(); + setEnabled(false); + } + + @Nonnull + @Override + public ItemStack getSettingsItem() { + return isEnabled() ? super.getSettingsItem() : DefaultItem.disabled().build(); + } + + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + return DefaultItem.enabled().amount(getValue()); + } + + @Override + public final boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + if (this.enabled == enabled) return; + this.enabled = enabled; + + if (enabled) onEnable(); + else onDisable(); + + updateItems(); + } + + public void playStatusUpdateTitle() { + ChallengeHelper.playToggleChallengeTitle(this); + } + + protected void onEnable() { + } + + protected void onDisable() { + } + + @Override + public void handleShutdown() { + super.handleShutdown(); + onDisable(); + } + + @Override + public void writeSettings(@Nonnull Document document) { + super.writeSettings(document); + document.set("enabled", enabled); + } + + @Override + public void loadSettings(@Nonnull Document document) { + super.loadSettings(document); + setEnabled(document.getBoolean("enabled")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java index 69234f1c6..a29db2230 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java @@ -11,65 +11,65 @@ public abstract class SettingModifierCollectionGoal extends ModifierCollectionGoal { - public SettingModifierCollectionGoal(int min, int max, @Nonnull Object... target) { - super(min, max, target); - } + public SettingModifierCollectionGoal(int min, int max, @Nonnull Object... target) { + super(min, max, target); + } - public SettingModifierCollectionGoal(int min, int max, int defaultValue, @Nonnull Object... target) { - super(min, max, defaultValue, target); - } + public SettingModifierCollectionGoal(int min, int max, int defaultValue, @Nonnull Object... target) { + super(min, max, defaultValue, target); + } - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - if (info.isUpperItemClick() || !enabled) { - setEnabled(!enabled); - SoundSample.playStatusSound(info.getPlayer(), enabled); - playStatusUpdateTitle(); - } else { - super.handleClick(info); - } - } + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + if (info.isUpperItemClick() || !enabled) { + setEnabled(!enabled); + SoundSample.playStatusSound(info.getPlayer(), enabled); + playStatusUpdateTitle(); + } else { + super.handleClick(info); + } + } - @Override - public void restoreDefaults() { - super.restoreDefaults(); - setEnabled(false); - } + @Override + public void restoreDefaults() { + super.restoreDefaults(); + setEnabled(false); + } - @Nonnull - @Override - public ItemStack getSettingsItem() { - return isEnabled() ? super.getSettingsItem() : DefaultItem.disabled().build(); - } + @Nonnull + @Override + public ItemStack getSettingsItem() { + return isEnabled() ? super.getSettingsItem() : DefaultItem.disabled().build(); + } - @Nonnull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.enabled().amount(getValue()); - } + @Nonnull + @Override + public ItemBuilder createSettingsItem() { + return DefaultItem.enabled().amount(getValue()); + } - @Override - public void handleShutdown() { - super.handleShutdown(); - onDisable(); - } + @Override + public void handleShutdown() { + super.handleShutdown(); + onDisable(); + } - @Override - public boolean isEnabled() { - return this.enabled; - } + @Override + public boolean isEnabled() { + return this.enabled; + } - @Override - public void writeSettings(@Nonnull Document document) { - super.writeSettings(document); - document.set("enabled", enabled); - } + @Override + public void writeSettings(@Nonnull Document document) { + super.writeSettings(document); + document.set("enabled", enabled); + } - @Override - public void loadSettings(@Nonnull Document document) { - super.loadSettings(document); - setEnabled(document.getBoolean("enabled")); - } + @Override + public void loadSettings(@Nonnull Document document) { + super.loadSettings(document); + setEnabled(document.getBoolean("enabled")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java index 66935584f..841c6e433 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java @@ -12,50 +12,50 @@ public abstract class SettingModifierGoal extends SettingModifier implements IGoal { - public SettingModifierGoal(@Nonnull MenuType menu) { - super(menu); - } - - public SettingModifierGoal(@Nonnull MenuType menu, int max) { - super(menu, max); - } - - public SettingModifierGoal(@Nonnull MenuType menu, int min, int max) { - super(menu, min, max); - } - - public SettingModifierGoal(@Nonnull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue); - } - - @Override - public final void setEnabled(boolean enabled) { - if (isEnabled() == enabled) return; - GoalHelper.handleSetEnabled(this, enabled); - super.setEnabled(enabled); - } - - @Nonnull - @Override - public SoundSample getStartSound() { - return SoundSample.DRAGON_BREATH; - } - - @Nullable - @Override - public SoundSample getWinSound() { - return SoundSample.WIN; - } - - @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { - if (info.isLowerItemClick() && isEnabled()) { - ChallengeHelper.handleModifierClick(info, this); - } else { - setEnabled(!isEnabled()); - SoundSample.playStatusSound(info.getPlayer(), isEnabled()); - playStatusUpdateTitle(); - } - } + public SettingModifierGoal(@Nonnull MenuType menu) { + super(menu); + } + + public SettingModifierGoal(@Nonnull MenuType menu, int max) { + super(menu, max); + } + + public SettingModifierGoal(@Nonnull MenuType menu, int min, int max) { + super(menu, min, max); + } + + public SettingModifierGoal(@Nonnull MenuType menu, int min, int max, int defaultValue) { + super(menu, min, max, defaultValue); + } + + @Override + public final void setEnabled(boolean enabled) { + if (isEnabled() == enabled) return; + GoalHelper.handleSetEnabled(this, enabled); + super.setEnabled(enabled); + } + + @Nonnull + @Override + public SoundSample getStartSound() { + return SoundSample.DRAGON_BREATH; + } + + @Nullable + @Override + public SoundSample getWinSound() { + return SoundSample.WIN; + } + + @Override + public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + if (info.isLowerItemClick() && isEnabled()) { + ChallengeHelper.handleModifierClick(info, this); + } else { + setEnabled(!isEnabled()); + SoundSample.playStatusSound(info.getPlayer(), isEnabled()); + playStatusUpdateTitle(); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java index 7cf353a96..2c527f4a4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java @@ -13,156 +13,156 @@ public abstract class TimedChallenge extends SettingModifier { - private final boolean runAsync; - @Setter + private final boolean runAsync; + @Setter protected int secondsUntilActivation; - private int originalSecondsUntilActivation; - private boolean timerStatus = false; - private boolean startedBefore = false; - - public TimedChallenge(@Nonnull MenuType menu) { - this(menu, true); - } - - public TimedChallenge(@Nonnull MenuType menu, int max) { - this(menu, max, true); - } - - public TimedChallenge(@Nonnull MenuType menu, int min, int max) { - this(menu, min, max, true); - } - - public TimedChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { - this(menu, min, max, defaultValue, true); - } - - public TimedChallenge(@Nonnull MenuType menu, boolean runAsync) { - super(menu); - this.runAsync = runAsync; - } - - public TimedChallenge(@Nonnull MenuType menu, int max, boolean runAsync) { - super(menu, max); - this.runAsync = runAsync; - } - - public TimedChallenge(@Nonnull MenuType menu, int min, int max, boolean runAsync) { - super(menu, min, max); - this.runAsync = runAsync; - } - - public TimedChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue, boolean runAsync) { - super(menu, min, max, defaultValue); - this.runAsync = runAsync; - } - - @Override - public void setValue(int value) { - super.setValue(value); - if (!timerStatus) { - restartTimer(); - } - } - - // Don't execute async to prevent sync issues with timer - @ScheduledTask(ticks = 20, async = false) - public final void handleTimedChallengeSecond() { - - if (!startedBefore) - restartTimer(); - - if (timerStatus) { - - if (getTimerTrigger()) { - secondsUntilActivation--; - if (secondsUntilActivation <= 0) { - secondsUntilActivation = 0; - timerStatus = false; - executeTimeActivation(); - } else { - handleCountdown(); - } - } else { - Logger.debug("getTimerTrigger returned false for {}", this.getClass().getSimpleName()); - } - } - - } - - public final void executeTimeActivation() { - if (runAsync) { - Bukkit.getScheduler().runTaskAsynchronously(plugin, this::onTimeActivation); - } else { - Bukkit.getScheduler().runTask(plugin, this::onTimeActivation); - } - } - - public final void shortCountDownTo(@Nonnegative int seconds) { - if (!timerStatus) throw new IllegalArgumentException("Countdown is not started"); - if (seconds > originalSecondsUntilActivation) - throw new IllegalArgumentException("Cannot short countdown to a higher length than originally set"); - this.secondsUntilActivation = seconds; - } - - public final boolean isTimerRunning() { - return timerStatus; - } - - public final int getSecondsLeftUntilNextActivation() { - return secondsUntilActivation; - } - - public final int getOriginalSecondsUntilActivation() { - return originalSecondsUntilActivation; - } - - protected float getProgress() { - return getOriginalSecondsUntilActivation() == 0 ? 1 : (float) (getSecondsLeftUntilNextActivation()) / getOriginalSecondsUntilActivation(); - } - - protected void handleCountdown() { - } - - protected boolean getTimerTrigger() { - return true; - } - - protected abstract int getSecondsUntilNextActivation(); + private int originalSecondsUntilActivation; + private boolean timerStatus = false; + private boolean startedBefore = false; + + public TimedChallenge(@Nonnull MenuType menu) { + this(menu, true); + } + + public TimedChallenge(@Nonnull MenuType menu, int max) { + this(menu, max, true); + } + + public TimedChallenge(@Nonnull MenuType menu, int min, int max) { + this(menu, min, max, true); + } + + public TimedChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { + this(menu, min, max, defaultValue, true); + } + + public TimedChallenge(@Nonnull MenuType menu, boolean runAsync) { + super(menu); + this.runAsync = runAsync; + } + + public TimedChallenge(@Nonnull MenuType menu, int max, boolean runAsync) { + super(menu, max); + this.runAsync = runAsync; + } + + public TimedChallenge(@Nonnull MenuType menu, int min, int max, boolean runAsync) { + super(menu, min, max); + this.runAsync = runAsync; + } + + public TimedChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue, boolean runAsync) { + super(menu, min, max, defaultValue); + this.runAsync = runAsync; + } + + @Override + public void setValue(int value) { + super.setValue(value); + if (!timerStatus) { + restartTimer(); + } + } + + // Don't execute async to prevent sync issues with timer + @ScheduledTask(ticks = 20, async = false) + public final void handleTimedChallengeSecond() { + + if (!startedBefore) + restartTimer(); + + if (timerStatus) { + + if (getTimerTrigger()) { + secondsUntilActivation--; + if (secondsUntilActivation <= 0) { + secondsUntilActivation = 0; + timerStatus = false; + executeTimeActivation(); + } else { + handleCountdown(); + } + } else { + Logger.debug("getTimerTrigger returned false for {}", this.getClass().getSimpleName()); + } + } + + } + + public final void executeTimeActivation() { + if (runAsync) { + Bukkit.getScheduler().runTaskAsynchronously(plugin, this::onTimeActivation); + } else { + Bukkit.getScheduler().runTask(plugin, this::onTimeActivation); + } + } + + public final void shortCountDownTo(@Nonnegative int seconds) { + if (!timerStatus) throw new IllegalArgumentException("Countdown is not started"); + if (seconds > originalSecondsUntilActivation) + throw new IllegalArgumentException("Cannot short countdown to a higher length than originally set"); + this.secondsUntilActivation = seconds; + } + + public final boolean isTimerRunning() { + return timerStatus; + } + + public final int getSecondsLeftUntilNextActivation() { + return secondsUntilActivation; + } + + public final int getOriginalSecondsUntilActivation() { + return originalSecondsUntilActivation; + } + + protected float getProgress() { + return getOriginalSecondsUntilActivation() == 0 ? 1 : (float) (getSecondsLeftUntilNextActivation()) / getOriginalSecondsUntilActivation(); + } + + protected void handleCountdown() { + } + + protected boolean getTimerTrigger() { + return true; + } + + protected abstract int getSecondsUntilNextActivation(); protected void restartTimer(int seconds) { - Logger.debug("Restarting timer of {} with {} second(s)", this.getClass().getSimpleName(), seconds); - - startedBefore = true; - secondsUntilActivation = seconds; - originalSecondsUntilActivation = seconds; - timerStatus = true; - } - - protected void restartTimer() { - restartTimer(getSecondsUntilNextActivation()); - } - - @Override - public void loadGameState(@NotNull Document document) { - if (document.isEmpty()) { - startedBefore = true; - timerStatus = true; - restartTimer(); - } else if (document.contains("time")) { - startedBefore = true; - timerStatus = true; - secondsUntilActivation = document.getInt("time"); - Logger.debug("Starting timer of {} from gamestate value with {} second(s)", this.getClass().getSimpleName(), secondsUntilActivation); - } - } - - @Override - public void writeGameState(@NotNull Document document) { - if (secondsUntilActivation != originalSecondsUntilActivation) { - document.set("time", secondsUntilActivation); - } - } - - protected abstract void onTimeActivation(); + Logger.debug("Restarting timer of {} with {} second(s)", this.getClass().getSimpleName(), seconds); + + startedBefore = true; + secondsUntilActivation = seconds; + originalSecondsUntilActivation = seconds; + timerStatus = true; + } + + protected void restartTimer() { + restartTimer(getSecondsUntilNextActivation()); + } + + @Override + public void loadGameState(@NotNull Document document) { + if (document.isEmpty()) { + startedBefore = true; + timerStatus = true; + restartTimer(); + } else if (document.contains("time")) { + startedBefore = true; + timerStatus = true; + secondsUntilActivation = document.getInt("time"); + Logger.debug("Starting timer of {} from gamestate value with {} second(s)", this.getClass().getSimpleName(), secondsUntilActivation); + } + } + + @Override + public void writeGameState(@NotNull Document document) { + if (secondsUntilActivation != originalSecondsUntilActivation) { + document.set("time", secondsUntilActivation); + } + } + + protected abstract void onTimeActivation(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java index a826eb11f..3b7a6253e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java @@ -22,134 +22,134 @@ public abstract class WorldDependentChallenge extends TimedChallenge { - private boolean inExtraWorld; - private BiConsumer lastTeleport; - private int teleportIndex; - - public WorldDependentChallenge(@Nonnull MenuType menu) { - super(menu); - } - - public WorldDependentChallenge(@Nonnull MenuType menu, int max) { - super(menu, max); - } - - public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max) { - super(menu, min, max); - } - - public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue); - } - - public WorldDependentChallenge(@Nonnull MenuType menu, boolean runAsync) { - super(menu, runAsync); - } - - public WorldDependentChallenge(@Nonnull MenuType menu, int max, boolean runAsync) { - super(menu, max, runAsync); - } - - public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max, boolean runAsync) { - super(menu, min, max, runAsync); - } - - public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue, boolean runAsync) { - super(menu, min, max, defaultValue, runAsync); - } - - /** - * Prevents the activation of two world challenges at the same time - */ - @Override - protected final void onTimeActivation() { - if (ChallengeAPI.isWorldInUse()) { - restartTimer(1); - } else { - startWorldChallenge(); - } - } - - public abstract void startWorldChallenge(); - - @Override - protected boolean getTimerTrigger() { - return inExtraWorld || !Challenges.getInstance().getWorldManager().isWorldInUse(); - } - - protected void teleportToWorld(boolean allowJoinCatchUp, @Nonnull BiConsumer action) { - if (Challenges.getInstance().getWorldManager().isWorldInUse()) return; - Challenges.getInstance().getWorldManager().setWorldInUse(inExtraWorld = true); - lastTeleport = allowJoinCatchUp ? action : null; - - teleportIndex = 0; - broadcastFiltered(player -> teleport(player, action)); - broadcastIgnored(player -> { - teleport(player, null); - teleportSpectator(player); - }); - } - - protected void teleportBack() { - if (!Challenges.getInstance().getWorldManager().isWorldInUse()) return; - Challenges.getInstance().getWorldManager().setWorldInUse(inExtraWorld = false); - lastTeleport = null; - teleportIndex = 0; - } - - protected void teleportBack(@Nonnull Player player) { - Challenges.getInstance().getWorldManager().restorePlayerData(player); - } - - private void teleport(@Nonnull Player player, @Nullable BiConsumer teleport) { - player.getInventory().clear(); - player.setFoodLevel(20); - player.setSaturation(20); - player.setNoDamageTicks(10); - player.setFallDistance(0); - player.setHealth(player.getMaxHealth()); - for (PotionEffect effect : player.getActivePotionEffects()) { - player.removePotionEffect(effect.getType()); - } - if (teleport != null) { - player.setVelocity(new Vector()); - teleport.accept(player, teleportIndex++); - SoundSample.TELEPORT.play(player); - } - } - - protected void teleportSpectator(@Nonnull Player player) { - player.setGameMode(GameMode.SPECTATOR); - List ingamePlayers = ChallengeHelper.getIngamePlayers(); - if (ingamePlayers.isEmpty()) return; - Player target = ingamePlayers.get(0); - player.teleport(target); - player.setSpectatorTarget(target); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onJoin(@Nonnull PlayerJoinEvent event) { - if (isInExtraWorld()) { - if (lastTeleport == null) return; - if (Challenges.getInstance().getWorldManager().hasPlayerData(event.getPlayer())) return; - teleport(event.getPlayer(), lastTeleport); - } else { - Challenges.getInstance().getWorldManager().restorePlayerData(event.getPlayer()); - } - } - - @Nonnull - protected final World getExtraWorld() { - return Challenges.getInstance().getWorldManager().getExtraWorld(); - } - - @Nonnull - protected final WorldSettings getExtraWorldSettings() { - return Challenges.getInstance().getWorldManager().getSettings(); - } - - public final boolean isInExtraWorld() { - return inExtraWorld; - } + private boolean inExtraWorld; + private BiConsumer lastTeleport; + private int teleportIndex; + + public WorldDependentChallenge(@Nonnull MenuType menu) { + super(menu); + } + + public WorldDependentChallenge(@Nonnull MenuType menu, int max) { + super(menu, max); + } + + public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max) { + super(menu, min, max); + } + + public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { + super(menu, min, max, defaultValue); + } + + public WorldDependentChallenge(@Nonnull MenuType menu, boolean runAsync) { + super(menu, runAsync); + } + + public WorldDependentChallenge(@Nonnull MenuType menu, int max, boolean runAsync) { + super(menu, max, runAsync); + } + + public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max, boolean runAsync) { + super(menu, min, max, runAsync); + } + + public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue, boolean runAsync) { + super(menu, min, max, defaultValue, runAsync); + } + + /** + * Prevents the activation of two world challenges at the same time + */ + @Override + protected final void onTimeActivation() { + if (ChallengeAPI.isWorldInUse()) { + restartTimer(1); + } else { + startWorldChallenge(); + } + } + + public abstract void startWorldChallenge(); + + @Override + protected boolean getTimerTrigger() { + return inExtraWorld || !Challenges.getInstance().getWorldManager().isWorldInUse(); + } + + protected void teleportToWorld(boolean allowJoinCatchUp, @Nonnull BiConsumer action) { + if (Challenges.getInstance().getWorldManager().isWorldInUse()) return; + Challenges.getInstance().getWorldManager().setWorldInUse(inExtraWorld = true); + lastTeleport = allowJoinCatchUp ? action : null; + + teleportIndex = 0; + broadcastFiltered(player -> teleport(player, action)); + broadcastIgnored(player -> { + teleport(player, null); + teleportSpectator(player); + }); + } + + protected void teleportBack() { + if (!Challenges.getInstance().getWorldManager().isWorldInUse()) return; + Challenges.getInstance().getWorldManager().setWorldInUse(inExtraWorld = false); + lastTeleport = null; + teleportIndex = 0; + } + + protected void teleportBack(@Nonnull Player player) { + Challenges.getInstance().getWorldManager().restorePlayerData(player); + } + + private void teleport(@Nonnull Player player, @Nullable BiConsumer teleport) { + player.getInventory().clear(); + player.setFoodLevel(20); + player.setSaturation(20); + player.setNoDamageTicks(10); + player.setFallDistance(0); + player.setHealth(player.getMaxHealth()); + for (PotionEffect effect : player.getActivePotionEffects()) { + player.removePotionEffect(effect.getType()); + } + if (teleport != null) { + player.setVelocity(new Vector()); + teleport.accept(player, teleportIndex++); + SoundSample.TELEPORT.play(player); + } + } + + protected void teleportSpectator(@Nonnull Player player) { + player.setGameMode(GameMode.SPECTATOR); + List ingamePlayers = ChallengeHelper.getIngamePlayers(); + if (ingamePlayers.isEmpty()) return; + Player target = ingamePlayers.get(0); + player.teleport(target); + player.setSpectatorTarget(target); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onJoin(@Nonnull PlayerJoinEvent event) { + if (isInExtraWorld()) { + if (lastTeleport == null) return; + if (Challenges.getInstance().getWorldManager().hasPlayerData(event.getPlayer())) return; + teleport(event.getPlayer(), lastTeleport); + } else { + Challenges.getInstance().getWorldManager().restorePlayerData(event.getPlayer()); + } + } + + @Nonnull + protected final World getExtraWorld() { + return Challenges.getInstance().getWorldManager().getExtraWorld(); + } + + @Nonnull + protected final WorldSettings getExtraWorldSettings() { + return Challenges.getInstance().getWorldManager().getSettings(); + } + + public final boolean isInExtraWorld() { + return inExtraWorld; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java index e17817559..a99261bce 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java @@ -8,19 +8,19 @@ public final class ChallengeConfigHelper { - private static final Document settingsDocument; + private static final Document settingsDocument; - static { - settingsDocument = Challenges.getInstance().getConfigDocument().getDocument("challenge-settings"); - } + static { + settingsDocument = Challenges.getInstance().getConfigDocument().getDocument("challenge-settings"); + } - private ChallengeConfigHelper() { - } + private ChallengeConfigHelper() { + } - @Nonnull - @CheckReturnValue - public static Document getSettingsDocument() { - return settingsDocument; - } + @Nonnull + @CheckReturnValue + public static Document getSettingsDocument() { + return settingsDocument; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index eaf6715c9..79a3b346d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -36,182 +36,182 @@ public final class ChallengeHelper { - @Getter + @Getter private static boolean inInstantKill = false; - private ChallengeHelper() { - } + private ChallengeHelper() { + } - public static void kill(@Nonnull Player player) { + public static void kill(@Nonnull Player player) { - if (!Bukkit.isPrimaryThread()) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> kill(player)); - return; - } + if (!Bukkit.isPrimaryThread()) { + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> kill(player)); + return; + } - inInstantKill = true; - player.damage(Integer.MAX_VALUE); - inInstantKill = false; - } + inInstantKill = true; + player.damage(Integer.MAX_VALUE); + inInstantKill = false; + } - public static void kill(@Nonnull Player player, int delay) { - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> kill(player), delay); - } + public static void kill(@Nonnull Player player, int delay) { + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> kill(player), delay); + } public static void updateItems(@Nonnull IChallenge challenge) { - challenge.getType().executeWithGenerator(ChallengeMenuGenerator.class, gen -> gen.updateItem(challenge)); - } - - public static boolean canInstaKillOnEnable(@Nonnull IChallenge challenge) { - return challenge.getClass().isAnnotationPresent(CanInstaKillOnEnable.class); - } - - public static boolean isExcludedFromRandomChallenges(@Nonnull IChallenge challenge) { - return challenge.getClass().isAnnotationPresent(ExcludeFromRandomChallenges.class); - } - - public static void handleModifierClick(@Nonnull MenuClickInfo info, @Nonnull IModifier modifier) { - int newValue = modifier.getValue(); - int amount = info.isShiftClick() - ? (modifier.getValue() == modifier.getMinValue() || info.isRightClick() && modifier.getValue() == (10 - (modifier.getMinValue() - 1)) ? 9 : 10) - : 1; - newValue += info.isRightClick() ? -amount : amount; - - if (newValue > modifier.getMaxValue()) - newValue = modifier.getMinValue(); - if (newValue < modifier.getMinValue()) - newValue = modifier.getMaxValue(); - - modifier.setValue(newValue); - modifier.playValueChangeTitle(); - SoundSample.CLICK.play(info.getPlayer()); - } - - @Nonnull - public static String getColoredChallengeName(@Nonnull AbstractChallenge challenge) { - ItemBuilder item = challenge.createDisplayItem(); - ItemDescription description = item.getBuiltByItemDescription(); - if (description == null) return Message.NULL; - return description.getOriginalName(); - } - - public static void breakBlock(@Nonnull Block block, @Nullable ItemStack tool) { - breakBlock(block, tool, null); - } - - public static void breakBlock(@Nonnull Block block, @Nullable ItemStack tool, @Nullable Inventory targetInventory) { - - if (!ChallengeAPI.getDropChance(block.getType())) return; - boolean putIntoInventory = ChallengeAPI.getItemsDirectIntoInventory() && targetInventory != null; - - List customDrops = ChallengeAPI.getCustomDrops(block.getType()); - Location location = block.getLocation().clone().add(0.5, 0, 0.5); - if (!customDrops.isEmpty()) { - if (putIntoInventory) { - customDrops.forEach(drop -> InventoryUtils.dropOrGiveItem(targetInventory, location, drop)); - } else { - customDrops.forEach(drop -> block.getWorld().dropItem(location, new ItemStack(drop))); - } - block.setType(Material.AIR); - return; - } - - if (putIntoInventory) { - block.getDrops(tool).forEach(drop -> InventoryUtils.dropOrGiveItem(targetInventory, location, drop)); - block.setType(Material.AIR); - return; - } - - block.breakNaturally(tool); - - } - - public static void dropItem(@Nonnull ItemStack itemStack, @Nonnull Location dropLocation, @Nonnull Inventory inventory) { - boolean directIntoInventory = Challenges.getInstance().getBlockDropManager().isItemsDirectIntoInventory(); - - if (directIntoInventory) { - InventoryUtils.dropOrGiveItem(inventory, dropLocation, itemStack); - return; - } - - if (dropLocation.getWorld() == null) return; - dropLocation.getWorld().dropItemNaturally(dropLocation, itemStack); - - } - - public static boolean ignoreDamager(@Nonnull Entity damager) { - Player damagerPlayer = getDamagerPlayer(damager); - if (damagerPlayer == null) return false; - return AbstractChallenge.ignorePlayer(damagerPlayer); - } - - public static Player getDamagerPlayer(@Nonnull Entity damager) { - if (damager instanceof Player) return ((Player) damager); - if (damager instanceof Projectile && ((Projectile) damager).getShooter() instanceof Player) - return ((Player) ((Projectile) damager).getShooter()); - return null; - } - - public static List getIngamePlayers() { - return Bukkit.getOnlinePlayers().stream().filter(player -> !AbstractChallenge.ignorePlayer(player)).collect(Collectors.toList()); - } - - public static void playToggleChallengeTitle(@Nonnull AbstractChallenge challenge) { - playToggleChallengeTitle(challenge, challenge.isEnabled()); - } - - public static void playToggleChallengeTitle(@Nonnull AbstractChallenge challenge, boolean enabled) { - Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(enabled ? Message.forName("title-challenge-enabled") : Message.forName("title-challenge-disabled"), getColoredChallengeName(challenge)); - } - - public static void playChangeChallengeValueTitle(@Nonnull AbstractChallenge challenge, @Nonnull IModifier modifier) { - playChangeChallengeValueTitle(challenge, modifier.getValue()); - } - - public static void playChangeChallengeValueTitle(@Nonnull Modifier modifier) { - playChangeChallengeValueTitle(modifier, modifier.getValue()); - } - - public static void playChangeChallengeValueTitle(@Nonnull AbstractChallenge modifier, @Nullable Object value) { - Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(Message.forName("title-challenge-value-changed"), getColoredChallengeName(modifier), value); - } - - public static void playChallengeHeartsValueChangeTitle(@Nonnull AbstractChallenge challenge, int health) { - playChangeChallengeValueTitle(challenge, (health / 2f) + " §c❤"); - } - - public static void playChallengeHeartsValueChangeTitle(@Nonnull Modifier modifier) { - playChallengeHeartsValueChangeTitle(modifier, modifier.getValue()); - } - - public static void playChallengeSecondsValueChangeTitle(@Nonnull AbstractChallenge challenge, int seconds) { - playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds").asString(seconds)); - } - - public static void playChallengeSecondsRangeValueChangeTitle(@Nonnull AbstractChallenge challenge, int min, int max) { - playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds-range").asString(min, max)); - } - - public static void playChallengeMinutesValueChangeTitle(@Nonnull AbstractChallenge challenge, int seconds) { - playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-minutes").asString(seconds)); - } - - @Nonnull - public static String[] getTimeRangeSettingsDescription(@Nonnull Modifier modifier, @Nonnegative int multiplier, @Nonnegative int range) { - return Message.forName("item-time-seconds-range-description").asArray(modifier.getValue() * multiplier - range, modifier.getValue() * multiplier + range); - } - - @Nonnull - public static String[] getTimeRangeSettingsDescription(@Nonnull Modifier modifier, @Nonnegative int range) { - return getTimeRangeSettingsDescription(modifier, 1, range); - } - - public static boolean finalDamageIsNull(@Nonnull EntityDamageEvent event) { - return getFinalDamage(event) == 0; - } - - public static double getFinalDamage(@Nonnull EntityDamageEvent event) { - return event.getFinalDamage() + event.getDamage(DamageModifier.ABSORPTION); - } + challenge.getType().executeWithGenerator(ChallengeMenuGenerator.class, gen -> gen.updateItem(challenge)); + } + + public static boolean canInstaKillOnEnable(@Nonnull IChallenge challenge) { + return challenge.getClass().isAnnotationPresent(CanInstaKillOnEnable.class); + } + + public static boolean isExcludedFromRandomChallenges(@Nonnull IChallenge challenge) { + return challenge.getClass().isAnnotationPresent(ExcludeFromRandomChallenges.class); + } + + public static void handleModifierClick(@Nonnull MenuClickInfo info, @Nonnull IModifier modifier) { + int newValue = modifier.getValue(); + int amount = info.isShiftClick() + ? (modifier.getValue() == modifier.getMinValue() || info.isRightClick() && modifier.getValue() == (10 - (modifier.getMinValue() - 1)) ? 9 : 10) + : 1; + newValue += info.isRightClick() ? -amount : amount; + + if (newValue > modifier.getMaxValue()) + newValue = modifier.getMinValue(); + if (newValue < modifier.getMinValue()) + newValue = modifier.getMaxValue(); + + modifier.setValue(newValue); + modifier.playValueChangeTitle(); + SoundSample.CLICK.play(info.getPlayer()); + } + + @Nonnull + public static String getColoredChallengeName(@Nonnull AbstractChallenge challenge) { + ItemBuilder item = challenge.createDisplayItem(); + ItemDescription description = item.getBuiltByItemDescription(); + if (description == null) return Message.NULL; + return description.getOriginalName(); + } + + public static void breakBlock(@Nonnull Block block, @Nullable ItemStack tool) { + breakBlock(block, tool, null); + } + + public static void breakBlock(@Nonnull Block block, @Nullable ItemStack tool, @Nullable Inventory targetInventory) { + + if (!ChallengeAPI.getDropChance(block.getType())) return; + boolean putIntoInventory = ChallengeAPI.getItemsDirectIntoInventory() && targetInventory != null; + + List customDrops = ChallengeAPI.getCustomDrops(block.getType()); + Location location = block.getLocation().clone().add(0.5, 0, 0.5); + if (!customDrops.isEmpty()) { + if (putIntoInventory) { + customDrops.forEach(drop -> InventoryUtils.dropOrGiveItem(targetInventory, location, drop)); + } else { + customDrops.forEach(drop -> block.getWorld().dropItem(location, new ItemStack(drop))); + } + block.setType(Material.AIR); + return; + } + + if (putIntoInventory) { + block.getDrops(tool).forEach(drop -> InventoryUtils.dropOrGiveItem(targetInventory, location, drop)); + block.setType(Material.AIR); + return; + } + + block.breakNaturally(tool); + + } + + public static void dropItem(@Nonnull ItemStack itemStack, @Nonnull Location dropLocation, @Nonnull Inventory inventory) { + boolean directIntoInventory = Challenges.getInstance().getBlockDropManager().isItemsDirectIntoInventory(); + + if (directIntoInventory) { + InventoryUtils.dropOrGiveItem(inventory, dropLocation, itemStack); + return; + } + + if (dropLocation.getWorld() == null) return; + dropLocation.getWorld().dropItemNaturally(dropLocation, itemStack); + + } + + public static boolean ignoreDamager(@Nonnull Entity damager) { + Player damagerPlayer = getDamagerPlayer(damager); + if (damagerPlayer == null) return false; + return AbstractChallenge.ignorePlayer(damagerPlayer); + } + + public static Player getDamagerPlayer(@Nonnull Entity damager) { + if (damager instanceof Player) return ((Player) damager); + if (damager instanceof Projectile && ((Projectile) damager).getShooter() instanceof Player) + return ((Player) ((Projectile) damager).getShooter()); + return null; + } + + public static List getIngamePlayers() { + return Bukkit.getOnlinePlayers().stream().filter(player -> !AbstractChallenge.ignorePlayer(player)).collect(Collectors.toList()); + } + + public static void playToggleChallengeTitle(@Nonnull AbstractChallenge challenge) { + playToggleChallengeTitle(challenge, challenge.isEnabled()); + } + + public static void playToggleChallengeTitle(@Nonnull AbstractChallenge challenge, boolean enabled) { + Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(enabled ? Message.forName("title-challenge-enabled") : Message.forName("title-challenge-disabled"), getColoredChallengeName(challenge)); + } + + public static void playChangeChallengeValueTitle(@Nonnull AbstractChallenge challenge, @Nonnull IModifier modifier) { + playChangeChallengeValueTitle(challenge, modifier.getValue()); + } + + public static void playChangeChallengeValueTitle(@Nonnull Modifier modifier) { + playChangeChallengeValueTitle(modifier, modifier.getValue()); + } + + public static void playChangeChallengeValueTitle(@Nonnull AbstractChallenge modifier, @Nullable Object value) { + Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(Message.forName("title-challenge-value-changed"), getColoredChallengeName(modifier), value); + } + + public static void playChallengeHeartsValueChangeTitle(@Nonnull AbstractChallenge challenge, int health) { + playChangeChallengeValueTitle(challenge, (health / 2f) + " §c❤"); + } + + public static void playChallengeHeartsValueChangeTitle(@Nonnull Modifier modifier) { + playChallengeHeartsValueChangeTitle(modifier, modifier.getValue()); + } + + public static void playChallengeSecondsValueChangeTitle(@Nonnull AbstractChallenge challenge, int seconds) { + playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds").asString(seconds)); + } + + public static void playChallengeSecondsRangeValueChangeTitle(@Nonnull AbstractChallenge challenge, int min, int max) { + playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds-range").asString(min, max)); + } + + public static void playChallengeMinutesValueChangeTitle(@Nonnull AbstractChallenge challenge, int seconds) { + playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-minutes").asString(seconds)); + } + + @Nonnull + public static String[] getTimeRangeSettingsDescription(@Nonnull Modifier modifier, @Nonnegative int multiplier, @Nonnegative int range) { + return Message.forName("item-time-seconds-range-description").asArray(modifier.getValue() * multiplier - range, modifier.getValue() * multiplier + range); + } + + @Nonnull + public static String[] getTimeRangeSettingsDescription(@Nonnull Modifier modifier, @Nonnegative int range) { + return getTimeRangeSettingsDescription(modifier, 1, range); + } + + public static boolean finalDamageIsNull(@Nonnull EntityDamageEvent event) { + return getFinalDamage(event) == 0; + } + + public static double getFinalDamage(@Nonnull EntityDamageEvent event) { + return event.getFinalDamage() + event.getDamage(DamageModifier.ABSORPTION); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java index b46770766..e567f1e48 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java @@ -23,121 +23,121 @@ public final class GoalHelper { - public static final int LEADERBOARD_SIZE = 9; - - private GoalHelper() { - } - - public static void handleSetEnabled(@Nonnull IGoal goal, boolean enabled) { - if (Challenges.getInstance().getChallengeManager().getCurrentGoal() != goal && enabled) { - Challenges.getInstance().getChallengeManager().setCurrentGoal(goal); - } else if (Challenges.getInstance().getChallengeManager().getCurrentGoal() == goal && !enabled) { - Challenges.getInstance().getChallengeManager().setCurrentGoal(null); - } - } - - @Nonnull - public static SortedMap> createLeaderboardFromPoints(@Nonnull Map points) { - SortedMap> leaderboard = new TreeMap<>(Collections.reverseOrder()); - for (Entry entry : points.entrySet()) { - List players = leaderboard.computeIfAbsent(entry.getValue(), key -> new ArrayList<>()); - players.add(entry.getKey()); - } - return leaderboard; - } - - @Nonnull - public static Map createPointsFromValues(@Nonnull AtomicInteger mostPoints, @Nonnull Map map, @Nonnull ToIntBiFunction mapper, boolean zeros) { - Map result = new HashMap<>(); - if (zeros) ChallengeAPI.getIngamePlayers().forEach(player -> result.put(player, 0)); - for (Entry entry : map.entrySet()) { - Player player = Bukkit.getPlayer(entry.getKey()); - if (player == null) - continue; - // Ignore spectators when playing but show spectators after challenge end - if (!AbstractChallenge.ignorePlayer(player) || (ChallengeAPI.isPaused() && player.getGameMode() == GameMode.SPECTATOR)) { - int points = mapper.applyAsInt(entry.getKey(), entry.getValue()); - if (points == 0) - continue; - - result.put(player, points); - - if (points >= mostPoints.get()) - mostPoints.set(points); - } - } - return result; - } - - public static int determinePosition(@Nonnull SortedMap> map, @Nonnull E target) { - int position = 1; - for (Entry> entry : map.entrySet()) { - if (entry.getValue().contains(target)) break; - position++; - } - return position; - } - - @Nonnull - public static BiConsumer createScoreboard(@Nonnull Supplier> points) { - return createScoreboard(points, player -> new LinkedList<>()); - } - - @Nonnull - public static BiConsumer createScoreboard(@Nonnull Supplier> points, Function> additionalLines) { - return (scoreboard, player) -> { - SortedMap> leaderboard = GoalHelper.createLeaderboardFromPoints(points.get()); - int playerPlace = GoalHelper.determinePosition(leaderboard, player); - - scoreboard.addLine(""); - scoreboard.addLine(Message.forName("your-place").asString(playerPlace)); - scoreboard.addLine(""); - { - int place = 1; - int displayed = 0; - for (Entry> entry : leaderboard.entrySet()) { - List players = entry.getValue(); - for (Player current : players) { - displayed++; - if (displayed >= LEADERBOARD_SIZE) break; - scoreboard.addLine(Message.forName("scoreboard-leaderboard").asString(place, NameHelper.getName(current), NumberFormatter.MIDDLE_NUMBER.format(entry.getKey()))); - } - if (displayed == LEADERBOARD_SIZE) break; - place++; - } - } - scoreboard.addLine(""); - - List lines = additionalLines.apply(player); - if (!lines.isEmpty()) { - int linesThatCanBeAdded = 15 - scoreboard.getLines().size() - 1; - for (int i = 0; i < lines.size() && linesThatCanBeAdded > 0; i++) { - linesThatCanBeAdded--; - String line = lines.get(i); - scoreboard.addLine(line); - } - } - }; - } - - public static void getWinnersOnEnd(@Nonnull List winners, @Nonnull Map points) { - AtomicInteger mostPoints = new AtomicInteger(); - List currentWinners = new LinkedList<>(); - - for (Entry entry : points.entrySet()) { - if (entry.getValue() <= 0) continue; - if (entry.getValue() == mostPoints.get()) { - currentWinners.add(entry.getKey()); - continue; - } - if (entry.getValue() > mostPoints.get()) { - mostPoints.set(entry.getValue()); - currentWinners.clear(); - currentWinners.add(entry.getKey()); - } - } - - winners.addAll(currentWinners); - } + public static final int LEADERBOARD_SIZE = 9; + + private GoalHelper() { + } + + public static void handleSetEnabled(@Nonnull IGoal goal, boolean enabled) { + if (Challenges.getInstance().getChallengeManager().getCurrentGoal() != goal && enabled) { + Challenges.getInstance().getChallengeManager().setCurrentGoal(goal); + } else if (Challenges.getInstance().getChallengeManager().getCurrentGoal() == goal && !enabled) { + Challenges.getInstance().getChallengeManager().setCurrentGoal(null); + } + } + + @Nonnull + public static SortedMap> createLeaderboardFromPoints(@Nonnull Map points) { + SortedMap> leaderboard = new TreeMap<>(Collections.reverseOrder()); + for (Entry entry : points.entrySet()) { + List players = leaderboard.computeIfAbsent(entry.getValue(), key -> new ArrayList<>()); + players.add(entry.getKey()); + } + return leaderboard; + } + + @Nonnull + public static Map createPointsFromValues(@Nonnull AtomicInteger mostPoints, @Nonnull Map map, @Nonnull ToIntBiFunction mapper, boolean zeros) { + Map result = new HashMap<>(); + if (zeros) ChallengeAPI.getIngamePlayers().forEach(player -> result.put(player, 0)); + for (Entry entry : map.entrySet()) { + Player player = Bukkit.getPlayer(entry.getKey()); + if (player == null) + continue; + // Ignore spectators when playing but show spectators after challenge end + if (!AbstractChallenge.ignorePlayer(player) || (ChallengeAPI.isPaused() && player.getGameMode() == GameMode.SPECTATOR)) { + int points = mapper.applyAsInt(entry.getKey(), entry.getValue()); + if (points == 0) + continue; + + result.put(player, points); + + if (points >= mostPoints.get()) + mostPoints.set(points); + } + } + return result; + } + + public static int determinePosition(@Nonnull SortedMap> map, @Nonnull E target) { + int position = 1; + for (Entry> entry : map.entrySet()) { + if (entry.getValue().contains(target)) break; + position++; + } + return position; + } + + @Nonnull + public static BiConsumer createScoreboard(@Nonnull Supplier> points) { + return createScoreboard(points, player -> new LinkedList<>()); + } + + @Nonnull + public static BiConsumer createScoreboard(@Nonnull Supplier> points, Function> additionalLines) { + return (scoreboard, player) -> { + SortedMap> leaderboard = GoalHelper.createLeaderboardFromPoints(points.get()); + int playerPlace = GoalHelper.determinePosition(leaderboard, player); + + scoreboard.addLine(""); + scoreboard.addLine(Message.forName("your-place").asString(playerPlace)); + scoreboard.addLine(""); + { + int place = 1; + int displayed = 0; + for (Entry> entry : leaderboard.entrySet()) { + List players = entry.getValue(); + for (Player current : players) { + displayed++; + if (displayed >= LEADERBOARD_SIZE) break; + scoreboard.addLine(Message.forName("scoreboard-leaderboard").asString(place, NameHelper.getName(current), NumberFormatter.MIDDLE_NUMBER.format(entry.getKey()))); + } + if (displayed == LEADERBOARD_SIZE) break; + place++; + } + } + scoreboard.addLine(""); + + List lines = additionalLines.apply(player); + if (!lines.isEmpty()) { + int linesThatCanBeAdded = 15 - scoreboard.getLines().size() - 1; + for (int i = 0; i < lines.size() && linesThatCanBeAdded > 0; i++) { + linesThatCanBeAdded--; + String line = lines.get(i); + scoreboard.addLine(line); + } + } + }; + } + + public static void getWinnersOnEnd(@Nonnull List winners, @Nonnull Map points) { + AtomicInteger mostPoints = new AtomicInteger(); + List currentWinners = new LinkedList<>(); + + for (Entry entry : points.entrySet()) { + if (entry.getValue() <= 0) continue; + if (entry.getValue() == mostPoints.get()) { + currentWinners.add(entry.getKey()); + continue; + } + if (entry.getValue() > mostPoints.get()) { + mostPoints.set(entry.getValue()); + currentWinners.clear(); + currentWinners.add(entry.getKey()); + } + } + + winners.addAll(currentWinners); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java index 4e10f6821..1f10fa067 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java @@ -19,140 +19,140 @@ public class SubSettingsHelper { - public static final String - ENTITY_TYPE = "entity_type", - BLOCK = "block", - ANY = "any", - ITEM = "item", - LIQUID = "liquid", - TARGET_ENTITY = "target_entity", - STRUCTURE = "structure"; - - public static ChooseMultipleItemSubSettingBuilder createEntityTypeSettingsBuilder(boolean any, boolean player) { - return SubSettingsBuilder.createChooseMultipleItem(ENTITY_TYPE).fill(builder -> { - - if (any) { - builder.addSetting(ANY, new ItemBuilder( - Material.NETHER_STAR, Message.forName("item-custom-setting-entity_type-any")).build()); - } - if (player) { - builder.addSetting("PLAYER", new ItemBuilder(Material.PLAYER_HEAD, Message.forName("item-custom-setting-entity_type-player")).build()); - } - for (EntityType type : EntityType.values()) { - if (!type.isSpawnable() || !type.isAlive()) continue; - try { - Material spawnEgg = Material.valueOf(type.name() + "_SPAWN_EGG"); - builder.addSetting(type.name(), new ItemBuilder(spawnEgg, - DefaultItem.getItemPrefix() + BukkitStringUtils.getEntityName(type).toPlainText()).build()); - } catch (Exception ex) { - builder.addSetting(type.name(), new ItemBuilder(Material.STRUCTURE_VOID, - DefaultItem.getItemPrefix() + BukkitStringUtils.getEntityName(type).toPlainText())); - } - } - }); - } - - public static ChooseMultipleItemSubSettingBuilder createBlockSettingsBuilder() { - return SubSettingsBuilder.createChooseMultipleItem(BLOCK).fill(builder -> { - builder.addSetting(ANY, new ItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-setting-block-any")).build()); - for (Material material : ExperimentalUtils.getMaterials()) { - if (material.isBlock() && material.isItem() && !BukkitReflectionUtils.isAir(material)) { - builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); - } - } - }); - } - - public static ChooseMultipleItemSubSettingBuilder createItemSettingsBuilder() { - return SubSettingsBuilder.createChooseMultipleItem(ITEM).fill(builder -> { - builder.addSetting(ANY, new ItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-setting-item-any")).build()); - for (Material material : ExperimentalUtils.getMaterials()) { - if (material.isItem() && !BukkitReflectionUtils.isAir(material)) { - builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); - } - } - }); - } - - public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean everyMob) { - return createEntityTargetSettingsBuilder(everyMob, false); - } - - public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean everyMob, boolean onlyPlayer) { - return createEntityTargetSettingsBuilder(everyMob, onlyPlayer, false); - } - - public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean everyMob, boolean onlyPlayer, boolean console) { - ChooseItemSubSettingsBuilder builder = SubSettingsBuilder.createChooseItem(TARGET_ENTITY); - - if (console) { - builder.addSetting("console", new ItemBuilder(Material.COMMAND_BLOCK_MINECART, Message.forName("item-custom-setting-target-console"))); - } - - if (!onlyPlayer) { - builder.addSetting("current", new ItemBuilder(Material.DRAGON_HEAD, - Message.forName("item-custom-setting-target-current"))); - } - - builder.addSetting("current_player", new ItemBuilder(Material.PLAYER_HEAD, - Message.forName("item-custom-setting-target-current_player"))); - builder.addSetting("random_player", new ItemBuilder(Material.ZOMBIE_HEAD, - Message.forName("item-custom-setting-target-random_player"))); - builder.addSetting("every_player", new ItemBuilder(Material.PLAYER_HEAD, - Message.forName("item-custom-setting-target-every_player"))); - - if (everyMob && !onlyPlayer) { - builder.addSetting("every_mob", new ItemBuilder(Material.WITHER_SKELETON_SKULL, - Message.forName("item-custom-setting-target-every_mob"))); - builder.addSetting("every_mob_except_current", new ItemBuilder(Material.SKELETON_SKULL, - Message.forName("item-custom-setting-target-every_mob_except_current"))); - builder.addSetting("every_mob_except_players", new ItemBuilder(Material.SKELETON_SKULL, - Message.forName("item-custom-setting-target-every_mob_except_players"))); - } - return builder; - } - - public static SubSettingsBuilder createPotionSettingsBuilder(boolean potionType, - boolean potionTime) { - - SubSettingsBuilder potionSettings = SubSettingsBuilder.createValueItem().fill(builder -> { - - if (potionTime) { - builder.addModifierSetting("length", new ItemBuilder(Material.CLOCK, - Message.forName("item-random-effect-length-challenge")), - 30, 1, 60, - value -> "", - value -> Message.forName(value == 1 ? "second" : "seconds").asString()); - } - builder.addModifierSetting("amplifier", new ItemBuilder(Material.STONE_SWORD, - Message.forName("item-random-effect-amplifier-challenge")), - 3, 1, 8, - value -> Message.forName("amplifier").asString(), - integer -> ""); - }); - - if (potionType) { - potionSettings = potionSettings.createChooseItemChild("potion_type").fill(builder -> { - for (PotionEffectType effectType : PotionEffectType.values()) { - builder.addSetting(effectType.getName(), new PotionBuilder(Material.POTION, - DefaultItem.getItemPrefix() + StringUtils.getEnumName(effectType.getName())) - .addEffect(effectType.createEffect(1, 0)) - .color(effectType.getColor()).build()); - } - }); - } - - - return potionSettings; - } - - public static SubSettingsBuilder createStructureSettingsBuilder() { - return SubSettingsBuilder.createChooseItem(STRUCTURE).fill(builder -> { - builder.addSetting("random_structure", new ItemBuilder(Material.STRUCTURE_BLOCK, Message.forName("item-custom-action-place_structure-random")).build()); - for (StructureType structure : StructureType.getStructureTypes().values()) { - builder.addSetting(structure.getName(), new ItemBuilder(StructureUtils.getStructureIcon(structure), DefaultItem.getItemPrefix() + StringUtils.getEnumName(structure.getName())).build()); - } - }); - } + public static final String + ENTITY_TYPE = "entity_type", + BLOCK = "block", + ANY = "any", + ITEM = "item", + LIQUID = "liquid", + TARGET_ENTITY = "target_entity", + STRUCTURE = "structure"; + + public static ChooseMultipleItemSubSettingBuilder createEntityTypeSettingsBuilder(boolean any, boolean player) { + return SubSettingsBuilder.createChooseMultipleItem(ENTITY_TYPE).fill(builder -> { + + if (any) { + builder.addSetting(ANY, new ItemBuilder( + Material.NETHER_STAR, Message.forName("item-custom-setting-entity_type-any")).build()); + } + if (player) { + builder.addSetting("PLAYER", new ItemBuilder(Material.PLAYER_HEAD, Message.forName("item-custom-setting-entity_type-player")).build()); + } + for (EntityType type : EntityType.values()) { + if (!type.isSpawnable() || !type.isAlive()) continue; + try { + Material spawnEgg = Material.valueOf(type.name() + "_SPAWN_EGG"); + builder.addSetting(type.name(), new ItemBuilder(spawnEgg, + DefaultItem.getItemPrefix() + BukkitStringUtils.getEntityName(type).toPlainText()).build()); + } catch (Exception ex) { + builder.addSetting(type.name(), new ItemBuilder(Material.STRUCTURE_VOID, + DefaultItem.getItemPrefix() + BukkitStringUtils.getEntityName(type).toPlainText())); + } + } + }); + } + + public static ChooseMultipleItemSubSettingBuilder createBlockSettingsBuilder() { + return SubSettingsBuilder.createChooseMultipleItem(BLOCK).fill(builder -> { + builder.addSetting(ANY, new ItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-setting-block-any")).build()); + for (Material material : ExperimentalUtils.getMaterials()) { + if (material.isBlock() && material.isItem() && !BukkitReflectionUtils.isAir(material)) { + builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); + } + } + }); + } + + public static ChooseMultipleItemSubSettingBuilder createItemSettingsBuilder() { + return SubSettingsBuilder.createChooseMultipleItem(ITEM).fill(builder -> { + builder.addSetting(ANY, new ItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-setting-item-any")).build()); + for (Material material : ExperimentalUtils.getMaterials()) { + if (material.isItem() && !BukkitReflectionUtils.isAir(material)) { + builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); + } + } + }); + } + + public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean everyMob) { + return createEntityTargetSettingsBuilder(everyMob, false); + } + + public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean everyMob, boolean onlyPlayer) { + return createEntityTargetSettingsBuilder(everyMob, onlyPlayer, false); + } + + public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean everyMob, boolean onlyPlayer, boolean console) { + ChooseItemSubSettingsBuilder builder = SubSettingsBuilder.createChooseItem(TARGET_ENTITY); + + if (console) { + builder.addSetting("console", new ItemBuilder(Material.COMMAND_BLOCK_MINECART, Message.forName("item-custom-setting-target-console"))); + } + + if (!onlyPlayer) { + builder.addSetting("current", new ItemBuilder(Material.DRAGON_HEAD, + Message.forName("item-custom-setting-target-current"))); + } + + builder.addSetting("current_player", new ItemBuilder(Material.PLAYER_HEAD, + Message.forName("item-custom-setting-target-current_player"))); + builder.addSetting("random_player", new ItemBuilder(Material.ZOMBIE_HEAD, + Message.forName("item-custom-setting-target-random_player"))); + builder.addSetting("every_player", new ItemBuilder(Material.PLAYER_HEAD, + Message.forName("item-custom-setting-target-every_player"))); + + if (everyMob && !onlyPlayer) { + builder.addSetting("every_mob", new ItemBuilder(Material.WITHER_SKELETON_SKULL, + Message.forName("item-custom-setting-target-every_mob"))); + builder.addSetting("every_mob_except_current", new ItemBuilder(Material.SKELETON_SKULL, + Message.forName("item-custom-setting-target-every_mob_except_current"))); + builder.addSetting("every_mob_except_players", new ItemBuilder(Material.SKELETON_SKULL, + Message.forName("item-custom-setting-target-every_mob_except_players"))); + } + return builder; + } + + public static SubSettingsBuilder createPotionSettingsBuilder(boolean potionType, + boolean potionTime) { + + SubSettingsBuilder potionSettings = SubSettingsBuilder.createValueItem().fill(builder -> { + + if (potionTime) { + builder.addModifierSetting("length", new ItemBuilder(Material.CLOCK, + Message.forName("item-random-effect-length-challenge")), + 30, 1, 60, + value -> "", + value -> Message.forName(value == 1 ? "second" : "seconds").asString()); + } + builder.addModifierSetting("amplifier", new ItemBuilder(Material.STONE_SWORD, + Message.forName("item-random-effect-amplifier-challenge")), + 3, 1, 8, + value -> Message.forName("amplifier").asString(), + integer -> ""); + }); + + if (potionType) { + potionSettings = potionSettings.createChooseItemChild("potion_type").fill(builder -> { + for (PotionEffectType effectType : PotionEffectType.values()) { + builder.addSetting(effectType.getName(), new PotionBuilder(Material.POTION, + DefaultItem.getItemPrefix() + StringUtils.getEnumName(effectType.getName())) + .addEffect(effectType.createEffect(1, 0)) + .color(effectType.getColor()).build()); + } + }); + } + + + return potionSettings; + } + + public static SubSettingsBuilder createStructureSettingsBuilder() { + return SubSettingsBuilder.createChooseItem(STRUCTURE).fill(builder -> { + builder.addSetting("random_structure", new ItemBuilder(Material.STRUCTURE_BLOCK, Message.forName("item-custom-action-place_structure-random")).build()); + for (StructureType structure : StructureType.getStructureTypes().values()) { + builder.addSetting(structure.getName(), new ItemBuilder(StructureUtils.getStructureIcon(structure), DefaultItem.getItemPrefix() + StringUtils.getEnumName(structure.getName())).build()); + } + }); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java index 803440ff4..11e321c84 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java @@ -12,127 +12,127 @@ public final class ItemDescription { - private static final Document config = Challenges.getInstance().getConfigDocument().getDocument("design"); - - private final String[] colors; - private final String[] lore; - private final String name; - private final String originalName; - - public ItemDescription(@Nonnull String[] themeColors, @Nonnull String name, @Nonnull String[] formattedLore) { - this.colors = themeColors; - this.name = Message.forName("item-prefix") + name; - this.originalName = name; - this.lore = formattedLore; - } - - public ItemDescription(@Nonnull String[] description) { - if (description.length == 0) - throw new IllegalArgumentException("Invalid item description: Cannot be empty"); - - originalName = description[0]; - name = Message.forName("item-prefix") + originalName; - colors = determineColors(originalName); - - List loreOutput = new ArrayList<>(); - fillLore(description, loreOutput); - lore = loreOutput.toArray(new String[0]); - } - - public static ItemDescription empty() { - return new ItemDescription(new String[]{"§e"}, Message.NULL, new String[0]); - } - - @Nonnull - public String getName() { - return name; - } - - @Nonnull - public String getOriginalName() { - return originalName; - } - - @Nonnull - public String[] getTheme() { - return colors; - } - - @Nonnull - public String[] getLore() { - return lore; - } - - private void fillLore(@Nonnull String[] origin, @Nonnull List output) { - - String colorBefore = "§7"; - boolean inColor = false; - boolean nextIsColor = false; - int themeIndex = 0; - - // Start at 1, first entry is not content of lore - for (int i = 1; i < origin.length; i++) { - StringBuilder line = new StringBuilder(); - line.append(colorBefore); - for (char c : origin[i].toCharArray()) { - if (c == '*') { - if (inColor) { - line.append(colorBefore); - inColor = false; - } else { - line.append(colors[themeIndex]); - themeIndex++; - if (themeIndex >= colors.length) - themeIndex = 0; - inColor = true; - } - } else { - line.append(c); - if (c == '§') { - nextIsColor = true; - } else if (nextIsColor) { - nextIsColor = false; - if (ColorConversions.isValidColorCode(c)) - colorBefore = ""; - colorBefore += "§" + c; - } - } - } - output.add(line.toString()); - } - - if (output.isEmpty()) return; - if (config.getBoolean("empty-line-above")) output.add(0, " "); - if (config.getBoolean("empty-line-underneath")) output.add(" "); - - } - - private String[] determineColors(@Nonnull String input) { - List colors = new LinkedList<>(); - int colorIndex = 0; - - boolean nextIsCode = false; - for (char c : input.toCharArray()) { - if (c == ChatColor.COLOR_CHAR) { - nextIsCode = true; - continue; - } - if (!nextIsCode) continue; - nextIsCode = false; - - String latestColors = ""; - if (colors.size() > colorIndex) - latestColors = colors.remove(colorIndex); - - colors.add(latestColors + ChatColor.COLOR_CHAR + c); - - if (ColorConversions.isValidColorCode(c)) - colorIndex++; - } - - if (colors.isEmpty()) - colors.add("§e"); - return colors.toArray(new String[0]); - } + private static final Document config = Challenges.getInstance().getConfigDocument().getDocument("design"); + + private final String[] colors; + private final String[] lore; + private final String name; + private final String originalName; + + public ItemDescription(@Nonnull String[] themeColors, @Nonnull String name, @Nonnull String[] formattedLore) { + this.colors = themeColors; + this.name = Message.forName("item-prefix") + name; + this.originalName = name; + this.lore = formattedLore; + } + + public ItemDescription(@Nonnull String[] description) { + if (description.length == 0) + throw new IllegalArgumentException("Invalid item description: Cannot be empty"); + + originalName = description[0]; + name = Message.forName("item-prefix") + originalName; + colors = determineColors(originalName); + + List loreOutput = new ArrayList<>(); + fillLore(description, loreOutput); + lore = loreOutput.toArray(new String[0]); + } + + public static ItemDescription empty() { + return new ItemDescription(new String[]{"§e"}, Message.NULL, new String[0]); + } + + @Nonnull + public String getName() { + return name; + } + + @Nonnull + public String getOriginalName() { + return originalName; + } + + @Nonnull + public String[] getTheme() { + return colors; + } + + @Nonnull + public String[] getLore() { + return lore; + } + + private void fillLore(@Nonnull String[] origin, @Nonnull List output) { + + String colorBefore = "§7"; + boolean inColor = false; + boolean nextIsColor = false; + int themeIndex = 0; + + // Start at 1, first entry is not content of lore + for (int i = 1; i < origin.length; i++) { + StringBuilder line = new StringBuilder(); + line.append(colorBefore); + for (char c : origin[i].toCharArray()) { + if (c == '*') { + if (inColor) { + line.append(colorBefore); + inColor = false; + } else { + line.append(colors[themeIndex]); + themeIndex++; + if (themeIndex >= colors.length) + themeIndex = 0; + inColor = true; + } + } else { + line.append(c); + if (c == '§') { + nextIsColor = true; + } else if (nextIsColor) { + nextIsColor = false; + if (ColorConversions.isValidColorCode(c)) + colorBefore = ""; + colorBefore += "§" + c; + } + } + } + output.add(line.toString()); + } + + if (output.isEmpty()) return; + if (config.getBoolean("empty-line-above")) output.add(0, " "); + if (config.getBoolean("empty-line-underneath")) output.add(" "); + + } + + private String[] determineColors(@Nonnull String input) { + List colors = new LinkedList<>(); + int colorIndex = 0; + + boolean nextIsCode = false; + for (char c : input.toCharArray()) { + if (c == ChatColor.COLOR_CHAR) { + nextIsCode = true; + continue; + } + if (!nextIsCode) continue; + nextIsCode = false; + + String latestColors = ""; + if (colors.size() > colorIndex) + latestColors = colors.remove(colorIndex); + + colors.add(latestColors + ChatColor.COLOR_CHAR + c); + + if (ColorConversions.isValidColorCode(c)) + colorIndex++; + } + + if (colors.isEmpty()) + colors.add("§e"); + return colors.toArray(new String[0]); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java index 302c0af39..2d5082f33 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java @@ -15,69 +15,69 @@ public interface Message { - String NULL = "§r§fN/A"; - Collection UNKNOWN_MESSAGES = new ArrayList<>(); + String NULL = "§r§fN/A"; + Collection UNKNOWN_MESSAGES = new ArrayList<>(); - static String unknown(@Nonnull String name) { - if (!UNKNOWN_MESSAGES.contains(name)) { - UNKNOWN_MESSAGES.add(name); - Logger.warn("Tried accessing unknown messages '{}'", name); - } + static String unknown(@Nonnull String name) { + if (!UNKNOWN_MESSAGES.contains(name)) { + UNKNOWN_MESSAGES.add(name); + Logger.warn("Tried accessing unknown messages '{}'", name); + } - return name; - } + return name; + } - @Nonnull - @CheckReturnValue - static Message forName(@Nonnull String name) { - return MessageManager.getOrCreateMessage(name); - } + @Nonnull + @CheckReturnValue + static Message forName(@Nonnull String name) { + return MessageManager.getOrCreateMessage(name); + } - @Nonnull - String asString(@Nonnull Object... args); + @Nonnull + String asString(@Nonnull Object... args); - @Nonnull - BaseComponent asComponent(@Nonnull Object... args); + @Nonnull + BaseComponent asComponent(@Nonnull Object... args); - @Nonnull - String asRandomString(@Nonnull IRandom random, @Nonnull Object... args); + @Nonnull + String asRandomString(@Nonnull IRandom random, @Nonnull Object... args); - @Nonnull - BaseComponent asRandomComponent(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args); + @Nonnull + BaseComponent asRandomComponent(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args); - @Nonnull - String asRandomString(@Nonnull Object... args); + @Nonnull + String asRandomString(@Nonnull Object... args); - @Nonnull - String[] asArray(@Nonnull Object... args); + @Nonnull + String[] asArray(@Nonnull Object... args); - @Nonnull - BaseComponent[] asComponentArray(@Nullable Prefix prefix, @Nonnull Object... args); + @Nonnull + BaseComponent[] asComponentArray(@Nullable Prefix prefix, @Nonnull Object... args); - @Nonnull - ItemDescription asItemDescription(@Nonnull Object... args); + @Nonnull + ItemDescription asItemDescription(@Nonnull Object... args); - void send(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args); + void send(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args); - void sendRandom(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args); + void sendRandom(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args); - void sendRandom(@Nonnull IRandom random, @Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args); + void sendRandom(@Nonnull IRandom random, @Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args); - void broadcast(@Nonnull Prefix prefix, @Nonnull Object... args); + void broadcast(@Nonnull Prefix prefix, @Nonnull Object... args); - void broadcastRandom(@Nonnull Prefix prefix, @Nonnull Object... args); + void broadcastRandom(@Nonnull Prefix prefix, @Nonnull Object... args); - void broadcastRandom(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args); + void broadcastRandom(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args); - void broadcastTitle(@Nonnull Object... args); + void broadcastTitle(@Nonnull Object... args); - void sendTitle(@Nonnull Player player, @Nonnull Object... args); + void sendTitle(@Nonnull Player player, @Nonnull Object... args); - void sendTitleInstant(@Nonnull Player player, @Nonnull Object... args); + void sendTitleInstant(@Nonnull Player player, @Nonnull Object... args); - void setValue(@Nonnull String[] value); + void setValue(@Nonnull String[] value); - @Nonnull - String getName(); + @Nonnull + String getName(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java index 3ab88d5e1..710264bdc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java @@ -10,61 +10,61 @@ public class Prefix { - private static final Map values = new HashMap<>(); + private static final Map values = new HashMap<>(); - public static final Prefix - CHALLENGES = forName("challenges", "§6Challenges"), - CUSTOM = forName("custom", "§bCustom"), - DAMAGE = forName("damage", "§cDamage"), - POSITION = forName("position", "§9Position"), - BACKPACK = forName("backpack", "§aBackpack"), - TIMER = forName("timer", "§5Timer"); + public static final Prefix + CHALLENGES = forName("challenges", "§6Challenges"), + CUSTOM = forName("custom", "§bCustom"), + DAMAGE = forName("damage", "§cDamage"), + POSITION = forName("position", "§9Position"), + BACKPACK = forName("backpack", "§aBackpack"), + TIMER = forName("timer", "§5Timer"); - private final String name; - private final String defaultValue; - private String value; + private final String name; + private final String defaultValue; + private String value; - private Prefix(@Nonnull String name, @Nonnull String defaultValue) { - this.defaultValue = getDefaultValueFor(defaultValue); - this.name = name; - } + private Prefix(@Nonnull String name, @Nonnull String defaultValue) { + this.defaultValue = getDefaultValueFor(defaultValue); + this.name = name; + } - @Nonnull - @CheckReturnValue - public static Collection values() { - return Collections.unmodifiableCollection(values.values()); - } + @Nonnull + @CheckReturnValue + public static Collection values() { + return Collections.unmodifiableCollection(values.values()); + } - @Nonnull - @CheckReturnValue - public static Prefix forName(@Nonnull String name, @Nonnull String defaultValue) { - return values.computeIfAbsent(name, key -> new Prefix(name, defaultValue)); - } + @Nonnull + @CheckReturnValue + public static Prefix forName(@Nonnull String name, @Nonnull String defaultValue) { + return values.computeIfAbsent(name, key -> new Prefix(name, defaultValue)); + } - @Nonnull - @CheckReturnValue - public static Prefix forName(@Nonnull String name) { - return forName(name, name); - } + @Nonnull + @CheckReturnValue + public static Prefix forName(@Nonnull String name) { + return forName(name, name); + } - @Nonnull - public static String getDefaultValueFor(@Nonnull String value) { - return "§8§l┃ " + value + " §8┃ "; - } + @Nonnull + public static String getDefaultValueFor(@Nonnull String value) { + return "§8§l┃ " + value + " §8┃ "; + } - public void setValue(@Nullable String value) { - this.value = value == null ? null : value.endsWith(" ") ? value : value + " "; - } + public void setValue(@Nullable String value) { + this.value = value == null ? null : value.endsWith(" ") ? value : value + " "; + } - @Nonnull - @Override - public String toString() { - return (value == null ? defaultValue : value) + "§7"; - } + @Nonnull + @Override + public String toString() { + return (value == null ? defaultValue : value) + "§7"; + } - @Nonnull - public String getName() { - return name; - } + @Nonnull + public String getName() { + return name; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java index c4cdd53e9..5c888eec8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java @@ -24,202 +24,202 @@ public class MessageImpl implements Message { - protected final String name; - protected String[] value; - - public MessageImpl(@Nonnull String name) { - this.name = name; - } - - @Nonnull - protected static IRandom defaultRandom() { - return IRandom.threadLocal(); - } - - @Nonnull - @Override - public String asString(@Nonnull Object... args) { - if (value == null) return name; - return String.join("\n", asArray(args)); - } - - @Nonnull - @Override - public BaseComponent asComponent(@Nonnull Object... args) { - if (value == null) return new TextComponent(name); - BaseComponent[] components = asComponentArray(null, args); - BaseComponent first = null; - // TODO: This will bug with colors as they wont be added to the next line - for (BaseComponent component : components) { - if (first == null) first = component; - else first.addExtra(component); - } - return first == null ? new TextComponent() : first; - } - - @Nonnull - @Override - public String asRandomString(@Nonnull Object... args) { - return asRandomString(defaultRandom(), args); - } - - @Nonnull - @Override - public String asRandomString(@Nonnull IRandom random, @Nonnull Object... args) { - String[] array = asArray(args); - if (array.length == 0) return Message.unknown(name); - return random.choose(array); - } - - @Nonnull - @Override - public BaseComponent asRandomComponent(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args) { - BaseComponent[] array = asComponentArray(prefix, args); - if (array.length == 0) return new TextComponent(Message.unknown(name)); - return random.choose(array); - } - - @Nonnull - @Override - public String[] asArray(@Nonnull Object... args) { - if (value == null) return new String[]{Message.unknown(name)}; - args = BukkitStringUtils.replaceArguments(args, true); - LanguageLoader loader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); - boolean capsFont = false; - if (loader != null) capsFont = loader.isSmallCapsFont(); - return capsFont ? FontUtils.toSmallCaps(StringUtils.format(value, args)) : StringUtils.format(value, args); - } - - @Nonnull - @Override - public BaseComponent[] asComponentArray(@Nullable Prefix prefix, @Nonnull Object... args) { - if (value == null) return new TextComponent[] { new TextComponent(Message.unknown(name)) }; - return BukkitStringUtils.format(prefix, value, args); - } - - @Nonnull - @Override - public ItemDescription asItemDescription(@Nonnull Object... args) { - if (value == null) { - Message.unknown(name); - return ItemDescription.empty(); - } - return new ItemDescription(asArray(args)); - } - - @Override - public void send(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args) { - doSendLines(component -> target.spigot().sendMessage(component), prefix, asComponentArray(prefix, args)); - } - - @Override - public void sendRandom(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args) { - sendRandom(defaultRandom(), target, prefix, args); - } - - @Override - public void sendRandom(@Nonnull IRandom random, @Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args) { - doSendLine(components -> target.spigot().sendMessage(components), prefix, asRandomComponent(random, prefix, args)); - } - - @Override - public void broadcast(@Nonnull Prefix prefix, @Nonnull Object... args) { - doSendLines(components -> Bukkit.spigot().broadcast(components), prefix, asComponentArray(prefix, args)); - } - - @Override - public void broadcastRandom(@Nonnull Prefix prefix, @Nonnull Object... args) { - broadcastRandom(defaultRandom(), prefix, args); - } - - @Override - public void broadcastRandom(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args) { - doSendLine(component -> Bukkit.spigot().broadcast(component), prefix, asRandomComponent(random, prefix, args)); - } - - private void doSendLines(@Nonnull Consumer sender, @Nonnull Prefix prefix, @Nonnull BaseComponent[] components) { - for (BaseComponent line : components) { - doSendLine(sender, prefix, line); - } - } - - private void doSendLine(@Nonnull Consumer sender, @Nonnull Prefix prefix, BaseComponent component) { - LanguageLoader loader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); - boolean capsFont = false; - if (loader != null) capsFont = loader.isSmallCapsFont(); - - BaseComponent component1 = component; - if (capsFont) { - if (component1 instanceof TextComponent) { - component1 = new TextComponent(FontUtils.toSmallCaps(((TextComponent) component1).getText())); - } - if (component != null) { - List extra = component.getExtra(); - if (extra != null) { - component.setExtra(new LinkedList<>()); - for (BaseComponent baseComponent : extra) { - if (baseComponent instanceof TextComponent) { - String text = ((TextComponent) baseComponent).getText(); - component1.addExtra(new TextComponent(text)); - } else { - component1.addExtra(baseComponent); - } - } - } - } - } - - // Weird bugs can cause this to be null if the line is empty and kicks the player in 1.19+ - if (component1 != null) { - sender.accept(component1); - } - - } - - @Override - public void broadcastTitle(@Nonnull Object... args) { - String[] title = asArray(args); - Bukkit.getOnlinePlayers().forEach(player -> doSendTitle(player, title)); - } - - @Override - public void sendTitle(@Nonnull Player player, @Nonnull Object... args) { - doSendTitle(player, asArray(args)); - } - - @Override - public void sendTitleInstant(@Nonnull Player player, @Nonnull Object... args) { - doSendTitleInstant(player, asArray(args)); - } - - protected void doSendTitle(@Nonnull Player player, @Nonnull String[] title) { - sendTitle(title, (line1, line2) -> Challenges.getInstance().getTitleManager().sendTitle(player, line1, line2)); - } - - protected void doSendTitleInstant(@Nonnull Player player, @Nonnull String[] title) { - sendTitle(title, (line1, line2) -> Challenges.getInstance().getTitleManager().sendTitleInstant(player, line1, line2)); - } - - protected void sendTitle(@Nonnull String[] title, @Nonnull BiConsumer send) { - if (title.length == 0) send.accept("", ""); - else if (title.length == 1) send.accept(title[0], ""); - else send.accept(title[0], title[1]); - } - - @Override - public void setValue(@Nonnull String[] value) { - this.value = value; - } - - @Nonnull - @Override - public String getName() { - return name; - } - - @Override - public String toString() { - return asString(); - } + protected final String name; + protected String[] value; + + public MessageImpl(@Nonnull String name) { + this.name = name; + } + + @Nonnull + protected static IRandom defaultRandom() { + return IRandom.threadLocal(); + } + + @Nonnull + @Override + public String asString(@Nonnull Object... args) { + if (value == null) return name; + return String.join("\n", asArray(args)); + } + + @Nonnull + @Override + public BaseComponent asComponent(@Nonnull Object... args) { + if (value == null) return new TextComponent(name); + BaseComponent[] components = asComponentArray(null, args); + BaseComponent first = null; + // TODO: This will bug with colors as they wont be added to the next line + for (BaseComponent component : components) { + if (first == null) first = component; + else first.addExtra(component); + } + return first == null ? new TextComponent() : first; + } + + @Nonnull + @Override + public String asRandomString(@Nonnull Object... args) { + return asRandomString(defaultRandom(), args); + } + + @Nonnull + @Override + public String asRandomString(@Nonnull IRandom random, @Nonnull Object... args) { + String[] array = asArray(args); + if (array.length == 0) return Message.unknown(name); + return random.choose(array); + } + + @Nonnull + @Override + public BaseComponent asRandomComponent(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args) { + BaseComponent[] array = asComponentArray(prefix, args); + if (array.length == 0) return new TextComponent(Message.unknown(name)); + return random.choose(array); + } + + @Nonnull + @Override + public String[] asArray(@Nonnull Object... args) { + if (value == null) return new String[]{Message.unknown(name)}; + args = BukkitStringUtils.replaceArguments(args, true); + LanguageLoader loader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); + boolean capsFont = false; + if (loader != null) capsFont = loader.isSmallCapsFont(); + return capsFont ? FontUtils.toSmallCaps(StringUtils.format(value, args)) : StringUtils.format(value, args); + } + + @Nonnull + @Override + public BaseComponent[] asComponentArray(@Nullable Prefix prefix, @Nonnull Object... args) { + if (value == null) return new TextComponent[]{new TextComponent(Message.unknown(name))}; + return BukkitStringUtils.format(prefix, value, args); + } + + @Nonnull + @Override + public ItemDescription asItemDescription(@Nonnull Object... args) { + if (value == null) { + Message.unknown(name); + return ItemDescription.empty(); + } + return new ItemDescription(asArray(args)); + } + + @Override + public void send(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args) { + doSendLines(component -> target.spigot().sendMessage(component), prefix, asComponentArray(prefix, args)); + } + + @Override + public void sendRandom(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args) { + sendRandom(defaultRandom(), target, prefix, args); + } + + @Override + public void sendRandom(@Nonnull IRandom random, @Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args) { + doSendLine(components -> target.spigot().sendMessage(components), prefix, asRandomComponent(random, prefix, args)); + } + + @Override + public void broadcast(@Nonnull Prefix prefix, @Nonnull Object... args) { + doSendLines(components -> Bukkit.spigot().broadcast(components), prefix, asComponentArray(prefix, args)); + } + + @Override + public void broadcastRandom(@Nonnull Prefix prefix, @Nonnull Object... args) { + broadcastRandom(defaultRandom(), prefix, args); + } + + @Override + public void broadcastRandom(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args) { + doSendLine(component -> Bukkit.spigot().broadcast(component), prefix, asRandomComponent(random, prefix, args)); + } + + private void doSendLines(@Nonnull Consumer sender, @Nonnull Prefix prefix, @Nonnull BaseComponent[] components) { + for (BaseComponent line : components) { + doSendLine(sender, prefix, line); + } + } + + private void doSendLine(@Nonnull Consumer sender, @Nonnull Prefix prefix, BaseComponent component) { + LanguageLoader loader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); + boolean capsFont = false; + if (loader != null) capsFont = loader.isSmallCapsFont(); + + BaseComponent component1 = component; + if (capsFont) { + if (component1 instanceof TextComponent) { + component1 = new TextComponent(FontUtils.toSmallCaps(((TextComponent) component1).getText())); + } + if (component != null) { + List extra = component.getExtra(); + if (extra != null) { + component.setExtra(new LinkedList<>()); + for (BaseComponent baseComponent : extra) { + if (baseComponent instanceof TextComponent) { + String text = ((TextComponent) baseComponent).getText(); + component1.addExtra(new TextComponent(text)); + } else { + component1.addExtra(baseComponent); + } + } + } + } + } + + // Weird bugs can cause this to be null if the line is empty and kicks the player in 1.19+ + if (component1 != null) { + sender.accept(component1); + } + + } + + @Override + public void broadcastTitle(@Nonnull Object... args) { + String[] title = asArray(args); + Bukkit.getOnlinePlayers().forEach(player -> doSendTitle(player, title)); + } + + @Override + public void sendTitle(@Nonnull Player player, @Nonnull Object... args) { + doSendTitle(player, asArray(args)); + } + + @Override + public void sendTitleInstant(@Nonnull Player player, @Nonnull Object... args) { + doSendTitleInstant(player, asArray(args)); + } + + protected void doSendTitle(@Nonnull Player player, @Nonnull String[] title) { + sendTitle(title, (line1, line2) -> Challenges.getInstance().getTitleManager().sendTitle(player, line1, line2)); + } + + protected void doSendTitleInstant(@Nonnull Player player, @Nonnull String[] title) { + sendTitle(title, (line1, line2) -> Challenges.getInstance().getTitleManager().sendTitleInstant(player, line1, line2)); + } + + protected void sendTitle(@Nonnull String[] title, @Nonnull BiConsumer send) { + if (title.length == 0) send.accept("", ""); + else if (title.length == 1) send.accept(title[0], ""); + else send.accept(title[0], title[1]); + } + + @Override + public void setValue(@Nonnull String[] value) { + this.value = value; + } + + @Nonnull + @Override + public String getName() { + return name; + } + + @Override + public String toString() { + return asString(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java index 80bf53e2e..bf3b08a3a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java @@ -9,24 +9,24 @@ public final class MessageManager { - private static final Map cache = new ConcurrentHashMap<>(); + private static final Map cache = new ConcurrentHashMap<>(); - private MessageManager() { - } + private MessageManager() { + } - @Nonnull - @CheckReturnValue - public static Message getOrCreateMessage(@Nonnull String name) { - return cache.computeIfAbsent(name, key -> new MessageImpl(key)); - } + @Nonnull + @CheckReturnValue + public static Message getOrCreateMessage(@Nonnull String name) { + return cache.computeIfAbsent(name, key -> new MessageImpl(key)); + } - @CheckReturnValue - public static boolean hasMessageInCache(@Nonnull String name) { - return cache.containsKey(name); - } + @CheckReturnValue + public static boolean hasMessageInCache(@Nonnull String name) { + return cache.containsKey(name); + } - public static int getMessageCountCached() { - return cache.size(); - } + public static int getMessageCountCached() { + return cache.size(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java index 97aa23441..7cc40dc00 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java @@ -7,21 +7,21 @@ public abstract class ContentLoader { - @Nonnull - protected final File getMessagesFolder() { - return Challenges.getInstance().getDataFile("messages"); - } - - @Nonnull - protected final File getMessageFile(@Nonnull String name, @Nonnull String extension) { - return new File(getMessagesFolder(), name + "." + extension); - } - - @Nonnull - protected final String getGitHubUrl(@Nonnull String path) { - return "https://raw.githubusercontent.com/anweisen/Challenges/" + (Challenges.getInstance().isDevMode() ? "development" : "master") + "/" + path; - } - - protected abstract void load(); + @Nonnull + protected final File getMessagesFolder() { + return Challenges.getInstance().getDataFile("messages"); + } + + @Nonnull + protected final File getMessageFile(@Nonnull String name, @Nonnull String extension) { + return new File(getMessagesFolder(), name + "." + extension); + } + + @Nonnull + protected final String getGitHubUrl(@Nonnull String path) { + return "https://raw.githubusercontent.com/anweisen/Challenges/" + (Challenges.getInstance().isDevMode() ? "development" : "master") + "/" + path; + } + + protected abstract void load(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index 9390c78ca..556bab187 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -22,187 +22,187 @@ public final class LanguageLoader extends ContentLoader { - public static final String DEFAULT_LANGUAGE = "en"; + public static final String DEFAULT_LANGUAGE = "en"; - public static final String KEY_LANGUAGE = "language", KEY_SMALL_CAPS = "smallcaps", KEY_DIRECT_LANGUAGE_FILE = "manualfile"; + public static final String KEY_LANGUAGE = "language", KEY_SMALL_CAPS = "smallcaps", KEY_DIRECT_LANGUAGE_FILE = "manualfile"; - @Getter + @Getter private static volatile boolean loaded = false; - @Getter + @Getter private String language; - @Getter + @Getter private boolean smallCapsFont; - public File getLanguagePropertiesFile() { - return getMessageFile("language", "properties"); - } + public File getLanguagePropertiesFile() { + return getMessageFile("language", "properties"); + } - public Document getLanguageProperties() { - try { - FileUtils.createFilesIfNecessary(getLanguagePropertiesFile()); + public Document getLanguageProperties() { + try { + FileUtils.createFilesIfNecessary(getLanguagePropertiesFile()); - FileDocument document = FileDocument.readPropertiesFile(getLanguagePropertiesFile()); - } catch (Exception e) { - Logger.error("Could not read language properties", e); - } - return Document.empty(); - } + FileDocument document = FileDocument.readPropertiesFile(getLanguagePropertiesFile()); + } catch (Exception e) { + Logger.error("Could not read language properties", e); + } + return Document.empty(); + } - public void migrateLanguageConfig() { - Document configDocument = Challenges.getInstance().getConfigDocument(); - String oldLanguage = configDocument.getString("language"); - String oldDirectFilePath = configDocument.getString("direct-language-file"); - boolean oldSmallCapsFont = configDocument.getBoolean("small-caps"); + public void migrateLanguageConfig() { + Document configDocument = Challenges.getInstance().getConfigDocument(); + String oldLanguage = configDocument.getString("language"); + String oldDirectFilePath = configDocument.getString("direct-language-file"); + boolean oldSmallCapsFont = configDocument.getBoolean("small-caps"); - Document languageProperties = getLanguageProperties(); - languageProperties.set(KEY_LANGUAGE, oldLanguage); - languageProperties.set(KEY_SMALL_CAPS, oldSmallCapsFont); + Document languageProperties = getLanguageProperties(); + languageProperties.set(KEY_LANGUAGE, oldLanguage); + languageProperties.set(KEY_SMALL_CAPS, oldSmallCapsFont); - if (configDocument.contains("direct-language-file")) { - languageProperties.set(KEY_DIRECT_LANGUAGE_FILE, oldDirectFilePath); - } - } + if (configDocument.contains("direct-language-file")) { + languageProperties.set(KEY_DIRECT_LANGUAGE_FILE, oldDirectFilePath); + } + } @Override - protected void load() { - migrateLanguageConfig(); - - Document config = getLanguageProperties(); - - smallCapsFont = config.getBoolean(KEY_SMALL_CAPS, false); - - if (config.contains(KEY_DIRECT_LANGUAGE_FILE)) { - language = config.getString(KEY_LANGUAGE, DEFAULT_LANGUAGE); - String path = config.getString(KEY_DIRECT_LANGUAGE_FILE); - if (path == null) return; - Logger.info("Using direct language file '{}'", path); - readLanguage(new File(path)); - return; - } - - loadDefault(); - } - - public void changeLanguage(@Nonnull String language) { - if (language.equalsIgnoreCase(this.language)) { - Logger.info("Language '{}' is already selected", language); - return; - } - - this.language = language; - Document properties = getLanguageProperties(); - properties.set(KEY_LANGUAGE, language); + protected void load() { + migrateLanguageConfig(); + + Document config = getLanguageProperties(); + + smallCapsFont = config.getBoolean(KEY_SMALL_CAPS, false); + + if (config.contains(KEY_DIRECT_LANGUAGE_FILE)) { + language = config.getString(KEY_LANGUAGE, DEFAULT_LANGUAGE); + String path = config.getString(KEY_DIRECT_LANGUAGE_FILE); + if (path == null) return; + Logger.info("Using direct language file '{}'", path); + readLanguage(new File(path)); + return; + } + + loadDefault(); + } + + public void changeLanguage(@Nonnull String language) { + if (language.equalsIgnoreCase(this.language)) { + Logger.info("Language '{}' is already selected", language); + return; + } + + this.language = language; + Document properties = getLanguageProperties(); + properties.set(KEY_LANGUAGE, language); try { properties.saveToFile(getLanguagePropertiesFile()); } catch (IOException e) { - Logger.error("Could not save language properties", e); + Logger.error("Could not save language properties", e); } reload(language); - Logger.info("Language changed to '{}'", language); - } - - public void reload(String language) { - this.language = language; - read(); - download(); - init(); - Challenges.getInstance().getScoreboardManager().updateAll(); - Challenges.getInstance().getConfigManager().getSettingsConfig().set("language", language); - } - - private void loadDefault() { - download(); - init(); - read(); - } - - private void init() { - - language = Challenges.getInstance().getConfigDocument().getString("language", DEFAULT_LANGUAGE); - File file = getMessageFile(language, "json"); - - if (!file.exists()) { - if (language.equalsIgnoreCase(DEFAULT_LANGUAGE)) return; - ConsolePrint.unknownLanguage(language); - language = DEFAULT_LANGUAGE; - } - - Logger.debug("Language '{}' is currently selected", language); - - } - - private void download() { - try { - - JsonArray languages = JsonParser.parseString(IOUtils.toString(getGitHubUrl("language/languages.json"))).getAsJsonArray(); - Logger.debug("Fetched languages {}", languages); - for (JsonElement element : languages) { - try { - String name = element.getAsString(); - String url = getGitHubUrl("language/files/" + name + ".json"); - - Document language = Document.parseJson(IOUtils.toString(url)); - File file = getMessageFile(name, "json"); - - Logger.debug("Writing language {} to {}", name, file); - verifyLanguage(language, file, name); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); - Logger.error("Could not download language for {}. {}: {}", element, exception.getClass().getSimpleName(), exception.getMessage()); - } - } - - } catch (Exception ex) { - Logger.error("Could not download languages", ex); - } - } - - private void verifyLanguage(@Nonnull Document download, @Nonnull File file, @Nonnull String name) throws IOException { - Document existing = Document.readJsonFile(file); - FileUtils.createFilesIfNecessary(file); - download.forEach((key, value) -> { - if (!existing.contains(key)) { - Logger.debug("Overwriting message {} in {} with {}", key, name, String.valueOf(value).replace("\"", "§r\"")); - existing.set(key, value); - } - }); - existing.saveToFile(file); - } - - private void read() { - readLanguage(getMessageFile(language, "json")); - } - - private void readLanguage(@Nonnull File file) { - try { - - if (!file.exists()) { - ConsolePrint.unableToGetLanguages(); - return; - } - - int messages = 0; - JsonObject read = JsonParser.parseReader(FileUtils.newBufferedReader(file)).getAsJsonObject(); - for (Entry entry : read.entrySet()) { - Message message = Message.forName(entry.getKey()); - JsonElement element = entry.getValue(); - if (element.isJsonPrimitive()) { - message.setValue(new String[]{element.getAsString()}); - messages++; - } else if (element.isJsonArray()) { - message.setValue(GsonUtils.convertJsonArrayToStringArray(element.getAsJsonArray())); - messages++; - } else { - Logger.warn("Illegal type '{}' for {}", element.getClass().getName(), message.getName()); - } - } - - loaded = true; - Logger.info("Successfully loaded language '{}' from config file: {} message(s)", language, messages); - - } catch (Exception ex) { - Logger.error("Could not read languages", ex); - } - } + Logger.info("Language changed to '{}'", language); + } + + public void reload(String language) { + this.language = language; + read(); + download(); + init(); + Challenges.getInstance().getScoreboardManager().updateAll(); + Challenges.getInstance().getConfigManager().getSettingsConfig().set("language", language); + } + + private void loadDefault() { + download(); + init(); + read(); + } + + private void init() { + + language = Challenges.getInstance().getConfigDocument().getString("language", DEFAULT_LANGUAGE); + File file = getMessageFile(language, "json"); + + if (!file.exists()) { + if (language.equalsIgnoreCase(DEFAULT_LANGUAGE)) return; + ConsolePrint.unknownLanguage(language); + language = DEFAULT_LANGUAGE; + } + + Logger.debug("Language '{}' is currently selected", language); + + } + + private void download() { + try { + + JsonArray languages = JsonParser.parseString(IOUtils.toString(getGitHubUrl("language/languages.json"))).getAsJsonArray(); + Logger.debug("Fetched languages {}", languages); + for (JsonElement element : languages) { + try { + String name = element.getAsString(); + String url = getGitHubUrl("language/files/" + name + ".json"); + + Document language = Document.parseJson(IOUtils.toString(url)); + File file = getMessageFile(name, "json"); + + Logger.debug("Writing language {} to {}", name, file); + verifyLanguage(language, file, name); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("", exception); + Logger.error("Could not download language for {}. {}: {}", element, exception.getClass().getSimpleName(), exception.getMessage()); + } + } + + } catch (Exception ex) { + Logger.error("Could not download languages", ex); + } + } + + private void verifyLanguage(@Nonnull Document download, @Nonnull File file, @Nonnull String name) throws IOException { + Document existing = Document.readJsonFile(file); + FileUtils.createFilesIfNecessary(file); + download.forEach((key, value) -> { + if (!existing.contains(key)) { + Logger.debug("Overwriting message {} in {} with {}", key, name, String.valueOf(value).replace("\"", "§r\"")); + existing.set(key, value); + } + }); + existing.saveToFile(file); + } + + private void read() { + readLanguage(getMessageFile(language, "json")); + } + + private void readLanguage(@Nonnull File file) { + try { + + if (!file.exists()) { + ConsolePrint.unableToGetLanguages(); + return; + } + + int messages = 0; + JsonObject read = JsonParser.parseReader(FileUtils.newBufferedReader(file)).getAsJsonObject(); + for (Entry entry : read.entrySet()) { + Message message = Message.forName(entry.getKey()); + JsonElement element = entry.getValue(); + if (element.isJsonPrimitive()) { + message.setValue(new String[]{element.getAsString()}); + messages++; + } else if (element.isJsonArray()) { + message.setValue(GsonUtils.convertJsonArrayToStringArray(element.getAsJsonArray())); + messages++; + } else { + Logger.warn("Illegal type '{}' for {}", element.getClass().getName(), message.getName()); + } + } + + loaded = true; + Logger.info("Successfully loaded language '{}' from config file: {} message(s)", language, messages); + + } catch (Exception ex) { + Logger.error("Could not read languages", ex); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java index c93ebe49a..9b9a8952d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java @@ -10,100 +10,101 @@ public final class LoaderRegistry { - private static final AtomicInteger loading = new AtomicInteger(); // Keeps track of how many loaders are still loading - private final Map, Subscribers> subscribers = new HashMap<>(); - private final Collection loaders; - public LoaderRegistry(@Nonnull ContentLoader... loaders) { - this.loaders = Arrays.asList(loaders); - } - - private static void execute(@Nonnull Class classOfLoader, @Nonnull Runnable action) { - try { - action.run(); - } catch (Exception ex) { - Logger.error("Could not execute subscriber for {}", classOfLoader.getSimpleName(), ex); - } - } - - public void load() { - if (isLoading()) { - ConsolePrint.alreadyExecutingContentLoader(); - return; - } - - loaders.forEach(this::executeLoader); - } - - private void executeLoader(@Nonnull ContentLoader loader) { - loading.incrementAndGet(); - loader.load(); - loading.decrementAndGet(); - handleCompleteLoading(loader.getClass()); - } - - private void handleCompleteLoading(@Nonnull Class classOfLoader) { - Logger.debug("{} finished loading. {} loader(s) left", classOfLoader.getSimpleName(), loading); - - if (loading.get() == 0) - Logger.info("All loaders finished loading"); - - if (Challenges.getInstance().isEnabled()) { - Subscribers subscribers = this.subscribers.get(classOfLoader); - if (subscribers == null) return; - subscribers.execute(); - } - } - - public void enable() { - for (Subscribers subscribers : subscribers.values()) { - if (subscribers.executed) continue; - subscribers.execute(); - } - } - - public void disable() { - subscribers.clear(); - } - - public boolean isLoading() { - return loading.get() > 0; - } - - public void subscribe(@Nonnull Class classOfLoader, @Nonnull Runnable action) { - Subscribers subscribers = this.subscribers.computeIfAbsent(classOfLoader, key -> new Subscribers(classOfLoader)); - subscribers.actions.add(action); - - if (subscribers.executed) - execute(classOfLoader, action); - } - - @SuppressWarnings("unchecked") - public T getFirstLoaderByClass(@Nonnull Class clazz) { - for (ContentLoader loader : loaders) { - if (loader.getClass().equals(clazz)) { - return (T) loader; - } - } - return null; - } - - private static class Subscribers { - - private final Class loader; - private final Collection actions = new ArrayList<>(1); - private boolean executed = false; - - public Subscribers(Class loader) { - this.loader = loader; - } - - public void execute() { - Logger.debug("Executing subscribers for {}", loader.getSimpleName()); - executed = true; - for (Runnable subscriber : actions) { - LoaderRegistry.execute(loader, subscriber); - } - } - - } + private static final AtomicInteger loading = new AtomicInteger(); // Keeps track of how many loaders are still loading + private final Map, Subscribers> subscribers = new HashMap<>(); + private final Collection loaders; + + public LoaderRegistry(@Nonnull ContentLoader... loaders) { + this.loaders = Arrays.asList(loaders); + } + + private static void execute(@Nonnull Class classOfLoader, @Nonnull Runnable action) { + try { + action.run(); + } catch (Exception ex) { + Logger.error("Could not execute subscriber for {}", classOfLoader.getSimpleName(), ex); + } + } + + public void load() { + if (isLoading()) { + ConsolePrint.alreadyExecutingContentLoader(); + return; + } + + loaders.forEach(this::executeLoader); + } + + private void executeLoader(@Nonnull ContentLoader loader) { + loading.incrementAndGet(); + loader.load(); + loading.decrementAndGet(); + handleCompleteLoading(loader.getClass()); + } + + private void handleCompleteLoading(@Nonnull Class classOfLoader) { + Logger.debug("{} finished loading. {} loader(s) left", classOfLoader.getSimpleName(), loading); + + if (loading.get() == 0) + Logger.info("All loaders finished loading"); + + if (Challenges.getInstance().isEnabled()) { + Subscribers subscribers = this.subscribers.get(classOfLoader); + if (subscribers == null) return; + subscribers.execute(); + } + } + + public void enable() { + for (Subscribers subscribers : subscribers.values()) { + if (subscribers.executed) continue; + subscribers.execute(); + } + } + + public void disable() { + subscribers.clear(); + } + + public boolean isLoading() { + return loading.get() > 0; + } + + public void subscribe(@Nonnull Class classOfLoader, @Nonnull Runnable action) { + Subscribers subscribers = this.subscribers.computeIfAbsent(classOfLoader, key -> new Subscribers(classOfLoader)); + subscribers.actions.add(action); + + if (subscribers.executed) + execute(classOfLoader, action); + } + + @SuppressWarnings("unchecked") + public T getFirstLoaderByClass(@Nonnull Class clazz) { + for (ContentLoader loader : loaders) { + if (loader.getClass().equals(clazz)) { + return (T) loader; + } + } + return null; + } + + private static class Subscribers { + + private final Class loader; + private final Collection actions = new ArrayList<>(1); + private boolean executed = false; + + public Subscribers(Class loader) { + this.loader = loader; + } + + public void execute() { + Logger.debug("Executing subscribers for {}", loader.getSimpleName()); + executed = true; + for (Runnable subscriber : actions) { + LoaderRegistry.execute(loader, subscriber); + } + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java index 012ef9408..4cd3d8f02 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java @@ -9,32 +9,32 @@ public final class PrefixLoader extends ContentLoader { - @Override - protected void load() { - try { + @Override + protected void load() { + try { - File file = getMessageFile("prefix", "properties"); - FileUtils.createFilesIfNecessary(file); + File file = getMessageFile("prefix", "properties"); + FileUtils.createFilesIfNecessary(file); - FileDocument document = FileDocument.readPropertiesFile(file); - boolean changed = false; + FileDocument document = FileDocument.readPropertiesFile(file); + boolean changed = false; - for (Prefix prefix : Prefix.values()) { - if (!document.contains(prefix.getName())) { - document.set(prefix.getName(), prefix.toString()); - changed = true; - continue; - } + for (Prefix prefix : Prefix.values()) { + if (!document.contains(prefix.getName())) { + document.set(prefix.getName(), prefix.toString()); + changed = true; + continue; + } - prefix.setValue(document.getString(prefix.getName())); - } + prefix.setValue(document.getString(prefix.getName())); + } - if (changed) document.save(); - Logger.info("Successfully loaded {} prefixes from config file", Prefix.values().size()); + if (changed) document.save(); + Logger.info("Successfully loaded {} prefixes from config file", Prefix.values().size()); - } catch (Exception ex) { - Logger.error("Could not load prefixes", ex); - } - } + } catch (Exception ex) { + Logger.error("Could not load prefixes", ex); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java index 85de7893c..bec84bcee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java @@ -11,40 +11,40 @@ public final class UpdateLoader extends ContentLoader { - public static final int RESOURCE_ID = 80548; - - @Getter - private static boolean newestPluginVersion = true; - @Getter - private static boolean newestConfigVersion = true; - @Getter - private static Version defaultConfigVersion; - @Getter - private static Version currentConfigVersion; - - @Override - protected void load() { - try { - URL url = new URL("https://api.spigotmc.org/legacy/update.php?resource=" + RESOURCE_ID); - String response = IOUtils.toString(url); - Version plugin = Challenges.getInstance().getVersion(); - YamlConfiguration defaultConfig = Challenges.getInstance().getConfigManager().getDefaultConfig(); - defaultConfigVersion = defaultConfig == null ? plugin : Version.parse(defaultConfig.getString("config-version")); - currentConfigVersion = Version.parse(Challenges.getInstance().getConfigDocument().getString("config-version")); - Version latestVersion = Version.parse(response); - - if (latestVersion.isNewerThan(plugin)) { - Logger.info("A new version of Challenges is available: {}, you have {}", latestVersion, plugin); - newestPluginVersion = false; - } - if (defaultConfigVersion.isNewerThan(currentConfigVersion)) { - Logger.info("A new version of the config (plugins/Challenges/config.yml) is available"); - newestConfigVersion = false; - } - - } catch (Exception ex) { - Logger.error("Could not check for update: {}", ex.getMessage()); - } - } + public static final int RESOURCE_ID = 80548; + + @Getter + private static boolean newestPluginVersion = true; + @Getter + private static boolean newestConfigVersion = true; + @Getter + private static Version defaultConfigVersion; + @Getter + private static Version currentConfigVersion; + + @Override + protected void load() { + try { + URL url = new URL("https://api.spigotmc.org/legacy/update.php?resource=" + RESOURCE_ID); + String response = IOUtils.toString(url); + Version plugin = Challenges.getInstance().getVersion(); + YamlConfiguration defaultConfig = Challenges.getInstance().getConfigManager().getDefaultConfig(); + defaultConfigVersion = defaultConfig == null ? plugin : Version.parse(defaultConfig.getString("config-version")); + currentConfigVersion = Version.parse(Challenges.getInstance().getConfigDocument().getString("config-version")); + Version latestVersion = Version.parse(response); + + if (latestVersion.isNewerThan(plugin)) { + Logger.info("A new version of Challenges is available: {}, you have {}", latestVersion, plugin); + newestPluginVersion = false; + } + if (defaultConfigVersion.isNewerThan(currentConfigVersion)) { + Logger.info("A new version of the config (plugins/Challenges/config.yml) is available"); + newestConfigVersion = false; + } + + } catch (Exception ex) { + Logger.error("Could not check for update: {}", ex.getMessage()); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java index 196905805..733f50598 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java @@ -13,31 +13,31 @@ public class MetricsLoader { - public void start() { - Challenges plugin = Challenges.getInstance(); - - Metrics metrics = new Metrics(plugin, 11494); - metrics.addCustomChart(new SimplePie("language", () -> { - LanguageLoader loader = Challenges.getInstance().getLoaderRegistry() - .getFirstLoaderByClass(LanguageLoader.class); - if (loader == null) return "NULL"; - return loader.getLanguage(); - })); - metrics.addCustomChart(new SimplePie("cloudType", () -> StringUtils.getEnumName(plugin.getCloudSupportManager().getType()))); - metrics.addCustomChart(new SimplePie("databaseType", () -> StringUtils.getEnumName(plugin.getDatabaseManager().getType()))); - metrics.addCustomChart(new SingleLineChart("totalMemory", this::getMemory)); - metrics.addCustomChart(new SingleLineChart("totalCores", () -> Runtime.getRuntime().availableProcessors())); - metrics.addCustomChart(new AdvancedPie("maxMemory", () -> { - HashMap map = new HashMap<>(); - if (Runtime.getRuntime().maxMemory() == Long.MAX_VALUE) return map; - map.put(String.valueOf(getMemory()), 1); - return map; - })); - - } - - private int getMemory() { - return MemoryConverter.getGB(Runtime.getRuntime().maxMemory()); - } + public void start() { + Challenges plugin = Challenges.getInstance(); + + Metrics metrics = new Metrics(plugin, 11494); + metrics.addCustomChart(new SimplePie("language", () -> { + LanguageLoader loader = Challenges.getInstance().getLoaderRegistry() + .getFirstLoaderByClass(LanguageLoader.class); + if (loader == null) return "NULL"; + return loader.getLanguage(); + })); + metrics.addCustomChart(new SimplePie("cloudType", () -> StringUtils.getEnumName(plugin.getCloudSupportManager().getType()))); + metrics.addCustomChart(new SimplePie("databaseType", () -> StringUtils.getEnumName(plugin.getDatabaseManager().getType()))); + metrics.addCustomChart(new SingleLineChart("totalMemory", this::getMemory)); + metrics.addCustomChart(new SingleLineChart("totalCores", () -> Runtime.getRuntime().availableProcessors())); + metrics.addCustomChart(new AdvancedPie("maxMemory", () -> { + HashMap map = new HashMap<>(); + if (Runtime.getRuntime().maxMemory() == Long.MAX_VALUE) return map; + map.put(String.valueOf(getMemory()), 1); + return map; + })); + + } + + private int getMemory() { + return MemoryConverter.getGB(Runtime.getRuntime().maxMemory()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java index 661d9cfa1..7938c1f73 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java @@ -24,229 +24,229 @@ public final class ChallengeManager { - private final List challenges = new LinkedList<>(); - private final List additionalSaver = new LinkedList<>(); - - private IGoal currentGoal; - - @Nonnull - public List getChallenges() { - return Collections.unmodifiableList(challenges); - } - - public void registerGameStateSaver(@Nonnull GamestateSaveable savable) { - additionalSaver.add(savable); - } - - public void register(@Nonnull IChallenge challenge) { - if (!challenge.getType().isUsable()) throw new IllegalArgumentException("Invalid MenuType"); - challenges.add(challenge); - } - - public void unregister(@Nonnull IChallenge challenge) { - challenges.remove(challenge); - } - - public void unregisterIf(@Nonnull Predicate predicate) { - challenges.removeIf(predicate); - } - - public void shutdownChallenges() { - for (IChallenge challenge : challenges) { - try { - challenge.handleShutdown(); - } catch (Exception ex) { - Logger.error("Could not handle shutdown for {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public void clearChallengeCache() { - challenges.clear(); - currentGoal = null; - } - - public void restoreDefaults() { - Logger.debug("Restoring default settings.."); - Challenges.getInstance().getCustomChallengesLoader().resetChallenges(); - for (IChallenge challenge : challenges) { - try { - challenge.restoreDefaults(); - } catch (Exception ex) { - Logger.error("Could not restore defaults for {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public void saveSettings(@Nonnull Player player) throws DatabaseException { - Document document = new GsonDocument(); - saveSettingsInto(document); - Challenges.getInstance().getDatabaseManager().getDatabase() - .insertOrUpdate("challenges") - .where("uuid", player.getUniqueId()) - .set("config", document) - .execute(); - } - - public void saveCustomChallenges(@Nonnull Player player) throws DatabaseException { - Document document = new GsonDocument(); - saveCustomChallengesInto(document); - Challenges.getInstance().getDatabaseManager().getDatabase() - .insertOrUpdate("challenges") - .where("uuid", player.getUniqueId()) - .set("custom_challenges", document) - .execute(); - } - - public void enable() { - loadGamestate(Challenges.getInstance().getConfigManager().getGamestateConfig().readonly()); - loadSettings(Challenges.getInstance().getConfigManager().getSettingsConfig().readonly()); - loadCustomChallenges(Challenges.getInstance().getConfigManager().getCustomChallengesConfig().readonly()); - } - - public synchronized void loadSettings(@Nonnull Document config) { - - for (IChallenge challenge : challenges) { - if (challenge instanceof CustomChallenge) continue; - - String name = challenge.getUniqueName(); - if (!config.contains(name)) continue; - try { - Document document = config.getDocument(name); - challenge.loadSettings(document); - } catch (Exception ex) { - Logger.error("Could not load setting for challenge {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public synchronized void loadGamestate(@Nonnull Document config) { - LinkedList list = new LinkedList<>(challenges); - list.addAll(additionalSaver); - for (GamestateSaveable challenge : list) { - String name = challenge.getUniqueGamestateName(); - if (!config.contains(name)) continue; - try { - Document document = config.getDocument(name); - challenge.loadGameState(document); - - if (challenge instanceof AbstractChallenge) { - AbstractChallenge abstractChallenge = (AbstractChallenge) challenge; - if (abstractChallenge.getBossbar().isShown()) { - abstractChallenge.getBossbar().update(); - } - if (abstractChallenge.getScoreboard().isShown()) { - abstractChallenge.getScoreboard().update(); - } - } - - } catch (Exception ex) { - Logger.error("Could not load gamestate for {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public synchronized void loadCustomChallenges(@Nonnull Document config) { - Challenges.getInstance().getCustomChallengesLoader().loadCustomChallengesFrom(config); - } - - public void resetGamestate() { - LinkedList list = new LinkedList<>(challenges); - list.addAll(additionalSaver); - for (GamestateSaveable challenge : list) { - try { - challenge.loadGameState(Document.empty()); - - if (challenge instanceof AbstractChallenge) { - AbstractChallenge abstractChallenge = (AbstractChallenge) challenge; - if (abstractChallenge.getBossbar().isShown()) { - abstractChallenge.getBossbar().update(); - } - if (abstractChallenge.getScoreboard().isShown()) { - abstractChallenge.getScoreboard().update(); - } - } - } catch (Exception ex) { - Logger.error("Could not load gamestate for {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public void saveGameStateInto(@Nonnull Document config) { - LinkedList list = new LinkedList<>(challenges); - list.addAll(additionalSaver); - for (GamestateSaveable challenge : list) { - try { - Document document = config.getDocument(challenge.getUniqueGamestateName()); - challenge.writeGameState(document); - } catch (Exception ex) { - Logger.error("Could not write gamestate of {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public synchronized void saveGamestate(boolean async) { - FileDocument config = Challenges.getInstance().getConfigManager().getGamestateConfig(); - saveGameStateInto(config); - config.save(async); - } - - public void saveSettingsInto(@Nonnull Document config) { - for (IChallenge challenge : challenges) { - if (challenge instanceof CustomChallenge) continue; - try { - Document document = config.getDocument(challenge.getUniqueGamestateName()); - challenge.writeSettings(document); - } catch (Exception ex) { - Logger.error("Could not write settings of {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public synchronized void saveLocalSettings(boolean async) { - FileDocument config = Challenges.getInstance().getConfigManager().getSettingsConfig(); - saveSettingsInto(config); - config.save(async); - } - - public void saveCustomChallengesInto(@Nonnull Document config) { - Collection customChallenges = Challenges.getInstance().getCustomChallengesLoader() - .getCustomChallenges().values(); - - for (IChallenge challenge : customChallenges) { - try { - Document document = config.getDocument(challenge.getUniqueName()); - challenge.writeSettings(document); - challenge.writeGameState(document); - } catch (Exception ex) { - Logger.error("Could not write settings of {}", challenge.getClass().getSimpleName(), ex); - } - } - } - - public synchronized void saveLocalCustomChallenges(boolean async) { - FileDocument config = new FileDocumentWrapper(Challenges.getInstance().getDataFile("internal/custom_challenges.json"), new GsonDocument()); - saveCustomChallengesInto(config); - config.save(async); - } - - - @Nullable - public IGoal getCurrentGoal() { - return currentGoal; - } - - public void setCurrentGoal(@Nullable IGoal goal) { - - IGoal oldGoal = currentGoal; - currentGoal = goal; - - if (oldGoal != null) - oldGoal.setEnabled(false); - - if (goal != null) - goal.setEnabled(true); - - } + private final List challenges = new LinkedList<>(); + private final List additionalSaver = new LinkedList<>(); + + private IGoal currentGoal; + + @Nonnull + public List getChallenges() { + return Collections.unmodifiableList(challenges); + } + + public void registerGameStateSaver(@Nonnull GamestateSaveable savable) { + additionalSaver.add(savable); + } + + public void register(@Nonnull IChallenge challenge) { + if (!challenge.getType().isUsable()) throw new IllegalArgumentException("Invalid MenuType"); + challenges.add(challenge); + } + + public void unregister(@Nonnull IChallenge challenge) { + challenges.remove(challenge); + } + + public void unregisterIf(@Nonnull Predicate predicate) { + challenges.removeIf(predicate); + } + + public void shutdownChallenges() { + for (IChallenge challenge : challenges) { + try { + challenge.handleShutdown(); + } catch (Exception ex) { + Logger.error("Could not handle shutdown for {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public void clearChallengeCache() { + challenges.clear(); + currentGoal = null; + } + + public void restoreDefaults() { + Logger.debug("Restoring default settings.."); + Challenges.getInstance().getCustomChallengesLoader().resetChallenges(); + for (IChallenge challenge : challenges) { + try { + challenge.restoreDefaults(); + } catch (Exception ex) { + Logger.error("Could not restore defaults for {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public void saveSettings(@Nonnull Player player) throws DatabaseException { + Document document = new GsonDocument(); + saveSettingsInto(document); + Challenges.getInstance().getDatabaseManager().getDatabase() + .insertOrUpdate("challenges") + .where("uuid", player.getUniqueId()) + .set("config", document) + .execute(); + } + + public void saveCustomChallenges(@Nonnull Player player) throws DatabaseException { + Document document = new GsonDocument(); + saveCustomChallengesInto(document); + Challenges.getInstance().getDatabaseManager().getDatabase() + .insertOrUpdate("challenges") + .where("uuid", player.getUniqueId()) + .set("custom_challenges", document) + .execute(); + } + + public void enable() { + loadGamestate(Challenges.getInstance().getConfigManager().getGamestateConfig().readonly()); + loadSettings(Challenges.getInstance().getConfigManager().getSettingsConfig().readonly()); + loadCustomChallenges(Challenges.getInstance().getConfigManager().getCustomChallengesConfig().readonly()); + } + + public synchronized void loadSettings(@Nonnull Document config) { + + for (IChallenge challenge : challenges) { + if (challenge instanceof CustomChallenge) continue; + + String name = challenge.getUniqueName(); + if (!config.contains(name)) continue; + try { + Document document = config.getDocument(name); + challenge.loadSettings(document); + } catch (Exception ex) { + Logger.error("Could not load setting for challenge {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public synchronized void loadGamestate(@Nonnull Document config) { + LinkedList list = new LinkedList<>(challenges); + list.addAll(additionalSaver); + for (GamestateSaveable challenge : list) { + String name = challenge.getUniqueGamestateName(); + if (!config.contains(name)) continue; + try { + Document document = config.getDocument(name); + challenge.loadGameState(document); + + if (challenge instanceof AbstractChallenge) { + AbstractChallenge abstractChallenge = (AbstractChallenge) challenge; + if (abstractChallenge.getBossbar().isShown()) { + abstractChallenge.getBossbar().update(); + } + if (abstractChallenge.getScoreboard().isShown()) { + abstractChallenge.getScoreboard().update(); + } + } + + } catch (Exception ex) { + Logger.error("Could not load gamestate for {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public synchronized void loadCustomChallenges(@Nonnull Document config) { + Challenges.getInstance().getCustomChallengesLoader().loadCustomChallengesFrom(config); + } + + public void resetGamestate() { + LinkedList list = new LinkedList<>(challenges); + list.addAll(additionalSaver); + for (GamestateSaveable challenge : list) { + try { + challenge.loadGameState(Document.empty()); + + if (challenge instanceof AbstractChallenge) { + AbstractChallenge abstractChallenge = (AbstractChallenge) challenge; + if (abstractChallenge.getBossbar().isShown()) { + abstractChallenge.getBossbar().update(); + } + if (abstractChallenge.getScoreboard().isShown()) { + abstractChallenge.getScoreboard().update(); + } + } + } catch (Exception ex) { + Logger.error("Could not load gamestate for {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public void saveGameStateInto(@Nonnull Document config) { + LinkedList list = new LinkedList<>(challenges); + list.addAll(additionalSaver); + for (GamestateSaveable challenge : list) { + try { + Document document = config.getDocument(challenge.getUniqueGamestateName()); + challenge.writeGameState(document); + } catch (Exception ex) { + Logger.error("Could not write gamestate of {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public synchronized void saveGamestate(boolean async) { + FileDocument config = Challenges.getInstance().getConfigManager().getGamestateConfig(); + saveGameStateInto(config); + config.save(async); + } + + public void saveSettingsInto(@Nonnull Document config) { + for (IChallenge challenge : challenges) { + if (challenge instanceof CustomChallenge) continue; + try { + Document document = config.getDocument(challenge.getUniqueGamestateName()); + challenge.writeSettings(document); + } catch (Exception ex) { + Logger.error("Could not write settings of {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public synchronized void saveLocalSettings(boolean async) { + FileDocument config = Challenges.getInstance().getConfigManager().getSettingsConfig(); + saveSettingsInto(config); + config.save(async); + } + + public void saveCustomChallengesInto(@Nonnull Document config) { + Collection customChallenges = Challenges.getInstance().getCustomChallengesLoader() + .getCustomChallenges().values(); + + for (IChallenge challenge : customChallenges) { + try { + Document document = config.getDocument(challenge.getUniqueName()); + challenge.writeSettings(document); + challenge.writeGameState(document); + } catch (Exception ex) { + Logger.error("Could not write settings of {}", challenge.getClass().getSimpleName(), ex); + } + } + } + + public synchronized void saveLocalCustomChallenges(boolean async) { + FileDocument config = new FileDocumentWrapper(Challenges.getInstance().getDataFile("internal/custom_challenges.json"), new GsonDocument()); + saveCustomChallengesInto(config); + config.save(async); + } + + + @Nullable + public IGoal getCurrentGoal() { + return currentGoal; + } + + public void setCurrentGoal(@Nullable IGoal goal) { + + IGoal oldGoal = currentGoal; + currentGoal = goal; + + if (oldGoal != null) + oldGoal.setEnabled(false); + + if (goal != null) + goal.setEnabled(true); + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java index d5b098432..c04f78eb5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java @@ -21,110 +21,110 @@ public class ModuleChallengeLoader { - protected final BukkitModule plugin; + protected final BukkitModule plugin; - public ModuleChallengeLoader(@Nonnull BukkitModule plugin) { - this.plugin = plugin; - } + public ModuleChallengeLoader(@Nonnull BukkitModule plugin) { + this.plugin = plugin; + } - public final void registerWithCommand(@Nonnull IChallenge challenge, @Nonnull String... commandNames) { - try { + public final void registerWithCommand(@Nonnull IChallenge challenge, @Nonnull String... commandNames) { + try { - Challenges.getInstance().getChallengeManager().register(challenge); - Challenges.getInstance().getScheduler().register(challenge); + Challenges.getInstance().getChallengeManager().register(challenge); + Challenges.getInstance().getScheduler().register(challenge); - if (challenge instanceof CommandExecutor) { - plugin.registerCommand((CommandExecutor) challenge, commandNames); - } - if (challenge instanceof Listener) { - plugin.registerListener((Listener) challenge); - } + if (challenge instanceof CommandExecutor) { + plugin.registerCommand((CommandExecutor) challenge, commandNames); + } + if (challenge instanceof Listener) { + plugin.registerListener((Listener) challenge); + } - } catch (Throwable ex) { - Logger.error("Could not register challenge {}", challenge.getClass().getSimpleName(), ex); - } - } + } catch (Throwable ex) { + Logger.error("Could not register challenge {}", challenge.getClass().getSimpleName(), ex); + } + } - public final void register(@Nonnull IChallenge challenge) { - registerWithCommand(challenge); - } + public final void register(@Nonnull IChallenge challenge) { + registerWithCommand(challenge); + } - public final void registerWithCommand(@Nonnull Class classOfChallenge, @Nonnull String[] commandNames, @Nonnull Class[] parameterClasses, @Nonnull Object... parameters) { - try { + public final void registerWithCommand(@Nonnull Class classOfChallenge, @Nonnull String[] commandNames, @Nonnull Class[] parameterClasses, @Nonnull Object... parameters) { + try { - if (classOfChallenge.isAnnotationPresent(RequireVersion.class)) { - RequireVersion annotation = classOfChallenge.getAnnotation(RequireVersion.class); - MinecraftVersion minVersion = annotation.value(); + if (classOfChallenge.isAnnotationPresent(RequireVersion.class)) { + RequireVersion annotation = classOfChallenge.getAnnotation(RequireVersion.class); + MinecraftVersion minVersion = annotation.value(); - if (!MinecraftVersion.current().isNewerOrEqualThan(minVersion)) { - Logger.debug("Did not register challenge {}, requires version {}, server running on {}", classOfChallenge.getSimpleName(), minVersion, MinecraftVersion.current()); - return; - } - } + if (!MinecraftVersion.current().isNewerOrEqualThan(minVersion)) { + Logger.debug("Did not register challenge {}, requires version {}, server running on {}", classOfChallenge.getSimpleName(), minVersion, MinecraftVersion.current()); + return; + } + } - Constructor constructor = classOfChallenge.getDeclaredConstructor(parameterClasses); - IChallenge challenge = constructor.newInstance(parameters); + Constructor constructor = classOfChallenge.getDeclaredConstructor(parameterClasses); + IChallenge challenge = constructor.newInstance(parameters); - registerWithCommand(challenge, commandNames); + registerWithCommand(challenge, commandNames); - } catch (Throwable ex) { - Logger.error("Could not create challenge {}", classOfChallenge.getSimpleName(), ex); - } - } + } catch (Throwable ex) { + Logger.error("Could not create challenge {}", classOfChallenge.getSimpleName(), ex); + } + } - public final void register(@Nonnull Class classOfChallenge, @Nonnull Class[] parameterClasses, @Nonnull Object... parameters) { - registerWithCommand(classOfChallenge, new String[0], parameterClasses, parameters); - } + public final void register(@Nonnull Class classOfChallenge, @Nonnull Class[] parameterClasses, @Nonnull Object... parameters) { + registerWithCommand(classOfChallenge, new String[0], parameterClasses, parameters); + } - public final void register(@Nonnull Class classOfChallenge, @Nonnull Object... parameters) { + public final void register(@Nonnull Class classOfChallenge, @Nonnull Object... parameters) { - Class[] parameterClasses = new Class[parameters.length]; - for (int i = 0; i < parameters.length; i++) { - parameterClasses[i] = Optional.ofNullable(parameters[i]).>map(Object::getClass).orElse(Object.class); - } + Class[] parameterClasses = new Class[parameters.length]; + for (int i = 0; i < parameters.length; i++) { + parameterClasses[i] = Optional.ofNullable(parameters[i]).>map(Object::getClass).orElse(Object.class); + } - register(classOfChallenge, parameterClasses, parameters); + register(classOfChallenge, parameterClasses, parameters); - } + } - public final void registerWithCommand(@Nonnull Class classOfChallenge, @Nonnull String... commandNames) { - registerWithCommand(classOfChallenge, commandNames, new Class[0]); - } + public final void registerWithCommand(@Nonnull Class classOfChallenge, @Nonnull String... commandNames) { + registerWithCommand(classOfChallenge, commandNames, new Class[0]); + } - public final void registerDamageRule(@Nonnull String name, @Nonnull Material material, @Nonnull DamageCause... causes) { - registerDamageRule(name, new ItemBuilder(material), causes); - } + public final void registerDamageRule(@Nonnull String name, @Nonnull Material material, @Nonnull DamageCause... causes) { + registerDamageRule(name, new ItemBuilder(material), causes); + } - public final void registerDamageRule(@Nonnull String name, @Nonnull ItemBuilder preset, @Nonnull DamageCause... causes) { - register(DamageRuleSetting.class, new Class[]{ItemBuilder.class, String.class, DamageCause[].class}, preset, name, causes); - } + public final void registerDamageRule(@Nonnull String name, @Nonnull ItemBuilder preset, @Nonnull DamageCause... causes) { + register(DamageRuleSetting.class, new Class[]{ItemBuilder.class, String.class, DamageCause[].class}, preset, name, causes); + } - public final void registerMaterialRule(@Nonnull String title, @Nonnull String replacement, @Nonnull Material... materials) { - registerMaterialRule("item-block-material", new Object[]{title, replacement}, materials); - } + public final void registerMaterialRule(@Nonnull String title, @Nonnull String replacement, @Nonnull Material... materials) { + registerMaterialRule("item-block-material", new Object[]{title, replacement}, materials); + } - public final void registerMaterialRule(@Nonnull String name, Object[] replacements, @Nonnull Material... materials) { - registerMaterialRule(name, new ItemBuilder(materials[0]), replacements, materials); - } + public final void registerMaterialRule(@Nonnull String name, Object[] replacements, @Nonnull Material... materials) { + registerMaterialRule(name, new ItemBuilder(materials[0]), replacements, materials); + } - public final void registerMaterialRule(@Nonnull String name, @Nonnull ItemBuilder preset, Object[] replacements, @Nonnull Material... materials) { - register(BlockMaterialSetting.class, new Class[]{String.class, ItemBuilder.class, Object[].class, Material[].class}, name, preset, replacements, materials); - } + public final void registerMaterialRule(@Nonnull String name, @Nonnull ItemBuilder preset, Object[] replacements, @Nonnull Material... materials) { + register(BlockMaterialSetting.class, new Class[]{String.class, ItemBuilder.class, Object[].class, Material[].class}, name, preset, replacements, materials); + } - /** - * Unregisters an existing challenge and deletes its settings. - * It does not unregister commands! - */ - public final void unregister(@Nonnull IChallenge challenge) { - Challenges.getInstance().getChallengeManager().unregister(challenge); - Challenges.getInstance().getScheduler().unregister(challenge); - Challenges.getInstance().getConfigManager().getSettingsConfig().remove(challenge.getUniqueName()); - Challenges.getInstance().getConfigManager().getGamestateConfig().remove(challenge.getUniqueGamestateName()); + /** + * Unregisters an existing challenge and deletes its settings. + * It does not unregister commands! + */ + public final void unregister(@Nonnull IChallenge challenge) { + Challenges.getInstance().getChallengeManager().unregister(challenge); + Challenges.getInstance().getScheduler().unregister(challenge); + Challenges.getInstance().getConfigManager().getSettingsConfig().remove(challenge.getUniqueName()); + Challenges.getInstance().getConfigManager().getGamestateConfig().remove(challenge.getUniqueGamestateName()); - if (challenge instanceof Listener) { - HandlerList.unregisterAll((Listener) challenge); - } - } + if (challenge instanceof Listener) { + HandlerList.unregisterAll((Listener) challenge); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java index c3f9e2a0b..7c2e60f52 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java @@ -14,43 +14,43 @@ public final class CloudNet3Support implements CloudSupport { - @Nonnull - @Override - public String getColoredName(@Nonnull Player player) { - return getColoredName(player.getUniqueId()); - } - - @Nonnull - @Override - public String getColoredName(@Nonnull UUID uuid) { - IPermissionManagement management = CloudNetDriver.getInstance().getPermissionManagement(); - IPermissionUser user = management.getUser(uuid); - if (user == null) return "Unknown CloudPlayer"; - IPermissionGroup group = management.getHighestPermissionGroup(user); - String color = group.getColor(); - return color.replace('&', '§') + user.getName(); - } - - @Override - public boolean hasNameFor(@Nonnull UUID uuid) { - return CloudNetDriver.getInstance().getPermissionManagement().getUser(uuid) != null; - } - - @Override - public void startNewService() { - BukkitCloudNetHelper.changeToIngame(); - } - - @Override - public void setIngame() { - BukkitCloudNetHelper.setState("INGAME"); - BridgeHelper.updateServiceInfo(); - } - - @Override - public void setLobby() { - BukkitCloudNetHelper.setState("LOBBY"); - BridgeHelper.updateServiceInfo(); - } + @Nonnull + @Override + public String getColoredName(@Nonnull Player player) { + return getColoredName(player.getUniqueId()); + } + + @Nonnull + @Override + public String getColoredName(@Nonnull UUID uuid) { + IPermissionManagement management = CloudNetDriver.getInstance().getPermissionManagement(); + IPermissionUser user = management.getUser(uuid); + if (user == null) return "Unknown CloudPlayer"; + IPermissionGroup group = management.getHighestPermissionGroup(user); + String color = group.getColor(); + return color.replace('&', '§') + user.getName(); + } + + @Override + public boolean hasNameFor(@Nonnull UUID uuid) { + return CloudNetDriver.getInstance().getPermissionManagement().getUser(uuid) != null; + } + + @Override + public void startNewService() { + BukkitCloudNetHelper.changeToIngame(); + } + + @Override + public void setIngame() { + BukkitCloudNetHelper.setState("INGAME"); + BridgeHelper.updateServiceInfo(); + } + + @Override + public void setLobby() { + BukkitCloudNetHelper.setState("LOBBY"); + BridgeHelper.updateServiceInfo(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java index 9ddc48971..ad1b72506 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java @@ -21,131 +21,131 @@ public final class MenuManager { - public static final String MANAGE_GUI_PERMISSION = "challenges.manage"; - public static final int[] GUI_SLOTS = {30, 32, 19, 25, 11, 15, 4}; - @Getter + public static final String MANAGE_GUI_PERMISSION = "challenges.manage"; + public static final int[] GUI_SLOTS = {30, 32, 19, 25, 11, 15, 4}; + @Getter private final boolean displayNewInFront; - private final boolean permissionToManageGUI; - private AnimatedInventory gui; - private boolean generated = false; - - public MenuManager() { - ChallengeAPI.subscribeLoader(LanguageLoader.class, this::generateMenus); - ChallengeAPI.subscribeLoader(LanguageLoader.class, this::generateMainMenu); - displayNewInFront = Challenges.getInstance().getConfigDocument().getBoolean("display-new-in-front"); - permissionToManageGUI = Challenges.getInstance().getConfigDocument().getBoolean("manage-settings-permission"); - generateMainMenu(); - } - - public void generateMainMenu() { - - gui = new AnimatedInventory(InventoryTitleManager.getMainMenuTitle(), 5 * 9, MenuPosition.HOLDER); - gui.addFrame(new AnimationFrame(5 * 9).fill(ItemBuilder.FILL_ITEM)); - gui.cloneLastAndAdd().setAccent(39, 41); - gui.cloneLastAndAdd().setAccent(38, 42); - gui.cloneLastAndAdd().setAccent(37, 43); - gui.cloneLastAndAdd().setAccent(28, 34); - gui.cloneLastAndAdd().setAccent(27, 35); - gui.cloneLastAndAdd().setAccent(18, 26); - gui.cloneLastAndAdd().setAccent(9, 17); - gui.cloneLastAndAdd().setAccent(10, 16); - gui.cloneLastAndAdd().setAccent(1, 7); - gui.cloneLastAndAdd().setAccent(2, 6); - - MenuType[] values = MenuType.values(); - for (int i = 0; i < values.length; i += 2) { - - AnimationFrame frame = gui.getLastFrame().clone(); - - MenuType first = values[i]; - frame.setItem(GUI_SLOTS[i], new ItemBuilder(first.getDisplayItem()).name( - DefaultItem.getItemPrefix() + first.getDisplayName()).hideAttributes()); - - if (values.length > i + 1) { - MenuType second = values[i + 1]; - frame.setItem(GUI_SLOTS[i + 1], new ItemBuilder(second.getDisplayItem()).name( - DefaultItem.getItemPrefix() + second.getDisplayName()).hideAttributes()); - } - - gui.addFrame(frame); - } - - } - - public void generateMenus() { - - for (MenuType value : MenuType.values()) { - value.executeWithGenerator(ChallengeMenuGenerator.class, ChallengeMenuGenerator::resetChallengeCache); - } - - for (IChallenge challenge : Challenges.getInstance().getChallengeManager().getChallenges()) { - MenuType type = challenge.getType(); - type.executeWithGenerator(ChallengeMenuGenerator.class, gen -> gen.addChallengeToCache(challenge)); - } - - for (MenuType value : MenuType.values()) { - value.getMenuGenerator().generateInventories(); - } - - generated = true; - } - - public void openGUI(@Nonnull Player player) { - SoundSample.PLOP.play(player); - MenuPosition.set(player, new MainMenuPosition()); - gui.open(player, Challenges.getInstance()); - } - - public void openGUIInstantly(@Nonnull Player player) { - MenuPosition.set(player, new MainMenuPosition()); - gui.openNotAnimated(player, true, Challenges.getInstance()); - } - - /** - * @return If the specified menu page could be opened. - * The menu may not be opened, when there are no challenges registered to that menu or the languages are not loaded - */ - public boolean openMenu(@Nonnull Player player, @Nonnull MenuType type, int page) { - if (!generated) { - SoundSample.BASS_OFF.play(player); - player.sendMessage(Prefix.CHALLENGES + "§cCould not open gui, languages are not loaded"); - player.sendMessage(Prefix.CHALLENGES + "§cIs the plugin set up correctly?"); - return false; - } - - type.getMenuGenerator().open(player, page); - - return true; - } + private final boolean permissionToManageGUI; + private AnimatedInventory gui; + private boolean generated = false; + + public MenuManager() { + ChallengeAPI.subscribeLoader(LanguageLoader.class, this::generateMenus); + ChallengeAPI.subscribeLoader(LanguageLoader.class, this::generateMainMenu); + displayNewInFront = Challenges.getInstance().getConfigDocument().getBoolean("display-new-in-front"); + permissionToManageGUI = Challenges.getInstance().getConfigDocument().getBoolean("manage-settings-permission"); + generateMainMenu(); + } + + public void generateMainMenu() { + + gui = new AnimatedInventory(InventoryTitleManager.getMainMenuTitle(), 5 * 9, MenuPosition.HOLDER); + gui.addFrame(new AnimationFrame(5 * 9).fill(ItemBuilder.FILL_ITEM)); + gui.cloneLastAndAdd().setAccent(39, 41); + gui.cloneLastAndAdd().setAccent(38, 42); + gui.cloneLastAndAdd().setAccent(37, 43); + gui.cloneLastAndAdd().setAccent(28, 34); + gui.cloneLastAndAdd().setAccent(27, 35); + gui.cloneLastAndAdd().setAccent(18, 26); + gui.cloneLastAndAdd().setAccent(9, 17); + gui.cloneLastAndAdd().setAccent(10, 16); + gui.cloneLastAndAdd().setAccent(1, 7); + gui.cloneLastAndAdd().setAccent(2, 6); + + MenuType[] values = MenuType.values(); + for (int i = 0; i < values.length; i += 2) { + + AnimationFrame frame = gui.getLastFrame().clone(); + + MenuType first = values[i]; + frame.setItem(GUI_SLOTS[i], new ItemBuilder(first.getDisplayItem()).name( + DefaultItem.getItemPrefix() + first.getDisplayName()).hideAttributes()); + + if (values.length > i + 1) { + MenuType second = values[i + 1]; + frame.setItem(GUI_SLOTS[i + 1], new ItemBuilder(second.getDisplayItem()).name( + DefaultItem.getItemPrefix() + second.getDisplayName()).hideAttributes()); + } + + gui.addFrame(frame); + } + + } + + public void generateMenus() { + + for (MenuType value : MenuType.values()) { + value.executeWithGenerator(ChallengeMenuGenerator.class, ChallengeMenuGenerator::resetChallengeCache); + } + + for (IChallenge challenge : Challenges.getInstance().getChallengeManager().getChallenges()) { + MenuType type = challenge.getType(); + type.executeWithGenerator(ChallengeMenuGenerator.class, gen -> gen.addChallengeToCache(challenge)); + } + + for (MenuType value : MenuType.values()) { + value.getMenuGenerator().generateInventories(); + } + + generated = true; + } + + public void openGUI(@Nonnull Player player) { + SoundSample.PLOP.play(player); + MenuPosition.set(player, new MainMenuPosition()); + gui.open(player, Challenges.getInstance()); + } + + public void openGUIInstantly(@Nonnull Player player) { + MenuPosition.set(player, new MainMenuPosition()); + gui.openNotAnimated(player, true, Challenges.getInstance()); + } + + /** + * @return If the specified menu page could be opened. + * The menu may not be opened, when there are no challenges registered to that menu or the languages are not loaded + */ + public boolean openMenu(@Nonnull Player player, @Nonnull MenuType type, int page) { + if (!generated) { + SoundSample.BASS_OFF.play(player); + player.sendMessage(Prefix.CHALLENGES + "§cCould not open gui, languages are not loaded"); + player.sendMessage(Prefix.CHALLENGES + "§cIs the plugin set up correctly?"); + return false; + } + + type.getMenuGenerator().open(player, page); + + return true; + } public void playNoPermissionsEffect(@Nonnull Player player) { - SoundSample.BASS_OFF.play(player); - Message.forName("no-permission").send(player, Prefix.CHALLENGES); - } + SoundSample.BASS_OFF.play(player); + Message.forName("no-permission").send(player, Prefix.CHALLENGES); + } - public boolean permissionToManageGUI() { - return permissionToManageGUI; - } + public boolean permissionToManageGUI() { + return permissionToManageGUI; + } - private class MainMenuPosition implements MenuPosition { + private class MainMenuPosition implements MenuPosition { - @Override - public void handleClick(@Nonnull MenuClickInfo info) { + @Override + public void handleClick(@Nonnull MenuClickInfo info) { - for (int i = 0; i < GUI_SLOTS.length; i++) { - int current = GUI_SLOTS[i]; - if (current == info.getSlot()) { - MenuType type = MenuType.values()[i]; - if (openMenu(info.getPlayer(), type, 0)) - SoundSample.CLICK.play(info.getPlayer()); - return; - } - } + for (int i = 0; i < GUI_SLOTS.length; i++) { + int current = GUI_SLOTS[i]; + if (current == info.getSlot()) { + MenuType type = MenuType.values()[i]; + if (openMenu(info.getPlayer(), type, 0)) + SoundSample.CLICK.play(info.getPlayer()); + return; + } + } - SoundSample.CLICK.play(info.getPlayer()); + SoundSample.CLICK.play(info.getPlayer()); - } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java index 08222a111..4a651f33e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java @@ -18,107 +18,107 @@ public abstract class ChooseItemGenerator extends MultiPageMenuGenerator { - private final LinkedHashMap items; + private final LinkedHashMap items; - public ChooseItemGenerator(LinkedHashMap items) { - this.items = items; - } + public ChooseItemGenerator(LinkedHashMap items) { + this.items = items; + } - private static int getNextMiddleSlot(@Nonnegative int currentSlot) { - if (currentSlot >= 53) return currentSlot; - if (isSideSlot(currentSlot)) return getNextMiddleSlot(currentSlot + 1); - return currentSlot; - } + private static int getNextMiddleSlot(@Nonnegative int currentSlot) { + if (currentSlot >= 53) return currentSlot; + if (isSideSlot(currentSlot)) return getNextMiddleSlot(currentSlot + 1); + return currentSlot; + } - private static boolean isSideSlot(@Nonnegative int slot) { - return slot % 9 == 0 || slot % 9 == 8; - } + private static boolean isSideSlot(@Nonnegative int slot) { + return slot % 9 == 0 || slot % 9 == 8; + } - private static boolean isTopOrBottomSlot(@Nonnegative int slot) { - return slot < 9 || slot > 35; - } + private static boolean isTopOrBottomSlot(@Nonnegative int slot) { + return slot < 9 || slot > 35; + } - @Override - public MenuPosition getMenuPosition(int page) { - return new GeneratorMenuPosition(this, page) { + @Override + public MenuPosition getMenuPosition(int page) { + return new GeneratorMenuPosition(this, page) { - @Override - public void handleClick(@Nonnull MenuClickInfo info) { + @Override + public void handleClick(@Nonnull MenuClickInfo info) { - if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { - return; - } + if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { + return; + } - int slot = info.getSlot(); - int index = getItemsPerPage() * page + slot - 10; + int slot = info.getSlot(); + int index = getItemsPerPage() * page + slot - 10; - if (slot > 18) index -= 2; - if (slot > 27) index -= 2; + if (slot > 18) index -= 2; + if (slot > 27) index -= 2; - if (index >= items.size()) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } + if (index >= items.size()) { + SoundSample.CLICK.play(info.getPlayer()); + return; + } - String[] array = items.keySet().toArray(new String[0]); + String[] array = items.keySet().toArray(new String[0]); - if (isSideSlot(slot) || isTopOrBottomSlot(slot)) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } + if (isSideSlot(slot) || isTopOrBottomSlot(slot)) { + SoundSample.CLICK.play(info.getPlayer()); + return; + } - String itemKey = array[index]; + String itemKey = array[index]; - onItemClick(info.getPlayer(), itemKey); - SoundSample.PLOP.play(info.getPlayer()); + onItemClick(info.getPlayer(), itemKey); + SoundSample.PLOP.play(info.getPlayer()); - } - }; - } + } + }; + } - @Override - public int getSize() { - return 5 * 9; - } + @Override + public int getSize() { + return 5 * 9; + } - @Override - public int getPagesCount() { - return (int) Math.ceil((float) items.size() / getItemsPerPage()); - } + @Override + public int getPagesCount() { + return (int) Math.ceil((float) items.size() / getItemsPerPage()); + } - public int getItemsPerPage() { - return 3 * 7; - } + public int getItemsPerPage() { + return 3 * 7; + } - @Override - public void generatePage(@Nonnull Inventory inventory, int page) { + @Override + public void generatePage(@Nonnull Inventory inventory, int page) { - int lastSlot = 10; - int startIndex = getItemsPerPage() * page; - for (int i = startIndex; i < startIndex + getItemsPerPage() && i < items.size(); i++) { - String key = items.keySet().toArray(new String[0])[i]; - ItemStack itemStack = items.get(key); - lastSlot = getNextMiddleSlot(lastSlot); - inventory.setItem(lastSlot, itemStack); - lastSlot++; - } + int lastSlot = 10; + int startIndex = getItemsPerPage() * page; + for (int i = startIndex; i < startIndex + getItemsPerPage() && i < items.size(); i++) { + String key = items.keySet().toArray(new String[0])[i]; + ItemStack itemStack = items.get(key); + lastSlot = getNextMiddleSlot(lastSlot); + inventory.setItem(lastSlot, itemStack); + lastSlot++; + } - } + } - @Override - public int[] getNavigationSlots(int page) { - return MainCustomMenuGenerator.NAVIGATION_SLOTS; - } + @Override + public int[] getNavigationSlots(int page) { + return MainCustomMenuGenerator.NAVIGATION_SLOTS; + } - @Override - protected String getTitle(int page) { - return InventoryTitleManager.getTitle(MenuType.CUSTOM, getSubTitles(page)); - } + @Override + protected String getTitle(int page) { + return InventoryTitleManager.getTitle(MenuType.CUSTOM, getSubTitles(page)); + } - public abstract String[] getSubTitles(int page); + public abstract String[] getSubTitles(int page); - public abstract void onItemClick(Player player, String itemKey); + public abstract void onItemClick(Player player, String itemKey); - public abstract void onBackToMenuItemClick(Player player); + public abstract void onBackToMenuItemClick(Player player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java index 24ae44c25..1cffe6938 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java @@ -1,10 +1,5 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; import net.anweisen.utilities.bukkit.utils.animation.SoundSample; import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; @@ -22,133 +17,139 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; + public abstract class ChooseMultipleItemGenerator extends MultiPageMenuGenerator { - public static final int FINISH_SLOT = 40; - - private final LinkedHashMap items; - private final List selectedKeys; - - public ChooseMultipleItemGenerator(LinkedHashMap items) { - this.items = items; - selectedKeys = new LinkedList<>(); - } - - private static int getNextMiddleSlot(@Nonnegative int currentSlot) { - if (currentSlot >= 53) return currentSlot; - if (isSideSlot(currentSlot)) return getNextMiddleSlot(currentSlot + 1); - return currentSlot; - } - - private static boolean isSideSlot(@Nonnegative int slot) { - return slot % 9 == 0 || slot % 9 == 8; - } - - private static boolean isTopOrBottomSlot(@Nonnegative int slot) { - return slot < 9 || slot > 35; - } - - @Override - public MenuPosition getMenuPosition(int page) { - return new GeneratorMenuPosition(this, page) { - - @Override - public void handleClick(@Nonnull MenuClickInfo info) { - - if (info.getSlot() == FINISH_SLOT) { - onItemClick(info.getPlayer(), selectedKeys.toArray(new String[0])); - SoundSample.PLOP.play(info.getPlayer()); - return; - } - - if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { - return; - } - - int slot = info.getSlot(); - int index = getItemsPerPage() * page + slot - 10; - - if (slot > 18) index -= 2; - if (slot > 27) index -= 2; - - if (index >= items.size()) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - String[] array = items.keySet().toArray(new String[0]); - - if (isSideSlot(slot) || isTopOrBottomSlot(slot)) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - String itemKey = array[index]; - - if (selectedKeys.contains(itemKey)) { - selectedKeys.remove(itemKey); - } else { - selectedKeys.add(itemKey); - } - generatePage(info.getInventory(), page); - SoundSample.LOW_PLOP.play(info.getPlayer()); - } - }; - } - - @Override - public int getSize() { - return 5 * 9; - } - - @Override - public int getPagesCount() { - return (items.size() / getItemsPerPage()) + 1; - } - - public int getItemsPerPage() { - return 3 * 7; - } - - @Override - public void generatePage(@Nonnull Inventory inventory, int page) { - - int lastSlot = 10; - int startIndex = getItemsPerPage() * page; - for (int i = startIndex; i < startIndex + getItemsPerPage() && i < items.size(); i++) { - String key = items.keySet().toArray(new String[0])[i]; - ItemBuilder itemBuilder = new ItemBuilder(items.get(key)).clone(); - itemBuilder.hideAttributes(); - - if (selectedKeys.contains(key)) { - itemBuilder.addEnchantment(MinecraftNameWrapper.UNBREAKING, 1); - itemBuilder.appendName(" §8┃ §2§l✔"); - } else { - itemBuilder.appendName(" §8┃ §c✖"); - } - - lastSlot = getNextMiddleSlot(lastSlot); - inventory.setItem(lastSlot, itemBuilder.build()); - lastSlot++; - } - - inventory.setItem(FINISH_SLOT, DefaultItem.create(Material.LIME_DYE, Message.forName("custom-sub-finish")).build()); - } - - @Override - public int[] getNavigationSlots(int page) { - return MainCustomMenuGenerator.NAVIGATION_SLOTS; - } - - @Override - protected String getTitle(int page) { - return InventoryTitleManager.getTitle(MenuType.CUSTOM, getSubTitles(page)); - } - - public abstract String[] getSubTitles(int page); - - public abstract void onItemClick(Player player, String[] itemKeys); - - public abstract void onBackToMenuItemClick(Player player); + public static final int FINISH_SLOT = 40; + + private final LinkedHashMap items; + private final List selectedKeys; + + public ChooseMultipleItemGenerator(LinkedHashMap items) { + this.items = items; + selectedKeys = new LinkedList<>(); + } + + private static int getNextMiddleSlot(@Nonnegative int currentSlot) { + if (currentSlot >= 53) return currentSlot; + if (isSideSlot(currentSlot)) return getNextMiddleSlot(currentSlot + 1); + return currentSlot; + } + + private static boolean isSideSlot(@Nonnegative int slot) { + return slot % 9 == 0 || slot % 9 == 8; + } + + private static boolean isTopOrBottomSlot(@Nonnegative int slot) { + return slot < 9 || slot > 35; + } + + @Override + public MenuPosition getMenuPosition(int page) { + return new GeneratorMenuPosition(this, page) { + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + + if (info.getSlot() == FINISH_SLOT) { + onItemClick(info.getPlayer(), selectedKeys.toArray(new String[0])); + SoundSample.PLOP.play(info.getPlayer()); + return; + } + + if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { + return; + } + + int slot = info.getSlot(); + int index = getItemsPerPage() * page + slot - 10; + + if (slot > 18) index -= 2; + if (slot > 27) index -= 2; + + if (index >= items.size()) { + SoundSample.CLICK.play(info.getPlayer()); + return; + } + + String[] array = items.keySet().toArray(new String[0]); + + if (isSideSlot(slot) || isTopOrBottomSlot(slot)) { + SoundSample.CLICK.play(info.getPlayer()); + return; + } + + String itemKey = array[index]; + + if (selectedKeys.contains(itemKey)) { + selectedKeys.remove(itemKey); + } else { + selectedKeys.add(itemKey); + } + generatePage(info.getInventory(), page); + SoundSample.LOW_PLOP.play(info.getPlayer()); + } + }; + } + + @Override + public int getSize() { + return 5 * 9; + } + + @Override + public int getPagesCount() { + return (items.size() / getItemsPerPage()) + 1; + } + + public int getItemsPerPage() { + return 3 * 7; + } + + @Override + public void generatePage(@Nonnull Inventory inventory, int page) { + + int lastSlot = 10; + int startIndex = getItemsPerPage() * page; + for (int i = startIndex; i < startIndex + getItemsPerPage() && i < items.size(); i++) { + String key = items.keySet().toArray(new String[0])[i]; + ItemBuilder itemBuilder = new ItemBuilder(items.get(key)).clone(); + itemBuilder.hideAttributes(); + + if (selectedKeys.contains(key)) { + itemBuilder.addEnchantment(MinecraftNameWrapper.UNBREAKING, 1); + itemBuilder.appendName(" §8┃ §2§l✔"); + } else { + itemBuilder.appendName(" §8┃ §c✖"); + } + + lastSlot = getNextMiddleSlot(lastSlot); + inventory.setItem(lastSlot, itemBuilder.build()); + lastSlot++; + } + + inventory.setItem(FINISH_SLOT, DefaultItem.create(Material.LIME_DYE, Message.forName("custom-sub-finish")).build()); + } + + @Override + public int[] getNavigationSlots(int page) { + return MainCustomMenuGenerator.NAVIGATION_SLOTS; + } + + @Override + protected String getTitle(int page) { + return InventoryTitleManager.getTitle(MenuType.CUSTOM, getSubTitles(page)); + } + + public abstract String[] getSubTitles(int page); + + public abstract void onItemClick(Player player, String[] itemKeys); + + public abstract void onBackToMenuItemClick(Player player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java index 4d8f2212f..c84df1f4c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java @@ -2,18 +2,18 @@ public class SmallCategorisedMenuGenerator extends CategorisedMenuGenerator { - @Override - public int getEntriesPerPage() { - return 7; - } + @Override + public int getEntriesPerPage() { + return 7; + } - @Override - public int getSize() { - return 9 * 3; - } + @Override + public int getSize() { + return 9 * 3; + } - @Override - public int[] getNavigationSlots(int page) { - return new int[]{18, 26}; - } + @Override + public int[] getNavigationSlots(int page) { + return new int[]{18, 26}; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java index 697f88629..7b3334c6b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java @@ -9,31 +9,31 @@ public class SettingsMenuGenerator extends ChallengeMenuGenerator { - public static final int[] SLOTS = {10, 11, 12, 13, 14, 15, 16}; - public static final int[] NAVIGATION_SLOTS = {27, 35}; - public static final int SIZE = 4 * 9; - - @Override - public int[] getSlots() { - return SLOTS; - } - - @Override - public int getSize() { - return SIZE; - } - - @Override - public int[] getNavigationSlots(int page) { - return NAVIGATION_SLOTS; - } - - @Override - public void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClickInfo info, int itemIndex) { - if (itemIndex <= 1) { - challenge.handleClick(new ChallengeMenuClickInfo(info, itemIndex == 0)); - } - - } + public static final int[] SLOTS = {10, 11, 12, 13, 14, 15, 16}; + public static final int[] NAVIGATION_SLOTS = {27, 35}; + public static final int SIZE = 4 * 9; + + @Override + public int[] getSlots() { + return SLOTS; + } + + @Override + public int getSize() { + return SIZE; + } + + @Override + public int[] getNavigationSlots(int page) { + return NAVIGATION_SLOTS; + } + + @Override + public void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClickInfo info, int itemIndex) { + if (itemIndex <= 1) { + challenge.handleClick(new ChallengeMenuClickInfo(info, itemIndex == 0)); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/IParentCustomGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/IParentCustomGenerator.java index 279db1727..47b13b20d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/IParentCustomGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/IParentCustomGenerator.java @@ -7,13 +7,13 @@ public interface IParentCustomGenerator { - /** - * @param player the player that has the menu open - * @param type the type of the current setting. Only needed if parent is the first setting menu. - * @param data a map that contains all the data of the settings - */ - void accept(Player player, SettingType type, Map data); + /** + * @param player the player that has the menu open + * @param type the type of the current setting. Only needed if parent is the first setting menu. + * @param data a map that contains all the data of the settings + */ + void accept(Player player, SettingType type, Map data); - void decline(Player player); + void decline(Player player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java index c142e632f..46ef222e5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java @@ -13,38 +13,38 @@ public class MaterialMenuGenerator extends ChooseItemGenerator { - private final IParentCustomGenerator parent; - - public MaterialMenuGenerator(IParentCustomGenerator parent) { - super(createMaterialsMap()); - this.parent = parent; - } - - public static LinkedHashMap createMaterialsMap() { - LinkedHashMap map = new LinkedHashMap<>(); - - for (Material material : ExperimentalUtils.getMaterials()) { - if (BukkitReflectionUtils.isAir(material)) continue; - if (!material.isItem()) continue; - map.put(material.name(), new ItemStack(material)); - } - - return map; - } - - @Override - public String[] getSubTitles(int page) { - return new String[]{"Material"}; - } - - @Override - public void onItemClick(Player player, String itemKey) { - parent.accept(player, SettingType.MATERIAL, MapUtils.createStringArrayMap("material", itemKey)); - } - - @Override - public void onBackToMenuItemClick(Player player) { - parent.decline(player); - } + private final IParentCustomGenerator parent; + + public MaterialMenuGenerator(IParentCustomGenerator parent) { + super(createMaterialsMap()); + this.parent = parent; + } + + public static LinkedHashMap createMaterialsMap() { + LinkedHashMap map = new LinkedHashMap<>(); + + for (Material material : ExperimentalUtils.getMaterials()) { + if (BukkitReflectionUtils.isAir(material)) continue; + if (!material.isItem()) continue; + map.put(material.name(), new ItemStack(material)); + } + + return map; + } + + @Override + public String[] getSubTitles(int page) { + return new String[]{"Material"}; + } + + @Override + public void onItemClick(Player player, String itemKey) { + parent.accept(player, SettingType.MATERIAL, MapUtils.createStringArrayMap("material", itemKey)); + } + + @Override + public void onBackToMenuItemClick(Player player) { + parent.decline(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java index dff2ba522..e02dd6e66 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java @@ -9,30 +9,30 @@ public class SubSettingChooseMenuGenerator extends ChooseItemGenerator { - private final IParentCustomGenerator parent; - private final String key; - private final String title; - - public SubSettingChooseMenuGenerator(String key, IParentCustomGenerator parent, LinkedHashMap map, String title) { - super(map); - this.key = key; - this.title = title; - this.parent = parent; - } - - @Override - public String[] getSubTitles(int page) { - return new String[]{title}; - } - - @Override - public void onItemClick(Player player, String itemKey) { - parent.accept(player, null, MapUtils.createStringArrayMap(key, itemKey)); - } - - @Override - public void onBackToMenuItemClick(Player player) { - parent.decline(player); - } + private final IParentCustomGenerator parent; + private final String key; + private final String title; + + public SubSettingChooseMenuGenerator(String key, IParentCustomGenerator parent, LinkedHashMap map, String title) { + super(map); + this.key = key; + this.title = title; + this.parent = parent; + } + + @Override + public String[] getSubTitles(int page) { + return new String[]{title}; + } + + @Override + public void onItemClick(Player player, String itemKey) { + parent.accept(player, null, MapUtils.createStringArrayMap(key, itemKey)); + } + + @Override + public void onBackToMenuItemClick(Player player) { + parent.decline(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java index 8dbf921d4..aa84364ad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java @@ -9,30 +9,30 @@ public class SubSettingChooseMultipleMenuGenerator extends ChooseMultipleItemGenerator { - private final IParentCustomGenerator parent; - private final String key; - private final String title; - - public SubSettingChooseMultipleMenuGenerator(String key, IParentCustomGenerator parent, LinkedHashMap map, String title) { - super(map); - this.key = key; - this.title = title; - this.parent = parent; - } - - @Override - public String[] getSubTitles(int page) { - return new String[]{title}; - } - - @Override - public void onItemClick(Player player, String[] itemKeys) { - parent.accept(player, null, MapUtils.createStringArrayMap(key, itemKeys)); - } - - @Override - public void onBackToMenuItemClick(Player player) { - parent.decline(player); - } + private final IParentCustomGenerator parent; + private final String key; + private final String title; + + public SubSettingChooseMultipleMenuGenerator(String key, IParentCustomGenerator parent, LinkedHashMap map, String title) { + super(map); + this.key = key; + this.title = title; + this.parent = parent; + } + + @Override + public String[] getSubTitles(int page) { + return new String[]{title}; + } + + @Override + public void onItemClick(Player player, String[] itemKeys) { + parent.accept(player, null, MapUtils.createStringArrayMap(key, itemKeys)); + } + + @Override + public void onBackToMenuItemClick(Player player) { + parent.decline(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java index a37bae7c4..ceff6e5cd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java @@ -11,33 +11,33 @@ @ToString public class ChallengeMenuClickInfo extends MenuClickInfo { - protected final boolean upperItem; - - public ChallengeMenuClickInfo(@Nonnull MenuClickInfo parent, boolean upperItem) { - this(parent.getPlayer(), parent.getInventory(), parent.isShiftClick(), parent.isRightClick(), parent.getSlot(), upperItem); - } - - public ChallengeMenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boolean shiftClick, boolean rightClick, @Nonnegative int slot, boolean upperItem) { - super(player, inventory, shiftClick, rightClick, slot); - this.upperItem = upperItem; - } - - public boolean isUpperItemClick() { - return upperItem; - } - - public boolean isLowerItemClick() { - return !upperItem; - } - - @Nonnull - public Player getPlayer() { - return player; - } - - @Nonnull - public Inventory getInventory() { - return inventory; - } + protected final boolean upperItem; + + public ChallengeMenuClickInfo(@Nonnull MenuClickInfo parent, boolean upperItem) { + this(parent.getPlayer(), parent.getInventory(), parent.isShiftClick(), parent.isRightClick(), parent.getSlot(), upperItem); + } + + public ChallengeMenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boolean shiftClick, boolean rightClick, @Nonnegative int slot, boolean upperItem) { + super(player, inventory, shiftClick, rightClick, slot); + this.upperItem = upperItem; + } + + public boolean isUpperItemClick() { + return upperItem; + } + + public boolean isLowerItemClick() { + return !upperItem; + } + + @Nonnull + public Player getPlayer() { + return player; + } + + @Nonnull + public Inventory getInventory() { + return inventory; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java index 86acca2c0..3fcbcb702 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java @@ -7,12 +7,12 @@ @Getter public abstract class GeneratorMenuPosition implements MenuPosition { - protected final MenuGenerator generator; - protected final int page; + protected final MenuGenerator generator; + protected final int page; - public GeneratorMenuPosition(MenuGenerator generator, int page) { - this.generator = generator; - this.page = page; - } + public GeneratorMenuPosition(MenuGenerator generator, int page) { + this.generator = generator; + this.page = page; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java index 0ed16c4f0..1e77f5ddf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java @@ -9,28 +9,28 @@ public abstract class AbstractTaskExecutor implements Runnable { - protected final List functions = new ArrayList<>(1); - - @Override - public void run() { - for (ScheduledFunction function : functions) { - try { - function.invoke(); - } catch (InvocationTargetException | IllegalAccessException ex) { - Logger.error("An exception occurred while executing {}", function, ex); - } - } - } - - @Nonnull - public abstract AbstractTaskConfig getConfig(); - - public void register(@Nonnull ScheduledFunction function) { - functions.add(function); - } - - public void unregister(@Nonnull Object holder) { - functions.removeIf(function -> function.getHolder() == holder); - } + protected final List functions = new ArrayList<>(1); + + @Override + public void run() { + for (ScheduledFunction function : functions) { + try { + function.invoke(); + } catch (InvocationTargetException | IllegalAccessException ex) { + Logger.error("An exception occurred while executing {}", function, ex); + } + } + } + + @Nonnull + public abstract AbstractTaskConfig getConfig(); + + public void register(@Nonnull ScheduledFunction function) { + functions.add(function); + } + + public void unregister(@Nonnull Object holder) { + functions.removeIf(function -> function.getHolder() == holder); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java index e28f4c0f6..7288d4d96 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java @@ -11,38 +11,38 @@ public class PoliciesContainer { - private final List policies = new ArrayList<>(); - - public PoliciesContainer(@Nonnull ScheduledTask annotation) { - addPolicies( - annotation.challengePolicy(), - annotation.timerPolicy(), - annotation.playerPolicy(), - annotation.worldPolicy(), - annotation.freshnessPolicy() - ); - } - - public PoliciesContainer(@Nonnull TimerTask annotation) { - addPolicies( - annotation.challengePolicy(), - annotation.playerPolicy(), - annotation.worldPolicy(), - annotation.freshnessPolicy() - ); - } - - private void addPolicies(@Nonnull IPolicy... policies) { - this.policies.addAll(Arrays.asList(policies)); - } - - public boolean allPoliciesAreTrue(@Nonnull Object holder) { - for (IPolicy policy : policies) { - if (!policy.isApplicable(holder)) continue; - if (!policy.check(holder)) - return false; - } - return true; - } + private final List policies = new ArrayList<>(); + + public PoliciesContainer(@Nonnull ScheduledTask annotation) { + addPolicies( + annotation.challengePolicy(), + annotation.timerPolicy(), + annotation.playerPolicy(), + annotation.worldPolicy(), + annotation.freshnessPolicy() + ); + } + + public PoliciesContainer(@Nonnull TimerTask annotation) { + addPolicies( + annotation.challengePolicy(), + annotation.playerPolicy(), + annotation.worldPolicy(), + annotation.freshnessPolicy() + ); + } + + private void addPolicies(@Nonnull IPolicy... policies) { + this.policies.addAll(Arrays.asList(policies)); + } + + public boolean allPoliciesAreTrue(@Nonnull Object holder) { + for (IPolicy policy : policies) { + if (!policy.isApplicable(holder)) continue; + if (!policy.check(holder)) + return false; + } + return true; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java index 0af70ab3e..e2bccf522 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java @@ -1,24 +1,25 @@ package net.codingarea.challenges.plugin.management.scheduler; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; import lombok.EqualsAndHashCode; import lombok.Getter; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; + @Getter @EqualsAndHashCode(callSuper = false) public final class ScheduledTaskConfig extends AbstractTaskConfig { - private final int rate; + private final int rate; - ScheduledTaskConfig(@Nonnull ScheduledTask annotation) { - this(annotation.ticks(), annotation.async()); - } + ScheduledTaskConfig(@Nonnull ScheduledTask annotation) { + this(annotation.ticks(), annotation.async()); + } - ScheduledTaskConfig(@Nonnegative int rate, boolean async) { - super(async); - this.rate = rate; - } + ScheduledTaskConfig(@Nonnegative int rate, boolean async) { + super(async); + this.rate = rate; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java index 1a31428b9..34cf541be 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java @@ -7,19 +7,19 @@ public enum TimerPolicy implements IPolicy { - ALWAYS(() -> true), - PAUSED(ChallengeAPI::isPaused), - STARTED(ChallengeAPI::isStarted); + ALWAYS(() -> true), + PAUSED(ChallengeAPI::isPaused), + STARTED(ChallengeAPI::isStarted); - private final BooleanSupplier check; + private final BooleanSupplier check; - TimerPolicy(@Nonnull BooleanSupplier check) { - this.check = check; - } + TimerPolicy(@Nonnull BooleanSupplier check) { + this.check = check; + } - @Override - public boolean check(@Nonnull Object holder) { - return check.getAsBoolean(); - } + @Override + public boolean check(@Nonnull Object holder) { + return check.getAsBoolean(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java index ff503aca6..5f9049f44 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java @@ -11,33 +11,33 @@ @Getter public final class TitleManager { - private static final int fadein = 5, duration = 20, fadeout = 10; - - private final boolean timerStatusEnabled; - private final boolean challengeStatusEnabled; - - public TitleManager() { - Document config = Challenges.getInstance().getConfigDocument().getDocument("titles"); - timerStatusEnabled = config.getBoolean("timer-status"); - challengeStatusEnabled = config.getBoolean("challenge-status"); - } - - public void sendTimerStatusTitle(@Nonnull Message message) { - if (!timerStatusEnabled) return; - message.broadcastTitle(); - } - - public void sendChallengeStatusTitle(@Nonnull Message message, @Nonnull Object... args) { - if (!challengeStatusEnabled) return; - message.broadcastTitle(args); - } - - public void sendTitle(@Nonnull Player player, @Nonnull String title, @Nonnull String subtitle) { - player.sendTitle(title, subtitle, fadein, duration, fadeout); - } - - public void sendTitleInstant(@Nonnull Player player, @Nonnull String title, @Nonnull String subtitle) { - player.sendTitle(title, subtitle, 0, duration, fadeout); - } + private static final int fadein = 5, duration = 20, fadeout = 10; + + private final boolean timerStatusEnabled; + private final boolean challengeStatusEnabled; + + public TitleManager() { + Document config = Challenges.getInstance().getConfigDocument().getDocument("titles"); + timerStatusEnabled = config.getBoolean("timer-status"); + challengeStatusEnabled = config.getBoolean("challenge-status"); + } + + public void sendTimerStatusTitle(@Nonnull Message message) { + if (!timerStatusEnabled) return; + message.broadcastTitle(); + } + + public void sendChallengeStatusTitle(@Nonnull Message message, @Nonnull Object... args) { + if (!challengeStatusEnabled) return; + message.broadcastTitle(args); + } + + public void sendTitle(@Nonnull Player player, @Nonnull String title, @Nonnull String subtitle) { + player.sendTitle(title, subtitle, fadein, duration, fadeout); + } + + public void sendTitleInstant(@Nonnull Player player, @Nonnull String title, @Nonnull String subtitle) { + player.sendTitle(title, subtitle, 0, duration, fadeout); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java index 923e1ad3f..81d8a76a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java @@ -7,14 +7,14 @@ public final class LeaderboardInfo { - private final Map values = new EnumMap<>(Statistic.class); + private final Map values = new EnumMap<>(Statistic.class); - public void setPlace(@Nonnull Statistic statistic, @Nonnegative int place) { - values.put(statistic, place); - } + public void setPlace(@Nonnull Statistic statistic, @Nonnegative int place) { + values.put(statistic, place); + } - public int getPlace(@Nonnull Statistic statistic) { - return values.getOrDefault(statistic, 1); - } + public int getPlace(@Nonnull Statistic statistic) { + return values.getOrDefault(statistic, 1); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java index fd29c7090..323ab33ec 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java @@ -11,55 +11,55 @@ public class PlayerStats { - private final Map values = new EnumMap<>(Statistic.class); - private final UUID uuid; - private final String name; + private final Map values = new EnumMap<>(Statistic.class); + private final UUID uuid; + private final String name; - public PlayerStats(@Nonnull UUID uuid, @Nonnull String name, @Nonnull Document document) { - this.uuid = uuid; - this.name = name; - for (Statistic statistic : Statistic.values()) { - values.put(statistic, document.getDouble(statistic.name())); - } - } + public PlayerStats(@Nonnull UUID uuid, @Nonnull String name, @Nonnull Document document) { + this.uuid = uuid; + this.name = name; + for (Statistic statistic : Statistic.values()) { + values.put(statistic, document.getDouble(statistic.name())); + } + } - public PlayerStats(@Nonnull UUID uuid, @Nonnull String name) { - this.uuid = uuid; - this.name = name; - } + public PlayerStats(@Nonnull UUID uuid, @Nonnull String name) { + this.uuid = uuid; + this.name = name; + } - public void incrementStatistic(@Nonnull Statistic statistic, double amount) { - Logger.debug("Incrementing statistic {} by {} for {}", statistic, amount, name); - double value = values.getOrDefault(statistic, 0d); - values.put(statistic, value + amount); - } + public void incrementStatistic(@Nonnull Statistic statistic, double amount) { + Logger.debug("Incrementing statistic {} by {} for {}", statistic, amount, name); + double value = values.getOrDefault(statistic, 0d); + values.put(statistic, value + amount); + } - @Nonnull - public Document asDocument() { - Document document = Document.create(); - for (Entry entry : values.entrySet()) { - document.set(entry.getKey().name(), entry.getValue()); - } - return document; - } + @Nonnull + public Document asDocument() { + Document document = Document.create(); + for (Entry entry : values.entrySet()) { + document.set(entry.getKey().name(), entry.getValue()); + } + return document; + } - public double getStatisticValue(@Nonnull Statistic statistic) { - return values.getOrDefault(statistic, 0d); - } + public double getStatisticValue(@Nonnull Statistic statistic) { + return values.getOrDefault(statistic, 0d); + } - @Nonnull - public UUID getPlayerUUID() { - return uuid; - } + @Nonnull + public UUID getPlayerUUID() { + return uuid; + } - @Nonnull - public String getPlayerName() { - return name; - } + @Nonnull + public String getPlayerName() { + return name; + } - @Override - public String toString() { - return "PlayerStats" + values; - } + @Override + public String toString() { + return "PlayerStats" + values; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java index 7c986528c..8f6e7e695 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java @@ -25,87 +25,87 @@ public class BackCommand implements PlayerCommand, TabCompleter, Listener { - private final Map> lastLocations = new HashMap<>(); - - // To check if the current teleportation is from the command - private boolean inTeleport = false; - - @Override - public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { - - int count = 1; - try { - if (args.length > 0) { - count = Integer.parseInt(args[0]); - } - } catch (NumberFormatException formatException) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "back [count]"); - return; - } - - List list = lastLocations - .getOrDefault(player.getUniqueId(), Lists.newArrayList()); - int savedCount = list.size(); - - if (savedCount == 0) { - Message.forName("command-back-no-locations").send(player, Prefix.CHALLENGES); - return; - } - - int countToTeleport = Math.min(list.size(), count); - - Message.forName("command-back-teleported" + (countToTeleport > 1 ? "-multiple" : "")) - .send(player, Prefix.CHALLENGES, countToTeleport); - Location location = list.get(countToTeleport - 1); - inTeleport = true; - player.teleport(location); - inTeleport = false; - - if (countToTeleport > 0) { - list.subList(0, countToTeleport).clear(); - } - } - - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, - @NotNull String alias, @NotNull String[] args) { - if (!(sender instanceof Player)) return Lists.newLinkedList(); - Player player = (Player) sender; - - LinkedList list = Lists.newLinkedList(); - for (int i = 0; i < lastLocations.getOrDefault(player.getUniqueId(), - Lists.newLinkedList()).size(); i++) { - list.add(String.valueOf(i + 1)); - } - return list; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onTeleport(PlayerTeleportEvent event) { - if (inTeleport) return; - - // Don't save the teleports of the pregame movement setting - if (!AbstractChallenge.getFirstInstance(PregameMovementSetting.class).isEnabled()) { - if ((event.getPlayer().getGameMode() == GameMode.SURVIVAL || - event.getPlayer().getGameMode() == GameMode.ADVENTURE) && - !ChallengeAPI.isStarted()) { - return; - } - } - if (event.getTo() == null) return; - if (event.getCause() == TeleportCause.ENDER_PEARL || - event.getCause() == TeleportCause.CHORUS_FRUIT) return; - - UUID uuid = event.getPlayer().getUniqueId(); - List locations = lastLocations - .getOrDefault(uuid, Lists.newArrayList()); - lastLocations.putIfAbsent(uuid, locations); - locations.add(0, event.getFrom()); - - if (locations.size() > 30) { - locations.remove(locations.size() - 1); - } - } + private final Map> lastLocations = new HashMap<>(); + + // To check if the current teleportation is from the command + private boolean inTeleport = false; + + @Override + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { + + int count = 1; + try { + if (args.length > 0) { + count = Integer.parseInt(args[0]); + } + } catch (NumberFormatException formatException) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "back [count]"); + return; + } + + List list = lastLocations + .getOrDefault(player.getUniqueId(), Lists.newArrayList()); + int savedCount = list.size(); + + if (savedCount == 0) { + Message.forName("command-back-no-locations").send(player, Prefix.CHALLENGES); + return; + } + + int countToTeleport = Math.min(list.size(), count); + + Message.forName("command-back-teleported" + (countToTeleport > 1 ? "-multiple" : "")) + .send(player, Prefix.CHALLENGES, countToTeleport); + Location location = list.get(countToTeleport - 1); + inTeleport = true; + player.teleport(location); + inTeleport = false; + + if (countToTeleport > 0) { + list.subList(0, countToTeleport).clear(); + } + } + + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, @NotNull String[] args) { + if (!(sender instanceof Player)) return Lists.newLinkedList(); + Player player = (Player) sender; + + LinkedList list = Lists.newLinkedList(); + for (int i = 0; i < lastLocations.getOrDefault(player.getUniqueId(), + Lists.newLinkedList()).size(); i++) { + list.add(String.valueOf(i + 1)); + } + return list; + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent event) { + if (inTeleport) return; + + // Don't save the teleports of the pregame movement setting + if (!AbstractChallenge.getFirstInstance(PregameMovementSetting.class).isEnabled()) { + if ((event.getPlayer().getGameMode() == GameMode.SURVIVAL || + event.getPlayer().getGameMode() == GameMode.ADVENTURE) && + !ChallengeAPI.isStarted()) { + return; + } + } + if (event.getTo() == null) return; + if (event.getCause() == TeleportCause.ENDER_PEARL || + event.getCause() == TeleportCause.CHORUS_FRUIT) return; + + UUID uuid = event.getPlayer().getUniqueId(); + List locations = lastLocations + .getOrDefault(uuid, Lists.newArrayList()); + lastLocations.putIfAbsent(uuid, locations); + locations.add(0, event.getFrom()); + + if (locations.size() > 30) { + locations.remove(locations.size() - 1); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java index 8b5572568..729716cad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java @@ -18,37 +18,37 @@ public class ChallengesCommand implements PlayerCommand, Completer { - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) { - if (args.length > 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "challenges [menu]"); - return; - } - - if (args.length == 1) { - String menuName = args[0].toUpperCase(); - try { - MenuType menuType = MenuType.valueOf(menuName); - Challenges.getInstance().getMenuManager().openMenu(player, menuType, 0); - } catch (IllegalArgumentException exception) { - Challenges.getInstance().getMenuManager().openGUI(player); - } - return; - } - - Challenges.getInstance().getMenuManager().openGUI(player); - - } - - - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { - return args.length != 1 ? null : Utils.filterRecommendations(args[0], - Arrays.stream(MenuType.values()) - .map(menuType -> menuType.name().toLowerCase()) - .toArray(String[]::new) - ); - } + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) { + if (args.length > 1) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "challenges [menu]"); + return; + } + + if (args.length == 1) { + String menuName = args[0].toUpperCase(); + try { + MenuType menuType = MenuType.valueOf(menuName); + Challenges.getInstance().getMenuManager().openMenu(player, menuType, 0); + } catch (IllegalArgumentException exception) { + Challenges.getInstance().getMenuManager().openGUI(player); + } + return; + } + + Challenges.getInstance().getMenuManager().openGUI(player); + + } + + + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { + return args.length != 1 ? null : Utils.filterRecommendations(args[0], + Arrays.stream(MenuType.values()) + .map(menuType -> menuType.name().toLowerCase()) + .toArray(String[]::new) + ); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java index 2b8de1c9b..69d1d4da7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java @@ -22,141 +22,141 @@ public class DatabaseCommand implements PlayerCommand, TabCompleter { - private final Map databaseExecutors; - private final boolean savePlayerConfigs; - private final boolean savePlayerChallenges; - - public DatabaseCommand() { - savePlayerConfigs = Challenges.getInstance().getConfigDocument().getBoolean("save-player-configs"); - savePlayerChallenges = Challenges.getInstance().getConfigDocument().getBoolean("save-player-custom_challenges"); - - databaseExecutors = new HashMap<>(); - databaseExecutors.put("settings", new DatabaseCommandExecutor() { - @Override - public void save(Player player) throws Exception { - if (checkFeatureDisabled(savePlayerConfigs, player)) return; - Challenges.getInstance().getChallengeManager().saveSettings(player); - Message.forName("player-config-loaded").send(player, Prefix.CHALLENGES); - } - - @Override - public void load(Player player) throws Exception { - if (checkFeatureDisabled(savePlayerConfigs, player)) return; - Document config = Challenges.getInstance().getDatabaseManager().getDatabase() - .query("challenges") - .select("config") - .where("uuid", player.getUniqueId()) - .execute().firstOrEmpty().getDocument("config"); - Challenges.getInstance().getChallengeManager().loadSettings(config); - Message.forName("player-config-loaded").send(player, Prefix.CHALLENGES); - } - - @Override - public void reset(Player player) throws Exception { - if (checkFeatureDisabled(savePlayerConfigs, player)) return; - Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges") - .where("uuid", player.getUniqueId()) - .set("config", null) - .execute(); - Message.forName("player-config-reset").send(player, Prefix.CHALLENGES); - } - }); - databaseExecutors.put("customs", new DatabaseCommandExecutor() { - - @Override - public void save(Player player) throws Exception { - if (checkFeatureDisabled(savePlayerChallenges, player)) return; - Challenges.getInstance().getChallengeManager().saveCustomChallenges(player); - Message.forName("player-custom_challenges-saved").send(player, Prefix.CHALLENGES); - } - - @Override - public void load(Player player) throws Exception { - if (checkFeatureDisabled(savePlayerChallenges, player)) return; - Document config = Challenges.getInstance().getDatabaseManager().getDatabase() - .query("challenges") - .select("custom_challenges") - .where("uuid", player.getUniqueId()) - .execute().firstOrEmpty().getDocument("custom_challenges"); - Challenges.getInstance().getChallengeManager().loadCustomChallenges(config); - Message.forName("player-custom_challenges-loaded").send(player, Prefix.CHALLENGES); - } - - @Override - public void reset(Player player) throws Exception { - if (checkFeatureDisabled(savePlayerChallenges, player)) return; - Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges") - .where("uuid", player.getUniqueId()) - .set("custom_challenges", null) - .execute(); - Message.forName("player-custom_challenges-reset").send(player, Prefix.CHALLENGES); - } - }); - } - - @Override - public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { - - if (checkFeatureDisabled(Challenges.getInstance().getDatabaseManager().isConnected(), player)) { - return; - } - - if (args.length != 2 || !databaseExecutors.containsKey(args[1])) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "database "); - return; - } - - String type = args[1].toLowerCase(); - DatabaseCommandExecutor executor = databaseExecutors.get(type); - - switch (args[0].toLowerCase()) { - case "save": - executor.save(player); - break; - case "load": - executor.load(player); - break; - case "reset": - executor.reset(player); - break; - default: - Message.forName("syntax").send(player, Prefix.CHALLENGES, "database "); - } - - } - - /** - * Checks for disabled features and sends a proper messages to indicate that - */ - private boolean checkFeatureDisabled(boolean enabled, @Nonnull Player player) { - if (!enabled) { - Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); - SoundSample.BASS_OFF.play(player); - return true; - } - return false; - } - - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, - @NotNull String alias, @NotNull String[] args) { - - if (args.length <= 1) { - return Utils.filterRecommendations(args[0], "save", "load", "reset"); - } else if (args.length == 2) { - return Utils.filterRecommendations(args[1], databaseExecutors.keySet().toArray(new String[0])); - } - return Lists.newLinkedList(); - } - - - private interface DatabaseCommandExecutor { - void save(Player player) throws Exception; - - void load(Player player) throws Exception; - - void reset(Player player) throws Exception; - } + private final Map databaseExecutors; + private final boolean savePlayerConfigs; + private final boolean savePlayerChallenges; + + public DatabaseCommand() { + savePlayerConfigs = Challenges.getInstance().getConfigDocument().getBoolean("save-player-configs"); + savePlayerChallenges = Challenges.getInstance().getConfigDocument().getBoolean("save-player-custom_challenges"); + + databaseExecutors = new HashMap<>(); + databaseExecutors.put("settings", new DatabaseCommandExecutor() { + @Override + public void save(Player player) throws Exception { + if (checkFeatureDisabled(savePlayerConfigs, player)) return; + Challenges.getInstance().getChallengeManager().saveSettings(player); + Message.forName("player-config-loaded").send(player, Prefix.CHALLENGES); + } + + @Override + public void load(Player player) throws Exception { + if (checkFeatureDisabled(savePlayerConfigs, player)) return; + Document config = Challenges.getInstance().getDatabaseManager().getDatabase() + .query("challenges") + .select("config") + .where("uuid", player.getUniqueId()) + .execute().firstOrEmpty().getDocument("config"); + Challenges.getInstance().getChallengeManager().loadSettings(config); + Message.forName("player-config-loaded").send(player, Prefix.CHALLENGES); + } + + @Override + public void reset(Player player) throws Exception { + if (checkFeatureDisabled(savePlayerConfigs, player)) return; + Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges") + .where("uuid", player.getUniqueId()) + .set("config", null) + .execute(); + Message.forName("player-config-reset").send(player, Prefix.CHALLENGES); + } + }); + databaseExecutors.put("customs", new DatabaseCommandExecutor() { + + @Override + public void save(Player player) throws Exception { + if (checkFeatureDisabled(savePlayerChallenges, player)) return; + Challenges.getInstance().getChallengeManager().saveCustomChallenges(player); + Message.forName("player-custom_challenges-saved").send(player, Prefix.CHALLENGES); + } + + @Override + public void load(Player player) throws Exception { + if (checkFeatureDisabled(savePlayerChallenges, player)) return; + Document config = Challenges.getInstance().getDatabaseManager().getDatabase() + .query("challenges") + .select("custom_challenges") + .where("uuid", player.getUniqueId()) + .execute().firstOrEmpty().getDocument("custom_challenges"); + Challenges.getInstance().getChallengeManager().loadCustomChallenges(config); + Message.forName("player-custom_challenges-loaded").send(player, Prefix.CHALLENGES); + } + + @Override + public void reset(Player player) throws Exception { + if (checkFeatureDisabled(savePlayerChallenges, player)) return; + Challenges.getInstance().getDatabaseManager().getDatabase().update("challenges") + .where("uuid", player.getUniqueId()) + .set("custom_challenges", null) + .execute(); + Message.forName("player-custom_challenges-reset").send(player, Prefix.CHALLENGES); + } + }); + } + + @Override + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { + + if (checkFeatureDisabled(Challenges.getInstance().getDatabaseManager().isConnected(), player)) { + return; + } + + if (args.length != 2 || !databaseExecutors.containsKey(args[1])) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "database "); + return; + } + + String type = args[1].toLowerCase(); + DatabaseCommandExecutor executor = databaseExecutors.get(type); + + switch (args[0].toLowerCase()) { + case "save": + executor.save(player); + break; + case "load": + executor.load(player); + break; + case "reset": + executor.reset(player); + break; + default: + Message.forName("syntax").send(player, Prefix.CHALLENGES, "database "); + } + + } + + /** + * Checks for disabled features and sends a proper messages to indicate that + */ + private boolean checkFeatureDisabled(boolean enabled, @Nonnull Player player) { + if (!enabled) { + Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); + SoundSample.BASS_OFF.play(player); + return true; + } + return false; + } + + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, @NotNull String[] args) { + + if (args.length <= 1) { + return Utils.filterRecommendations(args[0], "save", "load", "reset"); + } else if (args.length == 2) { + return Utils.filterRecommendations(args[1], databaseExecutors.keySet().toArray(new String[0])); + } + return Lists.newLinkedList(); + } + + + private interface DatabaseCommandExecutor { + void save(Player player) throws Exception; + + void load(Player player) throws Exception; + + void reset(Player player) throws Exception; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java index 6bc0b1e5a..381dff108 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java @@ -15,42 +15,42 @@ public class FeedCommand implements SenderCommand, Completer { - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - List targets = new ArrayList<>(); + List targets = new ArrayList<>(); - if (args.length > 0) { - targets.addAll(CommandHelper.getPlayers(sender, args[0])); + if (args.length > 0) { + targets.addAll(CommandHelper.getPlayers(sender, args[0])); - } else if (sender instanceof Player) { - targets.add((Player) sender); - } + } else if (sender instanceof Player) { + targets.add((Player) sender); + } - if (targets.isEmpty()) { - Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); - return; - } + if (targets.isEmpty()) { + Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); + return; + } - boolean otherPlayers = false; - for (Player target : targets) { - target.setFoodLevel(20); - Message.forName("command-feed-fed").send(target, Prefix.CHALLENGES); + boolean otherPlayers = false; + for (Player target : targets) { + target.setFoodLevel(20); + Message.forName("command-feed-fed").send(target, Prefix.CHALLENGES); - if (target != sender) - otherPlayers = true; + if (target != sender) + otherPlayers = true; - } + } - if (otherPlayers) - Message.forName("command-feed-others").send(sender, Prefix.CHALLENGES, targets.size()); + if (otherPlayers) + Message.forName("command-feed-others").send(sender, Prefix.CHALLENGES, targets.size()); - } + } - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - return CommandHelper.getCompletions(sender); - } + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + return CommandHelper.getCompletions(sender); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java index e176ea9dc..e09e858e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java @@ -15,47 +15,47 @@ public class FlyCommand implements SenderCommand, Completer { - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - List targets = new ArrayList<>(); + List targets = new ArrayList<>(); - if (args.length > 0) { - targets.addAll(CommandHelper.getPlayers(sender, args[0])); + if (args.length > 0) { + targets.addAll(CommandHelper.getPlayers(sender, args[0])); - } else if (sender instanceof Player) { - targets.add((Player) sender); - } + } else if (sender instanceof Player) { + targets.add((Player) sender); + } - if (targets.isEmpty()) { - Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); - return; - } + if (targets.isEmpty()) { + Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); + return; + } - boolean otherPlayers = false; - for (Player target : targets) { + boolean otherPlayers = false; + for (Player target : targets) { - if (target.getAllowFlight()) { - Message.forName("command-fly-disabled").send(target, Prefix.CHALLENGES); - } else { - Message.forName("command-fly-enabled").send(target, Prefix.CHALLENGES); - } - target.setAllowFlight(!target.getAllowFlight()); + if (target.getAllowFlight()) { + Message.forName("command-fly-disabled").send(target, Prefix.CHALLENGES); + } else { + Message.forName("command-fly-enabled").send(target, Prefix.CHALLENGES); + } + target.setAllowFlight(!target.getAllowFlight()); - if (target != sender) - otherPlayers = true; + if (target != sender) + otherPlayers = true; - } + } - if (otherPlayers) - Message.forName("command-fly-toggled-others").send(sender, Prefix.CHALLENGES, targets.size()); + if (otherPlayers) + Message.forName("command-fly-toggled-others").send(sender, Prefix.CHALLENGES, targets.size()); - } + } - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - return CommandHelper.getCompletions(sender); - } + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + return CommandHelper.getCompletions(sender); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java index e295cd168..3836680ad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java @@ -18,78 +18,78 @@ public class GamemodeCommand implements SenderCommand, Completer { - @Override - public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { - List targets = new ArrayList<>(); - - if (args.length == 0) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); - return; - } - - GameMode gamemode = getGameMode(args[0]); - - if (gamemode == null) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); - return; - } - - if (args.length > 1) { - targets.addAll(CommandHelper.getPlayers(sender, args[1])); - - } else if (sender instanceof Player) { - targets.add(((Player) sender).getPlayer()); - } - - if (targets.isEmpty()) { - Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); - return; - } - - boolean otherPlayers = false; - - for (Player player : targets) { - Message.forName("command-gamemode-gamemode-changed").send(player, Prefix.CHALLENGES, gamemode); - player.setGameMode(gamemode); - if (player != sender) - otherPlayers = true; - - } - if (otherPlayers) { - Message.forName("command-gamemode-gamemode-changed-others").send(sender, Prefix.CHALLENGES, gamemode, targets.size()); - } - - } - - @Nullable - private GameMode getGameMode(String input) { - switch (input.toLowerCase()) { - case "survival": - case "s": - case "0": - return GameMode.SURVIVAL; - case "spectator": - case "sp": - case "3": - return GameMode.SPECTATOR; - case "adventure": - case "a": - case "2": - return GameMode.ADVENTURE; - case "creative": - case "c": - case "1": - return GameMode.CREATIVE; - } - return null; - } - - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - if (args.length == 2) return CommandHelper.getCompletions(sender); - if (args.length > 1) return null; - return Utils.filterRecommendations(args[0], "0", "1", "2", "3", "survival", "creative", "spectator", "adventure", "s", "c", "sp", "a"); - } + @Override + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { + List targets = new ArrayList<>(); + + if (args.length == 0) { + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); + return; + } + + GameMode gamemode = getGameMode(args[0]); + + if (gamemode == null) { + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); + return; + } + + if (args.length > 1) { + targets.addAll(CommandHelper.getPlayers(sender, args[1])); + + } else if (sender instanceof Player) { + targets.add(((Player) sender).getPlayer()); + } + + if (targets.isEmpty()) { + Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); + return; + } + + boolean otherPlayers = false; + + for (Player player : targets) { + Message.forName("command-gamemode-gamemode-changed").send(player, Prefix.CHALLENGES, gamemode); + player.setGameMode(gamemode); + if (player != sender) + otherPlayers = true; + + } + if (otherPlayers) { + Message.forName("command-gamemode-gamemode-changed-others").send(sender, Prefix.CHALLENGES, gamemode, targets.size()); + } + + } + + @Nullable + private GameMode getGameMode(String input) { + switch (input.toLowerCase()) { + case "survival": + case "s": + case "0": + return GameMode.SURVIVAL; + case "spectator": + case "sp": + case "3": + return GameMode.SPECTATOR; + case "adventure": + case "a": + case "2": + return GameMode.ADVENTURE; + case "creative": + case "c": + case "1": + return GameMode.CREATIVE; + } + return null; + } + + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + if (args.length == 2) return CommandHelper.getCompletions(sender); + if (args.length > 1) return null; + return Utils.filterRecommendations(args[0], "0", "1", "2", "3", "survival", "creative", "spectator", "adventure", "s", "c", "sp", "a"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java index 1d8263af7..9fbeb77f5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java @@ -16,37 +16,37 @@ public class GamestateCommand implements SenderCommand, Completer { - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - - if (args.length != 1) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gamestate "); - return; - } - - FileDocument gamestate = Challenges.getInstance().getConfigManager().getGamestateConfig(); - switch (args[0].toLowerCase()) { - case "reset": - gamestate.clear(); - Challenges.getInstance().getChallengeManager().resetGamestate(); - Challenges.getInstance().getScoreboardManager().updateAll(); - Message.forName("command-gamestate-reset").send(sender, Prefix.CHALLENGES); - break; - case "reload": - Challenges.getInstance().getChallengeManager().loadGamestate(gamestate.readonly()); - Challenges.getInstance().getScoreboardManager().updateAll(); - Message.forName("command-gamestate-reload").send(sender, Prefix.CHALLENGES); - break; - default: - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gamestate "); - } - - } - - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - return args.length == 1 ? Utils.filterRecommendations(args[0], "reset", "reload") : Collections.emptyList(); - } + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + + if (args.length != 1) { + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gamestate "); + return; + } + + FileDocument gamestate = Challenges.getInstance().getConfigManager().getGamestateConfig(); + switch (args[0].toLowerCase()) { + case "reset": + gamestate.clear(); + Challenges.getInstance().getChallengeManager().resetGamestate(); + Challenges.getInstance().getScoreboardManager().updateAll(); + Message.forName("command-gamestate-reset").send(sender, Prefix.CHALLENGES); + break; + case "reload": + Challenges.getInstance().getChallengeManager().loadGamestate(gamestate.readonly()); + Challenges.getInstance().getScoreboardManager().updateAll(); + Message.forName("command-gamestate-reload").send(sender, Prefix.CHALLENGES); + break; + default: + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gamestate "); + } + + } + + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + return args.length == 1 ? Utils.filterRecommendations(args[0], "reset", "reload") : Collections.emptyList(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java index 53587b632..cfe48f18d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java @@ -21,68 +21,68 @@ public class GodModeCommand implements SenderCommand, Completer, Listener { - private final List godModePlayers = new ArrayList<>(); + private final List godModePlayers = new ArrayList<>(); - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - List targets = new ArrayList<>(); + List targets = new ArrayList<>(); - if (args.length > 0) { - targets.addAll(CommandHelper.getPlayers(sender, args[0])); + if (args.length > 0) { + targets.addAll(CommandHelper.getPlayers(sender, args[0])); - } else if (sender instanceof Player) { - targets.add((Player) sender); - } + } else if (sender instanceof Player) { + targets.add((Player) sender); + } - if (targets.isEmpty()) { - Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); - return; - } + if (targets.isEmpty()) { + Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); + return; + } - boolean otherPlayers = false; - for (Player target : targets) { - if (godModePlayers.contains(target.getUniqueId())) { - godModePlayers.remove(target.getUniqueId()); - Message.forName("command-god-mode-disabled").send(target, Prefix.CHALLENGES); - } else { - godModePlayers.add(target.getUniqueId()); - Message.forName("command-god-mode-enabled").send(target, Prefix.CHALLENGES); - target.setFoodLevel(20); - } + boolean otherPlayers = false; + for (Player target : targets) { + if (godModePlayers.contains(target.getUniqueId())) { + godModePlayers.remove(target.getUniqueId()); + Message.forName("command-god-mode-disabled").send(target, Prefix.CHALLENGES); + } else { + godModePlayers.add(target.getUniqueId()); + Message.forName("command-god-mode-enabled").send(target, Prefix.CHALLENGES); + target.setFoodLevel(20); + } - if (target != sender) - otherPlayers = true; + if (target != sender) + otherPlayers = true; - } + } - if (otherPlayers) - Message.forName("command-god-mode-toggled-others").send(sender, Prefix.CHALLENGES, targets.size()); + if (otherPlayers) + Message.forName("command-god-mode-toggled-others").send(sender, Prefix.CHALLENGES, targets.size()); - } + } - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - return CommandHelper.getCompletions(sender); - } + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + return CommandHelper.getCompletions(sender); + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onDamage(EntityDamageEvent event) { - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (godModePlayers.contains(player.getUniqueId())) { - event.setCancelled(true); - } + @EventHandler(priority = EventPriority.HIGHEST) + public void onDamage(EntityDamageEvent event) { + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (godModePlayers.contains(player.getUniqueId())) { + event.setCancelled(true); } - - @EventHandler - private void onFoodLevelChange(FoodLevelChangeEvent event) { - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (godModePlayers.contains(player.getUniqueId())) { - event.setCancelled(true); - } + } + + @EventHandler + private void onFoodLevelChange(FoodLevelChangeEvent event) { + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (godModePlayers.contains(player.getUniqueId())) { + event.setCancelled(true); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java index 16b5397fb..664b388d3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java @@ -17,50 +17,50 @@ public class HealCommand implements SenderCommand, Completer { - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { - List targets = new ArrayList<>(); + List targets = new ArrayList<>(); - if (args.length > 0) { - targets.addAll(CommandHelper.getPlayers(sender, args[0])); + if (args.length > 0) { + targets.addAll(CommandHelper.getPlayers(sender, args[0])); - } else if (sender instanceof Player) { - targets.add((Player) sender); - } + } else if (sender instanceof Player) { + targets.add((Player) sender); + } - if (targets.isEmpty()) { - Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); - return; - } + if (targets.isEmpty()) { + Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); + return; + } - boolean otherPlayers = false; - for (Player player : targets) { - Message.forName("command-heal-healed").send(player, Prefix.CHALLENGES); - AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); - if (attribute == null) { - player.setHealth(20); - } else { - player.setHealth(attribute.getValue()); - } - player.setFoodLevel(20); - player.setSaturation(20); - player.setFireTicks(0); - player.setFallDistance(0); - player.getActivePotionEffects().forEach(potionEffect -> player.removePotionEffect(potionEffect.getType())); + boolean otherPlayers = false; + for (Player player : targets) { + Message.forName("command-heal-healed").send(player, Prefix.CHALLENGES); + AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + if (attribute == null) { + player.setHealth(20); + } else { + player.setHealth(attribute.getValue()); + } + player.setFoodLevel(20); + player.setSaturation(20); + player.setFireTicks(0); + player.setFallDistance(0); + player.getActivePotionEffects().forEach(potionEffect -> player.removePotionEffect(potionEffect.getType())); - if (player != sender) - otherPlayers = true; - } + if (player != sender) + otherPlayers = true; + } - if (otherPlayers) - Message.forName("command-heal-healed-others").send(sender, Prefix.CHALLENGES, targets.size()); - } + if (otherPlayers) + Message.forName("command-heal-healed-others").send(sender, Prefix.CHALLENGES, targets.size()); + } - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - return CommandHelper.getCompletions(sender); - } + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + return CommandHelper.getCompletions(sender); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java index 75dc5098f..d5df6bd58 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java @@ -7,8 +7,8 @@ public class HelpCommand implements SenderCommand { - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { - } + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java index d5e8cd095..85cfe3f5f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java @@ -30,108 +30,108 @@ public class InvseeCommand implements PlayerCommand, Listener { - private static final int - startBottom = 36, - endBottom = 53, - helmetSlot = 46, - chestPlateSlot = 47, - leggingsSlot = 48, - bootsSlot = 49, - offHandSlot = 52; - - private final Map inventories = new HashMap<>(); - - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - - if (args.length < 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "invsee "); - return; - } - - Player target = Bukkit.getPlayer(args[0]); - - if (target == null) { - Message.forName("command-no-target").send(player, Prefix.CHALLENGES); - return; - } - - player.openInventory(getInventory(target)); - MenuPosition.set(player, new SlottedMenuPosition()); - Message.forName("command-invsee-open").send(player, Prefix.CHALLENGES, NameHelper.getName(target)); - } - - public Inventory getInventory(@Nonnull Player player) { - if (inventories.containsKey(player)) { - return inventories.get(player); - } - - Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(Message.forName("inventory-color").asString() + NameHelper.getName(player))); - inventories.put(player, inventory); - MenuPosition.set(player, event -> { - }); - updateInventoryContents(inventory, player.getInventory()); - return inventory; - } - - public void updateInventoryContents(@Nonnull Inventory inventory, @Nonnull PlayerInventory playerInventory) { - inventory.clear(); - - for (int slot = startBottom; slot <= endBottom; slot++) { - inventory.setItem(slot, ItemBuilder.FILL_ITEM); - } - - inventory.setItem(helmetSlot, playerInventory.getHelmet()); - inventory.setItem(chestPlateSlot, playerInventory.getChestplate()); - inventory.setItem(leggingsSlot, playerInventory.getLeggings()); - inventory.setItem(bootsSlot, playerInventory.getBoots()); - inventory.setItem(offHandSlot, playerInventory.getItemInOffHand()); - - for (int slot = 0; slot < 36; slot++) { - inventory.setItem(slot, playerInventory.getItem(slot)); - } - - } - - public void updateInventory(@Nonnull Player player) { - if (!inventories.containsKey(player)) return; - Inventory inventory = inventories.get(player); - updateInventoryContents(inventory, player.getInventory()); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { - if (event.getClickedInventory() == null) return; - if (event.getClickedInventory().getHolder() != event.getPlayer()) return; - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> updateInventory(event.getPlayer()), 1); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> updateInventory(event.getPlayer()), 1); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerQuit(@Nonnull PlayerQuitEvent event) { - Inventory inventory = inventories.remove(event.getPlayer()); - if (inventory == null) return; - for (HumanEntity viewer : new ArrayList<>(inventory.getViewers())) { - viewer.closeInventory(); - } - - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onClose(@Nonnull InventoryCloseEvent event) { - if (event.getInventory().getHolder() != MenuPosition.HOLDER) return; - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { - for (Entry entry : inventories.entrySet()) { - Inventory inventory = entry.getValue(); - if (inventory.getViewers().isEmpty()) { - inventories.remove(entry.getKey()); - } - } - }, 1); - } + private static final int + startBottom = 36, + endBottom = 53, + helmetSlot = 46, + chestPlateSlot = 47, + leggingsSlot = 48, + bootsSlot = 49, + offHandSlot = 52; + + private final Map inventories = new HashMap<>(); + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + + if (args.length < 1) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "invsee "); + return; + } + + Player target = Bukkit.getPlayer(args[0]); + + if (target == null) { + Message.forName("command-no-target").send(player, Prefix.CHALLENGES); + return; + } + + player.openInventory(getInventory(target)); + MenuPosition.set(player, new SlottedMenuPosition()); + Message.forName("command-invsee-open").send(player, Prefix.CHALLENGES, NameHelper.getName(target)); + } + + public Inventory getInventory(@Nonnull Player player) { + if (inventories.containsKey(player)) { + return inventories.get(player); + } + + Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(Message.forName("inventory-color").asString() + NameHelper.getName(player))); + inventories.put(player, inventory); + MenuPosition.set(player, event -> { + }); + updateInventoryContents(inventory, player.getInventory()); + return inventory; + } + + public void updateInventoryContents(@Nonnull Inventory inventory, @Nonnull PlayerInventory playerInventory) { + inventory.clear(); + + for (int slot = startBottom; slot <= endBottom; slot++) { + inventory.setItem(slot, ItemBuilder.FILL_ITEM); + } + + inventory.setItem(helmetSlot, playerInventory.getHelmet()); + inventory.setItem(chestPlateSlot, playerInventory.getChestplate()); + inventory.setItem(leggingsSlot, playerInventory.getLeggings()); + inventory.setItem(bootsSlot, playerInventory.getBoots()); + inventory.setItem(offHandSlot, playerInventory.getItemInOffHand()); + + for (int slot = 0; slot < 36; slot++) { + inventory.setItem(slot, playerInventory.getItem(slot)); + } + + } + + public void updateInventory(@Nonnull Player player) { + if (!inventories.containsKey(player)) return; + Inventory inventory = inventories.get(player); + updateInventoryContents(inventory, player.getInventory()); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + if (event.getClickedInventory() == null) return; + if (event.getClickedInventory().getHolder() != event.getPlayer()) return; + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> updateInventory(event.getPlayer()), 1); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> updateInventory(event.getPlayer()), 1); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerQuit(@Nonnull PlayerQuitEvent event) { + Inventory inventory = inventories.remove(event.getPlayer()); + if (inventory == null) return; + for (HumanEntity viewer : new ArrayList<>(inventory.getViewers())) { + viewer.closeInventory(); + } + + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onClose(@Nonnull InventoryCloseEvent event) { + if (event.getInventory().getHolder() != MenuPosition.HOLDER) return; + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { + for (Entry entry : inventories.entrySet()) { + Inventory inventory = entry.getValue(); + if (inventory.getViewers().isEmpty()) { + inventories.remove(entry.getKey()); + } + } + }, 1); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java index 87759746f..0b10f5325 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java @@ -16,31 +16,31 @@ public class LanguageCommand implements SenderCommand, Completer { - @Override - public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { - if (args.length < 1) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "setlang "); - return; - } - switch (args[0].toLowerCase()) { - case "german": - case "deutsch": - case "de": - Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("de"); - break; - case "english": - case "englisch": - case "en": - Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("en"); - break; - default: - Message.forName("unsuported-language").send(sender, Prefix.CHALLENGES, args[0]); - } + @Override + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { + if (args.length < 1) { + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "setlang "); + return; } - - @Override - public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { - return Utils.filterRecommendations(args[0], "german", "english"); + switch (args[0].toLowerCase()) { + case "german": + case "deutsch": + case "de": + Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("de"); + break; + case "english": + case "englisch": + case "en": + Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("en"); + break; + default: + Message.forName("unsuported-language").send(sender, Prefix.CHALLENGES, args[0]); } + } + + @Override + public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { + return Utils.filterRecommendations(args[0], "german", "english"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java index 8bbfb3e95..8f9752051 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java @@ -26,104 +26,104 @@ public class LeaderboardCommand implements PlayerCommand { - protected static final int[] slots = StatsHelper.getSlots(1); - protected static final int[] navigationSlots = {45, 53}; - protected static final AnimatedInventory loadingInventory; - - static { - loadingInventory = new AnimatedInventory(InventoryTitleManager.getLeaderboardTitle(), 6 * 9, MenuPosition.HOLDER).setEndSound(null).setFrameSound(null); - loadingInventory.createAndAdd().fill(ItemBuilder.FILL_ITEM).setItem(31, new ItemBuilder(Material.BARRIER, "§8» §cLoading..")); - } - - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - if (!Challenges.getInstance().getStatsManager().isEnabled()) { - Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); - SoundSample.BASS_OFF.play(player); - return; - } else if (!Challenges.getInstance().getStatsManager().hasDatabaseConnection()) { - Message.forName("no-database-connection").send(player, Prefix.CHALLENGES); - SoundSample.BASS_OFF.play(player); - return; - } - - createInventory(player).open(player, Challenges.getInstance()); - } - - @Nonnull - @CheckReturnValue - public AnimatedInventory createInventory(@Nonnull Player player) { - AnimatedInventory inventory = new AnimatedInventory(InventoryTitleManager.getLeaderboardTitle(), 4 * 9, MenuPosition.HOLDER); - StatsHelper.setAccent(inventory, 2); - SlottedMenuPosition position = new SlottedMenuPosition(); - for (int i = 0; i < Statistic.values().length; i++) { - Statistic statistic = Statistic.values()[i]; - ItemBuilder item = new ItemBuilder(StatsHelper.getMaterial(statistic), "§8» " + StatsHelper.getNameMessage(statistic).asString()); - inventory.cloneLastAndAdd().setItem(slots[i], item.hideAttributes()); - position.setAction(slots[i], () -> openMenu(player, statistic, 0, false)); - } - - MenuPosition.set(player, position); - return inventory; - } - - private void openMenu(@Nonnull Player player, @Nonnull Statistic statistic, int page, boolean openInstant) { - loadingInventory.open(player, Challenges.getInstance()); - MenuPosition.setEmpty(player); - Challenges.getInstance().runAsync(() -> openMenu0(player, statistic, page, openInstant)); - } - - private void openMenu0(@Nonnull Player player, @Nonnull Statistic statistic, int page, boolean openInstant) { - - int[] slots = { - 10, 11, 12, 13, 14, 15, 16, - 19, 20, 21, 22, 23, 24, 25, - 28, 29, 30, 31, 32, 33, 34, - 37, 38, 39, 40, 41, 42, 43 - }; - - String statisticName = StatsHelper.getNameMessage(statistic).asString(); - AnimatedInventory inventory = new AnimatedInventory(InventoryTitleManager.getLeaderboardTitle(ChatColor.stripColor(statisticName), page + 1), 6 * 9, MenuPosition.HOLDER); - inventory.createAndAdd().fill(ItemBuilder.FILL_ITEM); - - List leaderboard = Challenges.getInstance().getStatsManager().getLeaderboard(statistic); - int pages = leaderboard.size() / slots.length; - if (leaderboard.size() % slots.length > 0) pages++; - int offset = page * slots.length; - - InventoryUtils.setNavigationItemsToFrame(inventory.cloneLastAndAdd(), navigationSlots, true, page, pages); - SlottedMenuPosition position = new SlottedMenuPosition(); - CloudSupportManager cloudSupport = Challenges.getInstance().getCloudSupportManager(); - - for (int i = offset; i < leaderboard.size() && i < offset + slots.length; i++) { - int slot = slots[i - offset]; - PlayerStats stats = leaderboard.get(i); - String coloredName = cloudSupport.isNameSupport() && cloudSupport.hasNameFor(stats.getPlayerUUID()) ? cloudSupport.getColoredName(stats.getPlayerUUID()) : stats.getPlayerName(); - ItemBuilder item = new SkullBuilder().setOwner(stats.getPlayerUUID(), stats.getPlayerName()) - .setName(Message.forName("stats-leaderboard-display") - .asArray(coloredName, statistic.formatChat(stats.getStatisticValue(statistic)), statisticName, i + 1)); - inventory.cloneLastAndAdd().setItem(slot, item.hideAttributes()); - - position.setAction(slot, () -> { - MenuPosition.setEmpty(player); - loadingInventory.open(player, Challenges.getInstance()); - player.performCommand("stats " + stats.getPlayerName()); - }); - } - - position.setAction(navigationSlots[0], info -> { - if (page == 0 || info.isShiftClick()) { - createInventory(player).openNotAnimated(player, true, Challenges.getInstance()); - } else { - openMenu(player, statistic, page - 1, true); - } - }); - if (inventory.getLastFrame().getItemType(navigationSlots[1]) == Material.PLAYER_HEAD) - position.setAction(navigationSlots[1], () -> openMenu(player, statistic, page + 1, true)); - - if (openInstant) inventory.openNotAnimated(player, true, Challenges.getInstance()); - else inventory.open(player, Challenges.getInstance()); - MenuPosition.set(player, position); - } + protected static final int[] slots = StatsHelper.getSlots(1); + protected static final int[] navigationSlots = {45, 53}; + protected static final AnimatedInventory loadingInventory; + + static { + loadingInventory = new AnimatedInventory(InventoryTitleManager.getLeaderboardTitle(), 6 * 9, MenuPosition.HOLDER).setEndSound(null).setFrameSound(null); + loadingInventory.createAndAdd().fill(ItemBuilder.FILL_ITEM).setItem(31, new ItemBuilder(Material.BARRIER, "§8» §cLoading..")); + } + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + if (!Challenges.getInstance().getStatsManager().isEnabled()) { + Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); + SoundSample.BASS_OFF.play(player); + return; + } else if (!Challenges.getInstance().getStatsManager().hasDatabaseConnection()) { + Message.forName("no-database-connection").send(player, Prefix.CHALLENGES); + SoundSample.BASS_OFF.play(player); + return; + } + + createInventory(player).open(player, Challenges.getInstance()); + } + + @Nonnull + @CheckReturnValue + public AnimatedInventory createInventory(@Nonnull Player player) { + AnimatedInventory inventory = new AnimatedInventory(InventoryTitleManager.getLeaderboardTitle(), 4 * 9, MenuPosition.HOLDER); + StatsHelper.setAccent(inventory, 2); + SlottedMenuPosition position = new SlottedMenuPosition(); + for (int i = 0; i < Statistic.values().length; i++) { + Statistic statistic = Statistic.values()[i]; + ItemBuilder item = new ItemBuilder(StatsHelper.getMaterial(statistic), "§8» " + StatsHelper.getNameMessage(statistic).asString()); + inventory.cloneLastAndAdd().setItem(slots[i], item.hideAttributes()); + position.setAction(slots[i], () -> openMenu(player, statistic, 0, false)); + } + + MenuPosition.set(player, position); + return inventory; + } + + private void openMenu(@Nonnull Player player, @Nonnull Statistic statistic, int page, boolean openInstant) { + loadingInventory.open(player, Challenges.getInstance()); + MenuPosition.setEmpty(player); + Challenges.getInstance().runAsync(() -> openMenu0(player, statistic, page, openInstant)); + } + + private void openMenu0(@Nonnull Player player, @Nonnull Statistic statistic, int page, boolean openInstant) { + + int[] slots = { + 10, 11, 12, 13, 14, 15, 16, + 19, 20, 21, 22, 23, 24, 25, + 28, 29, 30, 31, 32, 33, 34, + 37, 38, 39, 40, 41, 42, 43 + }; + + String statisticName = StatsHelper.getNameMessage(statistic).asString(); + AnimatedInventory inventory = new AnimatedInventory(InventoryTitleManager.getLeaderboardTitle(ChatColor.stripColor(statisticName), page + 1), 6 * 9, MenuPosition.HOLDER); + inventory.createAndAdd().fill(ItemBuilder.FILL_ITEM); + + List leaderboard = Challenges.getInstance().getStatsManager().getLeaderboard(statistic); + int pages = leaderboard.size() / slots.length; + if (leaderboard.size() % slots.length > 0) pages++; + int offset = page * slots.length; + + InventoryUtils.setNavigationItemsToFrame(inventory.cloneLastAndAdd(), navigationSlots, true, page, pages); + SlottedMenuPosition position = new SlottedMenuPosition(); + CloudSupportManager cloudSupport = Challenges.getInstance().getCloudSupportManager(); + + for (int i = offset; i < leaderboard.size() && i < offset + slots.length; i++) { + int slot = slots[i - offset]; + PlayerStats stats = leaderboard.get(i); + String coloredName = cloudSupport.isNameSupport() && cloudSupport.hasNameFor(stats.getPlayerUUID()) ? cloudSupport.getColoredName(stats.getPlayerUUID()) : stats.getPlayerName(); + ItemBuilder item = new SkullBuilder().setOwner(stats.getPlayerUUID(), stats.getPlayerName()) + .setName(Message.forName("stats-leaderboard-display") + .asArray(coloredName, statistic.formatChat(stats.getStatisticValue(statistic)), statisticName, i + 1)); + inventory.cloneLastAndAdd().setItem(slot, item.hideAttributes()); + + position.setAction(slot, () -> { + MenuPosition.setEmpty(player); + loadingInventory.open(player, Challenges.getInstance()); + player.performCommand("stats " + stats.getPlayerName()); + }); + } + + position.setAction(navigationSlots[0], info -> { + if (page == 0 || info.isShiftClick()) { + createInventory(player).openNotAnimated(player, true, Challenges.getInstance()); + } else { + openMenu(player, statistic, page - 1, true); + } + }); + if (inventory.getLastFrame().getItemType(navigationSlots[1]) == Material.PLAYER_HEAD) + position.setAction(navigationSlots[1], () -> openMenu(player, statistic, page + 1, true)); + + if (openInstant) inventory.openNotAnimated(player, true, Challenges.getInstance()); + else inventory.open(player, Challenges.getInstance()); + MenuPosition.set(player, position); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java index b43981339..88cb3bc79 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java @@ -18,78 +18,78 @@ public class ResetCommand implements SenderCommand, Completer { - private final boolean confirmReset, seedResetCommand; - - public ResetCommand() { - Document pluginConfig = Challenges.getInstance().getConfigDocument(); - confirmReset = pluginConfig.getBoolean("confirm-reset"); - - Document seedResetConfig = pluginConfig.getDocument("custom-seed"); - seedResetCommand = seedResetConfig.getBoolean("command"); - } - - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { - - if (confirmReset && (args.length < 1 || !args[0].equalsIgnoreCase("confirm")) || (args.length > 0 && !args[0].equalsIgnoreCase("confirm"))) { - if (args.length > 0 && args[0].equalsIgnoreCase("settings")) { - Challenges.getInstance().getChallengeManager().restoreDefaults(); - Message.forName("config-reset").broadcast(Prefix.CHALLENGES); - return; - } else if (args.length > 0 && args[0].equalsIgnoreCase("customs")) { - Challenges.getInstance().getCustomChallengesLoader().resetChallenges(); - Message.forName("custom_challenges-reset").broadcast(Prefix.CHALLENGES); - return; - } - - if (!Challenges.getInstance().getWorldManager().isEnableFreshReset() && ChallengeAPI.isFresh()) { - Message.forName("no-fresh-reset").send(sender, Prefix.CHALLENGES); - SoundSample.BASS_OFF.playIfPlayer(sender); - return; - } - - if (confirmReset) { - Message.forName("confirm-reset").send(sender, Prefix.CHALLENGES, "reset confirm"); - return; - } - } - - if (!Challenges.getInstance().getWorldManager().isEnableFreshReset() && ChallengeAPI.isFresh()) { - Message.forName("no-fresh-reset").send(sender, Prefix.CHALLENGES); - SoundSample.BASS_OFF.playIfPlayer(sender); - return; - } - - Long seed = null; - - if (seedResetCommand) { - int index = confirmReset ? 1 : 0; - if (args.length > index) { - String seedInput = args[index]; - try { - seed = Long.parseLong(seedInput); - } catch (NumberFormatException exception) { - Challenges.getInstance().getLogger().error("", exception); - } - } - } - - Challenges.getInstance().getWorldManager().prepareWorldReset(sender, seed); - - } - - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - if (confirmReset && args.length == 1) return Utils.filterRecommendations( - args[0], "confirm", "settings", "customs"); - if (seedResetCommand && ((confirmReset && args.length == 2) || args.length == 1)) { - return args.length == 1 ? - Utils.filterRecommendations(args[args.length - 1], "[seed]", "settings", "customs") : - args[0].equalsIgnoreCase("confirm") ? Collections.singletonList("[seed]") : Lists - .newLinkedList(); - } - - return Lists.newLinkedList(); - } + private final boolean confirmReset, seedResetCommand; + + public ResetCommand() { + Document pluginConfig = Challenges.getInstance().getConfigDocument(); + confirmReset = pluginConfig.getBoolean("confirm-reset"); + + Document seedResetConfig = pluginConfig.getDocument("custom-seed"); + seedResetCommand = seedResetConfig.getBoolean("command"); + } + + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { + + if (confirmReset && (args.length < 1 || !args[0].equalsIgnoreCase("confirm")) || (args.length > 0 && !args[0].equalsIgnoreCase("confirm"))) { + if (args.length > 0 && args[0].equalsIgnoreCase("settings")) { + Challenges.getInstance().getChallengeManager().restoreDefaults(); + Message.forName("config-reset").broadcast(Prefix.CHALLENGES); + return; + } else if (args.length > 0 && args[0].equalsIgnoreCase("customs")) { + Challenges.getInstance().getCustomChallengesLoader().resetChallenges(); + Message.forName("custom_challenges-reset").broadcast(Prefix.CHALLENGES); + return; + } + + if (!Challenges.getInstance().getWorldManager().isEnableFreshReset() && ChallengeAPI.isFresh()) { + Message.forName("no-fresh-reset").send(sender, Prefix.CHALLENGES); + SoundSample.BASS_OFF.playIfPlayer(sender); + return; + } + + if (confirmReset) { + Message.forName("confirm-reset").send(sender, Prefix.CHALLENGES, "reset confirm"); + return; + } + } + + if (!Challenges.getInstance().getWorldManager().isEnableFreshReset() && ChallengeAPI.isFresh()) { + Message.forName("no-fresh-reset").send(sender, Prefix.CHALLENGES); + SoundSample.BASS_OFF.playIfPlayer(sender); + return; + } + + Long seed = null; + + if (seedResetCommand) { + int index = confirmReset ? 1 : 0; + if (args.length > index) { + String seedInput = args[index]; + try { + seed = Long.parseLong(seedInput); + } catch (NumberFormatException exception) { + Challenges.getInstance().getLogger().error("", exception); + } + } + } + + Challenges.getInstance().getWorldManager().prepareWorldReset(sender, seed); + + } + + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + if (confirmReset && args.length == 1) return Utils.filterRecommendations( + args[0], "confirm", "settings", "customs"); + if (seedResetCommand && ((confirmReset && args.length == 2) || args.length == 1)) { + return args.length == 1 ? + Utils.filterRecommendations(args[args.length - 1], "[seed]", "settings", "customs") : + args[0].equalsIgnoreCase("confirm") ? Collections.singletonList("[seed]") : Lists + .newLinkedList(); + } + + return Lists.newLinkedList(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java index 895769031..0c9313f58 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java @@ -12,22 +12,22 @@ import org.jetbrains.annotations.NotNull; public class ResultCommand implements PlayerCommand { - @Override - public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { - if (ChallengeAPI.isPaused()) { - Message.forName("timer-not-started").send(player, Prefix.CHALLENGES); - SoundSample.BASS_OFF.play(player); - return; - } + @Override + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { + if (ChallengeAPI.isPaused()) { + Message.forName("timer-not-started").send(player, Prefix.CHALLENGES); + SoundSample.BASS_OFF.play(player); + return; + } - IGoal currentGoal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); + IGoal currentGoal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); - if (currentGoal instanceof ForceBattleGoal) { - ForceBattleGoal forceBattleGoal = (ForceBattleGoal) currentGoal; - forceBattleGoal.sendResult(player); - return; - } + if (currentGoal instanceof ForceBattleGoal) { + ForceBattleGoal forceBattleGoal = (ForceBattleGoal) currentGoal; + forceBattleGoal.sendResult(player); + return; + } - Message.forName("command-result-no-battle-active").send(player, Prefix.CHALLENGES); - } + Message.forName("command-result-no-battle-active").send(player, Prefix.CHALLENGES); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java index 10ddd47ce..1248a6519 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.anweisen.utilities.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.RegisteredDrops; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; +import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.Utils; import org.bukkit.Material; @@ -24,51 +24,51 @@ public class SearchCommand implements SenderCommand, Completer { - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - if (args.length == 0) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "search "); - return; - } + if (args.length == 0) { + Message.forName("syntax").send(sender, Prefix.CHALLENGES, "search "); + return; + } - String input = String.join("_", args).toUpperCase(); - Material material = Utils.getMaterial(input); + String input = String.join("_", args).toUpperCase(); + Material material = Utils.getMaterial(input); - if (material == null) { - Message.forName("no-such-material").send(sender, Prefix.CHALLENGES); - return; - } - if (!material.isItem()) { - Message.forName("not-an-item").send(sender, Prefix.CHALLENGES, material); - return; - } + if (material == null) { + Message.forName("no-such-material").send(sender, Prefix.CHALLENGES); + return; + } + if (!material.isItem()) { + Message.forName("not-an-item").send(sender, Prefix.CHALLENGES, material); + return; + } - Map allDrops = Challenges.getInstance().getBlockDropManager().getRegisteredDrops(); + Map allDrops = Challenges.getInstance().getBlockDropManager().getRegisteredDrops(); - List blocks = new ArrayList<>(1); - for (Entry entry : allDrops.entrySet()) { - List drops = entry.getValue().getFirst().orElse(new ArrayList<>()); - if (drops.contains(material)) - blocks.add(entry.getKey()); - } + List blocks = new ArrayList<>(1); + for (Entry entry : allDrops.entrySet()) { + List drops = entry.getValue().getFirst().orElse(new ArrayList<>()); + if (drops.contains(material)) + blocks.add(entry.getKey()); + } - if (blocks.isEmpty()) { - Message.forName("command-search-nothing").send(sender, Prefix.CHALLENGES, material); - } else { - Message.forName("command-search-result").send(sender, Prefix.CHALLENGES, material, StringUtils.getIterableAsString(blocks, ", ", StringUtils::getEnumName)); - } - } + if (blocks.isEmpty()) { + Message.forName("command-search-nothing").send(sender, Prefix.CHALLENGES, material); + } else { + Message.forName("command-search-result").send(sender, Prefix.CHALLENGES, material, StringUtils.getIterableAsString(blocks, ", ", StringUtils::getEnumName)); + } + } - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - return args.length != 1 ? null : - Arrays.stream(ExperimentalUtils.getMaterials()) - .filter(ItemUtils::isObtainableInSurvival) - .filter(Material::isItem) - .map(material -> material.name().toLowerCase()) - .collect(Collectors.toList()); - } + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + return args.length != 1 ? null : + Arrays.stream(ExperimentalUtils.getMaterials()) + .filter(ItemUtils::isObtainableInSurvival) + .filter(Material::isItem) + .map(material -> material.name().toLowerCase()) + .collect(Collectors.toList()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java index 93fbafdeb..875387c43 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java @@ -14,21 +14,21 @@ public class SkipTimerCommand implements SenderCommand, Completer { - @Override - public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { - for (IChallenge challenge : Challenges.getInstance().getChallengeManager().getChallenges()) { - if (!challenge.isEnabled()) continue; - if (challenge instanceof TimedChallenge) { - TimedChallenge timedChallenge = (TimedChallenge) challenge; - timedChallenge.setSecondsUntilActivation(0); - } - } - } + @Override + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { + for (IChallenge challenge : Challenges.getInstance().getChallengeManager().getChallenges()) { + if (!challenge.isEnabled()) continue; + if (challenge instanceof TimedChallenge) { + TimedChallenge timedChallenge = (TimedChallenge) challenge; + timedChallenge.setSecondsUntilActivation(0); + } + } + } - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { - return Collections.emptyList(); - } + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { + return Collections.emptyList(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java index 861d1fb02..5e222ab6d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java @@ -27,93 +27,93 @@ public class StatsCommand implements PlayerCommand { - private final Map submitTimeByPlayer = new ConcurrentHashMap<>(); - - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) { - if (!Challenges.getInstance().getStatsManager().isEnabled()) { - Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); - SoundSample.BASS_OFF.play(player); - return; - } else if (!Challenges.getInstance().getStatsManager().hasDatabaseConnection()) { - Message.forName("no-database-connection").send(player, Prefix.CHALLENGES); - SoundSample.BASS_OFF.play(player); - return; - } - - if (System.currentTimeMillis() - submitTimeByPlayer.getOrDefault(player, System.currentTimeMillis() - 10 * 1000) < 5 * 1000) { - SoundSample.BASS_OFF.play(player); - return; - } - submitTimeByPlayer.put(player, System.currentTimeMillis()); - - switch (args.length) { - case 0: - Message.forName("fetching-data").send(player, Prefix.CHALLENGES); - handleCommand(player); - break; - case 1: - Message.forName("fetching-data").send(player, Prefix.CHALLENGES); - handleCommand(player, args[0]); - break; - default: - Message.forName("syntax").send(player, Prefix.CHALLENGES, "stats [player]"); - } - } - - private void handleCommand(@Nonnull Player player) { - Challenges.getInstance().runAsync(() -> { - open(player, player.getUniqueId(), player.getName()); - }); - } - - private void handleCommand(@Nonnull Player player, @Nonnull String name) { - Challenges.getInstance().runAsync(() -> { - Player target = Bukkit.getPlayer(name); - if (target != null) { - open(player, target.getUniqueId(), target.getName()); - return; - } - - try { - UUID uuid = Utils.fetchUUID(name); - open(player, uuid, name); - } catch (IOException ex) { - player.sendMessage(Prefix.CHALLENGES + "§7Something went wrong"); - } - }); - } - - private void open(@Nonnull Player player, @Nonnull UUID uuid, @Nonnull String name) { - - PlayerStats stats = Challenges.getInstance().getStatsManager().getStats(uuid, name); - name = stats.getPlayerName(); - - CloudSupportManager cloudSupport = Challenges.getInstance().getCloudSupportManager(); - String coloredName = cloudSupport.isNameSupport() && cloudSupport.hasNameFor(uuid) ? cloudSupport.getColoredName(uuid) : name; - - AnimatedInventory inventory = new AnimatedInventory(InventoryTitleManager.getStatsTitle(name), 5 * 9, MenuPosition.HOLDER); - StatsHelper.setAccent(inventory, 3); - inventory.cloneLastAndAdd().setItem(13, new SkullBuilder(Message.forName("stats-of").asString(coloredName)).setOwner(uuid, name).build()); - - LeaderboardInfo info = Challenges.getInstance().getStatsManager().getLeaderboardInfo(uuid); - createInventory(stats, info, inventory, StatsHelper.getSlots(2)); - - MenuPosition.setEmpty(player); - inventory.open(player, Challenges.getInstance()); - - submitTimeByPlayer.remove(player); - } - - private void createInventory(@Nonnull PlayerStats stats, @Nonnull LeaderboardInfo info, @Nonnull AnimatedInventory inventory, @Nonnull int... slots) { - for (int i = 0; i < Statistic.values().length; i++) { - Statistic statistic = Statistic.values()[i]; - double value = stats.getStatisticValue(statistic); - String format = statistic.formatChat(value); - - ItemBuilder item = new ItemBuilder(StatsHelper.getMaterial(statistic), StatsHelper.getNameMessage(statistic).asString()).setLore(Message.forName("stats-display").asArray(format, info.getPlace(statistic))).hideAttributes(); - inventory.cloneLastAndAdd().setItem(slots[i], item); - } - } + private final Map submitTimeByPlayer = new ConcurrentHashMap<>(); + + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) { + if (!Challenges.getInstance().getStatsManager().isEnabled()) { + Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); + SoundSample.BASS_OFF.play(player); + return; + } else if (!Challenges.getInstance().getStatsManager().hasDatabaseConnection()) { + Message.forName("no-database-connection").send(player, Prefix.CHALLENGES); + SoundSample.BASS_OFF.play(player); + return; + } + + if (System.currentTimeMillis() - submitTimeByPlayer.getOrDefault(player, System.currentTimeMillis() - 10 * 1000) < 5 * 1000) { + SoundSample.BASS_OFF.play(player); + return; + } + submitTimeByPlayer.put(player, System.currentTimeMillis()); + + switch (args.length) { + case 0: + Message.forName("fetching-data").send(player, Prefix.CHALLENGES); + handleCommand(player); + break; + case 1: + Message.forName("fetching-data").send(player, Prefix.CHALLENGES); + handleCommand(player, args[0]); + break; + default: + Message.forName("syntax").send(player, Prefix.CHALLENGES, "stats [player]"); + } + } + + private void handleCommand(@Nonnull Player player) { + Challenges.getInstance().runAsync(() -> { + open(player, player.getUniqueId(), player.getName()); + }); + } + + private void handleCommand(@Nonnull Player player, @Nonnull String name) { + Challenges.getInstance().runAsync(() -> { + Player target = Bukkit.getPlayer(name); + if (target != null) { + open(player, target.getUniqueId(), target.getName()); + return; + } + + try { + UUID uuid = Utils.fetchUUID(name); + open(player, uuid, name); + } catch (IOException ex) { + player.sendMessage(Prefix.CHALLENGES + "§7Something went wrong"); + } + }); + } + + private void open(@Nonnull Player player, @Nonnull UUID uuid, @Nonnull String name) { + + PlayerStats stats = Challenges.getInstance().getStatsManager().getStats(uuid, name); + name = stats.getPlayerName(); + + CloudSupportManager cloudSupport = Challenges.getInstance().getCloudSupportManager(); + String coloredName = cloudSupport.isNameSupport() && cloudSupport.hasNameFor(uuid) ? cloudSupport.getColoredName(uuid) : name; + + AnimatedInventory inventory = new AnimatedInventory(InventoryTitleManager.getStatsTitle(name), 5 * 9, MenuPosition.HOLDER); + StatsHelper.setAccent(inventory, 3); + inventory.cloneLastAndAdd().setItem(13, new SkullBuilder(Message.forName("stats-of").asString(coloredName)).setOwner(uuid, name).build()); + + LeaderboardInfo info = Challenges.getInstance().getStatsManager().getLeaderboardInfo(uuid); + createInventory(stats, info, inventory, StatsHelper.getSlots(2)); + + MenuPosition.setEmpty(player); + inventory.open(player, Challenges.getInstance()); + + submitTimeByPlayer.remove(player); + } + + private void createInventory(@Nonnull PlayerStats stats, @Nonnull LeaderboardInfo info, @Nonnull AnimatedInventory inventory, @Nonnull int... slots) { + for (int i = 0; i < Statistic.values().length; i++) { + Statistic statistic = Statistic.values()[i]; + double value = stats.getStatisticValue(statistic); + String format = statistic.formatChat(value); + + ItemBuilder item = new ItemBuilder(StatsHelper.getMaterial(statistic), StatsHelper.getNameMessage(statistic).asString()).setLore(Message.forName("stats-display").asArray(format, info.getPlace(statistic))).hideAttributes(); + inventory.cloneLastAndAdd().setItem(slots[i], item); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java index 4d8bb05fe..a202e72c5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java @@ -17,124 +17,124 @@ public class TimeCommand implements PlayerCommand, Completer { - private final Map names; + private final Map names; - public TimeCommand() { - names = new HashMap<>(); - names.put(1000L, "Day"); - names.put(6000L, "Noon"); - names.put(13000L, "Night"); - names.put(18000L, "Midnight"); - } + public TimeCommand() { + names = new HashMap<>(); + names.put(1000L, "Day"); + names.put(6000L, "Noon"); + names.put(13000L, "Night"); + names.put(18000L, "Midnight"); + } - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - if (args.length == 0) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time "); - return; - } - World world = player.getWorld(); + if (args.length == 0) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "time "); + return; + } + World world = player.getWorld(); - switch (args[0].toLowerCase()) { - case "day": - player.performCommand("time set day"); - break; - case "night": - player.performCommand("time set night"); - break; - case "noon": - player.performCommand("time set noon"); - break; - case "midnight": - player.performCommand("time set midnight"); - break; - case "set": { - if (args.length == 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time set "); - break; - } - long time = getTime(args[1]); - if (time < 0) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time set "); - break; - } - world.setTime(time); - if (names.containsKey(time)) { - String timeName = names.get(time).toLowerCase(); - String timeTranslation = Message.forName("command-time-" + timeName).asString(); - Message.forName("command-time-set-exact").send(player, Prefix.CHALLENGES, timeTranslation, time); - } else { - Message.forName("command-time-set").send(player, Prefix.CHALLENGES, time, getNearestTime(world)); - } - break; - } - case "add": { - if (args.length == 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time add "); - break; - } - long time = getLongFromString(args[1]); - if (time < 0) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time add "); - break; - } - player.performCommand("time set " + (world.getTime() + time)); - break; - } - case "subtract": { - if (args.length == 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time subtract "); - break; - } - long time = getLongFromString(args[1]); - if (time < 0) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time subtract "); - break; - } - player.performCommand("time set " + (world.getTime() - time)); - break; - } - case "query": { - Message.forName("command-time-query").send(player, Prefix.CHALLENGES, NumberFormatter.MIDDLE_NUMBER.format(world.getFullTime()), world.getFullTime() / 24000, NumberFormatter.MIDDLE_NUMBER.format(world.getTime()), getNearestTime(world)); - break; - } + switch (args[0].toLowerCase()) { + case "day": + player.performCommand("time set day"); + break; + case "night": + player.performCommand("time set night"); + break; + case "noon": + player.performCommand("time set noon"); + break; + case "midnight": + player.performCommand("time set midnight"); + break; + case "set": { + if (args.length == 1) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "time set "); + break; + } + long time = getTime(args[1]); + if (time < 0) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "time set "); + break; + } + world.setTime(time); + if (names.containsKey(time)) { + String timeName = names.get(time).toLowerCase(); + String timeTranslation = Message.forName("command-time-" + timeName).asString(); + Message.forName("command-time-set-exact").send(player, Prefix.CHALLENGES, timeTranslation, time); + } else { + Message.forName("command-time-set").send(player, Prefix.CHALLENGES, time, getNearestTime(world)); + } + break; + } + case "add": { + if (args.length == 1) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "time add "); + break; + } + long time = getLongFromString(args[1]); + if (time < 0) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "time add "); + break; + } + player.performCommand("time set " + (world.getTime() + time)); + break; + } + case "subtract": { + if (args.length == 1) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "time subtract "); + break; + } + long time = getLongFromString(args[1]); + if (time < 0) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "time subtract "); + break; + } + player.performCommand("time set " + (world.getTime() - time)); + break; + } + case "query": { + Message.forName("command-time-query").send(player, Prefix.CHALLENGES, NumberFormatter.MIDDLE_NUMBER.format(world.getFullTime()), world.getFullTime() / 24000, NumberFormatter.MIDDLE_NUMBER.format(world.getTime()), getNearestTime(world)); + break; + } - } + } - } + } - private String getNearestTime(@Nonnull World world) { - return names.entrySet().stream() - .min(Comparator.comparingLong(entry -> Math.abs(world.getTime() - entry.getKey()))) - .map(Entry::getValue) - .orElse("Day"); - } + private String getNearestTime(@Nonnull World world) { + return names.entrySet().stream() + .min(Comparator.comparingLong(entry -> Math.abs(world.getTime() - entry.getKey()))) + .map(Entry::getValue) + .orElse("Day"); + } - private long getTime(@Nonnull String input) { - for (Entry entry : names.entrySet()) { - if (entry.getValue().equalsIgnoreCase(input)) - return entry.getKey(); - } - return getLongFromString(input); - } + private long getTime(@Nonnull String input) { + for (Entry entry : names.entrySet()) { + if (entry.getValue().equalsIgnoreCase(input)) + return entry.getKey(); + } + return getLongFromString(input); + } - private long getLongFromString(@Nonnull String input) { - try { - return Long.parseLong(input); - } catch (NumberFormatException ex) { - return -1; - } - } + private long getLongFromString(@Nonnull String input) { + try { + return Long.parseLong(input); + } catch (NumberFormatException ex) { + return -1; + } + } - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - if (args.length <= 1) - return Utils.filterRecommendations(args[0], "set", "subtract", "query", "day", "night", "noon", "midnight"); - if (args[0].equalsIgnoreCase("set")) - return Utils.filterRecommendations(args[1], "day", "night", "noon", "midnight"); - return new ArrayList<>(); - } + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + if (args.length <= 1) + return Utils.filterRecommendations(args[0], "set", "subtract", "query", "day", "night", "noon", "midnight"); + if (args[0].equalsIgnoreCase("set")) + return Utils.filterRecommendations(args[1], "day", "night", "noon", "midnight"); + return new ArrayList<>(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java index 234662988..2a451558d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java @@ -21,93 +21,93 @@ public class TimerCommand implements SenderCommand, Completer { - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { - if (args.length == 0) { - if (sender instanceof Player) { - Player player = (Player) sender; - Challenges.getInstance().getMenuManager().openMenu(player, MenuType.TIMER, 0); - SoundSample.OPEN.play(player); - } - return; - } + if (args.length == 0) { + if (sender instanceof Player) { + Player player = (Player) sender; + Challenges.getInstance().getMenuManager().openMenu(player, MenuType.TIMER, 0); + SoundSample.OPEN.play(player); + } + return; + } - switch (args[0].toLowerCase()) { - default: - Message.forName("syntax").send(sender, Prefix.TIMER, "timer "); - return; - case "resume": - case "start": - if (ChallengeAPI.isStarted()) { - Message.forName("timer-already-started").send(sender, Prefix.TIMER); - SoundSample.BASS_OFF.playIfPlayer(sender); - break; - } - Challenges.getInstance().getChallengeTimer().resume(); - break; - case "stop": - case "pause": - if (ChallengeAPI.isPaused()) { - Message.forName("timer-already-paused").send(sender, Prefix.TIMER); - SoundSample.BASS_OFF.playIfPlayer(sender); - break; - } - Challenges.getInstance().getChallengeTimer().pause(true); - break; - case "reset": - Challenges.getInstance().getChallengeTimer().reset(); - break; - case "set": - long seconds = StringUtils.parseSeconds(String.join(" ", args)); - if (seconds >= Integer.MAX_VALUE || seconds < 0) { - seconds = Integer.MAX_VALUE; - } - Challenges.getInstance().getChallengeTimer().setSeconds(seconds); - Message.forName("timer-was-set").send(sender, Prefix.TIMER, Challenges.getInstance().getChallengeTimer().getFormattedTime()); - break; - case "show": - Challenges.getInstance().getChallengeTimer().setHidden(false); - break; - case "hide": - Challenges.getInstance().getChallengeTimer().setHidden(true); - break; - case "mode": - if (args.length != 2) { - Message.forName("syntax").send(sender, Prefix.TIMER, "timer mode "); - break; - } - switch (args[1].toLowerCase()) { - case "up": - case "forward": - Challenges.getInstance().getChallengeTimer().setCountingUp(true); - break; - case "down": - case "back": - case "backwards": - Challenges.getInstance().getChallengeTimer().setCountingUp(false); - break; - default: - Message.forName("syntax").send(sender, Prefix.TIMER, "timer mode "); - break; - } + switch (args[0].toLowerCase()) { + default: + Message.forName("syntax").send(sender, Prefix.TIMER, "timer "); + return; + case "resume": + case "start": + if (ChallengeAPI.isStarted()) { + Message.forName("timer-already-started").send(sender, Prefix.TIMER); + SoundSample.BASS_OFF.playIfPlayer(sender); + break; + } + Challenges.getInstance().getChallengeTimer().resume(); + break; + case "stop": + case "pause": + if (ChallengeAPI.isPaused()) { + Message.forName("timer-already-paused").send(sender, Prefix.TIMER); + SoundSample.BASS_OFF.playIfPlayer(sender); + break; + } + Challenges.getInstance().getChallengeTimer().pause(true); + break; + case "reset": + Challenges.getInstance().getChallengeTimer().reset(); + break; + case "set": + long seconds = StringUtils.parseSeconds(String.join(" ", args)); + if (seconds >= Integer.MAX_VALUE || seconds < 0) { + seconds = Integer.MAX_VALUE; + } + Challenges.getInstance().getChallengeTimer().setSeconds(seconds); + Message.forName("timer-was-set").send(sender, Prefix.TIMER, Challenges.getInstance().getChallengeTimer().getFormattedTime()); + break; + case "show": + Challenges.getInstance().getChallengeTimer().setHidden(false); + break; + case "hide": + Challenges.getInstance().getChallengeTimer().setHidden(true); + break; + case "mode": + if (args.length != 2) { + Message.forName("syntax").send(sender, Prefix.TIMER, "timer mode "); + break; + } + switch (args[1].toLowerCase()) { + case "up": + case "forward": + Challenges.getInstance().getChallengeTimer().setCountingUp(true); + break; + case "down": + case "back": + case "backwards": + Challenges.getInstance().getChallengeTimer().setCountingUp(false); + break; + default: + Message.forName("syntax").send(sender, Prefix.TIMER, "timer mode "); + break; + } - } + } - } + } - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - if (args.length == 0) return new ArrayList<>(); - String last = args[args.length - 1]; - if (args.length == 1) { - return Utils.filterRecommendations(args[0], "resume", "pause", "stop", "start", "reset", "show", "hide", "mode", "set"); - } else if (args.length == 2 && "mode".equalsIgnoreCase(args[0])) { - return Utils.filterRecommendations(args[1], "up", "down"); - } else if ("set".equalsIgnoreCase(args[0])) { - return StringUtils.isNumber(last) ? Utils.filterRecommendations(last, last + "m", last + "h", last + "d", last + "w") : last.isEmpty() ? Arrays.asList("10", "30", "60", "120") : Collections.singletonList(last); - } - return new ArrayList<>(); - } + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + if (args.length == 0) return new ArrayList<>(); + String last = args[args.length - 1]; + if (args.length == 1) { + return Utils.filterRecommendations(args[0], "resume", "pause", "stop", "start", "reset", "show", "hide", "mode", "set"); + } else if (args.length == 2 && "mode".equalsIgnoreCase(args[0])) { + return Utils.filterRecommendations(args[1], "up", "down"); + } else if ("set".equalsIgnoreCase(args[0])) { + return StringUtils.isNumber(last) ? Utils.filterRecommendations(last, last + "m", last + "h", last + "d", last + "w") : last.isEmpty() ? Arrays.asList("10", "30", "60", "120") : Collections.singletonList(last); + } + return new ArrayList<>(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java index 40c3ffe17..f4a514e70 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java @@ -14,31 +14,31 @@ public class VillageCommand implements PlayerCommand { - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - player.setNoDamageTicks(10); - Message.forName("command-village-search").send(player, Prefix.CHALLENGES); + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + player.setNoDamageTicks(10); + Message.forName("command-village-search").send(player, Prefix.CHALLENGES); - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - Location village = player.getWorld().locateNearestStructure(player.getLocation(), StructureType.VILLAGE, 5000, true); - if (village == null) { - Message.forName("command-village-not-found").send(player, Prefix.CHALLENGES); - return; - } + Location village = player.getWorld().locateNearestStructure(player.getLocation(), StructureType.VILLAGE, 5000, true); + if (village == null) { + Message.forName("command-village-not-found").send(player, Prefix.CHALLENGES); + return; + } - village = player.getWorld().getHighestBlockAt(village).getLocation().add(0.5, 1, 0.5); - village.getChunk().load(true); + village = player.getWorld().getHighestBlockAt(village).getLocation().add(0.5, 1, 0.5); + village.getChunk().load(true); - Location finalVillage = village; - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { - player.teleport(finalVillage); - SoundSample.TELEPORT.play(player); - Message.forName("command-village-teleport").send(player, Prefix.CHALLENGES); - }, 20 /* run after 1 second to give the chunks/world time to load/generate */); + Location finalVillage = village; + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { + player.teleport(finalVillage); + SoundSample.TELEPORT.play(player); + Message.forName("command-village-teleport").send(player, Prefix.CHALLENGES); + }, 20 /* run after 1 second to give the chunks/world time to load/generate */); - }); + }); - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java index c66a33394..67244e1d2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java @@ -16,45 +16,45 @@ public class WeatherCommand implements PlayerCommand, Completer { - @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { - - if (args.length == 0) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "weather "); - return; - } - - World world = player.getWorld(); - - switch (args[0].toLowerCase()) { - - case "clear": - case "sun": - world.setStorm(false); - world.setThundering(false); - Message.forName("command-weather-set-clear").send(player, Prefix.CHALLENGES); - break; - case "rain": - world.setThundering(false); - world.setStorm(true); - Message.forName("command-weather-set-rain").send(player, Prefix.CHALLENGES); - break; - case "thunder": - world.setStorm(true); - world.setThundering(true); - Message.forName("command-weather-set-thunder").send(player, Prefix.CHALLENGES); - break; - default: - Message.forName("syntax").send(player, Prefix.CHALLENGES, "weather "); - } - - } - - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { - if (args.length > 1) return new ArrayList<>(); - return Utils.filterRecommendations(args[0], "sun", "clear", "rain", "thunder"); - } + @Override + public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + + if (args.length == 0) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "weather "); + return; + } + + World world = player.getWorld(); + + switch (args[0].toLowerCase()) { + + case "clear": + case "sun": + world.setStorm(false); + world.setThundering(false); + Message.forName("command-weather-set-clear").send(player, Prefix.CHALLENGES); + break; + case "rain": + world.setThundering(false); + world.setStorm(true); + Message.forName("command-weather-set-rain").send(player, Prefix.CHALLENGES); + break; + case "thunder": + world.setStorm(true); + world.setThundering(true); + Message.forName("command-weather-set-thunder").send(player, Prefix.CHALLENGES); + break; + default: + Message.forName("syntax").send(player, Prefix.CHALLENGES, "weather "); + } + + } + + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + if (args.length > 1) return new ArrayList<>(); + return Utils.filterRecommendations(args[0], "sun", "clear", "rain", "thunder"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java index c6ba05aca..30157b8a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java @@ -22,64 +22,64 @@ public class WorldCommand implements PlayerCommand, TabCompleter { - @Override - public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { + @Override + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { - if (args.length < 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "world "); - return; - } + if (args.length < 1) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "world "); + return; + } - String worldName = args[0]; + String worldName = args[0]; - Environment environment = PositionSetting.getWorldEnvironment(worldName); + Environment environment = PositionSetting.getWorldEnvironment(worldName); - boolean targetIsVoidMap = worldName.equalsIgnoreCase("void"); - if (environment == null && !targetIsVoidMap) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "world "); - return; - } + boolean targetIsVoidMap = worldName.equalsIgnoreCase("void"); + if (environment == null && !targetIsVoidMap) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "world "); + return; + } - World world = targetIsVoidMap ? Challenges.getInstance().getGameWorldStorage().getOrCreateVoidWorld() : ChallengeAPI.getGameWorld(environment); - if (world == null) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "world "); - return; - } + World world = targetIsVoidMap ? Challenges.getInstance().getGameWorldStorage().getOrCreateVoidWorld() : ChallengeAPI.getGameWorld(environment); + if (world == null) { + Message.forName("syntax").send(player, Prefix.CHALLENGES, "world "); + return; + } - Location location = getSpawn(world, player); + Location location = getSpawn(world, player); - Message.forName("command-world-teleport").send(player, Prefix.CHALLENGES, targetIsVoidMap ? "Void" : getWorldName(location)); - player.teleport(location); - } + Message.forName("command-world-teleport").send(player, Prefix.CHALLENGES, targetIsVoidMap ? "Void" : getWorldName(location)); + player.teleport(location); + } - public Location getSpawn(@Nonnull World world, @Nonnull Player player) { - Location location = world.getSpawnLocation(); - Location bedSpawnLocation = player.getBedSpawnLocation(); - if (bedSpawnLocation != null && bedSpawnLocation.getWorld() == world) { - location = bedSpawnLocation; - } else if (world.getEnvironment() == Environment.THE_END) { - location = world.getHighestBlockAt(0, 0).getLocation().add(0.5, 1, 0.5); - } - return location; - } + public Location getSpawn(@Nonnull World world, @Nonnull Player player) { + Location location = world.getSpawnLocation(); + Location bedSpawnLocation = player.getBedSpawnLocation(); + if (bedSpawnLocation != null && bedSpawnLocation.getWorld() == world) { + location = bedSpawnLocation; + } else if (world.getEnvironment() == Environment.THE_END) { + location = world.getHighestBlockAt(0, 0).getLocation().add(0.5, 1, 0.5); + } + return location; + } - public String getWorldName(@Nonnull Location location) { - if (location.getWorld() == null) return "?"; - switch (location.getWorld().getEnvironment()) { - default: - return "Overworld"; - case NETHER: - return "Nether"; - case THE_END: - return "End"; - } - } + public String getWorldName(@Nonnull Location location) { + if (location.getWorld() == null) return "?"; + switch (location.getWorld().getEnvironment()) { + default: + return "Overworld"; + case NETHER: + return "Nether"; + case THE_END: + return "End"; + } + } - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, - @NotNull String alias, @NotNull String[] args) { - return Utils.filterRecommendations(args[0], "Overworld", "Nether", "End", "Void"); - } + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, @NotNull String[] args) { + return Utils.filterRecommendations(args[0], "Overworld", "Nether", "End", "Void"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDamageByPlayerEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDamageByPlayerEvent.java index be99a6abe..bff29d436 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDamageByPlayerEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDamageByPlayerEvent.java @@ -10,40 +10,40 @@ public class EntityDamageByPlayerEvent extends EntityEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); + private static final HandlerList handlers = new HandlerList(); - @Getter + @Getter private final Player damager; - @Getter + @Getter private final double finalDamage; - private final Cancellable parentEvent; + private final Cancellable parentEvent; - public EntityDamageByPlayerEvent(@NotNull Entity victim, Player damager, double finalDamage, Cancellable parent) { - super(victim); - this.damager = damager; - this.finalDamage = finalDamage; - this.parentEvent = parent; - } + public EntityDamageByPlayerEvent(@NotNull Entity victim, Player damager, double finalDamage, Cancellable parent) { + super(victim); + this.damager = damager; + this.finalDamage = finalDamage; + this.parentEvent = parent; + } - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } + @NotNull + public static HandlerList getHandlerList() { + return handlers; + } @Override - public boolean isCancelled() { - return parentEvent.isCancelled(); - } - - @Override - public void setCancelled(boolean cancel) { - parentEvent.setCancelled(cancel); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } + public boolean isCancelled() { + return parentEvent.isCancelled(); + } + + @Override + public void setCancelled(boolean cancel) { + parentEvent.setCancelled(cancel); + } + + @NotNull + @Override + public HandlerList getHandlers() { + return handlers; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDeathByPlayerEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDeathByPlayerEvent.java index 3517e3138..038c48cd1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDeathByPlayerEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/EntityDeathByPlayerEvent.java @@ -10,37 +10,37 @@ public class EntityDeathByPlayerEvent extends EntityEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - - @Getter - private final Player killer; - private final Cancellable parentEvent; - - public EntityDeathByPlayerEvent(@NotNull Entity victim, Player killer, Cancellable parent) { - super(victim); - this.killer = killer; - this.parentEvent = parent; - } - - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public boolean isCancelled() { - return parentEvent.isCancelled(); - } - - @Override - public void setCancelled(boolean cancel) { - parentEvent.setCancelled(cancel); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } + private static final HandlerList handlers = new HandlerList(); + + @Getter + private final Player killer; + private final Cancellable parentEvent; + + public EntityDeathByPlayerEvent(@NotNull Entity victim, Player killer, Cancellable parent) { + super(victim); + this.killer = killer; + this.parentEvent = parent; + } + + @NotNull + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public boolean isCancelled() { + return parentEvent.isCancelled(); + } + + @Override + public void setCancelled(boolean cancel) { + parentEvent.setCancelled(cancel); + } + + @NotNull + @Override + public HandlerList getHandlers() { + return handlers; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java index 018156bf1..93b836718 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java @@ -16,110 +16,110 @@ public abstract class InventoryClickEventWrapper extends Event { - private final InventoryClickEvent event; - - public InventoryClickEventWrapper(@Nonnull InventoryClickEvent event) { - this.event = event; - } - - @Nullable - public Inventory getClickedInventory() { - return event.getClickedInventory(); - } - - @Nonnull - public Inventory getInventory() { - return event.getInventory(); - } - - @Nonnull - public InventoryView getView() { - return event.getView(); - } - - @Nonnull - public ClickType getClick() { - return event.getClick(); - } - - @Nonnull - public HumanEntity getWhoClicked() { - return event.getWhoClicked(); - } - - public int getSlot() { - return event.getSlot(); - } - - public int getRawSlot() { - return event.getRawSlot(); - } - - @Nonnull - public InventoryAction getAction() { - return event.getAction(); - } - - @Nullable - public ItemStack getCursor() { - return event.getCursor(); - } - - public int getHotbarButton() { - return event.getHotbarButton(); - } - - @Nonnull - public SlotType getSlotType() { - return event.getSlotType(); - } - - @Nonnull - public Result getResult() { - return event.getResult(); - } - - public void setResult(@Nonnull Result result) { - event.setResult(result); - } - - @Nullable - public ItemStack getCurrentItem() { - return event.getCurrentItem(); - } - - public void setCurrentItem(@Nullable ItemStack item) { - event.setCurrentItem(item); - } - - @Nonnull - public List getViewers() { - return event.getViewers(); - } - - @Nonnull - public InventoryClickEvent getEvent() { - return event; - } - - public boolean isCancelled() { - return event.isCancelled(); - } - - public void setCancelled(boolean cancel) { - event.setCancelled(cancel); - } - - public boolean isRightClick() { - return event.isRightClick(); - } - - public boolean isLeftClick() { - return event.isLeftClick(); - } - - public boolean isShiftClick() { - return event.isShiftClick(); - } + private final InventoryClickEvent event; + + public InventoryClickEventWrapper(@Nonnull InventoryClickEvent event) { + this.event = event; + } + + @Nullable + public Inventory getClickedInventory() { + return event.getClickedInventory(); + } + + @Nonnull + public Inventory getInventory() { + return event.getInventory(); + } + + @Nonnull + public InventoryView getView() { + return event.getView(); + } + + @Nonnull + public ClickType getClick() { + return event.getClick(); + } + + @Nonnull + public HumanEntity getWhoClicked() { + return event.getWhoClicked(); + } + + public int getSlot() { + return event.getSlot(); + } + + public int getRawSlot() { + return event.getRawSlot(); + } + + @Nonnull + public InventoryAction getAction() { + return event.getAction(); + } + + @Nullable + public ItemStack getCursor() { + return event.getCursor(); + } + + public int getHotbarButton() { + return event.getHotbarButton(); + } + + @Nonnull + public SlotType getSlotType() { + return event.getSlotType(); + } + + @Nonnull + public Result getResult() { + return event.getResult(); + } + + public void setResult(@Nonnull Result result) { + event.setResult(result); + } + + @Nullable + public ItemStack getCurrentItem() { + return event.getCurrentItem(); + } + + public void setCurrentItem(@Nullable ItemStack item) { + event.setCurrentItem(item); + } + + @Nonnull + public List getViewers() { + return event.getViewers(); + } + + @Nonnull + public InventoryClickEvent getEvent() { + return event; + } + + public boolean isCancelled() { + return event.isCancelled(); + } + + public void setCancelled(boolean cancel) { + event.setCancelled(cancel); + } + + public boolean isRightClick() { + return event.isRightClick(); + } + + public boolean isLeftClick() { + return event.isLeftClick(); + } + + public boolean isShiftClick() { + return event.isShiftClick(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerIgnoreStatusChangeEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerIgnoreStatusChangeEvent.java index b65366107..97da8cd8f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerIgnoreStatusChangeEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerIgnoreStatusChangeEvent.java @@ -7,32 +7,32 @@ public class PlayerIgnoreStatusChangeEvent extends PlayerEvent { - private static final HandlerList handlers = new HandlerList(); + private static final HandlerList handlers = new HandlerList(); - private final boolean isIgnored; + private final boolean isIgnored; - public PlayerIgnoreStatusChangeEvent(@NotNull Player who, boolean isIgnored) { - super(who); - this.isIgnored = isIgnored; - } + public PlayerIgnoreStatusChangeEvent(@NotNull Player who, boolean isIgnored) { + super(who); + this.isIgnored = isIgnored; + } - @NotNull - public static HandlerList getHandlerList() { - return handlers; - } + @NotNull + public static HandlerList getHandlerList() { + return handlers; + } - public boolean isIgnored() { - return isIgnored; - } + public boolean isIgnored() { + return isIgnored; + } - public boolean isNotIgnored() { - return !isIgnored; - } + public boolean isNotIgnored() { + return !isIgnored; + } - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } + @NotNull + @Override + public HandlerList getHandlers() { + return handlers; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java index 7c5078c7e..ff347c0a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java @@ -10,24 +10,24 @@ @Getter public class PlayerInventoryClickEvent extends InventoryClickEventWrapper { - private static final HandlerList handlers = new HandlerList(); + private static final HandlerList handlers = new HandlerList(); - private final Player player; + private final Player player; - public PlayerInventoryClickEvent(@Nonnull InventoryClickEvent event) { - super(event); - player = ((Player) event.getWhoClicked()); - } + public PlayerInventoryClickEvent(@Nonnull InventoryClickEvent event) { + super(event); + player = ((Player) event.getWhoClicked()); + } - @Nonnull - public static HandlerList getHandlerList() { - return handlers; - } + @Nonnull + public static HandlerList getHandlerList() { + return handlers; + } - @Nonnull - @Override - public HandlerList getHandlers() { - return getHandlerList(); - } + @Nonnull + @Override + public HandlerList getHandlers() { + return getHandlerList(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java index 975740144..ec02033e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java @@ -10,34 +10,34 @@ public class PlayerJumpEvent extends PlayerEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - - private final PlayerStatisticIncrementEvent event; - - public PlayerJumpEvent(@Nonnull Player who, PlayerStatisticIncrementEvent statisticIncrementEvent) { - super(who); - this.event = statisticIncrementEvent; - } - - @Nonnull - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public boolean isCancelled() { - return event.isCancelled(); - } - - @Override - public void setCancelled(boolean b) { - event.setCancelled(true); - } - - @Nonnull - @Override - public HandlerList getHandlers() { - return handlers; - } + private static final HandlerList handlers = new HandlerList(); + + private final PlayerStatisticIncrementEvent event; + + public PlayerJumpEvent(@Nonnull Player who, PlayerStatisticIncrementEvent statisticIncrementEvent) { + super(who); + this.event = statisticIncrementEvent; + } + + @Nonnull + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public boolean isCancelled() { + return event.isCancelled(); + } + + @Override + public void setCancelled(boolean b) { + event.setCancelled(true); + } + + @Nonnull + @Override + public HandlerList getHandlers() { + return handlers; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java index 9a52cf53a..bf1ece3e6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java @@ -12,36 +12,36 @@ @Getter public class PlayerPickupItemEvent extends PlayerEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); - - private final Item item; - private final int remaining; - private boolean cancel = false; - - public PlayerPickupItemEvent(@Nonnull Player player, @Nonnull Item item, int remaining) { - super(player); - this.item = item; - this.remaining = remaining; - } - - @Nonnull - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public boolean isCancelled() { - return cancel; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancel = cancel; - } - - @Nonnull - @Override - public HandlerList getHandlers() { - return handlers; - } + private static final HandlerList handlers = new HandlerList(); + + private final Item item; + private final int remaining; + private boolean cancel = false; + + public PlayerPickupItemEvent(@Nonnull Player player, @Nonnull Item item, int remaining) { + super(player); + this.item = item; + this.remaining = remaining; + } + + @Nonnull + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public boolean isCancelled() { + return cancel; + } + + @Override + public void setCancelled(boolean cancel) { + this.cancel = cancel; + } + + @Nonnull + @Override + public HandlerList getHandlers() { + return handlers; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java index 60e77344b..ce34a1044 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java @@ -13,27 +13,27 @@ public class VoidMapGenerator extends ChunkGenerator { - private static final boolean generateEndPortal = MinecraftVersion.current().getMinor() == 18; - - @Override - @Nonnull - public ChunkData generateChunkData(@Nonnull World world, @Nonnull Random random, int x, int z, @Nonnull BiomeGrid biome) { - - ChunkData chunkData = createChunkData(world); - if (x == 0 && z == 0) { - chunkData.setBlock(0, 59, 0, Material.BEDROCK); - } - - // Stronghold location is weirdly the same for every void map - // TODO: FIX FOLLOWING ISSUES - // Only works in 1.18 worlds - // maybe try to locate the three first strongholds and place portal in chunk (code commented out above) - // Maybe don't generate a portal at all to prevent issues with the feature - if (generateEndPortal) { - if (x == -7 && z == -105) { - generateEndPortal(chunkData); - } - } + private static final boolean generateEndPortal = MinecraftVersion.current().getMinor() == 18; + + @Override + @Nonnull + public ChunkData generateChunkData(@Nonnull World world, @Nonnull Random random, int x, int z, @Nonnull BiomeGrid biome) { + + ChunkData chunkData = createChunkData(world); + if (x == 0 && z == 0) { + chunkData.setBlock(0, 59, 0, Material.BEDROCK); + } + + // Stronghold location is weirdly the same for every void map + // TODO: FIX FOLLOWING ISSUES + // Only works in 1.18 worlds + // maybe try to locate the three first strongholds and place portal in chunk (code commented out above) + // Maybe don't generate a portal at all to prevent issues with the feature + if (generateEndPortal) { + if (x == -7 && z == -105) { + generateEndPortal(chunkData); + } + } // if (portalChunk.chunkX == x && portalChunk.chunkZ == z) { // Challenges.getInstance().getLogger().info("Generating End Portal"); @@ -42,37 +42,37 @@ public ChunkData generateChunkData(@Nonnull World world, @Nonnull Random random, // } // } - return chunkData; - } + return chunkData; + } - public void generateEndPortal(@Nonnull ChunkData data) { + public void generateEndPortal(@Nonnull ChunkData data) { - int x = 6; - int y = 29; - int z = 6; - for (int x1 = 0; x1 < 5; x1++) { + int x = 6; + int y = 29; + int z = 6; + for (int x1 = 0; x1 < 5; x1++) { - for (int z1 = 0; z1 < 5; z1++) { - if ((x1 == 0 && z1 == 0) || (x1 == 4 && z1 == 4) || - (x1 == 0 && z1 == 4) || (x1 == 4 && z1 == 0)) continue; - if (x1 > 0 && z1 > 0 && x1 < 4 && z1 < 4) continue; + for (int z1 = 0; z1 < 5; z1++) { + if ((x1 == 0 && z1 == 0) || (x1 == 4 && z1 == 4) || + (x1 == 0 && z1 == 4) || (x1 == 4 && z1 == 0)) continue; + if (x1 > 0 && z1 > 0 && x1 < 4 && z1 < 4) continue; - Directional blockData = (Directional) Bukkit.createBlockData(Material.END_PORTAL_FRAME); + Directional blockData = (Directional) Bukkit.createBlockData(Material.END_PORTAL_FRAME); - if (x1 == 0) { - blockData.setFacing(BlockFace.EAST); - } else if (x1 == 4) { - blockData.setFacing(BlockFace.WEST); - } else if (z1 == 0) { - blockData.setFacing(BlockFace.SOUTH); - } else { - blockData.setFacing(BlockFace.NORTH); - } + if (x1 == 0) { + blockData.setFacing(BlockFace.EAST); + } else if (x1 == 4) { + blockData.setFacing(BlockFace.WEST); + } else if (z1 == 0) { + blockData.setFacing(BlockFace.SOUTH); + } else { + blockData.setFacing(BlockFace.NORTH); + } - data.setBlock(x + x1, y, z + z1, blockData); - } - } + data.setBlock(x + x1, y, z + z1, blockData); + } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java index d93e5c6cd..1a82f62ba 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java @@ -21,54 +21,54 @@ public class BlockDropListener implements Listener { - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (event.getPlayer().getGameMode() == GameMode.CREATIVE) return; - if (!event.isDropItems()) return; - dropCustomDrops(event.getBlock(), () -> event.setDropItems(false)); - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (event.getPlayer().getGameMode() == GameMode.CREATIVE) return; + if (!event.isDropItems()) return; + dropCustomDrops(event.getBlock(), () -> event.setDropItems(false)); + } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockExplosion(@Nonnull BlockExplodeEvent event) { - handleExplosion(event.blockList(), () -> event.setYield(0)); - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockExplosion(@Nonnull BlockExplodeEvent event) { + handleExplosion(event.blockList(), () -> event.setYield(0)); + } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityExplosion(@Nonnull EntityExplodeEvent event) { - handleExplosion(event.blockList(), () -> event.setYield(0)); - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityExplosion(@Nonnull EntityExplodeEvent event) { + handleExplosion(event.blockList(), () -> event.setYield(0)); + } - protected void handleExplosion(@Nonnull Iterable blocklist, @Nonnull Runnable dropsExist) { - for (Block block : blocklist) { - dropCustomDrops(block, dropsExist); - } - } + protected void handleExplosion(@Nonnull Iterable blocklist, @Nonnull Runnable dropsExist) { + for (Block block : blocklist) { + dropCustomDrops(block, dropsExist); + } + } - protected void dropCustomDrops(@Nonnull Block block, @Nonnull Runnable dropsExist) { + protected void dropCustomDrops(@Nonnull Block block, @Nonnull Runnable dropsExist) { - Material material = block.getType(); - if (BukkitReflectionUtils.isAir(material)) return; + Material material = block.getType(); + if (BukkitReflectionUtils.isAir(material)) return; - if (!ChallengeAPI.getDropChance(material)) { - dropsExist.run(); - return; - } + if (!ChallengeAPI.getDropChance(material)) { + dropsExist.run(); + return; + } - List drops = Challenges.getInstance().getBlockDropManager().getCustomDrops(material); - if (drops.isEmpty()) return; + List drops = Challenges.getInstance().getBlockDropManager().getCustomDrops(material); + if (drops.isEmpty()) return; - Location location = block.getLocation().clone().add(0.5, 0, 0.5); - if (location.getWorld() == null) return; + Location location = block.getLocation().clone().add(0.5, 0, 0.5); + if (location.getWorld() == null) return; - dropsExist.run(); - for (Material drop : drops) { - try { - location.getWorld().dropItem(location, new ItemStack(drop)); - } catch (Exception ex) { - Logger.warn("Unable to drop custom drop {}", drop, ex); - } - } + dropsExist.run(); + for (Material drop : drops) { + try { + location.getWorld().dropItem(location, new ItemStack(drop)); + } catch (Exception ex) { + Logger.warn("Unable to drop custom drop {}", drop, ex); + } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java index 32aef252e..6596e1b5c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java @@ -14,30 +14,30 @@ public class ChatInputListener implements Listener { - private static Map> inputActions = new HashMap<>(); + private static Map> inputActions = new HashMap<>(); - public ChatInputListener() { - inputActions = new HashMap<>(); - } + public ChatInputListener() { + inputActions = new HashMap<>(); + } - public static void setInputAction(Player player, Consumer event) { - inputActions.put(player.getUniqueId(), event); - } + public static void setInputAction(Player player, Consumer event) { + inputActions.put(player.getUniqueId(), event); + } - @EventHandler(priority = EventPriority.LOW) - public void onChat(AsyncPlayerChatEvent event) { + @EventHandler(priority = EventPriority.LOW) + public void onChat(AsyncPlayerChatEvent event) { - Consumer action = inputActions.remove(event.getPlayer().getUniqueId()); - if (action != null) { - action.accept(event); - event.setCancelled(true); - } + Consumer action = inputActions.remove(event.getPlayer().getUniqueId()); + if (action != null) { + action.accept(event); + event.setCancelled(true); + } - } + } - @EventHandler(priority = EventPriority.LOW) - public void onQuit(PlayerQuitEvent event) { - inputActions.remove(event.getPlayer().getUniqueId()); - } + @EventHandler(priority = EventPriority.LOW) + public void onQuit(PlayerQuitEvent event) { + inputActions.remove(event.getPlayer().getUniqueId()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java index 453464bac..00b11602f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java @@ -19,79 +19,79 @@ public class CheatListener implements Listener { - public CheatListener() { - Bukkit.getOnlinePlayers().stream() - .filter(player -> player.getGameMode() == GameMode.CREATIVE) - .findFirst().ifPresent(this::handleCheatsDetected); - } + public CheatListener() { + Bukkit.getOnlinePlayers().stream() + .filter(player -> player.getGameMode() == GameMode.CREATIVE) + .findFirst().ifPresent(this::handleCheatsDetected); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { - if (event.getNewGameMode() == GameMode.CREATIVE) - handleCheatsDetected(event.getPlayer()); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { + if (event.getNewGameMode() == GameMode.CREATIVE) + handleCheatsDetected(event.getPlayer()); + } - @EventHandler(priority = EventPriority.MONITOR) - public void onSneak(PlayerToggleSneakEvent event) { - if (!event.isSneaking()) { - } + @EventHandler(priority = EventPriority.MONITOR) + public void onSneak(PlayerToggleSneakEvent event) { + if (!event.isSneaking()) { + } //// Structure structure = entry.getValue(); - } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onCommand(@Nonnull PlayerCommandPreprocessEvent event) { - String[] commands = { - "give", - "replaceitem", - "effect", - "i", - "summon", - "enchant", - "heal", - "kill", - "setblock", - "fill" - }; - String message = event.getMessage().toLowerCase(); - if (message.isEmpty()) return; + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onCommand(@Nonnull PlayerCommandPreprocessEvent event) { + String[] commands = { + "give", + "replaceitem", + "effect", + "i", + "summon", + "enchant", + "heal", + "kill", + "setblock", + "fill" + }; + String message = event.getMessage().toLowerCase(); + if (message.isEmpty()) return; - String[] args = message.substring(1).trim().split(" "); - String commandName = args[0]; - if (commandName.contains(":")) { - commandName = commandName.substring(commandName.indexOf(':') + 1); - } + String[] args = message.substring(1).trim().split(" "); + String commandName = args[0]; + if (commandName.contains(":")) { + commandName = commandName.substring(commandName.indexOf(':') + 1); + } - for (String command : commands) { - if (!commandName.equalsIgnoreCase("/" + command)) continue; - if (!hasPermission(event.getPlayer(), command)) continue; - handleCheatsDetected(event.getPlayer()); - break; - } - } + for (String command : commands) { + if (!commandName.equalsIgnoreCase("/" + command)) continue; + if (!hasPermission(event.getPlayer(), command)) continue; + handleCheatsDetected(event.getPlayer()); + break; + } + } - private boolean hasPermission(@Nonnull Player player, @Nonnull String command) { - String[] prefixes = { - "challenges.", - "minecraft.command.", - "essentials.", - "bukkit." - }; + private boolean hasPermission(@Nonnull Player player, @Nonnull String command) { + String[] prefixes = { + "challenges.", + "minecraft.command.", + "essentials.", + "bukkit." + }; - for (String prefix : prefixes) { - if (player.hasPermission(prefix + command)) - return true; - } + for (String prefix : prefixes) { + if (player.hasPermission(prefix + command)) + return true; + } - return false; - } + return false; + } - private void handleCheatsDetected(@Nonnull Player player) { - if (Challenges.getInstance().getServerManager().hasCheated()) return; - if (!Challenges.getInstance().getStatsManager().isNoStatsAfterCheating()) return; - Challenges.getInstance().getServerManager().setHasCheated(); - Logger.info("Detected cheating: No more stats can be collected"); - Message.forName("cheats-detected").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); - } + private void handleCheatsDetected(@Nonnull Player player) { + if (Challenges.getInstance().getServerManager().hasCheated()) return; + if (!Challenges.getInstance().getStatsManager().isNoStatsAfterCheating()) return; + Challenges.getInstance().getServerManager().setHasCheated(); + Logger.info("Detected cheating: No more stats can be collected"); + Message.forName("cheats-detected").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java index 0b6729a3b..05e6668f2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java @@ -22,71 +22,71 @@ public class CustomEventListener implements Listener { - /** - * Detecting jumps and calls a {@link PlayerJumpEvent} - */ - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerStatisticIncrement(@Nonnull PlayerStatisticIncrementEvent event) { - if (BukkitReflectionUtils.isInWater(event.getPlayer())) return; - if (event.getStatistic() == Statistic.JUMP) { - Bukkit.getPluginManager().callEvent(new PlayerJumpEvent(event.getPlayer(), event)); - } - } + /** + * Detecting jumps and calls a {@link PlayerJumpEvent} + */ + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerStatisticIncrement(@Nonnull PlayerStatisticIncrementEvent event) { + if (BukkitReflectionUtils.isInWater(event.getPlayer())) return; + if (event.getStatistic() == Statistic.JUMP) { + Bukkit.getPluginManager().callEvent(new PlayerJumpEvent(event.getPlayer(), event)); + } + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onInventoryClick(@Nonnull InventoryClickEvent event) { - if (!(event.getWhoClicked() instanceof Player)) return; - PlayerInventoryClickEvent eventCall = new PlayerInventoryClickEvent(event); - eventCall.setCancelled(event.isCancelled()); - Bukkit.getPluginManager().callEvent(eventCall); - event.setCancelled(eventCall.isCancelled()); - } + @EventHandler(priority = EventPriority.HIGHEST) + public void onInventoryClick(@Nonnull InventoryClickEvent event) { + if (!(event.getWhoClicked() instanceof Player)) return; + PlayerInventoryClickEvent eventCall = new PlayerInventoryClickEvent(event); + eventCall.setCancelled(event.isCancelled()); + Bukkit.getPluginManager().callEvent(eventCall); + event.setCancelled(eventCall.isCancelled()); + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onEntityPickupItem(@Nonnull EntityPickupItemEvent event) { - if (!(event.getEntity() instanceof Player)) return; - PlayerPickupItemEvent eventCall = new PlayerPickupItemEvent(((Player) event.getEntity()), event.getItem(), event.getRemaining()); - eventCall.setCancelled(event.isCancelled()); - Bukkit.getPluginManager().callEvent(eventCall); - event.setCancelled(eventCall.isCancelled()); - } + @EventHandler(priority = EventPriority.HIGHEST) + public void onEntityPickupItem(@Nonnull EntityPickupItemEvent event) { + if (!(event.getEntity() instanceof Player)) return; + PlayerPickupItemEvent eventCall = new PlayerPickupItemEvent(((Player) event.getEntity()), event.getItem(), event.getRemaining()); + eventCall.setCancelled(event.isCancelled()); + Bukkit.getPluginManager().callEvent(eventCall); + event.setCancelled(eventCall.isCancelled()); + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { - Entity damager = event.getDamager(); - if (damager instanceof Projectile) { - if (((Projectile) damager).getShooter() instanceof Entity) { - damager = (Entity) ((Projectile) damager).getShooter(); - } - } - if (!(damager instanceof Player)) return; - if (!(event.getEntity() instanceof LivingEntity)) return; - LivingEntity entity = (LivingEntity) event.getEntity(); + @EventHandler(priority = EventPriority.HIGHEST) + public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { + Entity damager = event.getDamager(); + if (damager instanceof Projectile) { + if (((Projectile) damager).getShooter() instanceof Entity) { + damager = (Entity) ((Projectile) damager).getShooter(); + } + } + if (!(damager instanceof Player)) return; + if (!(event.getEntity() instanceof LivingEntity)) return; + LivingEntity entity = (LivingEntity) event.getEntity(); - EntityDamageByPlayerEvent damageEvent = new EntityDamageByPlayerEvent(event.getEntity(), (Player) damager, event.getFinalDamage(), event); - Bukkit.getPluginManager().callEvent(damageEvent); + EntityDamageByPlayerEvent damageEvent = new EntityDamageByPlayerEvent(event.getEntity(), (Player) damager, event.getFinalDamage(), event); + Bukkit.getPluginManager().callEvent(damageEvent); - if (entity.getHealth() - event.getDamage() > 0) return; - EntityDeathByPlayerEvent deathEvent = new EntityDeathByPlayerEvent(event.getEntity(), (Player) damager, event); - Bukkit.getPluginManager().callEvent(deathEvent); - } + if (entity.getHealth() - event.getDamage() > 0) return; + EntityDeathByPlayerEvent deathEvent = new EntityDeathByPlayerEvent(event.getEntity(), (Player) damager, event); + Bukkit.getPluginManager().callEvent(deathEvent); + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onGameModeChange(PlayerGameModeChangeEvent event) { - boolean execute = false; - boolean isIgnored = false; - if (AbstractChallenge.ignoreGameMode(event.getNewGameMode()) && !AbstractChallenge.ignoreGameMode(event.getPlayer().getGameMode())) { - execute = true; - isIgnored = true; - } else if (!AbstractChallenge.ignoreGameMode(event.getNewGameMode()) && AbstractChallenge.ignoreGameMode(event.getPlayer().getGameMode())) { - execute = true; - } + @EventHandler(priority = EventPriority.HIGHEST) + public void onGameModeChange(PlayerGameModeChangeEvent event) { + boolean execute = false; + boolean isIgnored = false; + if (AbstractChallenge.ignoreGameMode(event.getNewGameMode()) && !AbstractChallenge.ignoreGameMode(event.getPlayer().getGameMode())) { + execute = true; + isIgnored = true; + } else if (!AbstractChallenge.ignoreGameMode(event.getNewGameMode()) && AbstractChallenge.ignoreGameMode(event.getPlayer().getGameMode())) { + execute = true; + } - if (execute) { - PlayerIgnoreStatusChangeEvent statusEvent = new PlayerIgnoreStatusChangeEvent(event.getPlayer(), isIgnored); - Bukkit.getPluginManager().callEvent(statusEvent); - } - } + if (execute) { + PlayerIgnoreStatusChangeEvent statusEvent = new PlayerIgnoreStatusChangeEvent(event.getPlayer(), isIgnored); + Bukkit.getPluginManager().callEvent(statusEvent); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java index a3348e7e1..22da2139f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java @@ -15,46 +15,46 @@ public class ExtraWorldRestrictionListener implements Listener { - @EventHandler(priority = EventPriority.LOW) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { - if (!isInExtraWorld(event.getBlock().getLocation())) return; - if (Challenges.getInstance().getWorldManager().getSettings().isPlaceBlocks()) return; - - event.setBuild(false); - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (!isInExtraWorld(event.getBlock().getLocation())) return; - if (Challenges.getInstance().getWorldManager().getSettings().isDestroyBlocks()) return; - - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onDrop(@Nonnull PlayerDropItemEvent event) { - if (!isInExtraWorld(event.getPlayer().getWorld())) return; - if (Challenges.getInstance().getWorldManager().getSettings().isDropItems()) return; - - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onPickUp(@Nonnull PlayerPickupItemEvent event) { - if (!isInExtraWorld(event.getPlayer().getWorld())) return; - if (Challenges.getInstance().getWorldManager().getSettings().isPickupItems()) return; - - event.setCancelled(true); - } - - private boolean isInExtraWorld(@Nonnull Location location) { - if (location.getWorld() == null) return false; - return isInExtraWorld(location.getWorld()); - } - - private boolean isInExtraWorld(@Nonnull World world) { - return Challenges.getInstance().getWorldManager().getExtraWorld().equals(world); - } + @EventHandler(priority = EventPriority.LOW) + public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + if (!isInExtraWorld(event.getBlock().getLocation())) return; + if (Challenges.getInstance().getWorldManager().getSettings().isPlaceBlocks()) return; + + event.setBuild(false); + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (!isInExtraWorld(event.getBlock().getLocation())) return; + if (Challenges.getInstance().getWorldManager().getSettings().isDestroyBlocks()) return; + + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onDrop(@Nonnull PlayerDropItemEvent event) { + if (!isInExtraWorld(event.getPlayer().getWorld())) return; + if (Challenges.getInstance().getWorldManager().getSettings().isDropItems()) return; + + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onPickUp(@Nonnull PlayerPickupItemEvent event) { + if (!isInExtraWorld(event.getPlayer().getWorld())) return; + if (Challenges.getInstance().getWorldManager().getSettings().isPickupItems()) return; + + event.setCancelled(true); + } + + private boolean isInExtraWorld(@Nonnull Location location) { + if (location.getWorld() == null) return false; + return isInExtraWorld(location.getWorld()); + } + + private boolean isInExtraWorld(@Nonnull World world) { + return Challenges.getInstance().getWorldManager().getExtraWorld().equals(world); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/GeneratorWorldsListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/GeneratorWorldsListener.java index 885f17067..0edfa3bd7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/GeneratorWorldsListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/GeneratorWorldsListener.java @@ -14,42 +14,42 @@ public class GeneratorWorldsListener implements Listener { - @EventHandler(priority = EventPriority.LOW) - public void onChangeWorld(PlayerTeleportEvent event) { - if (event.getTo() == null) return; + @EventHandler(priority = EventPriority.LOW) + public void onChangeWorld(PlayerTeleportEvent event) { + if (event.getTo() == null) return; - GeneratorWorldPortalManager worldManager = Challenges.getInstance().getGeneratorWorldPortalManager(); - Player player = event.getPlayer(); - World from = event.getFrom().getWorld(); - World to = event.getTo().getWorld(); - if (from == null || to == null) return; - if (from == to) return; + GeneratorWorldPortalManager worldManager = Challenges.getInstance().getGeneratorWorldPortalManager(); + Player player = event.getPlayer(); + World from = event.getFrom().getWorld(); + World to = event.getTo().getWorld(); + if (from == null || to == null) return; + if (from == to) return; - boolean wasCustomWorld = worldManager.isCustomWorld(from.getName()); - boolean isCustomWorld = worldManager.isCustomWorld(to.getName()); + boolean wasCustomWorld = worldManager.isCustomWorld(from.getName()); + boolean isCustomWorld = worldManager.isCustomWorld(to.getName()); - if (wasCustomWorld && !isCustomWorld) { + if (wasCustomWorld && !isCustomWorld) { - if (to.getEnvironment() == Environment.NETHER || to.getEnvironment() == Environment.THE_END) { - worldManager.setLastLocation(player, event.getFrom()); - } + if (to.getEnvironment() == Environment.NETHER || to.getEnvironment() == Environment.THE_END) { + worldManager.setLastLocation(player, event.getFrom()); + } - } else if (!wasCustomWorld) { + } else if (!wasCustomWorld) { - if (event.getCause() != TeleportCause.END_PORTAL && event.getCause() != TeleportCause.NETHER_PORTAL) { - return; - } + if (event.getCause() != TeleportCause.END_PORTAL && event.getCause() != TeleportCause.NETHER_PORTAL) { + return; + } - if (from.getEnvironment() == Environment.NETHER || from.getEnvironment() == Environment.THE_END) { - Location location = worldManager.getAndRemoveLastWorld(player); - if (location != null) { - location = location.getBlock().getLocation().clone(); - event.setTo(location); - } - } + if (from.getEnvironment() == Environment.NETHER || from.getEnvironment() == Environment.THE_END) { + Location location = worldManager.getAndRemoveLastWorld(player); + if (location != null) { + location = location.getBlock().getLocation().clone(); + event.setTo(location); + } + } - } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java index 73acb3143..244ca2a48 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java @@ -18,43 +18,43 @@ public class HelpListener implements Listener { - @EventHandler(priority = EventPriority.MONITOR) - public void onCommand(@Nonnull PlayerCommandPreprocessEvent event) { + @EventHandler(priority = EventPriority.MONITOR) + public void onCommand(@Nonnull PlayerCommandPreprocessEvent event) { - String message = event.getMessage().toLowerCase(); - if (message.isEmpty()) return; + String message = event.getMessage().toLowerCase(); + if (message.isEmpty()) return; - String[] args = message.substring(1).trim().split(" "); - String commandName = args[0]; - if (commandName.contains(":")) { - commandName = commandName.substring(commandName.indexOf(':') + 1); - } + String[] args = message.substring(1).trim().split(" "); + String commandName = args[0]; + if (commandName.contains(":")) { + commandName = commandName.substring(commandName.indexOf(':') + 1); + } - PluginCommand command = Challenges.getInstance().getCommand("help"); - if (command == null) return; - List names = new ArrayList<>(command.getAliases()); - names.add("help"); + PluginCommand command = Challenges.getInstance().getCommand("help"); + if (command == null) return; + List names = new ArrayList<>(command.getAliases()); + names.add("help"); - if (!names.contains(commandName)) return; + if (!names.contains(commandName)) return; - Player sender = event.getPlayer(); + Player sender = event.getPlayer(); - sendMessage(sender, "§7This server is running §e§lChallenges §ev" + Challenges.getInstance().getVersion()); - sendMessage(sender, ""); - sendMessage(sender, "§7Made by §eCodingArea §8(§eanweisen & KxmischesDomi§8)"); - sendMessage(sender, "§7Visit the source at §egithub.com/anweisen/Challenges"); - sendMessage(sender, "§7Download at §espigotmc.org/resources/80548"); - sendMessage(sender, "§7For more join our discord §ediscord.gg/74Ay5zF"); + sendMessage(sender, "§7This server is running §e§lChallenges §ev" + Challenges.getInstance().getVersion()); + sendMessage(sender, ""); + sendMessage(sender, "§7Made by §eCodingArea §8(§eanweisen & KxmischesDomi§8)"); + sendMessage(sender, "§7Visit the source at §egithub.com/anweisen/Challenges"); + sendMessage(sender, "§7Download at §espigotmc.org/resources/80548"); + sendMessage(sender, "§7For more join our discord §ediscord.gg/74Ay5zF"); - } + } - public void sendMessage(CommandSender sender, String msg) { - LanguageLoader languageLoader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); - if (languageLoader != null && languageLoader.isSmallCapsFont()) { - msg = FontUtils.toSmallCaps(msg); - } - sender.sendMessage(Prefix.CHALLENGES + msg); + public void sendMessage(CommandSender sender, String msg) { + LanguageLoader languageLoader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); + if (languageLoader != null && languageLoader.isSmallCapsFont()) { + msg = FontUtils.toSmallCaps(msg); + } + sender.sendMessage(Prefix.CHALLENGES + msg); - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index 720988271..f8a2f62f1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.spigot.listener; -import java.util.List; -import javax.annotation.Nonnull; import net.anweisen.utilities.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; @@ -20,131 +18,134 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; +import javax.annotation.Nonnull; +import java.util.List; + public class PlayerConnectionListener implements Listener { - private final boolean messages; - private final boolean timerPausedInfo; - private final boolean startTimerOnJoin; - private final boolean resetOnLastQuit; - private final boolean pauseOnLastQuit; - private final boolean restoreDefaultsOnLastQuit; - - public PlayerConnectionListener() { - Document config = Challenges.getInstance().getConfigDocument(); - messages = config.getBoolean("join-quit-messages"); - timerPausedInfo = config.getBoolean("timer-is-paused-info"); - startTimerOnJoin = config.getBoolean("start-on-first-join"); - resetOnLastQuit = config.getBoolean("reset-on-last-leave"); - pauseOnLastQuit = config.getBoolean("pause-on-last-leave"); - restoreDefaultsOnLastQuit = config.getBoolean("restore-defaults-on-last-leave"); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onJoin(@Nonnull PlayerJoinEvent event) { - - Player player = event.getPlayer(); - - player.getLocation().getChunk().load(true); - ParticleUtils.spawnUpGoingParticleCircle(Challenges.getInstance(), player.getLocation(), - MinecraftNameWrapper.ENTITY_EFFECT, 17, 1, 2); - Challenges.getInstance().getScoreboardManager().handleJoin(player); - - if (Challenges.getInstance().isFirstInstall() && !player.hasPermission("challenges.gui")) { - Message.forName("not-op").send(player, Prefix.CHALLENGES); - } - - if (player.hasPermission("challenges.gui")) { - if (Challenges.getInstance().isFirstInstall()) { - player.sendMessage(""); - player.sendMessage(Prefix.CHALLENGES + "§7Thanks for downloading §e§lChallenges§7!"); - player.sendMessage(Prefix.CHALLENGES + "§7You can change the language in the settings or with /setlang [language]"); - player.sendMessage(Prefix.CHALLENGES + "§7For more join our discord §ediscord.gg/74Ay5zF"); - } - - if (timerPausedInfo && !startTimerOnJoin && ChallengeAPI.isPaused()) { - player.sendMessage(""); - Message.forName("timer-paused-message").send(player, Prefix.CHALLENGES); - } - } - - if (Challenges.getInstance().getStatsManager().isNoStatsAfterCheating() && Challenges.getInstance().getServerManager().hasCheated()) { - player.sendMessage(""); - Message.forName("cheats-already-detected").send(player, Prefix.CHALLENGES); - } - - - if (startTimerOnJoin) { - player.sendMessage(""); - ChallengeAPI.resumeTimer(); - } - - if (player.hasPermission("challenges.gui")) { - if (!UpdateLoader.isNewestConfigVersion()) { - player.sendMessage(""); - Message.forName("deprecated-config-version").send(player, Prefix.CHALLENGES, UpdateLoader.getDefaultConfigVersion().format(), UpdateLoader.getCurrentConfigVersion().format()); - } - - List missingConfigSettings = Challenges.getInstance().getConfigManager().getMissingConfigSettings(); - if (!missingConfigSettings.isEmpty()) { - player.sendMessage(""); - String separator = Message.forName("missing-config-settings-separator").asString(); - Message.forName("missing-config-settings").send(player, Prefix.CHALLENGES, String.join(separator, missingConfigSettings)); - } else if (!UpdateLoader.isNewestConfigVersion()) { - player.sendMessage(""); - Message.forName("no-missing-config-settings").send(player, Prefix.CHALLENGES, UpdateLoader.getDefaultConfigVersion().format()); - } - if (!UpdateLoader.isNewestPluginVersion()) { - player.sendMessage(""); - Message.forName("deprecated-plugin-version").send(player, Prefix.CHALLENGES, "spigotmc.org/resources/" + UpdateLoader.RESOURCE_ID); - } - } - - - if (messages) { - player.sendMessage(""); - event.setJoinMessage(Prefix.CHALLENGES + Message.forName("join-message").asString(NameHelper.getName(event.getPlayer()))); - } - - if (Challenges.getInstance().getDatabaseManager().isConnected()) { - Challenges.getInstance().runAsync(() -> DatabaseHelper.savePlayerData(player)); - } - - } - - @EventHandler(priority = EventPriority.HIGH) - public void onQuit(@Nonnull PlayerQuitEvent event) { - - try { - Player player = event.getPlayer(); - Challenges.getInstance().getScoreboardManager().handleQuit(player); - DatabaseHelper.clearCache(event.getPlayer().getUniqueId()); - - if (Challenges.getInstance().getWorldManager().isShutdownBecauseOfReset()) { - event.setQuitMessage(null); - } else if (messages) { - event.setQuitMessage(null); - Message.forName("quit-message").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - } - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Error while handling disconnect", exception); - } - - if (Bukkit.getOnlinePlayers().size() <= 1) { - - if (!Challenges.getInstance().getWorldManager().isShutdownBecauseOfReset()) { - if (resetOnLastQuit && !ChallengeAPI.isFresh()) { - Challenges.getInstance().getWorldManager().prepareWorldReset(Bukkit.getConsoleSender()); - return; - } else if (pauseOnLastQuit && ChallengeAPI.isStarted()) { - ChallengeAPI.pauseTimer(); - } - } - - if (restoreDefaultsOnLastQuit) { - Challenges.getInstance().getChallengeManager().restoreDefaults(); - } - } - - } + private final boolean messages; + private final boolean timerPausedInfo; + private final boolean startTimerOnJoin; + private final boolean resetOnLastQuit; + private final boolean pauseOnLastQuit; + private final boolean restoreDefaultsOnLastQuit; + + public PlayerConnectionListener() { + Document config = Challenges.getInstance().getConfigDocument(); + messages = config.getBoolean("join-quit-messages"); + timerPausedInfo = config.getBoolean("timer-is-paused-info"); + startTimerOnJoin = config.getBoolean("start-on-first-join"); + resetOnLastQuit = config.getBoolean("reset-on-last-leave"); + pauseOnLastQuit = config.getBoolean("pause-on-last-leave"); + restoreDefaultsOnLastQuit = config.getBoolean("restore-defaults-on-last-leave"); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJoin(@Nonnull PlayerJoinEvent event) { + + Player player = event.getPlayer(); + + player.getLocation().getChunk().load(true); + ParticleUtils.spawnUpGoingParticleCircle(Challenges.getInstance(), player.getLocation(), + MinecraftNameWrapper.ENTITY_EFFECT, 17, 1, 2); + Challenges.getInstance().getScoreboardManager().handleJoin(player); + + if (Challenges.getInstance().isFirstInstall() && !player.hasPermission("challenges.gui")) { + Message.forName("not-op").send(player, Prefix.CHALLENGES); + } + + if (player.hasPermission("challenges.gui")) { + if (Challenges.getInstance().isFirstInstall()) { + player.sendMessage(""); + player.sendMessage(Prefix.CHALLENGES + "§7Thanks for downloading §e§lChallenges§7!"); + player.sendMessage(Prefix.CHALLENGES + "§7You can change the language in the settings or with /setlang [language]"); + player.sendMessage(Prefix.CHALLENGES + "§7For more join our discord §ediscord.gg/74Ay5zF"); + } + + if (timerPausedInfo && !startTimerOnJoin && ChallengeAPI.isPaused()) { + player.sendMessage(""); + Message.forName("timer-paused-message").send(player, Prefix.CHALLENGES); + } + } + + if (Challenges.getInstance().getStatsManager().isNoStatsAfterCheating() && Challenges.getInstance().getServerManager().hasCheated()) { + player.sendMessage(""); + Message.forName("cheats-already-detected").send(player, Prefix.CHALLENGES); + } + + + if (startTimerOnJoin) { + player.sendMessage(""); + ChallengeAPI.resumeTimer(); + } + + if (player.hasPermission("challenges.gui")) { + if (!UpdateLoader.isNewestConfigVersion()) { + player.sendMessage(""); + Message.forName("deprecated-config-version").send(player, Prefix.CHALLENGES, UpdateLoader.getDefaultConfigVersion().format(), UpdateLoader.getCurrentConfigVersion().format()); + } + + List missingConfigSettings = Challenges.getInstance().getConfigManager().getMissingConfigSettings(); + if (!missingConfigSettings.isEmpty()) { + player.sendMessage(""); + String separator = Message.forName("missing-config-settings-separator").asString(); + Message.forName("missing-config-settings").send(player, Prefix.CHALLENGES, String.join(separator, missingConfigSettings)); + } else if (!UpdateLoader.isNewestConfigVersion()) { + player.sendMessage(""); + Message.forName("no-missing-config-settings").send(player, Prefix.CHALLENGES, UpdateLoader.getDefaultConfigVersion().format()); + } + if (!UpdateLoader.isNewestPluginVersion()) { + player.sendMessage(""); + Message.forName("deprecated-plugin-version").send(player, Prefix.CHALLENGES, "spigotmc.org/resources/" + UpdateLoader.RESOURCE_ID); + } + } + + + if (messages) { + player.sendMessage(""); + event.setJoinMessage(Prefix.CHALLENGES + Message.forName("join-message").asString(NameHelper.getName(event.getPlayer()))); + } + + if (Challenges.getInstance().getDatabaseManager().isConnected()) { + Challenges.getInstance().runAsync(() -> DatabaseHelper.savePlayerData(player)); + } + + } + + @EventHandler(priority = EventPriority.HIGH) + public void onQuit(@Nonnull PlayerQuitEvent event) { + + try { + Player player = event.getPlayer(); + Challenges.getInstance().getScoreboardManager().handleQuit(player); + DatabaseHelper.clearCache(event.getPlayer().getUniqueId()); + + if (Challenges.getInstance().getWorldManager().isShutdownBecauseOfReset()) { + event.setQuitMessage(null); + } else if (messages) { + event.setQuitMessage(null); + Message.forName("quit-message").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + } + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Error while handling disconnect", exception); + } + + if (Bukkit.getOnlinePlayers().size() <= 1) { + + if (!Challenges.getInstance().getWorldManager().isShutdownBecauseOfReset()) { + if (resetOnLastQuit && !ChallengeAPI.isFresh()) { + Challenges.getInstance().getWorldManager().prepareWorldReset(Bukkit.getConsoleSender()); + return; + } else if (pauseOnLastQuit && ChallengeAPI.isStarted()) { + ChallengeAPI.pauseTimer(); + } + } + + if (restoreDefaultsOnLastQuit) { + Challenges.getInstance().getChallengeManager().restoreDefaults(); + } + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java index 523b9331c..f111ace66 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java @@ -25,142 +25,142 @@ public class RestrictionListener implements Listener { - @EventHandler(priority = EventPriority.LOW) - public void onEntityDamage(@Nonnull EntityDamageEvent event) { - if (ChallengeAPI.isStarted()) return; - Entity entity = event.getEntity(); - if (entity instanceof Player && ((Player) entity).getGameMode() == GameMode.CREATIVE) { - return; - } - - if (event.getCause() != DamageCause.VOID && (entity instanceof Player || event.getCause() == DamageCause.ENTITY_ATTACK || event.getCause() == DamageCause.PROJECTILE)) { - entity.setFireTicks(entity instanceof Player ? 0 : entity.getFireTicks()); - event.setCancelled(true); - ParticleUtils.spawnParticleCircleAroundEntity(Challenges.getInstance(), entity); - } - } - - @EventHandler(priority = EventPriority.LOW) - public void onEntityDeath(@Nonnull EntityDeathEvent event) { - if (ChallengeAPI.isStarted()) return; - if (!(event.getEntity() instanceof Player)) return; - event.getDrops().clear(); - event.setDroppedExp(0); - } - - @EventHandler(priority = EventPriority.LOW) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { - if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onFoodLevelChange(@Nonnull FoodLevelChangeEvent event) { - if (ChallengeAPI.isPaused()) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onEntityRegainHealth(@Nonnull EntityRegainHealthEvent event) { - if (ChallengeAPI.isPaused()) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onItemPickup(@Nonnull EntityPickupItemEvent event) { - if (ChallengeAPI.isStarted()) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - if (player.getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onDrop(@Nonnull PlayerDropItemEvent event) { - if (ChallengeAPI.isStarted()) return; - if (event.getPlayer().getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onInteract(@Nonnull PlayerInteractEvent event) { - if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onInteract(@Nonnull PlayerInteractAtEntityEvent event) { - if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onInteract(@Nonnull PlayerInteractEntityEvent event) { - if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onOffHandItemSwitch(@Nonnull PlayerSwapHandItemsEvent event) { - if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onDamage(@Nonnull VehicleDamageEvent event) { - if (ChallengeAPI.isStarted()) return; - Entity entity = event.getVehicle(); - event.setCancelled(true); - if (event.getAttacker() instanceof Player) { - if (((Player) event.getAttacker()).getGameMode() == GameMode.CREATIVE) - event.setCancelled(false); - ParticleUtils.spawnParticleCircleAroundEntity(Challenges.getInstance(), entity); - } - } - - @EventHandler(priority = EventPriority.LOW) - public void onDamage(@Nonnull VehicleDestroyEvent event) { - if (ChallengeAPI.isPaused() && !(event.getAttacker() instanceof Player && ((Player) event.getAttacker()).getGameMode() == GameMode.CREATIVE)) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onWeatherChange(@Nonnull WeatherChangeEvent event) { - if (ChallengeAPI.isPaused() && event.toWeatherState()) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onThunderChange(@Nonnull ThunderChangeEvent event) { - if (ChallengeAPI.isPaused() && event.toThunderState()) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onTarget(@Nonnull EntityTargetEvent event) { - if (ChallengeAPI.isPaused() && event.getTarget() != null) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onClick(@Nonnull InventoryClickEvent event) { - if (!(event.getWhoClicked() instanceof Player)) return; - Player player = (Player) event.getWhoClicked(); - if (ChallengeAPI.isPaused() && player.getGameMode() != GameMode.CREATIVE) - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onBlockSpread(@Nonnull BlockSpreadEvent event) { - if (ChallengeAPI.isStarted()) return; - event.setCancelled(true); - - } + @EventHandler(priority = EventPriority.LOW) + public void onEntityDamage(@Nonnull EntityDamageEvent event) { + if (ChallengeAPI.isStarted()) return; + Entity entity = event.getEntity(); + if (entity instanceof Player && ((Player) entity).getGameMode() == GameMode.CREATIVE) { + return; + } + + if (event.getCause() != DamageCause.VOID && (entity instanceof Player || event.getCause() == DamageCause.ENTITY_ATTACK || event.getCause() == DamageCause.PROJECTILE)) { + entity.setFireTicks(entity instanceof Player ? 0 : entity.getFireTicks()); + event.setCancelled(true); + ParticleUtils.spawnParticleCircleAroundEntity(Challenges.getInstance(), entity); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onEntityDeath(@Nonnull EntityDeathEvent event) { + if (ChallengeAPI.isStarted()) return; + if (!(event.getEntity() instanceof Player)) return; + event.getDrops().clear(); + event.setDroppedExp(0); + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onFoodLevelChange(@Nonnull FoodLevelChangeEvent event) { + if (ChallengeAPI.isPaused()) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onEntityRegainHealth(@Nonnull EntityRegainHealthEvent event) { + if (ChallengeAPI.isPaused()) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onItemPickup(@Nonnull EntityPickupItemEvent event) { + if (ChallengeAPI.isStarted()) return; + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + if (player.getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onDrop(@Nonnull PlayerDropItemEvent event) { + if (ChallengeAPI.isStarted()) return; + if (event.getPlayer().getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onInteract(@Nonnull PlayerInteractEvent event) { + if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onInteract(@Nonnull PlayerInteractAtEntityEvent event) { + if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onInteract(@Nonnull PlayerInteractEntityEvent event) { + if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onOffHandItemSwitch(@Nonnull PlayerSwapHandItemsEvent event) { + if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onDamage(@Nonnull VehicleDamageEvent event) { + if (ChallengeAPI.isStarted()) return; + Entity entity = event.getVehicle(); + event.setCancelled(true); + if (event.getAttacker() instanceof Player) { + if (((Player) event.getAttacker()).getGameMode() == GameMode.CREATIVE) + event.setCancelled(false); + ParticleUtils.spawnParticleCircleAroundEntity(Challenges.getInstance(), entity); + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onDamage(@Nonnull VehicleDestroyEvent event) { + if (ChallengeAPI.isPaused() && !(event.getAttacker() instanceof Player && ((Player) event.getAttacker()).getGameMode() == GameMode.CREATIVE)) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onWeatherChange(@Nonnull WeatherChangeEvent event) { + if (ChallengeAPI.isPaused() && event.toWeatherState()) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onThunderChange(@Nonnull ThunderChangeEvent event) { + if (ChallengeAPI.isPaused() && event.toThunderState()) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onTarget(@Nonnull EntityTargetEvent event) { + if (ChallengeAPI.isPaused() && event.getTarget() != null) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onClick(@Nonnull InventoryClickEvent event) { + if (!(event.getWhoClicked() instanceof Player)) return; + Player player = (Player) event.getWhoClicked(); + if (ChallengeAPI.isPaused() && player.getGameMode() != GameMode.CREATIVE) + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockSpread(@Nonnull BlockSpreadEvent event) { + if (ChallengeAPI.isStarted()) return; + event.setCancelled(true); + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java index 71f3d03b3..2e9e7b5d4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ScoreboardUpdateListener.java @@ -9,16 +9,16 @@ public class ScoreboardUpdateListener implements Listener { - @EventHandler - public void onIgnoredChange(PlayerIgnoreStatusChangeEvent event) { + @EventHandler + public void onIgnoredChange(PlayerIgnoreStatusChangeEvent event) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - ChallengeScoreboard currentScoreboard = Challenges.getInstance().getScoreboardManager().getCurrentScoreboard(); - if (currentScoreboard != null) { - currentScoreboard.update(); - } - }); + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + ChallengeScoreboard currentScoreboard = Challenges.getInstance().getScoreboardManager().getCurrentScoreboard(); + if (currentScoreboard != null) { + currentScoreboard.update(); + } + }); - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java index 57c560066..163aaac8e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java @@ -35,112 +35,112 @@ public class StatsListener implements Listener { - private final List dragonDamager = new ArrayList<>(); - - @TimerTask(status = TimerStatus.RUNNING, freshnessPolicy = FreshnessPolicy.FRESH, async = false) - public void onStart() { - if (!Challenges.getInstance().getStatsManager().isEnabled()) return; - - for (Player player : Bukkit.getOnlinePlayers()) { - Challenges.getInstance().getStatsManager().getStats(player).incrementStatistic(Statistic.CHALLENGES_PLAYED, 1); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { - if (countNoStats()) return; - if (!(event.getEntity() instanceof Player)) return; - if (event.getCause() == DamageCause.VOID) return; - - Player player = (Player) event.getEntity(); - if (AbstractChallenge.ignorePlayer(player)) return; - incrementStatistic(player, Statistic.DAMAGE_TAKEN, event.getFinalDamage()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageByEntityEvent event) { - if (countNoStats()) return; - - if (event.getDamager() instanceof Player) { - Player player = (Player) event.getDamager(); - if (player.getGameMode() == GameMode.SPECTATOR || player.getGameMode() == GameMode.CREATIVE) - return; - incrementStatistic(player, Statistic.DAMAGE_DEALT, event.getFinalDamage()); - - if (event.getEntity() instanceof EnderDragon && !dragonDamager.contains(player)) - dragonDamager.add(player); - } else if (event.getDamager() instanceof Projectile) { - Projectile projectile = (Projectile) event.getDamager(); - if (!((projectile.getShooter()) instanceof Player)) return; - Player player = (Player) projectile.getShooter(); - if (AbstractChallenge.ignorePlayer(player)) return; - incrementStatistic(player, Statistic.DAMAGE_DEALT, event.getFinalDamage()); - - if (event.getEntity() instanceof EnderDragon && !dragonDamager.contains(player)) - dragonDamager.add(player); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { - if (countNoStats()) return; - if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; - incrementStatistic(event.getPlayer(), Statistic.BLOCKS_PLACED, 1); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { - if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; - if (countNoStats()) return; - incrementStatistic(event.getPlayer(), Statistic.BLOCKS_MINED, 1); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onDeath(@Nonnull PlayerDeathEvent event) { - if (countNoStats()) return; - incrementStatistic(event.getEntity(), Statistic.DEATHS, 1); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onKill(@Nonnull EntityDeathEvent event) { - if (countNoStats()) return; - LivingEntity entity = event.getEntity(); - Player player = entity.getKiller(); - if (player == null) return; - if (AbstractChallenge.ignorePlayer(player)) return; - - incrementStatistic(player, Statistic.ENTITY_KILLS, 1); - if (entity instanceof EnderDragon && entity.getWorld().getEnvironment() == Environment.THE_END) { - dragonDamager.forEach(damager -> incrementStatistic(damager, Statistic.DRAGON_KILLED, 1)); - dragonDamager.clear(); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { - if (countNoStats()) return; - if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; - if (ChallengeAPI.isPaused()) return; - if (event.getTo() == null) return; - if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; - incrementStatistic(event.getPlayer(), Statistic.BLOCKS_TRAVELED, 1); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onJump(@Nonnull PlayerJumpEvent event) { - if (countNoStats()) return; - if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; - if (ChallengeAPI.isPaused()) return; - incrementStatistic(event.getPlayer(), Statistic.JUMPS, 1); - } - - private void incrementStatistic(@Nonnull Player player, @Nonnull Statistic statistic, double amount) { - PlayerStats stats = Challenges.getInstance().getStatsManager().getStats(player); - stats.incrementStatistic(statistic, amount); - } - - private boolean countNoStats() { - return Challenges.getInstance().getServerManager().hasCheated() && Challenges.getInstance().getStatsManager().isNoStatsAfterCheating(); - } + private final List dragonDamager = new ArrayList<>(); + + @TimerTask(status = TimerStatus.RUNNING, freshnessPolicy = FreshnessPolicy.FRESH, async = false) + public void onStart() { + if (!Challenges.getInstance().getStatsManager().isEnabled()) return; + + for (Player player : Bukkit.getOnlinePlayers()) { + Challenges.getInstance().getStatsManager().getStats(player).incrementStatistic(Statistic.CHALLENGES_PLAYED, 1); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageEvent event) { + if (countNoStats()) return; + if (!(event.getEntity() instanceof Player)) return; + if (event.getCause() == DamageCause.VOID) return; + + Player player = (Player) event.getEntity(); + if (AbstractChallenge.ignorePlayer(player)) return; + incrementStatistic(player, Statistic.DAMAGE_TAKEN, event.getFinalDamage()); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onDamage(@Nonnull EntityDamageByEntityEvent event) { + if (countNoStats()) return; + + if (event.getDamager() instanceof Player) { + Player player = (Player) event.getDamager(); + if (player.getGameMode() == GameMode.SPECTATOR || player.getGameMode() == GameMode.CREATIVE) + return; + incrementStatistic(player, Statistic.DAMAGE_DEALT, event.getFinalDamage()); + + if (event.getEntity() instanceof EnderDragon && !dragonDamager.contains(player)) + dragonDamager.add(player); + } else if (event.getDamager() instanceof Projectile) { + Projectile projectile = (Projectile) event.getDamager(); + if (!((projectile.getShooter()) instanceof Player)) return; + Player player = (Player) projectile.getShooter(); + if (AbstractChallenge.ignorePlayer(player)) return; + incrementStatistic(player, Statistic.DAMAGE_DEALT, event.getFinalDamage()); + + if (event.getEntity() instanceof EnderDragon && !dragonDamager.contains(player)) + dragonDamager.add(player); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + if (countNoStats()) return; + if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; + incrementStatistic(event.getPlayer(), Statistic.BLOCKS_PLACED, 1); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onBlockBreak(@Nonnull BlockBreakEvent event) { + if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; + if (countNoStats()) return; + incrementStatistic(event.getPlayer(), Statistic.BLOCKS_MINED, 1); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onDeath(@Nonnull PlayerDeathEvent event) { + if (countNoStats()) return; + incrementStatistic(event.getEntity(), Statistic.DEATHS, 1); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onKill(@Nonnull EntityDeathEvent event) { + if (countNoStats()) return; + LivingEntity entity = event.getEntity(); + Player player = entity.getKiller(); + if (player == null) return; + if (AbstractChallenge.ignorePlayer(player)) return; + + incrementStatistic(player, Statistic.ENTITY_KILLS, 1); + if (entity instanceof EnderDragon && entity.getWorld().getEnvironment() == Environment.THE_END) { + dragonDamager.forEach(damager -> incrementStatistic(damager, Statistic.DRAGON_KILLED, 1)); + dragonDamager.clear(); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(@Nonnull PlayerMoveEvent event) { + if (countNoStats()) return; + if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; + if (ChallengeAPI.isPaused()) return; + if (event.getTo() == null) return; + if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; + incrementStatistic(event.getPlayer(), Statistic.BLOCKS_TRAVELED, 1); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onJump(@Nonnull PlayerJumpEvent event) { + if (countNoStats()) return; + if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; + if (ChallengeAPI.isPaused()) return; + incrementStatistic(event.getPlayer(), Statistic.JUMPS, 1); + } + + private void incrementStatistic(@Nonnull Player player, @Nonnull Statistic statistic, double amount) { + PlayerStats stats = Challenges.getInstance().getStatsManager().getStats(player); + stats.incrementStatistic(statistic, amount); + } + + private boolean countNoStats() { + return Challenges.getInstance().getServerManager().hasCheated() && Challenges.getInstance().getStatsManager().isNoStatsAfterCheating(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java index c81a982d1..685acfe58 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java @@ -10,12 +10,12 @@ public interface Completer extends TabCompleter { - @Override - @Nullable - default List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) { - return onTabComplete(sender, args); - } + @Override + @Nullable + default List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) { + return onTabComplete(sender, args); + } - @Nullable - List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args); + @Nullable + List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java index 9ccfbb7fb..258830152 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java @@ -12,27 +12,27 @@ public class ForwardingCommand implements SenderCommand, TabCompleter { - private final String forwardCommand; - private final boolean overrideTab; - - public ForwardingCommand(@Nonnull String forwardCommand) { - this(forwardCommand, true); - } - - public ForwardingCommand(@Nonnull String forwardCommand, boolean overrideTab) { - this.forwardCommand = forwardCommand; - this.overrideTab = overrideTab; - } - - @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { - Bukkit.dispatchCommand(sender, forwardCommand + " " + String.join(" ", args)); - } - - @Nullable - @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String alias, @Nonnull String[] args) { - return overrideTab ? new ArrayList<>() : null; - } + private final String forwardCommand; + private final boolean overrideTab; + + public ForwardingCommand(@Nonnull String forwardCommand) { + this(forwardCommand, true); + } + + public ForwardingCommand(@Nonnull String forwardCommand, boolean overrideTab) { + this.forwardCommand = forwardCommand; + this.overrideTab = overrideTab; + } + + @Override + public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + Bukkit.dispatchCommand(sender, forwardCommand + " " + String.join(" ", args)); + } + + @Nullable + @Override + public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String alias, @Nonnull String[] args) { + return overrideTab ? new ArrayList<>() : null; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java index 385740ae8..a2f83c357 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java @@ -12,21 +12,21 @@ public interface PlayerCommand extends CommandExecutor { - @Override - default boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) { - if (sender instanceof Player) { - try { - onCommand((Player) sender, args); - } catch (Exception ex) { - sender.sendMessage(Prefix.CHALLENGES + "§cSomething went wrong while executing the command"); - Logger.error("Something went wrong while processing the command '{}'", label, ex); - } - } else { - Message.forName("player-command").send(sender, Prefix.CHALLENGES); - } - return true; - } + @Override + default boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) { + if (sender instanceof Player) { + try { + onCommand((Player) sender, args); + } catch (Exception ex) { + sender.sendMessage(Prefix.CHALLENGES + "§cSomething went wrong while executing the command"); + Logger.error("Something went wrong while processing the command '{}'", label, ex); + } + } else { + Message.forName("player-command").send(sender, Prefix.CHALLENGES); + } + return true; + } - void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception; + void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java index 41aca835e..924e681a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java @@ -10,17 +10,17 @@ public interface SenderCommand extends CommandExecutor { - @Override - default boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) { - try { - onCommand(sender, args); - } catch (Exception ex) { - sender.sendMessage(Prefix.CHALLENGES + "§cSomething went wrong while executing the command"); - Logger.error("Something went wrong while processing the command '{}'", label, ex); - } - return true; - } + @Override + default boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) { + try { + onCommand(sender, args); + } catch (Exception ex) { + sender.sendMessage(Prefix.CHALLENGES + "§cSomething went wrong while executing the command"); + Logger.error("Something went wrong while processing the command '{}'", label, ex); + } + return true; + } - void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception; + void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java index 6711694e9..3de673ac2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java @@ -13,138 +13,138 @@ public class BukkitSerialization { - /** - * Converts the player inventory to a String array of Base64 strings. First string is the content and second string is the armor. - * - * @param playerInventory to turn into an array of strings. - * @return Array of strings: [ main content, armor content ] - */ - public static String[] playerInventoryToBase64(PlayerInventory playerInventory) throws IllegalStateException { - //get the main content part, this doesn't return the armor - String content = toBase64(playerInventory); - String armor = itemStackArrayToBase64(playerInventory.getArmorContents()); - - return new String[]{content, armor}; - } - - /** - * A method to serialize an {@link ItemStack} array to Base64 String. - *

- *

- *

- * Based off of {@link #toBase64(Inventory)}. - * - * @param items to turn into a Base64 String. - * @return Base64 string of the items. - */ - public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException { - try { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); - - // Write the size of the inventory - dataOutput.writeInt(items.length); - - // Save every element in the list - for (int i = 0; i < items.length; i++) { - dataOutput.writeObject(items[i]); - } - - // Serialize that array - dataOutput.close(); - return Base64Coder.encodeLines(outputStream.toByteArray()); - } catch (Exception e) { - throw new IllegalStateException("Unable to save item stacks.", e); - } - } - - /** - * A method to serialize an inventory to Base64 string. - *

- *

- *

- * Special thanks to Comphenix in the Bukkit forums or also known - * as aadnk on GitHub. - * - * Original Source - * - * @param inventory to serialize - * @return Base64 string of the provided inventory - */ - public static String toBase64(Inventory inventory) throws IllegalStateException { - try { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); - - // Save every element in the list - for (int i = 0; i < inventory.getSize(); i++) { - dataOutput.writeObject(inventory.getItem(i)); - } - - // Serialize that array - dataOutput.close(); - return Base64Coder.encodeLines(outputStream.toByteArray()); - } catch (Exception e) { - throw new IllegalStateException("Unable to save item stacks.", e); - } - } - - /** - * A method to get an {@link Inventory} from an encoded, Base64, string. - *

- *

- *

- * Special thanks to Comphenix in the Bukkit forums or also known - * as aadnk on GitHub. - * - * Original Source - * - * @param data Base64 string of data containing an inventory. - * @return Inventory created from the Base64 string. - */ - public static Inventory fromBase64(Inventory inventory, String data) throws IOException { - try { - ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); - BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); - - // Read the serialized inventory - for (int i = 0; i < inventory.getSize(); i++) { - inventory.setItem(i, (ItemStack) dataInput.readObject()); - } - - dataInput.close(); - return inventory; - } catch (ClassNotFoundException e) { - throw new IOException("Unable to decode class type.", e); - } - } - - /** - * Gets an array of ItemStacks from Base64 string. - *

- *

- *

- * Base off of . - * - * @param data Base64 string to convert to ItemStack array. - * @return ItemStack array created from the Base64 string. - */ - public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException { - try { - ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); - BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); - ItemStack[] items = new ItemStack[dataInput.readInt()]; - - // Read the serialized inventory - for (int i = 0; i < items.length; i++) { - items[i] = (ItemStack) dataInput.readObject(); - } - - dataInput.close(); - return items; - } catch (ClassNotFoundException e) { - throw new IOException("Unable to decode class type.", e); - } - } + /** + * Converts the player inventory to a String array of Base64 strings. First string is the content and second string is the armor. + * + * @param playerInventory to turn into an array of strings. + * @return Array of strings: [ main content, armor content ] + */ + public static String[] playerInventoryToBase64(PlayerInventory playerInventory) throws IllegalStateException { + //get the main content part, this doesn't return the armor + String content = toBase64(playerInventory); + String armor = itemStackArrayToBase64(playerInventory.getArmorContents()); + + return new String[]{content, armor}; + } + + /** + * A method to serialize an {@link ItemStack} array to Base64 String. + *

+ *

+ *

+ * Based off of {@link #toBase64(Inventory)}. + * + * @param items to turn into a Base64 String. + * @return Base64 string of the items. + */ + public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); + + // Write the size of the inventory + dataOutput.writeInt(items.length); + + // Save every element in the list + for (int i = 0; i < items.length; i++) { + dataOutput.writeObject(items[i]); + } + + // Serialize that array + dataOutput.close(); + return Base64Coder.encodeLines(outputStream.toByteArray()); + } catch (Exception e) { + throw new IllegalStateException("Unable to save item stacks.", e); + } + } + + /** + * A method to serialize an inventory to Base64 string. + *

+ *

+ *

+ * Special thanks to Comphenix in the Bukkit forums or also known + * as aadnk on GitHub. + * + * Original Source + * + * @param inventory to serialize + * @return Base64 string of the provided inventory + */ + public static String toBase64(Inventory inventory) throws IllegalStateException { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); + + // Save every element in the list + for (int i = 0; i < inventory.getSize(); i++) { + dataOutput.writeObject(inventory.getItem(i)); + } + + // Serialize that array + dataOutput.close(); + return Base64Coder.encodeLines(outputStream.toByteArray()); + } catch (Exception e) { + throw new IllegalStateException("Unable to save item stacks.", e); + } + } + + /** + * A method to get an {@link Inventory} from an encoded, Base64, string. + *

+ *

+ *

+ * Special thanks to Comphenix in the Bukkit forums or also known + * as aadnk on GitHub. + * + * Original Source + * + * @param data Base64 string of data containing an inventory. + * @return Inventory created from the Base64 string. + */ + public static Inventory fromBase64(Inventory inventory, String data) throws IOException { + try { + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); + BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); + + // Read the serialized inventory + for (int i = 0; i < inventory.getSize(); i++) { + inventory.setItem(i, (ItemStack) dataInput.readObject()); + } + + dataInput.close(); + return inventory; + } catch (ClassNotFoundException e) { + throw new IOException("Unable to decode class type.", e); + } + } + + /** + * Gets an array of ItemStacks from Base64 string. + *

+ *

+ *

+ * Base off of . + * + * @param data Base64 string to convert to ItemStack array. + * @return ItemStack array created from the Base64 string. + */ + public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException { + try { + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); + BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); + ItemStack[] items = new ItemStack[dataInput.readInt()]; + + // Read the serialized inventory + for (int i = 0; i < items.length; i++) { + items[i] = (ItemStack) dataInput.readObject(); + } + + dataInput.close(); + return items; + } catch (ClassNotFoundException e) { + throw new IOException("Unable to decode class type.", e); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java index 3a64320c8..07c18695f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.utils.bukkit.container; -import java.util.Collection; -import javax.annotation.Nonnull; import lombok.Data; import org.bukkit.GameMode; import org.bukkit.Location; @@ -9,79 +7,82 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; +import javax.annotation.Nonnull; +import java.util.Collection; + @Data public final class PlayerData { - private final GameMode gamemode; - private final Location location; - private final ItemStack[] inventory; - private final ItemStack[] armor; - private final Collection effects; + private final GameMode gamemode; + private final Location location; + private final ItemStack[] inventory; + private final ItemStack[] armor; + private final Collection effects; - private final double health; - private final int food; - private final float saturation; - private final int heldItemSlot; - private final boolean allowedFlight; - private final boolean flying; + private final double health; + private final int food; + private final float saturation; + private final int heldItemSlot; + private final boolean allowedFlight; + private final boolean flying; - public PlayerData(@Nonnull Player player) { - this( - player.getGameMode(), - player.getLocation(), - player.getInventory().getContents(), - player.getInventory().getArmorContents(), - player.getActivePotionEffects(), - player.getHealth(), - player.getFoodLevel(), - player.getSaturation(), - player.getInventory().getHeldItemSlot(), - player.getAllowFlight(), - player.isFlying() - ); - } + public PlayerData(@Nonnull Player player) { + this( + player.getGameMode(), + player.getLocation(), + player.getInventory().getContents(), + player.getInventory().getArmorContents(), + player.getActivePotionEffects(), + player.getHealth(), + player.getFoodLevel(), + player.getSaturation(), + player.getInventory().getHeldItemSlot(), + player.getAllowFlight(), + player.isFlying() + ); + } - public PlayerData( - @Nonnull GameMode gamemode, - @Nonnull Location location, - @Nonnull ItemStack[] inventory, - @Nonnull ItemStack[] armor, - @Nonnull Collection effects, - double health, - int food, - float saturation, - int heldItemSlot, - boolean allowedFlight, - boolean flying - ) { - this.gamemode = gamemode; - this.location = location; - this.inventory = inventory; - this.armor = armor; - this.effects = effects; - this.health = health; - this.food = food; - this.saturation = saturation; - this.heldItemSlot = heldItemSlot; - this.allowedFlight = allowedFlight; - this.flying = allowedFlight && flying; - } + public PlayerData( + @Nonnull GameMode gamemode, + @Nonnull Location location, + @Nonnull ItemStack[] inventory, + @Nonnull ItemStack[] armor, + @Nonnull Collection effects, + double health, + int food, + float saturation, + int heldItemSlot, + boolean allowedFlight, + boolean flying + ) { + this.gamemode = gamemode; + this.location = location; + this.inventory = inventory; + this.armor = armor; + this.effects = effects; + this.health = health; + this.food = food; + this.saturation = saturation; + this.heldItemSlot = heldItemSlot; + this.allowedFlight = allowedFlight; + this.flying = allowedFlight && flying; + } - public void apply(@Nonnull Player player) { - for (PotionEffect effect : player.getActivePotionEffects()) { - player.removePotionEffect(effect.getType()); - } - player.setGameMode(gamemode); - player.teleport(location); - player.setHealth(health); - player.setFoodLevel(food); - player.setSaturation(saturation); - player.getInventory().setContents(inventory); - player.getInventory().setArmorContents(armor); - player.getInventory().setHeldItemSlot(heldItemSlot); - player.addPotionEffects(effects); - player.setAllowFlight(allowedFlight); - player.setFlying(flying); - } + public void apply(@Nonnull Player player) { + for (PotionEffect effect : player.getActivePotionEffects()) { + player.removePotionEffect(effect.getType()); + } + player.setGameMode(gamemode); + player.teleport(location); + player.setHealth(health); + player.setFoodLevel(food); + player.setSaturation(saturation); + player.getInventory().setContents(inventory); + player.getInventory().setArmorContents(armor); + player.getInventory().setHeldItemSlot(heldItemSlot); + player.addPotionEffects(effects); + player.setAllowFlight(allowedFlight); + player.setFlying(flying); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java index 8f2c6bb10..10294e07c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java @@ -9,8 +9,8 @@ @FunctionalInterface public interface IJumpGenerator { - @Nonnull - @CheckReturnValue - Block next(@Nonnull IRandom random, @Nonnull Block startingPoint, boolean includeFourBlockJumps, boolean includeUpGoing); + @Nonnull + @CheckReturnValue + Block next(@Nonnull IRandom random, @Nonnull Block startingPoint, boolean includeFourBlockJumps, boolean includeUpGoing); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java index 18bf7befa..c0d460d35 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java @@ -9,50 +9,50 @@ public class RandomJumpGenerator implements IJumpGenerator { - @Nonnull - @Override - @CheckReturnValue - public Block next(@Nonnull IRandom random, @Nonnull Block startingPoint, boolean includeFourBlockJumps, boolean includeUpGoing) { - - int layer = random.nextInt(includeUpGoing ? 3 : 2) - 1; - int range = layer == 0 ? 4 : 3; - - int mainDirection = random.nextInt(range * 2) - range; - int mainDirectionValue = Math.abs(mainDirection); - if (mainDirectionValue < 2) { - mainDirection = random.choose(-range, range); - mainDirectionValue = Math.abs(mainDirection); - } - - int secondDirection = determineSecondDirection(random, mainDirectionValue, range); - return translate(startingPoint, random, layer, mainDirection, secondDirection); - - } - - protected int determineSecondDirection(@Nonnull IRandom random, int mainDirection, int range) { - if (mainDirection == range || mainDirection == range - 1) { - return random.choose(-1, 0, 1); - } else if (mainDirection == range - 2) { - return random.choose(-2, -1, 0, 1, 2); - } else if (mainDirection == range - 3) { - return random.choose(-3, -2, -1, 0, 1, 2, 3); - } else if (mainDirection == range - 4 || mainDirection == range - 5) { - return random.choose(-4, -3, -2, -1, 0, 1, 2, 3, 4); - } - throw new IllegalArgumentException("Could not determine second direction for main direction " + mainDirection + ", range " + range); - } - - @Nonnull - @CheckReturnValue - protected Block translate(@Nonnull Block startingPoint, @Nonnull IRandom random, int layer, int mainDirection, int secondDirection) { - - boolean intoX = random.nextBoolean(); - - int x = intoX ? mainDirection : secondDirection; - int z = intoX ? secondDirection : mainDirection; - - return startingPoint.getRelative(x, layer, z); - - } + @Nonnull + @Override + @CheckReturnValue + public Block next(@Nonnull IRandom random, @Nonnull Block startingPoint, boolean includeFourBlockJumps, boolean includeUpGoing) { + + int layer = random.nextInt(includeUpGoing ? 3 : 2) - 1; + int range = layer == 0 ? 4 : 3; + + int mainDirection = random.nextInt(range * 2) - range; + int mainDirectionValue = Math.abs(mainDirection); + if (mainDirectionValue < 2) { + mainDirection = random.choose(-range, range); + mainDirectionValue = Math.abs(mainDirection); + } + + int secondDirection = determineSecondDirection(random, mainDirectionValue, range); + return translate(startingPoint, random, layer, mainDirection, secondDirection); + + } + + protected int determineSecondDirection(@Nonnull IRandom random, int mainDirection, int range) { + if (mainDirection == range || mainDirection == range - 1) { + return random.choose(-1, 0, 1); + } else if (mainDirection == range - 2) { + return random.choose(-2, -1, 0, 1, 2); + } else if (mainDirection == range - 3) { + return random.choose(-3, -2, -1, 0, 1, 2, 3); + } else if (mainDirection == range - 4 || mainDirection == range - 5) { + return random.choose(-4, -3, -2, -1, 0, 1, 2, 3, 4); + } + throw new IllegalArgumentException("Could not determine second direction for main direction " + mainDirection + ", range " + range); + } + + @Nonnull + @CheckReturnValue + protected Block translate(@Nonnull Block startingPoint, @Nonnull IRandom random, int layer, int mainDirection, int secondDirection) { + + boolean intoX = random.nextBoolean(); + + int x = intoX ? mainDirection : secondDirection; + int z = intoX ? secondDirection : mainDirection; + + return startingPoint.getRelative(x, layer, z); + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java index 6c0f43430..a41712252 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java @@ -14,275 +14,278 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; import java.util.concurrent.Callable; import java.util.function.Supplier; public class BukkitStringUtils { - @Nonnull - public static BaseComponent[] format(@Nullable Prefix prefix, @Nonnull String[] array, @Nonnull Object... args) { - List results = new ArrayList<>(); - for (String value : array) { - String s = value; - if (!s.trim().isEmpty() && prefix != null) { - s = prefix + s; - } - BaseComponent comp = null; - for (BaseComponent component : format(s, args)) { - if (comp == null) { - comp = component; - } else { - comp.addExtra(component); - } - } - results.add(comp); - } - return results.toArray(new BaseComponent[0]); - } - - @Nonnull - public static List format(@Nonnull String sequence, @Nonnull Object... args) { - - args = replaceArguments(args, false); - - List results = new ArrayList<>(); - char start = '{', end = '}'; - boolean inArgument = false; - - boolean lastWasParagraph = false; - ChatColor currentColor = null; - List currentFormatting = new LinkedList<>(); - - StringBuilder argument = new StringBuilder(); - TextComponent currentText = new TextComponent(); - for (char c : sequence.toCharArray()) { - - if (c == '§') { - lastWasParagraph = true; - } else { - if (lastWasParagraph) { - ChatColor newColor = ChatColor.getByChar(c); - assert newColor != null; - if (!newColor.isColor()) { - if (newColor == ChatColor.RESET) { - currentFormatting.clear(); - currentColor = null; - } else { - currentFormatting.add(newColor); - } - } else { - currentColor = newColor; - currentFormatting.clear(); - } - } - lastWasParagraph = false; - } - - if (c == end && inArgument) { - inArgument = false; - try { - int arg = Integer.parseInt(argument.toString()); - Object current = args[arg]; - BaseComponent replacement = - current instanceof BaseComponent ? (BaseComponent) current : - current instanceof Supplier ? new TextComponent(String.valueOf(((Supplier) current).get())) : - current instanceof Callable ? new TextComponent(String.valueOf(((Callable) current).call())) : - new TextComponent(String.valueOf(current)); - - if (replacement instanceof TextComponent) { - currentText.setText(currentText.getText() + ((TextComponent) replacement).getText()); - } else { - results.add(currentText); - currentText = new TextComponent(); - - if (currentColor != null && replacement.getColor() == net.md_5.bungee.api.ChatColor.WHITE) { - replacement.setColor(currentColor.asBungee()); - } - for (ChatColor color : currentFormatting) { - switch (color) { - case BOLD: - replacement.setBold(true); - break; - case MAGIC: - replacement.setObfuscated(true); - break; - case ITALIC: - replacement.setItalic(true); - break; - case STRIKETHROUGH: - replacement.setStrikethrough(true); - break; - case UNDERLINE: - replacement.setUnderlined(true); - break; - } - } - results.add(replacement); - } - - currentColor = null; - } catch (NumberFormatException | IndexOutOfBoundsException ex) { - ILogger.forThisClass().warn("Invalid argument index '{}'", argument); - results.add(new TextComponent(String.valueOf(start))); - results.add(new TextComponent(String.valueOf(argument))); - results.add(new TextComponent(String.valueOf(end))); - } catch (Exception ex) { - throw new WrappedException(ex); - } - argument = new StringBuilder(); - continue; - } - if (c == start && !inArgument) { - inArgument = true; - continue; - } - if (inArgument) { - argument.append(c); - continue; - } - currentText = new TextComponent(currentText.getText() + c); - } - if (!currentText.getText().isEmpty()) { - results.add(currentText); - } - if (argument.length() > 0) { - results.add(new TextComponent(String.valueOf(start))); - results.add(new TextComponent(String.valueOf(argument))); - } - return results; - } - - public static Object[] replaceArguments(Object[] args, boolean toStrings) { - args = Arrays.copyOf(args, args.length); - for (int i = 0; i < args.length; i++) { - Object arg = args[i]; - - arg = arg instanceof Material ? getItemComponent((Material) arg) : - arg instanceof EntityType ? getEntityName((EntityType) arg) : - arg instanceof PotionEffectType ? getPotionEffectName((PotionEffectType) arg) : - arg instanceof Biome ? getBiomeName((Biome) arg) : - arg instanceof GameMode ? getGameModeName((GameMode) arg) : - arg instanceof Advancement ? getAdvancementComponent((Advancement) arg) : - arg instanceof LootTable ? getEntityName((LootTable) arg) : - arg instanceof Difficulty ? getDifficultyName((Difficulty) arg) : - arg; - - if (toStrings) { - if (arg instanceof BaseComponent) { - arg = ((BaseComponent) arg).toPlainText(); - } - } - args[i] = arg; - - } - return args; - } - - public static TranslatableComponent getItemName(@Nonnull Material material) { - NamespacedKey key = material.getKey(); - return new TranslatableComponent((material.isBlock() ? "block" : "item") + "." + key.getNamespace() + "." + key.getKey()); - } - - public static @Nullable BaseComponent getMusicDiscName(@Nonnull Material material) { - if (!material.name().startsWith("MUSIC_DISC")) return null; - String key = "item.minecraft." + material.name().toLowerCase() + ".desc"; - return new TranslatableComponent(key); - } - - public static BaseComponent getItemComponent(@Nonnull Material material) { - BaseComponent component = getItemName(material); - BaseComponent musicDiscName = getMusicDiscName(material); - if (musicDiscName != null) { - component.addExtra(" ("); - component.addExtra(musicDiscName); - component.addExtra(")"); - } - return component; - } - - - public static TranslatableComponent getEntityName(@Nonnull EntityType type) { - - String key; - String namespace = "minecraft"; - - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { - NamespacedKey namespacedKey = type.getKey(); - key = namespacedKey.getKey(); - namespace = namespacedKey.getNamespace(); - } else { - key = type.getName(); - } - - return new TranslatableComponent("entity." + namespace + "." + key); - } - - public static TranslatableComponent getEntityName(@Nonnull LootTable type) { - NamespacedKey key = type.getKey(); - return new TranslatableComponent("entity." + key.getNamespace() + "." + key.getKey().replace("entities/", "")); - } - - public static TranslatableComponent getPotionEffectName(@Nonnull PotionEffectType type) { - - String key; - String namespace = "minecraft"; - - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { - NamespacedKey namespacedKey = type.getKey(); - key = namespacedKey.getKey(); - namespace = namespacedKey.getNamespace(); - } else { - key = type.getName().toLowerCase(); - } - - - return new TranslatableComponent("effect." + namespace + "." + key); - } - - public static TranslatableComponent getBiomeName(@Nonnull Biome biome) { - String key; - String namespace = "minecraft"; - - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { - NamespacedKey namespacedKey = biome.getKey(); - key = namespacedKey.getKey(); - namespace = namespacedKey.getNamespace(); - } else { - key = biome.name().toLowerCase(); - } - - return new TranslatableComponent("biome." + namespace + "." + key); - } - - public static TranslatableComponent getGameModeName(@Nonnull GameMode gameMode) { - return new TranslatableComponent("selectWorld.gameMode." + gameMode.name().toLowerCase()); - } - - public static BaseComponent getAdvancementTitle(@Nonnull Advancement advancement) { - String replace = advancement.getKey().getKey().replace("/", "."); - return new TranslatableComponent("advancements." + correctAdvancementKeys(replace) + ".title"); - } - - public static BaseComponent getAdvancementDescription(@Nonnull Advancement advancement) { - String replace = advancement.getKey().getKey().replace("/", "."); - return new TranslatableComponent("advancements." + correctAdvancementKeys(replace) + ".description"); - } - - public static BaseComponent getAdvancementComponent(@Nonnull Advancement advancement) { - BaseComponent title = getAdvancementTitle(advancement); - BaseComponent description = getAdvancementDescription(advancement); - description.setColor(net.md_5.bungee.api.ChatColor.GREEN); - title.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(description).create())); - return title; - } - - private static String correctAdvancementKeys(String s) { - return s.replace("bred_all_animals", "breed_all_animals").replace("obtain_netherite_hoe", "netherite_hoe"); // mc sucks - } - - public static TranslatableComponent getDifficultyName(@Nonnull Difficulty difficulty) { - return new TranslatableComponent("options.difficulty." + difficulty.name().toLowerCase()); - } + @Nonnull + public static BaseComponent[] format(@Nullable Prefix prefix, @Nonnull String[] array, @Nonnull Object... args) { + List results = new ArrayList<>(); + for (String value : array) { + String s = value; + if (!s.trim().isEmpty() && prefix != null) { + s = prefix + s; + } + BaseComponent comp = null; + for (BaseComponent component : format(s, args)) { + if (comp == null) { + comp = component; + } else { + comp.addExtra(component); + } + } + results.add(comp); + } + return results.toArray(new BaseComponent[0]); + } + + @Nonnull + public static List format(@Nonnull String sequence, @Nonnull Object... args) { + + args = replaceArguments(args, false); + + List results = new ArrayList<>(); + char start = '{', end = '}'; + boolean inArgument = false; + + boolean lastWasParagraph = false; + ChatColor currentColor = null; + List currentFormatting = new LinkedList<>(); + + StringBuilder argument = new StringBuilder(); + TextComponent currentText = new TextComponent(); + for (char c : sequence.toCharArray()) { + + if (c == '§') { + lastWasParagraph = true; + } else { + if (lastWasParagraph) { + ChatColor newColor = ChatColor.getByChar(c); + assert newColor != null; + if (!newColor.isColor()) { + if (newColor == ChatColor.RESET) { + currentFormatting.clear(); + currentColor = null; + } else { + currentFormatting.add(newColor); + } + } else { + currentColor = newColor; + currentFormatting.clear(); + } + } + lastWasParagraph = false; + } + + if (c == end && inArgument) { + inArgument = false; + try { + int arg = Integer.parseInt(argument.toString()); + Object current = args[arg]; + BaseComponent replacement = + current instanceof BaseComponent ? (BaseComponent) current : + current instanceof Supplier ? new TextComponent(String.valueOf(((Supplier) current).get())) : + current instanceof Callable ? new TextComponent(String.valueOf(((Callable) current).call())) : + new TextComponent(String.valueOf(current)); + + if (replacement instanceof TextComponent) { + currentText.setText(currentText.getText() + ((TextComponent) replacement).getText()); + } else { + results.add(currentText); + currentText = new TextComponent(); + + if (currentColor != null && replacement.getColor() == net.md_5.bungee.api.ChatColor.WHITE) { + replacement.setColor(currentColor.asBungee()); + } + for (ChatColor color : currentFormatting) { + switch (color) { + case BOLD: + replacement.setBold(true); + break; + case MAGIC: + replacement.setObfuscated(true); + break; + case ITALIC: + replacement.setItalic(true); + break; + case STRIKETHROUGH: + replacement.setStrikethrough(true); + break; + case UNDERLINE: + replacement.setUnderlined(true); + break; + } + } + results.add(replacement); + } + + currentColor = null; + } catch (NumberFormatException | IndexOutOfBoundsException ex) { + ILogger.forThisClass().warn("Invalid argument index '{}'", argument); + results.add(new TextComponent(String.valueOf(start))); + results.add(new TextComponent(String.valueOf(argument))); + results.add(new TextComponent(String.valueOf(end))); + } catch (Exception ex) { + throw new WrappedException(ex); + } + argument = new StringBuilder(); + continue; + } + if (c == start && !inArgument) { + inArgument = true; + continue; + } + if (inArgument) { + argument.append(c); + continue; + } + currentText = new TextComponent(currentText.getText() + c); + } + if (!currentText.getText().isEmpty()) { + results.add(currentText); + } + if (argument.length() > 0) { + results.add(new TextComponent(String.valueOf(start))); + results.add(new TextComponent(String.valueOf(argument))); + } + return results; + } + + public static Object[] replaceArguments(Object[] args, boolean toStrings) { + args = Arrays.copyOf(args, args.length); + for (int i = 0; i < args.length; i++) { + Object arg = args[i]; + + arg = arg instanceof Material ? getItemComponent((Material) arg) : + arg instanceof EntityType ? getEntityName((EntityType) arg) : + arg instanceof PotionEffectType ? getPotionEffectName((PotionEffectType) arg) : + arg instanceof Biome ? getBiomeName((Biome) arg) : + arg instanceof GameMode ? getGameModeName((GameMode) arg) : + arg instanceof Advancement ? getAdvancementComponent((Advancement) arg) : + arg instanceof LootTable ? getEntityName((LootTable) arg) : + arg instanceof Difficulty ? getDifficultyName((Difficulty) arg) : + arg; + + if (toStrings) { + if (arg instanceof BaseComponent) { + arg = ((BaseComponent) arg).toPlainText(); + } + } + args[i] = arg; + + } + return args; + } + + public static TranslatableComponent getItemName(@Nonnull Material material) { + NamespacedKey key = material.getKey(); + return new TranslatableComponent((material.isBlock() ? "block" : "item") + "." + key.getNamespace() + "." + key.getKey()); + } + + public static @Nullable BaseComponent getMusicDiscName(@Nonnull Material material) { + if (!material.name().startsWith("MUSIC_DISC")) return null; + String key = "item.minecraft." + material.name().toLowerCase() + ".desc"; + return new TranslatableComponent(key); + } + + public static BaseComponent getItemComponent(@Nonnull Material material) { + BaseComponent component = getItemName(material); + BaseComponent musicDiscName = getMusicDiscName(material); + if (musicDiscName != null) { + component.addExtra(" ("); + component.addExtra(musicDiscName); + component.addExtra(")"); + } + return component; + } + + + public static TranslatableComponent getEntityName(@Nonnull EntityType type) { + + String key; + String namespace = "minecraft"; + + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { + NamespacedKey namespacedKey = type.getKey(); + key = namespacedKey.getKey(); + namespace = namespacedKey.getNamespace(); + } else { + key = type.getName(); + } + + return new TranslatableComponent("entity." + namespace + "." + key); + } + + public static TranslatableComponent getEntityName(@Nonnull LootTable type) { + NamespacedKey key = type.getKey(); + return new TranslatableComponent("entity." + key.getNamespace() + "." + key.getKey().replace("entities/", "")); + } + + public static TranslatableComponent getPotionEffectName(@Nonnull PotionEffectType type) { + + String key; + String namespace = "minecraft"; + + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { + NamespacedKey namespacedKey = type.getKey(); + key = namespacedKey.getKey(); + namespace = namespacedKey.getNamespace(); + } else { + key = type.getName().toLowerCase(); + } + + + return new TranslatableComponent("effect." + namespace + "." + key); + } + + public static TranslatableComponent getBiomeName(@Nonnull Biome biome) { + String key; + String namespace = "minecraft"; + + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_14)) { + NamespacedKey namespacedKey = biome.getKey(); + key = namespacedKey.getKey(); + namespace = namespacedKey.getNamespace(); + } else { + key = biome.name().toLowerCase(); + } + + return new TranslatableComponent("biome." + namespace + "." + key); + } + + public static TranslatableComponent getGameModeName(@Nonnull GameMode gameMode) { + return new TranslatableComponent("selectWorld.gameMode." + gameMode.name().toLowerCase()); + } + + public static BaseComponent getAdvancementTitle(@Nonnull Advancement advancement) { + String replace = advancement.getKey().getKey().replace("/", "."); + return new TranslatableComponent("advancements." + correctAdvancementKeys(replace) + ".title"); + } + + public static BaseComponent getAdvancementDescription(@Nonnull Advancement advancement) { + String replace = advancement.getKey().getKey().replace("/", "."); + return new TranslatableComponent("advancements." + correctAdvancementKeys(replace) + ".description"); + } + + public static BaseComponent getAdvancementComponent(@Nonnull Advancement advancement) { + BaseComponent title = getAdvancementTitle(advancement); + BaseComponent description = getAdvancementDescription(advancement); + description.setColor(net.md_5.bungee.api.ChatColor.GREEN); + title.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(description).create())); + return title; + } + + private static String correctAdvancementKeys(String s) { + return s.replace("bred_all_animals", "breed_all_animals").replace("obtain_netherite_hoe", "netherite_hoe"); // mc sucks + } + + public static TranslatableComponent getDifficultyName(@Nonnull Difficulty difficulty) { + return new TranslatableComponent("options.difficulty." + difficulty.name().toLowerCase()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java index c40302d9d..65c5b4e43 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java @@ -7,108 +7,108 @@ public enum MinecraftVersion implements Version { - V1_0, // 1.0 - V1_1, // 1.1 - V1_2_1, // 1.2.1 - V1_3_1, // 1.3.1 - V1_4_2, // 1.4.2 - V1_5, // 1.5 - V1_6, // 1.6 - V1_7, // 1.7 - V1_7_2, // 1.7.2 - V1_8, // 1.8 - V1_9, // 1.9 - V1_10, // 1.10 - V1_11, // 1.11 - V1_12, // 1.12 - V1_13, // 1.13 - V1_14, // 1.14 - V1_15, // 1.15 - V1_16, // 1.16 - V1_16_5, // 1.16.5 - V1_17, // 1.17 - V1_18, // 1.18 - V1_19, // 1.19 - V1_20, // 1.20 - V1_20_1, // 1.20.1 - V1_20_2, // 1.20.2 - V1_20_3, // 1.20.3 - V1_20_4, // 1.20.4 - V1_20_5, // 1.20.5 - V1_21, // 1.21 - V1_21_1, // 1.21.1 - V1_21_2, // 1.21.2 - V1_21_3, // 1.21.3 - V1_21_4, // 1.21.4 - V1_21_5 // 1.21.5 - ; - - private final int major, minor, revision; - - MinecraftVersion() { - - String name = this.name().substring(1); - String[] version = name.split("_"); - - if (version.length != 2 && version.length != 3) - throw new IllegalArgumentException("Name '" + name() + "' does not match pattern: V{major}_{minor}_[revision]"); - - major = Integer.parseInt(version[0]); - minor = Integer.parseInt(version[1]); - revision = version.length > 2 ? Integer.parseInt(version[2]) : 0; - - } - - @Override - public int getMajor() { - return major; - } - - @Override - public int getMinor() { - return minor; - } - - @Override - public int getRevision() { - return revision; - } - - @Override - public String toString() { - return this.format(); - } - - @Nonnull - @CheckReturnValue - public static Version parseExact(@Nonnull String bukkitVersion) { - bukkitVersion = bukkitVersion.substring(0, bukkitVersion.indexOf("-")); - return Version.parse(bukkitVersion); - } - - @Nonnull - @CheckReturnValue - public static Version findNearest(@Nonnull Version realVersion) { - return Version.findNearest(realVersion, values()); - } - - private static Version currentExact; - private static Version current; - - @Nonnull - @CheckReturnValue - public static Version currentExact() { - if (currentExact == null) - currentExact = parseExact(Bukkit.getBukkitVersion()); - return currentExact; - } - - @Nonnull - @CheckReturnValue - public static Version current() { - if (current == null) - current = findNearest(currentExact()); - return current; - } + V1_0, // 1.0 + V1_1, // 1.1 + V1_2_1, // 1.2.1 + V1_3_1, // 1.3.1 + V1_4_2, // 1.4.2 + V1_5, // 1.5 + V1_6, // 1.6 + V1_7, // 1.7 + V1_7_2, // 1.7.2 + V1_8, // 1.8 + V1_9, // 1.9 + V1_10, // 1.10 + V1_11, // 1.11 + V1_12, // 1.12 + V1_13, // 1.13 + V1_14, // 1.14 + V1_15, // 1.15 + V1_16, // 1.16 + V1_16_5, // 1.16.5 + V1_17, // 1.17 + V1_18, // 1.18 + V1_19, // 1.19 + V1_20, // 1.20 + V1_20_1, // 1.20.1 + V1_20_2, // 1.20.2 + V1_20_3, // 1.20.3 + V1_20_4, // 1.20.4 + V1_20_5, // 1.20.5 + V1_21, // 1.21 + V1_21_1, // 1.21.1 + V1_21_2, // 1.21.2 + V1_21_3, // 1.21.3 + V1_21_4, // 1.21.4 + V1_21_5 // 1.21.5 + ; + + private final int major, minor, revision; + + MinecraftVersion() { + + String name = this.name().substring(1); + String[] version = name.split("_"); + + if (version.length != 2 && version.length != 3) + throw new IllegalArgumentException("Name '" + name() + "' does not match pattern: V{major}_{minor}_[revision]"); + + major = Integer.parseInt(version[0]); + minor = Integer.parseInt(version[1]); + revision = version.length > 2 ? Integer.parseInt(version[2]) : 0; + + } + + @Override + public int getMajor() { + return major; + } + + @Override + public int getMinor() { + return minor; + } + + @Override + public int getRevision() { + return revision; + } + + @Override + public String toString() { + return this.format(); + } + + @Nonnull + @CheckReturnValue + public static Version parseExact(@Nonnull String bukkitVersion) { + bukkitVersion = bukkitVersion.substring(0, bukkitVersion.indexOf("-")); + return Version.parse(bukkitVersion); + } + + @Nonnull + @CheckReturnValue + public static Version findNearest(@Nonnull Version realVersion) { + return Version.findNearest(realVersion, values()); + } + + private static Version currentExact; + private static Version current; + + @Nonnull + @CheckReturnValue + public static Version currentExact() { + if (currentExact == null) + currentExact = parseExact(Bukkit.getBukkitVersion()); + return currentExact; + } + + @Nonnull + @CheckReturnValue + public static Version current() { + if (current == null) + current = findNearest(currentExact()); + return current; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java index b7918391b..17f4ddeae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java @@ -1,108 +1,105 @@ package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; +import net.anweisen.utilities.common.annotations.Since; + import javax.annotation.CheckReturnValue; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import net.anweisen.utilities.common.annotations.Since; +import java.util.*; public interface Version { - @Nonnegative - int getMajor(); - - @Nonnegative - int getMinor(); - - @Nonnegative - int getRevision(); - - default boolean isNewerThan(@Nonnull Version other) { - return this.intValue() > other.intValue(); + @Nonnegative + int getMajor(); + + @Nonnegative + int getMinor(); + + @Nonnegative + int getRevision(); + + default boolean isNewerThan(@Nonnull Version other) { + return this.intValue() > other.intValue(); + } + + default boolean isNewerOrEqualThan(@Nonnull Version other) { + return this.intValue() >= other.intValue(); + } + + default boolean isOlderThan(@Nonnull Version other) { + return this.intValue() < other.intValue(); + } + + default boolean isOlderOrEqualThan(@Nonnull Version other) { + return this.intValue() <= other.intValue(); + } + + default boolean equals(@Nonnull Version other) { + return this.intValue() == other.intValue(); + } + + @Nonnull + default String format() { + int revision = this.getRevision(); + return revision > 0 ? String.format("%s.%s.%s", this.getMajor(), this.getMinor(), revision) : String.format("%s.%s", this.getMajor(), this.getMinor()); + } + + default int intValue() { + int major = this.getMajor(); + int minor = this.getMinor(); + int revision = this.getRevision(); + if (major > 99) { + throw new IllegalStateException("Malformed version: major is greater than 99"); + } else if (minor > 99) { + throw new IllegalStateException("Malformed version: minor is greater than 99"); + } else if (revision > 99) { + throw new IllegalStateException("Malformed version: revision is greater than 99"); + } else { + return revision + minor * 100 + major * 10000; } - - default boolean isNewerOrEqualThan(@Nonnull Version other) { - return this.intValue() >= other.intValue(); + } + + @Nonnull + @CheckReturnValue + static Version parse(@Nullable String input) { + return parse(input, new VersionInfo(1, 0, 0)); + } + + @CheckReturnValue + static Version parse(@Nullable String input, Version def) { + return VersionInfo.parse(input, def); + } + + @Nonnull + @CheckReturnValue + static Version parseExceptionally(@Nullable String input) { + return VersionInfo.parseExceptionally(input); + } + + @Nonnull + @CheckReturnValue + static Version getAnnotatedSince(@Nonnull Object object) { + return (Version) (!object.getClass().isAnnotationPresent(Since.class) ? new VersionInfo(1, 0, 0) : parse(object.getClass().getAnnotation(Since.class).value())); + } + + @Nonnull + @CheckReturnValue + static V findNearest(@Nonnull Version target, @Nonnull V[] sortedVersionsArray) { + List versions = new ArrayList(Arrays.asList(sortedVersionsArray)); + Collections.reverse(versions); + + for (V version : versions) { + if (!version.isNewerThan(target)) { + return version; + } } - default boolean isOlderThan(@Nonnull Version other) { - return this.intValue() < other.intValue(); - } + throw new IllegalArgumentException("No version found for '" + target + "'"); + } - default boolean isOlderOrEqualThan(@Nonnull Version other) { - return this.intValue() <= other.intValue(); - } - - default boolean equals(@Nonnull Version other) { - return this.intValue() == other.intValue(); - } - - @Nonnull - default String format() { - int revision = this.getRevision(); - return revision > 0 ? String.format("%s.%s.%s", this.getMajor(), this.getMinor(), revision) : String.format("%s.%s", this.getMajor(), this.getMinor()); - } - - default int intValue() { - int major = this.getMajor(); - int minor = this.getMinor(); - int revision = this.getRevision(); - if (major > 99) { - throw new IllegalStateException("Malformed version: major is greater than 99"); - } else if (minor > 99) { - throw new IllegalStateException("Malformed version: minor is greater than 99"); - } else if (revision > 99) { - throw new IllegalStateException("Malformed version: revision is greater than 99"); - } else { - return revision + minor * 100 + major * 10000; - } - } - - @Nonnull - @CheckReturnValue - static Version parse(@Nullable String input) { - return parse(input, new VersionInfo(1, 0, 0)); - } - - @CheckReturnValue - static Version parse(@Nullable String input, Version def) { - return VersionInfo.parse(input, def); - } - - @Nonnull - @CheckReturnValue - static Version parseExceptionally(@Nullable String input) { - return VersionInfo.parseExceptionally(input); - } - - @Nonnull - @CheckReturnValue - static Version getAnnotatedSince(@Nonnull Object object) { - return (Version)(!object.getClass().isAnnotationPresent(Since.class) ? new VersionInfo(1, 0, 0) : parse(object.getClass().getAnnotation(Since.class).value())); - } - - @Nonnull - @CheckReturnValue - static V findNearest(@Nonnull Version target, @Nonnull V[] sortedVersionsArray) { - List versions = new ArrayList(Arrays.asList(sortedVersionsArray)); - Collections.reverse(versions); - - for(V version : versions) { - if (!version.isNewerThan(target)) { - return version; - } - } - - throw new IllegalArgumentException("No version found for '" + target + "'"); - } - - @Nonnull - @CheckReturnValue - static Comparator comparator() { - return new VersionComparator(); - } + @Nonnull + @CheckReturnValue + static Comparator comparator() { + return new VersionComparator(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java index 4c856af7a..93cc33322 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; -import java.util.Comparator; import javax.annotation.Nonnull; +import java.util.Comparator; public class VersionComparator implements Comparator { - public VersionComparator() { - } + public VersionComparator() { + } - public int compare(@Nonnull Version v1, @Nonnull Version v2) { - return v1.equals(v2) ? 0 : (v1.isNewerThan(v2) ? 1 : -1); - } + public int compare(@Nonnull Version v1, @Nonnull Version v2) { + return v1.equals(v2) ? 0 : (v1.isNewerThan(v2) ? 1 : -1); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java index 1564993bd..3bd2f5b33 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java @@ -1,70 +1,70 @@ package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; -import java.util.Objects; -import javax.annotation.Nullable; - import lombok.Getter; import net.anweisen.utilities.common.logging.ILogger; +import javax.annotation.Nullable; +import java.util.Objects; + @Getter public class VersionInfo implements Version { - protected static final ILogger logger = ILogger.forThisClass(); - private final int major; - private final int minor; - private final int revision; - - public VersionInfo() { - this(1, 0, 0); - } + protected static final ILogger logger = ILogger.forThisClass(); + private final int major; + private final int minor; + private final int revision; - public VersionInfo(int major, int minor, int revision) { - this.major = major; - this.minor = minor; - this.revision = revision; - } + public VersionInfo() { + this(1, 0, 0); + } - public boolean equals(Object other) { - if (this == other) { - return true; - } else { - return other instanceof Version && this.equals(other); - } - } + public VersionInfo(int major, int minor, int revision) { + this.major = major; + this.minor = minor; + this.revision = revision; + } - public int hashCode() { - return Objects.hash(this.major, this.minor, this.revision); + public boolean equals(Object other) { + if (this == other) { + return true; + } else { + return other instanceof Version && this.equals(other); } + } - public String toString() { - return this.format(); - } + public int hashCode() { + return Objects.hash(this.major, this.minor, this.revision); + } - public static Version parseExceptionally(@Nullable String input) { - if (input == null) { - throw new IllegalArgumentException("Version cannot be null"); - } else { - String[] array = input.split("\\."); - if (array.length == 0) { - throw new IllegalArgumentException("Version cannot be empty"); - } else { - try { - int major = Integer.parseInt(array[0]); - int minor = array.length >= 2 ? Integer.parseInt(array[1]) : 0; - int revision = array.length >= 3 ? Integer.parseInt(array[2]) : 0; - return new VersionInfo(major, minor, revision); - } catch (Exception ex) { - throw new IllegalArgumentException("Cannot parse Version: " + input + " (" + ex.getMessage() + ")"); - } - } - } - } + public String toString() { + return this.format(); + } - public static Version parse(@Nullable String input, Version def) { + public static Version parseExceptionally(@Nullable String input) { + if (input == null) { + throw new IllegalArgumentException("Version cannot be null"); + } else { + String[] array = input.split("\\."); + if (array.length == 0) { + throw new IllegalArgumentException("Version cannot be empty"); + } else { try { - return parseExceptionally(input); + int major = Integer.parseInt(array[0]); + int minor = array.length >= 2 ? Integer.parseInt(array[1]) : 0; + int revision = array.length >= 3 ? Integer.parseInt(array[2]) : 0; + return new VersionInfo(major, minor, revision); } catch (Exception ex) { - logger.error("Could not parse version for input {}", ex.getMessage()); - return def; + throw new IllegalArgumentException("Cannot parse Version: " + input + " (" + ex.getMessage() + ")"); } + } + } + } + + public static Version parse(@Nullable String input, Version def) { + try { + return parseExceptionally(input); + } catch (Exception ex) { + logger.error("Could not parse version for input {}", ex.getMessage()); + return def; } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java index 07bc07991..66995d593 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java @@ -15,105 +15,109 @@ public class NMSProvider { - private final static int majorVersion; - /** - * -- GETTER -- - * - * @return A border packet factory - * - */ - @Getter - private static final BorderPacketFactory borderPacketFactory; + private final static int majorVersion; + /** + * -- GETTER -- + * + * @return A border packet factory + */ + @Getter + private static final BorderPacketFactory borderPacketFactory; - static { - majorVersion = ReflectionUtil.getMajorVersion(); - if (versionIsAtLeast(17)) { - borderPacketFactory = new BorderPacketFactory_1_17(); - } else if (versionIsAtLeast(13)) { - borderPacketFactory = new BorderPacketFactory_1_13(); - } else { - throw new IllegalStateException("Could not find a BorderPacketFactory implementation for version " + getFormattedVersion()); - } + static { + majorVersion = ReflectionUtil.getMajorVersion(); + if (versionIsAtLeast(17)) { + borderPacketFactory = new BorderPacketFactory_1_17(); + } else if (versionIsAtLeast(13)) { + borderPacketFactory = new BorderPacketFactory_1_13(); + } else { + throw new IllegalStateException("Could not find a BorderPacketFactory implementation for version " + getFormattedVersion()); } + } - /** - * Creates a world server for the given world - * @param world The world - * @return The world server - * @throws IllegalStateException If no implementation was found for the current version - */ - public static WorldServer createWorldServer(World world) { - try { - if (versionIsAtLeast(13)) { - return new WorldServer_1_13(world); - } - } catch (ClassNotFoundException exception) { - Challenges.getInstance().getLogger().error("Failed to create WorldServer instance for version {}:", majorVersion, exception); - } - throw new IllegalStateException("Could not find a WorldServer implementation for version " + getFormattedVersion()); + /** + * Creates a world server for the given world + * + * @param world The world + * @return The world server + * @throws IllegalStateException If no implementation was found for the current version + */ + public static WorldServer createWorldServer(World world) { + try { + if (versionIsAtLeast(13)) { + return new WorldServer_1_13(world); + } + } catch (ClassNotFoundException exception) { + Challenges.getInstance().getLogger().error("Failed to create WorldServer instance for version {}:", majorVersion, exception); } + throw new IllegalStateException("Could not find a WorldServer implementation for version " + getFormattedVersion()); + } - /** - * Creates a craft player for the given player - * @param player The player - * @return The craft player - * @throws IllegalStateException If no implementation was found for the current version - */ - public static CraftPlayer createCraftPlayer(Player player) { - try { - if (versionIsAtLeast(17)) { - return new CraftPlayer_1_17(player); - } else if (versionIsAtLeast(13)) { - return new CraftPlayer_1_13(player); - } - } catch (ClassNotFoundException exception) { - Challenges.getInstance().getLogger().error("Failed to create CraftPlayer instance for version {}:", majorVersion, exception); - } - throw new IllegalStateException("Could not find a CraftServer implementation for version " + getFormattedVersion()); + /** + * Creates a craft player for the given player + * + * @param player The player + * @return The craft player + * @throws IllegalStateException If no implementation was found for the current version + */ + public static CraftPlayer createCraftPlayer(Player player) { + try { + if (versionIsAtLeast(17)) { + return new CraftPlayer_1_17(player); + } else if (versionIsAtLeast(13)) { + return new CraftPlayer_1_13(player); + } + } catch (ClassNotFoundException exception) { + Challenges.getInstance().getLogger().error("Failed to create CraftPlayer instance for version {}:", majorVersion, exception); } + throw new IllegalStateException("Could not find a CraftServer implementation for version " + getFormattedVersion()); + } - /** - * Creates a player connection for the given CraftPlayer - * @param player The CraftPlayer - * @return The player connection - * @throws IllegalStateException If no implementation was found for the current version - */ - public static PlayerConnection createPlayerConnection(CraftPlayer player) { - try { - if (versionIsAtLeast(18)) { - return new PlayerConnection_1_18(player.getPlayerConnectionObject()); - } else if (versionIsAtLeast(13)) { - return new PlayerConnection_1_13(player.getPlayerConnectionObject()); - } - } catch (ClassNotFoundException exception) { - Challenges.getInstance().getLogger().error("Failed to create PlayerConnection instance for version {}:", majorVersion, exception); - } - - throw new IllegalStateException("Could not find a PlayerConnection implementation for version " + getFormattedVersion()); + /** + * Creates a player connection for the given CraftPlayer + * + * @param player The CraftPlayer + * @return The player connection + * @throws IllegalStateException If no implementation was found for the current version + */ + public static PlayerConnection createPlayerConnection(CraftPlayer player) { + try { + if (versionIsAtLeast(18)) { + return new PlayerConnection_1_18(player.getPlayerConnectionObject()); + } else if (versionIsAtLeast(13)) { + return new PlayerConnection_1_13(player.getPlayerConnectionObject()); + } + } catch (ClassNotFoundException exception) { + Challenges.getInstance().getLogger().error("Failed to create PlayerConnection instance for version {}:", majorVersion, exception); } - /** Creates a packet border for the given world - * @param world The world - * @return The packet border - * @throws IllegalStateException If no implementation was found for the current version - */ - public static PacketBorder createPacketBorder(World world) { - if (versionIsAtLeast(18)) { - return new PacketBorder_1_18(world); - } else if (versionIsAtLeast(17)) { - return new PacketBorder_1_17(world); - } else if (versionIsAtLeast(13)) { - return new PacketBorder_1_13(world); - } - throw new IllegalStateException("Could not find a PacketBorder implementation for version " + getFormattedVersion()); - } + throw new IllegalStateException("Could not find a PlayerConnection implementation for version " + getFormattedVersion()); + } - private static boolean versionIsAtLeast(int majorVersion) { - return NMSProvider.majorVersion >= majorVersion; + /** + * Creates a packet border for the given world + * + * @param world The world + * @return The packet border + * @throws IllegalStateException If no implementation was found for the current version + */ + public static PacketBorder createPacketBorder(World world) { + if (versionIsAtLeast(18)) { + return new PacketBorder_1_18(world); + } else if (versionIsAtLeast(17)) { + return new PacketBorder_1_17(world); + } else if (versionIsAtLeast(13)) { + return new PacketBorder_1_13(world); } + throw new IllegalStateException("Could not find a PacketBorder implementation for version " + getFormattedVersion()); + } - private static String getFormattedVersion() { - return MinecraftVersion.current().format(); - } + private static boolean versionIsAtLeast(int majorVersion) { + return NMSProvider.majorVersion >= majorVersion; + } + + private static String getFormattedVersion() { + return MinecraftVersion.current().format(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java index ca81f2938..ec89489cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java @@ -8,64 +8,64 @@ public final class NMSUtils { - public static void setEntityName(Entity entity, BaseComponent baseComponent) { - String json = ComponentSerializer.toString(baseComponent); + public static void setEntityName(Entity entity, BaseComponent baseComponent) { + String json = ComponentSerializer.toString(baseComponent); - try { - Class componentClass = getClass("network.chat.IChatBaseComponent"); - Class componentSerializerClass = getClass("network.chat.IChatBaseComponent$ChatSerializer"); - Object componentObject = ReflectionUtil.invokeMethod(componentSerializerClass, null, "a", new Class[]{String.class}, new Object[]{json}); - Class entityClass = getClass("world.entity.Entity"); - Class craftEntityClass = ReflectionUtil.getBukkitClass("entity.CraftEntity"); - Object entityObject = ReflectionUtil.invokeMethod(craftEntityClass, entity, "getHandle"); - ReflectionUtil.invokeMethod(entityClass, entityObject, "a", new Class[]{ componentClass }, new Object[]{componentObject}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); - } + try { + Class componentClass = getClass("network.chat.IChatBaseComponent"); + Class componentSerializerClass = getClass("network.chat.IChatBaseComponent$ChatSerializer"); + Object componentObject = ReflectionUtil.invokeMethod(componentSerializerClass, null, "a", new Class[]{String.class}, new Object[]{json}); + Class entityClass = getClass("world.entity.Entity"); + Class craftEntityClass = ReflectionUtil.getBukkitClass("entity.CraftEntity"); + Object entityObject = ReflectionUtil.invokeMethod(craftEntityClass, entity, "getHandle"); + ReflectionUtil.invokeMethod(entityClass, entityObject, "a", new Class[]{componentClass}, new Object[]{componentObject}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("", exception); } + } - public static void setBossBarTitle(BossBar bossBar, BaseComponent baseComponent) { - Object component = toIChatBaseComponent(baseComponent); - - try { - Class bossBattleClass = getClass("world.BossBattle"); - Class craftBossBarClass = ReflectionUtil.getBukkitClass("boss.CraftBossBar"); - Object bossBattleObject = ReflectionUtil.invokeMethod(craftBossBarClass, bossBar, "getHandle"); - ReflectionUtil.invokeMethod(bossBattleClass, bossBattleObject, "a", new Class[]{ getComponentClass() }, new Object[]{component}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); - } + public static void setBossBarTitle(BossBar bossBar, BaseComponent baseComponent) { + Object component = toIChatBaseComponent(baseComponent); + try { + Class bossBattleClass = getClass("world.BossBattle"); + Class craftBossBarClass = ReflectionUtil.getBukkitClass("boss.CraftBossBar"); + Object bossBattleObject = ReflectionUtil.invokeMethod(craftBossBarClass, bossBar, "getHandle"); + ReflectionUtil.invokeMethod(bossBattleClass, bossBattleObject, "a", new Class[]{getComponentClass()}, new Object[]{component}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("", exception); } - public static Object toIChatBaseComponent(BaseComponent baseComponent) { - String json = ComponentSerializer.toString(baseComponent); - try { - Class componentSerializerClass = getClass("network.chat.IChatBaseComponent$ChatSerializer"); - return ReflectionUtil.invokeMethod(componentSerializerClass, null, "a", new Class[]{String.class}, new Object[]{json}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); - } - return null; - } + } - public static Class getComponentClass() { - return getClass("network.chat.IChatBaseComponent"); + public static Object toIChatBaseComponent(BaseComponent baseComponent) { + String json = ComponentSerializer.toString(baseComponent); + try { + Class componentSerializerClass = getClass("network.chat.IChatBaseComponent$ChatSerializer"); + return ReflectionUtil.invokeMethod(componentSerializerClass, null, "a", new Class[]{String.class}, new Object[]{json}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("", exception); } + return null; + } - public static Class getClass(String path) { - try { - if (ReflectionUtil.isUseNewSpigotPackaging()) { - return ReflectionUtil.getMinecraftClass(path); - } else { - String[] split = path.split("\\."); - String className = split.length == 1 ? path : split[split.length - 1]; - return ReflectionUtil.getNmsClass(className); - } - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); - } - return null; + public static Class getComponentClass() { + return getClass("network.chat.IChatBaseComponent"); + } + + public static Class getClass(String path) { + try { + if (ReflectionUtil.isUseNewSpigotPackaging()) { + return ReflectionUtil.getMinecraftClass(path); + } else { + String[] split = path.split("\\."); + String className = split.length == 1 ? path : split[split.length - 1]; + return ReflectionUtil.getNmsClass(className); + } + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("", exception); } - + return null; + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java index d0415f66a..e3aa8212c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java @@ -1,454 +1,450 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.StringJoiner; -import java.util.regex.Pattern; import lombok.Getter; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.Bukkit; +import java.lang.reflect.*; +import java.util.StringJoiner; +import java.util.regex.Pattern; + /** * @author TobiasDeBruijn | .* @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil + * ">* @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil */ public class ReflectionUtil { - public static String SERVER_VERSION; + public static String SERVER_VERSION; /** * -- GETTER -- - * Check if the new way of packaging Spigot is used
- * For >=1.17 this will be true, for =<1.16 this will be false.
- *

- * This dictates if you should use - * (<=1.16) or - * (>=1.17). - * + * Check if the new way of packaging Spigot is used
+ * For >=1.17 this will be true, for =<1.16 this will be false.
+ *

+ * This dictates if you should use + * (<=1.16) or + * (>=1.17). */ @Getter private static boolean useNewSpigotPackaging; /** * -- GETTER -- - * Get the current major Minecraft version. - *

- * E.g for Minecraft 1.18 this is 18. - * + * Get the current major Minecraft version. + *

+ * E.g for Minecraft 1.18 this is 18. */ @Getter private static int majorVersion; /** * -- GETTER -- - * Get the current minor Minecraft version. - *

- * E.g. for Minecraft 1.18.2 this is 2. - * + * Get the current minor Minecraft version. + *

+ * E.g. for Minecraft 1.18.2 this is 2. */ @Getter private static int minorVersion; - static { - try { - // Legacy support - Class bukkitClass = Class.forName("org.bukkit.Bukkit"); - Object serverObject = getMethod(bukkitClass, "getServer").invoke(null); - String serverPackageName = serverObject.getClass().getPackage().getName(); + static { + try { + // Legacy support + Class bukkitClass = Class.forName("org.bukkit.Bukkit"); + Object serverObject = getMethod(bukkitClass, "getServer").invoke(null); + String serverPackageName = serverObject.getClass().getPackage().getName(); + + SERVER_VERSION = serverPackageName.substring(serverPackageName.lastIndexOf('.') + 1); + + // example: Bukkit version: 3638-Spigot-d90018e-7dcb59b (MC: 1.19.3) + String version = Bukkit.getVersion(); + + String[] parts = version.split(Pattern.quote("(MC: ")); + String[] versionParts = parts[1].split(Pattern.quote(".")); + + // There's a minor version + String major, minor; + if (versionParts.length > 2) { + major = versionParts[1]; + minor = versionParts[2].replace(")", ""); + } else { + major = versionParts[1].replace(")", ""); + minor = "0"; + } + + majorVersion = Integer.parseInt(major); + minorVersion = Integer.parseInt(minor); + + useNewSpigotPackaging = majorVersion >= 17; + + } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | + NoSuchMethodException e) { + Challenges.getInstance().getLogger().error("Failed to initialize the ReflectionUtil:", e); + } + } + + /** + * Get a Class from the org.bukkit.craftbukkit.SERVER_VERSION. package + * + * @param className The name of the class + * @return Returns the Class + * @throws ClassNotFoundException Thrown when the Class was not found + */ + public static Class getBukkitClass(String className) throws ClassNotFoundException { + return Class.forName("org.bukkit.craftbukkit." + SERVER_VERSION + "." + className); + } + + /** + * 1.16 and older only + *

+ * Get a Class from the net.minecraft.server.SERVER_VERSION. package + * + * @param className The name of the class + * @return Returns the Class + * @throws ClassNotFoundException Thrown when the Class was not found + */ + @Deprecated + public static Class getNmsClass(String className) throws ClassNotFoundException { + return Class.forName("net.minecraft.server." + SERVER_VERSION + "." + className); + } + + /** + * 1.17 and newer only + *

+ * Get a Class from the net.minecraft package + * + * @param className The name of the class + * @return Returns the class + * @throws ClassNotFoundException Thrown when the Class was not found + */ + public static Class getMinecraftClass(String className) throws ClassNotFoundException { + return Class.forName("net.minecraft." + className); + } + + /** + * Get the Constructor of a Class + * + * @param clazz The Class in which the Constructor is defined + * @param args Arguments taken by the Constructor + * @return Returns the Constructor + * @throws NoSuchMethodException Thrown when no Constructor in the Class was found with the provided combination of arguments + */ + public static Constructor getConstructor(Class clazz, Class... args) throws NoSuchMethodException { + Constructor con = clazz.getConstructor(args); + con.setAccessible(true); - SERVER_VERSION = serverPackageName.substring(serverPackageName.lastIndexOf('.') + 1); + return con; + } - // example: Bukkit version: 3638-Spigot-d90018e-7dcb59b (MC: 1.19.3) - String version = Bukkit.getVersion(); + /** + * Get an Enum from an Enum constant + * + * @param clazz The Class in which the Enum is defined + * @param constant The name of the Enum Constant + * @return Returns the Enum or null if the Enum does not have a member called constant + */ + public static Enum getEnum(Class clazz, String constant) { + Enum[] constants = (Enum[]) clazz.getEnumConstants(); - String[] parts = version.split(Pattern.quote("(MC: ")); - String[] versionParts = parts[1].split(Pattern.quote(".")); + for (Enum e : constants) { + if (e.name().equalsIgnoreCase(constant)) { + return e; + } + } - // There's a minor version - String major, minor; - if(versionParts.length > 2) { - major = versionParts[1]; - minor = versionParts[2].replace(")", ""); - } else { - major = versionParts[1].replace(")", ""); - minor = "0"; - } + return null; + } - majorVersion = Integer.parseInt(major); - minorVersion = Integer.parseInt(minor); + /** + * Get an Enum constant by it's name and constant + * + * @param clazz The Class in which the Enum is defined + * @param enumname The name of the Enum + * @param constant The name of the Constant + * @return Returns the Enum or null if the Enum does not have a member called constant + * @throws ClassNotFoundException If the Class does not have an Enum called enumname + */ + public static Enum getEnum(Class clazz, String enumname, String constant) throws ClassNotFoundException { + Class c = Class.forName(clazz.getName() + "$" + enumname); + return getEnum(c, constant); + } - useNewSpigotPackaging = majorVersion >= 17; + /** + * Get a Field + * + * @param clazz The Class in which the Field is defined + * @param fieldName The name of the Field + * @return Returns the Field + * @throws NoSuchFieldException Thrown when the Field was not present in the Class + */ + public static Field getField(Class clazz, String fieldName) throws NoSuchFieldException { + Field f = clazz.getDeclaredField(fieldName); + f.setAccessible(true); + return f; + } + + /** + * Sets the value of a field + * + * @param instance The instance of the class in which the field is defined + * @param fieldName The name of the field + * @param value The value the field should be set to + */ + public static void setFieldValue(Object instance, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { + Field field = instance.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + field.set(instance, value); + } - } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) { - Challenges.getInstance().getLogger().error("Failed to initialize the ReflectionUtil:", e); - } - } + /** + * Get a Method + * + * @param clazz The Class in which the Method is defined + * @param methodName The name of the method + * @param args The argument types the method takes + * @return Returns the Method + */ + public static Method getMethod(Class clazz, String methodName, Class... args) throws NoSuchMethodException { + Method m = clazz.getDeclaredMethod(methodName, args); + m.setAccessible(true); + return m; + } /** - * Get a Class from the org.bukkit.craftbukkit.SERVER_VERSION. package - * - * @param className The name of the class - * @return Returns the Class - * @throws ClassNotFoundException Thrown when the Class was not found - */ - public static Class getBukkitClass(String className) throws ClassNotFoundException { - return Class.forName("org.bukkit.craftbukkit." + SERVER_VERSION + "." + className); - } - - /** - * 1.16 and older only - *

- * Get a Class from the net.minecraft.server.SERVER_VERSION. package - * - * @param className The name of the class - * @return Returns the Class - * @throws ClassNotFoundException Thrown when the Class was not found - */ - @Deprecated - public static Class getNmsClass(String className) throws ClassNotFoundException { - return Class.forName("net.minecraft.server." + SERVER_VERSION + "." + className); - } - - /** - * 1.17 and newer only - *

- * Get a Class from the net.minecraft package - * - * @param className The name of the class - * @return Returns the class - * @throws ClassNotFoundException Thrown when the Class was not found - */ - public static Class getMinecraftClass(String className) throws ClassNotFoundException { - return Class.forName("net.minecraft." + className); - } - - /** - * Get the Constructor of a Class - * - * @param clazz The Class in which the Constructor is defined - * @param args Arguments taken by the Constructor - * @return Returns the Constructor - * @throws NoSuchMethodException Thrown when no Constructor in the Class was found with the provided combination of arguments - */ - public static Constructor getConstructor(Class clazz, Class... args) throws NoSuchMethodException { - Constructor con = clazz.getConstructor(args); - con.setAccessible(true); - - return con; - } - - /** - * Get an Enum from an Enum constant - * - * @param clazz The Class in which the Enum is defined - * @param constant The name of the Enum Constant - * @return Returns the Enum or null if the Enum does not have a member called constant - */ - public static Enum getEnum(Class clazz, String constant) { - Enum[] constants = (Enum[]) clazz.getEnumConstants(); - - for (Enum e : constants) { - if (e.name().equalsIgnoreCase(constant)) { - return e; - } - } - - return null; - } - - /** - * Get an Enum constant by it's name and constant - * - * @param clazz The Class in which the Enum is defined - * @param enumname The name of the Enum - * @param constant The name of the Constant - * @return Returns the Enum or null if the Enum does not have a member called constant - * @throws ClassNotFoundException If the Class does not have an Enum called enumname - */ - public static Enum getEnum(Class clazz, String enumname, String constant) throws ClassNotFoundException { - Class c = Class.forName(clazz.getName() + "$" + enumname); - return getEnum(c, constant); - } - - /** - * Get a Field - * - * @param clazz The Class in which the Field is defined - * @param fieldName The name of the Field - * @return Returns the Field - * @throws NoSuchFieldException Thrown when the Field was not present in the Class - */ - public static Field getField(Class clazz, String fieldName) throws NoSuchFieldException { - Field f = clazz.getDeclaredField(fieldName); - f.setAccessible(true); - return f; - } - - /** - * Sets the value of a field - * @param instance The instance of the class in which the field is defined - * @param fieldName The name of the field - * @param value The value the field should be set to - */ - public static void setFieldValue(Object instance, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { - Field field = instance.getClass().getDeclaredField(fieldName); - field.setAccessible(true); - field.set(instance, value); - } - - /** - * Get a Method - * - * @param clazz The Class in which the Method is defined - * @param methodName The name of the method - * @param args The argument types the method takes - * @return Returns the Method - */ - public static Method getMethod(Class clazz, String methodName, Class... args) throws NoSuchMethodException { - Method m = clazz.getDeclaredMethod(methodName, args); - m.setAccessible(true); - return m; - } - - /** - * Invoke a Method which takes no arguments. The Class in which the Method is defined is derived from the provided Object - * - * @param obj The object to invoke the method on - * @param methodName The name of the Method - * @return Returns the result of the method, can be null if the method returns void - */ - public static Object invokeMethod(Object obj, String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - return invokeMethod(obj.getClass(), obj, methodName); - } - - /** - * Invoke a Method where the argument types are derived from the provided arguments. The Class in which the Method is defined is derived from the provided Object - * - * @param obj The object to invoke the method on - * @param methodName The name of the Method - * @param args The arguments to pass to the Method - * @return Returns the result of the method, can be null if the method returns void - */ - public static Object invokeMethod(Object obj, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - return invokeMethod(obj.getClass(), obj, methodName, args); - } - - /** - * Invoke a Method where the argument types are explicitly given (Helpful when working with primitives). The Class in which the Method is defined is derived from the provided Object. - * - * @param obj The Object to invoke the method on - * @param methodName The name of the Method - * @param argTypes The types of arguments as a Class array - * @param args The arguments as an object array - * @return Returns the result of the method, can be null if the method returns void - */ - public static Object invokeMethod(Object obj, String methodName, Class[] argTypes, Object[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - return invokeMethod(obj.getClass(), obj, methodName, argTypes, args); - } - - /** - * Invoke a Method where the Class where to find the method is explicitly given (Helpful if the method is located in a superclass). The argument types are derived from the provided arguments - * - * @param clazz The Class where the method is located - * @param obj The Object to invoke the method on - * @param methodName The name of the method - * @param args The arguments to be passed to the method - * @return Returns the result of the method, can be null if the method returns void - */ - public static Object invokeMethod(Class clazz, Object obj, String methodName, Object... args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Class[] argTypes = new Class[args.length]; - for (int i = 0; i < args.length; i++) { - argTypes[i] = args[i].getClass(); - } - - return invokeMethod(clazz, obj, methodName, argTypes, args); - } - - /** - * Invoke a Method where the Class where the Method is defined is explicitly given, and the argument types are explicitly given - * - * @param clazz The Class in which the Method is located - * @param obj The Object on which to invoke the Method - * @param methodName The name of the Method - * @param argTypes Argument types - * @param args Arguments to pass to the method - * @return Returns the result of the method, can be null if the method returns void - */ - public static Object invokeMethod(Class clazz, Object obj, String methodName, Class[] argTypes, Object[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method m = getMethod(clazz, methodName, argTypes); - return m.invoke(obj, args); - } - - /** - * Get the value of a Field, where the Class in which the field is defined is derived from the provided Object - * - * @param obj The object in which the field is located, and from which to get the value - * @param name The name of the Field to get the value from - * @return Returns the value of the Field - */ - public static Object getObject(Object obj, String name) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { - return getObject(obj.getClass(), obj, name); - } - - /** - * Get the value of a Field, where the Class in which the Field is defined is explicitly given. (Helpful when the Field is in a superclass) - * - * @param obj The Object to get the value from - * @param clazz The Class in which the Field is defined - * @param name The name of the Field - * @return Returns the value of the Field - * @deprecated Use {@link #getObject(Class, Object, String)} instead - */ - @Deprecated - public static Object getObject(Object obj, Class clazz, String name) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { - return getObject(clazz, obj, name); - } - - /** - * Get the value of a Field, where the Class in which the Field is defined is explicitly given. (Helpful when the Field is in a superclass) - * - * @param clazz The Class in which the Field is defined - * @param obj The Object to get the value from - * @param name The name of the Field - * @return Returns the value of the Field - */ - public static Object getObject(Class clazz, Object obj, String name) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { - Field f = getField(clazz, name); - f.setAccessible(true); - return f.get(obj); - } - - /** - * Invoke a Class' constructor. The argument types are derived from the provided arguments - * - * @param clazz The Class in which the Constructor is defined - * @param args The arguments to pass to the Constructor - * @return Returns an instance of the provided Class in which the Constructor is located - */ - public static Object invokeConstructor(Class clazz, Object... args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Class[] argTypes = new Class[args.length]; - for (int i = 0; i < args.length; i++) { - argTypes[i] = args[i].getClass(); - } - - return invokeConstructor(clazz, argTypes, args); - } - - /** - * Invoke a Class' Constructor, where the argument types are explicitly given (Helpful when working with primitives) - * - * @param clazz The Class in which the Constructor is defined - * @param argTypes The argument types - * @param args The arguments to pass to the constructor - * @return Returns an instance of the provided Class in which the Constructor is located - */ - public static Object invokeConstructor(Class clazz, Class[] argTypes, Object[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Constructor con = getConstructor(clazz, argTypes); - return con.newInstance(args); - } - - /** - * Print all Methods in a Class with their parameters. Will print the Method's modifiers, return type, name and arguments and their types - * - * @param clazz The class to get methods from - */ - public static void printMethodsInClass(Class clazz) { - System.out.println("Methods in " + clazz.getName() + ":"); - - for (Method m : clazz.getDeclaredMethods()) { - StringBuilder print = new StringBuilder(128); - print.append(getModifiers(m.getModifiers())).append(" "); - print.append(m.getReturnType().getName()).append(" "); - print.append(m.getName()).append("("); - - Class[] parameterTypes = m.getParameterTypes(); - int parameterTypesLength = parameterTypes.length; - for (int i = 0; i < parameterTypesLength; i++) { - print.append(parameterTypes[i].getName()); - - if (i != parameterTypesLength - 1) { - print.append(", "); - } - } - - print.append(")"); - System.out.println(print.toString().trim()); - } - } - - /** - * Print all Fields in a Class. Will print the Field's modifiers, type and name - * - * @param clazz The class to get fields from - */ - public static void printFieldsInClass(Class clazz) { - System.out.println("Fields in " + clazz.getName() + ":"); - for (Field f : clazz.getDeclaredFields()) { - String print = getModifiers(f.getModifiers()) + " " + f.getType().getName() + " " + f.getName(); - System.out.println(print.trim()); - } - } - - /** - * Get modifiers as a String - * - * @param modifiers int value of the modifiers - * @return Returns the modifiers as a String - * @see Field#getModifiers() - * @see Class#getModifiers() - * @see Method#getModifiers() - */ - private static String getModifiers(int modifiers) { - StringJoiner modifiersStr = new StringJoiner(" "); - if (Modifier.isPrivate(modifiers)) { - modifiersStr.add("private"); - } - - if (Modifier.isProtected(modifiers)) { - modifiersStr.add("protected"); - } - - if (Modifier.isPublic(modifiers)) { - modifiersStr.add("public"); - } - - if (Modifier.isAbstract(modifiers)) { - modifiersStr.add("abstract"); - } - - if (Modifier.isStatic(modifiers)) { - modifiersStr.add("static"); - } - - if (Modifier.isFinal(modifiers)) { - modifiersStr.add("final"); - } - - if (Modifier.isTransient(modifiers)) { - modifiersStr.add("transient"); - } - - if (Modifier.isVolatile(modifiers)) { - modifiersStr.add("volatile"); - } - - if (Modifier.isNative(modifiers)) { - modifiersStr.add("native"); - } - - if (Modifier.isStrict(modifiers)) { - modifiersStr.add("strictfp"); - } - - if (Modifier.isSynchronized(modifiers)) { - modifiersStr.add("synchronized"); - } - - if (Modifier.isInterface(modifiers)) { - modifiersStr.add("interface"); - } - - return modifiersStr.toString().trim(); - } + * Invoke a Method which takes no arguments. The Class in which the Method is defined is derived from the provided Object + * + * @param obj The object to invoke the method on + * @param methodName The name of the Method + * @return Returns the result of the method, can be null if the method returns void + */ + public static Object invokeMethod(Object obj, String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + return invokeMethod(obj.getClass(), obj, methodName); + } + + /** + * Invoke a Method where the argument types are derived from the provided arguments. The Class in which the Method is defined is derived from the provided Object + * + * @param obj The object to invoke the method on + * @param methodName The name of the Method + * @param args The arguments to pass to the Method + * @return Returns the result of the method, can be null if the method returns void + */ + public static Object invokeMethod(Object obj, String methodName, Object[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + return invokeMethod(obj.getClass(), obj, methodName, args); + } + + /** + * Invoke a Method where the argument types are explicitly given (Helpful when working with primitives). The Class in which the Method is defined is derived from the provided Object. + * + * @param obj The Object to invoke the method on + * @param methodName The name of the Method + * @param argTypes The types of arguments as a Class array + * @param args The arguments as an object array + * @return Returns the result of the method, can be null if the method returns void + */ + public static Object invokeMethod(Object obj, String methodName, Class[] argTypes, Object[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + return invokeMethod(obj.getClass(), obj, methodName, argTypes, args); + } + + /** + * Invoke a Method where the Class where to find the method is explicitly given (Helpful if the method is located in a superclass). The argument types are derived from the provided arguments + * + * @param clazz The Class where the method is located + * @param obj The Object to invoke the method on + * @param methodName The name of the method + * @param args The arguments to be passed to the method + * @return Returns the result of the method, can be null if the method returns void + */ + public static Object invokeMethod(Class clazz, Object obj, String methodName, Object... args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Class[] argTypes = new Class[args.length]; + for (int i = 0; i < args.length; i++) { + argTypes[i] = args[i].getClass(); + } + + return invokeMethod(clazz, obj, methodName, argTypes, args); + } + + /** + * Invoke a Method where the Class where the Method is defined is explicitly given, and the argument types are explicitly given + * + * @param clazz The Class in which the Method is located + * @param obj The Object on which to invoke the Method + * @param methodName The name of the Method + * @param argTypes Argument types + * @param args Arguments to pass to the method + * @return Returns the result of the method, can be null if the method returns void + */ + public static Object invokeMethod(Class clazz, Object obj, String methodName, Class[] argTypes, Object[] args) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method m = getMethod(clazz, methodName, argTypes); + return m.invoke(obj, args); + } + + /** + * Get the value of a Field, where the Class in which the field is defined is derived from the provided Object + * + * @param obj The object in which the field is located, and from which to get the value + * @param name The name of the Field to get the value from + * @return Returns the value of the Field + */ + public static Object getObject(Object obj, String name) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { + return getObject(obj.getClass(), obj, name); + } + + /** + * Get the value of a Field, where the Class in which the Field is defined is explicitly given. (Helpful when the Field is in a superclass) + * + * @param obj The Object to get the value from + * @param clazz The Class in which the Field is defined + * @param name The name of the Field + * @return Returns the value of the Field + * @deprecated Use {@link #getObject(Class, Object, String)} instead + */ + @Deprecated + public static Object getObject(Object obj, Class clazz, String name) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { + return getObject(clazz, obj, name); + } + + /** + * Get the value of a Field, where the Class in which the Field is defined is explicitly given. (Helpful when the Field is in a superclass) + * + * @param clazz The Class in which the Field is defined + * @param obj The Object to get the value from + * @param name The name of the Field + * @return Returns the value of the Field + */ + public static Object getObject(Class clazz, Object obj, String name) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { + Field f = getField(clazz, name); + f.setAccessible(true); + return f.get(obj); + } + + /** + * Invoke a Class' constructor. The argument types are derived from the provided arguments + * + * @param clazz The Class in which the Constructor is defined + * @param args The arguments to pass to the Constructor + * @return Returns an instance of the provided Class in which the Constructor is located + */ + public static Object invokeConstructor(Class clazz, Object... args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Class[] argTypes = new Class[args.length]; + for (int i = 0; i < args.length; i++) { + argTypes[i] = args[i].getClass(); + } + + return invokeConstructor(clazz, argTypes, args); + } + + /** + * Invoke a Class' Constructor, where the argument types are explicitly given (Helpful when working with primitives) + * + * @param clazz The Class in which the Constructor is defined + * @param argTypes The argument types + * @param args The arguments to pass to the constructor + * @return Returns an instance of the provided Class in which the Constructor is located + */ + public static Object invokeConstructor(Class clazz, Class[] argTypes, Object[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Constructor con = getConstructor(clazz, argTypes); + return con.newInstance(args); + } + + /** + * Print all Methods in a Class with their parameters. Will print the Method's modifiers, return type, name and arguments and their types + * + * @param clazz The class to get methods from + */ + public static void printMethodsInClass(Class clazz) { + System.out.println("Methods in " + clazz.getName() + ":"); + + for (Method m : clazz.getDeclaredMethods()) { + StringBuilder print = new StringBuilder(128); + print.append(getModifiers(m.getModifiers())).append(" "); + print.append(m.getReturnType().getName()).append(" "); + print.append(m.getName()).append("("); + + Class[] parameterTypes = m.getParameterTypes(); + int parameterTypesLength = parameterTypes.length; + for (int i = 0; i < parameterTypesLength; i++) { + print.append(parameterTypes[i].getName()); + + if (i != parameterTypesLength - 1) { + print.append(", "); + } + } + + print.append(")"); + System.out.println(print.toString().trim()); + } + } + + /** + * Print all Fields in a Class. Will print the Field's modifiers, type and name + * + * @param clazz The class to get fields from + */ + public static void printFieldsInClass(Class clazz) { + System.out.println("Fields in " + clazz.getName() + ":"); + for (Field f : clazz.getDeclaredFields()) { + String print = getModifiers(f.getModifiers()) + " " + f.getType().getName() + " " + f.getName(); + System.out.println(print.trim()); + } + } + + /** + * Get modifiers as a String + * + * @param modifiers int value of the modifiers + * @return Returns the modifiers as a String + * @see Field#getModifiers() + * @see Class#getModifiers() + * @see Method#getModifiers() + */ + private static String getModifiers(int modifiers) { + StringJoiner modifiersStr = new StringJoiner(" "); + if (Modifier.isPrivate(modifiers)) { + modifiersStr.add("private"); + } + + if (Modifier.isProtected(modifiers)) { + modifiersStr.add("protected"); + } + + if (Modifier.isPublic(modifiers)) { + modifiersStr.add("public"); + } + + if (Modifier.isAbstract(modifiers)) { + modifiersStr.add("abstract"); + } + + if (Modifier.isStatic(modifiers)) { + modifiersStr.add("static"); + } + + if (Modifier.isFinal(modifiers)) { + modifiersStr.add("final"); + } + + if (Modifier.isTransient(modifiers)) { + modifiersStr.add("transient"); + } + + if (Modifier.isVolatile(modifiers)) { + modifiersStr.add("volatile"); + } + + if (Modifier.isNative(modifiers)) { + modifiersStr.add("native"); + } + + if (Modifier.isStrict(modifiers)) { + modifiersStr.add("strictfp"); + } + + if (Modifier.isSynchronized(modifiers)) { + modifiersStr.add("synchronized"); + } + + if (Modifier.isInterface(modifiers)) { + modifiersStr.add("interface"); + } + + return modifiersStr.toString().trim(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java index c104b2598..ab832b11c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java @@ -8,39 +8,39 @@ public class BorderPacketFactory_1_13 extends BorderPacketFactory { - @Override - public Object center(PacketBorder packetBorder) { - return createPacket(packetBorder, "SET_CENTER"); - } + @Override + public Object center(PacketBorder packetBorder) { + return createPacket(packetBorder, "SET_CENTER"); + } - @Override - public Object size(PacketBorder packetBorder) { - return createPacket(packetBorder, "SET_SIZE"); - } + @Override + public Object size(PacketBorder packetBorder) { + return createPacket(packetBorder, "SET_SIZE"); + } - @Override - public Object warningDelay(PacketBorder packetBorder) { - return createPacket(packetBorder, "SET_WARNING_TIME"); - } + @Override + public Object warningDelay(PacketBorder packetBorder) { + return createPacket(packetBorder, "SET_WARNING_TIME"); + } - @Override - public Object warningDistance(PacketBorder packetBorder) { - return createPacket(packetBorder, "SET_WARNING_BLOCKS"); - } + @Override + public Object warningDistance(PacketBorder packetBorder) { + return createPacket(packetBorder, "SET_WARNING_BLOCKS"); + } - private Object createPacket(PacketBorder packetBorder, String worldBorderAction) { - try { - Class clazz = NMSUtils.getClass("PacketPlayOutWorldBorder"); - Class actionClazz = NMSUtils.getClass("PacketPlayOutWorldBorder$EnumWorldBorderAction"); - assert actionClazz != null; - for (Object enumConstant : actionClazz.getEnumConstants()) { - if (enumConstant.toString().equalsIgnoreCase(worldBorderAction)) { - return ReflectionUtil.invokeConstructor(clazz, new Class[]{packetBorder.getNMSClass(), actionClazz}, new Object[]{packetBorder.getWorldBorderObject(), enumConstant}); - } - } - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create packet for action {}:", worldBorderAction, exception); + private Object createPacket(PacketBorder packetBorder, String worldBorderAction) { + try { + Class clazz = NMSUtils.getClass("PacketPlayOutWorldBorder"); + Class actionClazz = NMSUtils.getClass("PacketPlayOutWorldBorder$EnumWorldBorderAction"); + assert actionClazz != null; + for (Object enumConstant : actionClazz.getEnumConstants()) { + if (enumConstant.toString().equalsIgnoreCase(worldBorderAction)) { + return ReflectionUtil.invokeConstructor(clazz, new Class[]{packetBorder.getNMSClass(), actionClazz}, new Object[]{packetBorder.getWorldBorderObject(), enumConstant}); } - return null; + } + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to create packet for action {}:", worldBorderAction, exception); } + return null; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java index 97968be4f..056bdf485 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java @@ -6,41 +6,41 @@ import org.bukkit.entity.Player; public class CraftPlayer_1_13 extends CraftPlayer { - /** - * @param player The player to create the CraftPlayer for - */ - public CraftPlayer_1_13(Player player) throws ClassNotFoundException { - super(ReflectionUtil.getBukkitClass("entity.CraftPlayer"), player); - } + /** + * @param player The player to create the CraftPlayer for + */ + public CraftPlayer_1_13(Player player) throws ClassNotFoundException { + super(ReflectionUtil.getBukkitClass("entity.CraftPlayer"), player); + } - /** - * Creates an NMS object of the specified player - * - * @param player The player to create the CraftPlayer for - * @return The NMS object - */ - @Override - public Object get(Player player) { - Object craftPlayer; - try { - craftPlayer = ReflectionUtil.invokeMethod(nmsClass, player, "getHandle"); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create CraftPlayer:", exception); - craftPlayer = null; - } - return craftPlayer; + /** + * Creates an NMS object of the specified player + * + * @param player The player to create the CraftPlayer for + * @return The NMS object + */ + @Override + public Object get(Player player) { + Object craftPlayer; + try { + craftPlayer = ReflectionUtil.invokeMethod(nmsClass, player, "getHandle"); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to create CraftPlayer:", exception); + craftPlayer = null; } + return craftPlayer; + } - /** - * @return The PlayerConnection of the Player as an object - */ - @Override - public Object getPlayerConnectionObject() { - try { - return ReflectionUtil.getObject(this.nmsObject, "playerConnection"); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get the playerConnection object:", exception); - return null; - } + /** + * @return The PlayerConnection of the Player as an object + */ + @Override + public Object getPlayerConnectionObject() { + try { + return ReflectionUtil.getObject(this.nmsObject, "playerConnection"); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to get the playerConnection object:", exception); + return null; } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java index a5c65b210..de25d60f0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java @@ -10,108 +10,110 @@ import org.bukkit.entity.Player; public class PacketBorder_1_13 extends PacketBorder { - /** - * Creates a new packet border. - * Use this constructor if you override this implementation. - * @param nmsClass The NMS class - * @param world The world the border is in - */ - protected PacketBorder_1_13(World world, Class nmsClass) { - super( - nmsClass, - world - ); - } + /** + * Creates a new packet border. + * Use this constructor if you override this implementation. + * + * @param nmsClass The NMS class + * @param world The world the border is in + */ + protected PacketBorder_1_13(World world, Class nmsClass) { + super( + nmsClass, + world + ); + } - /** - * Creates a new packet border. - * @param world The world the border is in. - */ - public PacketBorder_1_13(World world) { - this( - world, - NMSUtils.getClass("WorldBorder") - ); - } + /** + * Creates a new packet border. + * + * @param world The world the border is in. + */ + public PacketBorder_1_13(World world) { + this( + world, + NMSUtils.getClass("WorldBorder") + ); + } - @Override - protected Object createWorldBorder() { - try { - return ReflectionUtil.invokeConstructor(nmsClass); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create world border:", exception); - return null; - } + @Override + protected Object createWorldBorder() { + try { + return ReflectionUtil.invokeConstructor(nmsClass); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to create world border:", exception); + return null; } + } - /** - * Sets the world the border is in - * - * @param world The world - */ - @Override - protected void setWorld(World world) { - try { - ReflectionUtil.setFieldValue(worldBorder, "world", getWorldServer(world)); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set world:", exception); - } + /** + * Sets the world the border is in + * + * @param world The world + */ + @Override + protected void setWorld(World world) { + try { + ReflectionUtil.setFieldValue(worldBorder, "world", getWorldServer(world)); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to set world:", exception); } + } - @Override - protected void setSizeField(double size) { - try { - ReflectionUtil.invokeMethod(worldBorder, "setSize", new Class[] {double.class}, new Object[]{size}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border size:", exception); - } + @Override + protected void setSizeField(double size) { + try { + ReflectionUtil.invokeMethod(worldBorder, "setSize", new Class[]{double.class}, new Object[]{size}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to set border size:", exception); } + } - @Override - protected void transitionSizeBetween(double oldSize, double newSize, long animationTime) { - try { - ReflectionUtil.invokeMethod(worldBorder, "transitionSizeBetween", new Class[]{double.class, double.class, long.class}, new Object[]{oldSize, newSize, animationTime}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border size:", exception); - } + @Override + protected void transitionSizeBetween(double oldSize, double newSize, long animationTime) { + try { + ReflectionUtil.invokeMethod(worldBorder, "transitionSizeBetween", new Class[]{double.class, double.class, long.class}, new Object[]{oldSize, newSize, animationTime}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to set border size:", exception); } + } - @Override - protected void setCenterField(double x, double z) { - try { - ReflectionUtil.invokeMethod(worldBorder, "setCenter", new Class[] {double.class, double.class}, new Object[]{x, z}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border center:", exception); - } + @Override + protected void setCenterField(double x, double z) { + try { + ReflectionUtil.invokeMethod(worldBorder, "setCenter", new Class[]{double.class, double.class}, new Object[]{x, z}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to set border center:", exception); } + } - @Override - protected void setWarningTimeField(int warningTime) { - try { - ReflectionUtil.invokeMethod(worldBorder, "setWarningTime", new Class[] {int.class}, new Object[]{warningTime}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border warning time:", exception); - } + @Override + protected void setWarningTimeField(int warningTime) { + try { + ReflectionUtil.invokeMethod(worldBorder, "setWarningTime", new Class[]{int.class}, new Object[]{warningTime}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to set border warning time:", exception); } + } - @Override - protected void setWarningDistanceField(int warningDistance) { - try { - ReflectionUtil.invokeMethod(worldBorder, "setWarningDistance", new Class[] {int.class}, new Object[]{warningDistance}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border warning distance:", exception); - } + @Override + protected void setWarningDistanceField(int warningDistance) { + try { + ReflectionUtil.invokeMethod(worldBorder, "setWarningDistance", new Class[]{int.class}, new Object[]{warningDistance}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to set border warning distance:", exception); } + } - @Override - public void send(Player player, UpdateType updateType) { - try { - Object packet = updateType.createPacket(this); - CraftPlayer craftPlayer = NMSProvider.createCraftPlayer(player); - craftPlayer.getConnection().sendPacket(packet); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to send update {} to player {}:", updateType.name(), player.getName(), exception); - } + @Override + public void send(Player player, UpdateType updateType) { + try { + Object packet = updateType.createPacket(this); + CraftPlayer craftPlayer = NMSProvider.createCraftPlayer(player); + craftPlayer.getConnection().sendPacket(packet); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to send update {} to player {}:", updateType.name(), player.getName(), exception); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java index 4720ffea6..c336ab8c4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java @@ -6,16 +6,16 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.type.PlayerConnection; public class PlayerConnection_1_13 extends PlayerConnection { - public PlayerConnection_1_13(Object connection) throws ClassNotFoundException { - super(NMSUtils.getClass("network.protocol.Packet"), connection); - } + public PlayerConnection_1_13(Object connection) throws ClassNotFoundException { + super(NMSUtils.getClass("network.protocol.Packet"), connection); + } - @Override - public void sendPacket(Object packet) { - try { - ReflectionUtil.invokeMethod(this.connection, "sendPacket", new Class[]{nmsClass}, new Object[]{packet}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); - } + @Override + public void sendPacket(Object packet) { + try { + ReflectionUtil.invokeMethod(this.connection, "sendPacket", new Class[]{nmsClass}, new Object[]{packet}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java index 62e7037e4..1b85a2ee4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java @@ -7,28 +7,28 @@ public class WorldServer_1_13 extends WorldServer { - /** - * @param object The instance of the specified bukkit type - */ - public WorldServer_1_13(World object) throws ClassNotFoundException { - super(object, ReflectionUtil.getBukkitClass("CraftWorld")); - } + /** + * @param object The instance of the specified bukkit type + */ + public WorldServer_1_13(World object) throws ClassNotFoundException { + super(object, ReflectionUtil.getBukkitClass("CraftWorld")); + } - /** - * Creates an NMS object of the specified bukkit type object - * - * @param world An instance of the specified bukkit type - * @return The NMS object - */ - @Override - public Object get(World world) { - Object worldServer; - try { - worldServer = ReflectionUtil.invokeMethod(nmsClass, world, "getHandle"); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get WorldServer:", exception); - worldServer = null; - } - return worldServer; + /** + * Creates an NMS object of the specified bukkit type object + * + * @param world An instance of the specified bukkit type + * @return The NMS object + */ + @Override + public Object get(World world) { + Object worldServer; + try { + worldServer = ReflectionUtil.invokeMethod(nmsClass, world, "getHandle"); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to get WorldServer:", exception); + worldServer = null; } + return worldServer; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java index 678a0bfe7..3159aa309 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java @@ -8,33 +8,33 @@ public class BorderPacketFactory_1_17 extends BorderPacketFactory { - @Override - public Object center(PacketBorder packetBorder) { - return createPacket(packetBorder, "ClientboundSetBorderCenterPacket"); - } + @Override + public Object center(PacketBorder packetBorder) { + return createPacket(packetBorder, "ClientboundSetBorderCenterPacket"); + } - @Override - public Object size(PacketBorder packetBorder) { - return createPacket(packetBorder, "ClientboundSetBorderSizePacket"); - } + @Override + public Object size(PacketBorder packetBorder) { + return createPacket(packetBorder, "ClientboundSetBorderSizePacket"); + } - @Override - public Object warningDelay(PacketBorder packetBorder) { - return createPacket(packetBorder, "ClientboundSetBorderWarningDelayPacket"); - } + @Override + public Object warningDelay(PacketBorder packetBorder) { + return createPacket(packetBorder, "ClientboundSetBorderWarningDelayPacket"); + } - @Override - public Object warningDistance(PacketBorder packetBorder) { - return createPacket(packetBorder, "ClientboundSetBorderWarningDistancePacket"); - } + @Override + public Object warningDistance(PacketBorder packetBorder) { + return createPacket(packetBorder, "ClientboundSetBorderWarningDistancePacket"); + } - private Object createPacket(PacketBorder packetBorder, String className) { - Class clazz = NMSUtils.getClass("network.protocol.game." + className); - try { - return ReflectionUtil.invokeConstructor(clazz, new Class[]{packetBorder.getNMSClass()}, new Object[]{packetBorder.getWorldBorderObject()}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create packet {}:", className, exception); - return null; - } + private Object createPacket(PacketBorder packetBorder, String className) { + Class clazz = NMSUtils.getClass("network.protocol.game." + className); + try { + return ReflectionUtil.invokeConstructor(clazz, new Class[]{packetBorder.getNMSClass()}, new Object[]{packetBorder.getWorldBorderObject()}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to create packet {}:", className, exception); + return null; } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java index 2798bf7c4..1fe13159b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java @@ -1,40 +1,40 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_17; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.utils.bukkit.nms.type.CraftPlayer; import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; +import net.codingarea.challenges.plugin.utils.bukkit.nms.type.CraftPlayer; import org.bukkit.entity.Player; public class CraftPlayer_1_17 extends CraftPlayer { - /** - * Create a new CraftPlayer - * - * @param player The Player - */ - public CraftPlayer_1_17(Player player) throws ClassNotFoundException { - super(ReflectionUtil.getBukkitClass("entity.CraftPlayer"), player); - } + /** + * Create a new CraftPlayer + * + * @param player The Player + */ + public CraftPlayer_1_17(Player player) throws ClassNotFoundException { + super(ReflectionUtil.getBukkitClass("entity.CraftPlayer"), player); + } - @Override - public Object get(Player player) { - Object craftPlayer; - try { - craftPlayer = ReflectionUtil.invokeMethod(nmsClass, player, "getHandle"); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get CraftPlayer:", exception); - craftPlayer = null; - } - return craftPlayer; + @Override + public Object get(Player player) { + Object craftPlayer; + try { + craftPlayer = ReflectionUtil.invokeMethod(nmsClass, player, "getHandle"); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to get CraftPlayer:", exception); + craftPlayer = null; } + return craftPlayer; + } - @Override - public Object getPlayerConnectionObject() { - try { - return ReflectionUtil.getObject(this.nmsObject, "b"); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get player connection object:", exception); - return null; - } + @Override + public Object getPlayerConnectionObject() { + try { + return ReflectionUtil.getObject(this.nmsObject, "b"); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to get player connection object:", exception); + return null; } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java index 9ec5f716b..fb5429065 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/PacketBorder_1_17.java @@ -1,19 +1,17 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_17; -import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.bukkit.nms.NMSUtils; -import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_13.PacketBorder_1_13; import org.bukkit.World; public class PacketBorder_1_17 extends PacketBorder_1_13 { - public PacketBorder_1_17(World world) { - super( - world, - NMSUtils.getClass("world.level.border.WorldBorder") - ); - } + public PacketBorder_1_17(World world) { + super( + world, + NMSUtils.getClass("world.level.border.WorldBorder") + ); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java index f1a3c832a..0e39fdbc8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java @@ -7,52 +7,52 @@ public class PacketBorder_1_18 extends PacketBorder_1_17 { - public PacketBorder_1_18(World world) { - super(world); + public PacketBorder_1_18(World world) { + super(world); + } + + @Override + protected void setCenterField(double x, double z) { + try { + ReflectionUtil.invokeMethod(worldBorder, "c", new Class[]{double.class, double.class}, new Object[]{x, z}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to set center:", exception); } - - @Override - protected void setCenterField(double x, double z) { - try { - ReflectionUtil.invokeMethod(worldBorder, "c", new Class[] {double.class, double.class}, new Object[]{x, z}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set center:", exception); - } - } - - @Override - protected void setSizeField(double size) { - try { - ReflectionUtil.invokeMethod(worldBorder, "a", new Class[] {double.class}, new Object[]{size}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set size:", exception); - } + } + + @Override + protected void setSizeField(double size) { + try { + ReflectionUtil.invokeMethod(worldBorder, "a", new Class[]{double.class}, new Object[]{size}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to set size:", exception); } - - @Override - protected void setWarningDistanceField(int warningDistance) { - try { - ReflectionUtil.invokeMethod(worldBorder, "c", new Class[] {int.class}, new Object[]{warningDistance}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set warning distance:", exception); - } + } + + @Override + protected void setWarningDistanceField(int warningDistance) { + try { + ReflectionUtil.invokeMethod(worldBorder, "c", new Class[]{int.class}, new Object[]{warningDistance}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to set warning distance:", exception); } - - @Override - protected void setWarningTimeField(int warningTime) { - try { - ReflectionUtil.invokeMethod(worldBorder, "b", new Class[] {int.class}, new Object[]{warningTime}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set warning time:", exception); - } + } + + @Override + protected void setWarningTimeField(int warningTime) { + try { + ReflectionUtil.invokeMethod(worldBorder, "b", new Class[]{int.class}, new Object[]{warningTime}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to set warning time:", exception); } - - @Override - protected void transitionSizeBetween(double oldSize, double newSize, long animationTime) { - try { - ReflectionUtil.invokeMethod(worldBorder, "a", new Class[]{double.class, double.class, long.class}, new Object[]{oldSize, newSize, animationTime}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set size:", exception); - } + } + + @Override + protected void transitionSizeBetween(double oldSize, double newSize, long animationTime) { + try { + ReflectionUtil.invokeMethod(worldBorder, "a", new Class[]{double.class, double.class, long.class}, new Object[]{oldSize, newSize, animationTime}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to set size:", exception); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java index c466e679c..d96c4c3ec 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java @@ -6,16 +6,16 @@ public class PlayerConnection_1_18 extends PlayerConnection_1_13 { - public PlayerConnection_1_18(Object connection) throws ClassNotFoundException { - super(connection); - } + public PlayerConnection_1_18(Object connection) throws ClassNotFoundException { + super(connection); + } - @Override - public void sendPacket(Object packet) { - try { - ReflectionUtil.invokeMethod(this.connection, "a", new Class[]{nmsClass}, new Object[]{packet}); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); - } + @Override + public void sendPacket(Object packet) { + try { + ReflectionUtil.invokeMethod(this.connection, "a", new Class[]{nmsClass}, new Object[]{packet}); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/AbstractNMSClass.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/AbstractNMSClass.java index 79cf77cd9..d759cf87b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/AbstractNMSClass.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/AbstractNMSClass.java @@ -2,16 +2,16 @@ public abstract class AbstractNMSClass { - protected final Class nmsClass; + protected final Class nmsClass; - /** - * @param nmsClass The NMS class - */ - public AbstractNMSClass(Class nmsClass) { - this.nmsClass = nmsClass; - } + /** + * @param nmsClass The NMS class + */ + public AbstractNMSClass(Class nmsClass) { + this.nmsClass = nmsClass; + } - public Class getNMSClass() { - return nmsClass; - } + public Class getNMSClass() { + return nmsClass; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BorderPacketFactory.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BorderPacketFactory.java index 04d514842..2a17b2de9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BorderPacketFactory.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BorderPacketFactory.java @@ -2,9 +2,12 @@ public abstract class BorderPacketFactory { - public abstract Object center(PacketBorder packetBorder); - public abstract Object size(PacketBorder packetBorder); - public abstract Object warningDelay(PacketBorder packetBorder); - public abstract Object warningDistance(PacketBorder packetBorder); + public abstract Object center(PacketBorder packetBorder); + + public abstract Object size(PacketBorder packetBorder); + + public abstract Object warningDelay(PacketBorder packetBorder); + + public abstract Object warningDistance(PacketBorder packetBorder); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BukkitNMSClass.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BukkitNMSClass.java index 2b3afb1eb..7ea0c31ce 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BukkitNMSClass.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/BukkitNMSClass.java @@ -5,20 +5,21 @@ */ public abstract class BukkitNMSClass extends AbstractNMSClass { - public Object nmsObject; + public Object nmsObject; - /** - * @param nmsClass The NMS class - */ - public BukkitNMSClass(Class nmsClass, T bukkitObject) { - super(nmsClass); - this.nmsObject = get(bukkitObject); - } + /** + * @param nmsClass The NMS class + */ + public BukkitNMSClass(Class nmsClass, T bukkitObject) { + super(nmsClass); + this.nmsObject = get(bukkitObject); + } - /** - * Creates an NMS object of the specified bukkit type object - * @param bukkitObject An instance of the specified bukkit type - * @return The NMS object - */ - public abstract Object get(T bukkitObject); + /** + * Creates an NMS object of the specified bukkit type object + * + * @param bukkitObject An instance of the specified bukkit type + * @return The NMS object + */ + public abstract Object get(T bukkitObject); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java index afff1f330..5c241b23a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/CraftPlayer.java @@ -5,29 +5,29 @@ /** * @author TobiasDeBruijn | .* @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil + * ">* @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil */ public abstract class CraftPlayer extends BukkitNMSClass { - /** - * @param player The player to create the CraftPlayer for - * @param nmsClass The NMS class - */ - public CraftPlayer(Class nmsClass, Player player) { - super(nmsClass, player); - } + /** + * @param player The player to create the CraftPlayer for + * @param nmsClass The NMS class + */ + public CraftPlayer(Class nmsClass, Player player) { + super(nmsClass, player); + } - /** - * @return The PlayerConnection of the Player as an object - */ - public abstract Object getPlayerConnectionObject(); + /** + * @return The PlayerConnection of the Player as an object + */ + public abstract Object getPlayerConnectionObject(); - /** - * Get a connection to the Player - * - * @return The PlayerConnection - */ - public PlayerConnection getConnection() { - return NMSProvider.createPlayerConnection(this); - } + /** + * Get a connection to the Player + * + * @return The PlayerConnection + */ + public PlayerConnection getConnection() { + return NMSProvider.createPlayerConnection(this); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PacketBorder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PacketBorder.java index 0a5d1ac8f..21f84f094 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PacketBorder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PacketBorder.java @@ -14,140 +14,152 @@ */ public abstract class PacketBorder extends AbstractNMSClass { - protected Object worldBorder; - - protected final World world; - @Getter - protected double size = 0; - @Getter - protected double centerX = 0; - @Getter - protected double centerZ = 0; - @Getter - protected int warningTime = 0; - @Getter - protected int warningDistance = 0; - - /** - * @param nmsClass The NMS class - * @param world The world the border is in - */ - public PacketBorder(Class nmsClass, World world) { - super(nmsClass); - this.world = world; - - worldBorder = createWorldBorder(); - setWorld(world); + protected Object worldBorder; + + protected final World world; + @Getter + protected double size = 0; + @Getter + protected double centerX = 0; + @Getter + protected double centerZ = 0; + @Getter + protected int warningTime = 0; + @Getter + protected int warningDistance = 0; + + /** + * @param nmsClass The NMS class + * @param world The world the border is in + */ + public PacketBorder(Class nmsClass, World world) { + super(nmsClass); + this.world = world; + + worldBorder = createWorldBorder(); + setWorld(world); + } + + protected abstract Object createWorldBorder(); + + /** + * Sets the world the border is in + * + * @param world The world + */ + protected abstract void setWorld(World world); + + /** + * Sets the size of the border + * + * @param size The size of the border + */ + public void setSize(double size) { + this.size = size; + setSizeField(size); + } + + /** + * Sets the size of the border with an animation + * + * @param size The size of the border + * @param animationTime The time the animation should take (in seconds) + */ + public void setSize(double size, long animationTime) { + animationTime *= 1000; // Convert to milliseconds + transitionSizeBetween(this.size, size, animationTime); + this.size = size; + } + + protected abstract void setSizeField(double size); + + protected abstract void transitionSizeBetween(double oldSize, double newSize, long animationTime); + + /** + * Sets the center of the border + * + * @param x The x coordinate of the center + * @param z The z coordinate of the center + */ + public void setCenter(double x, double z) { + this.centerX = x; + this.centerZ = z; + setCenterField(x, z); + } + + protected abstract void setCenterField(double x, double z); + + /** + * Sets the warning time of the border + * + * @param warningTime The warning time + */ + public void setWarningTime(int warningTime) { + this.warningTime = warningTime; + setWarningTimeField(warningTime); + } + + protected abstract void setWarningTimeField(int warningTime); + + /** + * Sets the warning distance of the border + * + * @param warningDistance The warning distance + */ + public void setWarningDistance(int warningDistance) { + this.warningDistance = warningDistance; + setWarningDistanceField(warningDistance); + } + + protected abstract void setWarningDistanceField(int warningDistance); + + /** + * @param world The world + * @return The world server of the world + */ + protected Object getWorldServer(World world) { + return NMSProvider.createWorldServer(world).getWorldServerObject(); + } + + public void reset(Player player) { + WorldBorder border = player.getWorld().getWorldBorder(); + setSize(border.getSize()); + setCenter(border.getCenter().getX(), border.getCenter().getZ()); + setWarningTime(border.getWarningTime()); + setWarningDistance(border.getWarningDistance()); + send(player, PacketBorder_1_17.UpdateType.values()); + } + + public void send(Player player) { + send(player, UpdateType.values()); + } + + public void send(Player player, UpdateType... updateTypes) { + for (UpdateType updateType : updateTypes) { + send(player, updateType); } + } - protected abstract Object createWorldBorder(); - - /** - * Sets the world the border is in - * @param world The world - */ - protected abstract void setWorld(World world); - - /** - * Sets the size of the border - * @param size The size of the border - */ - public void setSize(double size) { - this.size = size; - setSizeField(size); - } - - /** - * Sets the size of the border with an animation - * @param size The size of the border - * @param animationTime The time the animation should take (in seconds) - */ - public void setSize(double size, long animationTime) { - animationTime *= 1000; // Convert to milliseconds - transitionSizeBetween(this.size, size, animationTime); - this.size = size; - } - - protected abstract void setSizeField(double size); - protected abstract void transitionSizeBetween(double oldSize, double newSize, long animationTime); - - /** - * Sets the center of the border - * @param x The x coordinate of the center - * @param z The z coordinate of the center - */ - public void setCenter(double x, double z) { - this.centerX = x; - this.centerZ = z; - setCenterField(x, z); - } - protected abstract void setCenterField(double x, double z); - - /** - * Sets the warning time of the border - * @param warningTime The warning time - */ - public void setWarningTime(int warningTime) { - this.warningTime = warningTime; - setWarningTimeField(warningTime); - } - protected abstract void setWarningTimeField(int warningTime); - - /** - * Sets the warning distance of the border - * @param warningDistance The warning distance - */ - public void setWarningDistance(int warningDistance) { - this.warningDistance = warningDistance; - setWarningDistanceField(warningDistance); - } - protected abstract void setWarningDistanceField(int warningDistance); - - /** - * @param world The world - * @return The world server of the world - */ - protected Object getWorldServer(World world) { - return NMSProvider.createWorldServer(world).getWorldServerObject(); - } - - public void reset(Player player) { - WorldBorder border = player.getWorld().getWorldBorder(); - setSize(border.getSize()); - setCenter(border.getCenter().getX(), border.getCenter().getZ()); - setWarningTime(border.getWarningTime()); - setWarningDistance(border.getWarningDistance()); - send(player, PacketBorder_1_17.UpdateType.values()); - } - - public void send(Player player) { - send(player, UpdateType.values()); - } - public void send(Player player, UpdateType... updateTypes) { - for (UpdateType updateType : updateTypes) { - send(player, updateType); - } - } - public abstract void send(Player player, PacketBorder_1_17.UpdateType updateType); + public abstract void send(Player player, PacketBorder_1_17.UpdateType updateType); public Object getWorldBorderObject() { - return worldBorder; - } + return worldBorder; + } - public enum UpdateType { - CENTER(NMSProvider.getBorderPacketFactory()::center), - SIZE(NMSProvider.getBorderPacketFactory()::size), - WARNING_DELAY(NMSProvider.getBorderPacketFactory()::warningDelay), - WARNING_DISTANCE(NMSProvider.getBorderPacketFactory()::warningDistance); + public enum UpdateType { + CENTER(NMSProvider.getBorderPacketFactory()::center), + SIZE(NMSProvider.getBorderPacketFactory()::size), + WARNING_DELAY(NMSProvider.getBorderPacketFactory()::warningDelay), + WARNING_DISTANCE(NMSProvider.getBorderPacketFactory()::warningDistance); - private final Function packetFactory; + private final Function packetFactory; - UpdateType(Function packetFactory) { - this.packetFactory = packetFactory; - } + UpdateType(Function packetFactory) { + this.packetFactory = packetFactory; + } - public Object createPacket(PacketBorder border) { - return packetFactory.apply(border); - } + public Object createPacket(PacketBorder border) { + return packetFactory.apply(border); } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java index 96fcd5a26..d78c28323 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/PlayerConnection.java @@ -2,23 +2,23 @@ /** * @author TobiasDeBruijn | .* @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil + * ">* @source https://github.com/TobiasDeBruijn/BukkitReflectionUtil */ public abstract class PlayerConnection extends AbstractNMSClass { - protected final Object connection; + protected final Object connection; - public PlayerConnection(Class nmsClass, Object connection) { - super(nmsClass); - this.connection = connection; - } + public PlayerConnection(Class nmsClass, Object connection) { + super(nmsClass); + this.connection = connection; + } - /** - * Send a packet - *

- * The caller must guarantee the passed in object is a Packet - * - * @param packet The packet to send - */ - public abstract void sendPacket(Object packet); + /** + * Send a packet + *

+ * The caller must guarantee the passed in object is a Packet + * + * @param packet The packet to send + */ + public abstract void sendPacket(Object packet); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/WorldServer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/WorldServer.java index 48a91c78b..6cf82f8ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/WorldServer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/type/WorldServer.java @@ -3,15 +3,15 @@ import org.bukkit.World; public abstract class WorldServer extends BukkitNMSClass { - /** - * @param object The instance of the specified bukkit type - * @param nmsClass The NMS class - */ - protected WorldServer(World object, Class nmsClass) { - super(nmsClass, object); - } + /** + * @param object The instance of the specified bukkit type + * @param nmsClass The NMS class + */ + protected WorldServer(World object, Class nmsClass) { + super(nmsClass, object); + } - public Object getWorldServerObject() { - return nmsObject; - } + public Object getWorldServerObject() { + return nmsObject; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java index 415637d7a..942aa4f58 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java @@ -9,78 +9,78 @@ public final class DefaultItem { - private static final String ARROW_LEFT = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjAwNmVjMWVjYTJmMjY4NWY3MGU2NTQxMWNmZTg4MDhhMDg4ZjdjZjA4MDg3YWQ4ZWVjZTk2MTgzNjEwNzBlMyJ9fX0=", - ARROW_RIGHT = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZmY5ZTE5ZTVmMmNlMzQ4OGMyOTU4MmI2ZDI2MDE1MDA2MjZlOGRiMmE4OGNkMTgxNjQ0MzJmZWYyZTM0ZGU2YiJ9fX0="; - - @Nonnull - public static String getItemPrefix() { - return Message.forName("item-prefix").asString() + "§e"; - } - - @Nonnull - public static ItemBuilder navigateBack() { - return new SkullBuilder().setBase64Texture(ARROW_LEFT).setName(Message.forName("navigate-back")).hideAttributes(); - } - - @Nonnull - public static ItemBuilder navigateNext() { - return new SkullBuilder().setBase64Texture(ARROW_RIGHT).setName(Message.forName("navigate-next")).hideAttributes(); - } - - @Nonnull - public static ItemBuilder navigateBackMainMenu() { - return new ItemBuilder(Material.DARK_OAK_DOOR).setName(Message.forName("navigate-back")).hideAttributes(); - } - - @Nonnull - public static ItemBuilder status(boolean enabled) { - return enabled ? enabled() : disabled(); - } - - @Nonnull - public static ItemBuilder enabled() { - return new ItemBuilder(Material.LIME_DYE).setName(getTitle(Message.forName("enabled"))).hideAttributes(); - } - - @Nonnull - public static ItemBuilder disabled() { - return new ItemBuilder(MinecraftNameWrapper.RED_DYE).setName(getTitle(Message.forName("disabled"))).hideAttributes(); - } - - @Nonnull - public static ItemBuilder customize() { - return new ItemBuilder(MinecraftNameWrapper.SIGN).setName(getTitle(Message.forName("customize"))).hideAttributes(); - } - - @Nonnull - public static ItemBuilder value(int value) { - return value(value, "§e"); - } - - @Nonnull - public static ItemBuilder value(int value, @Nonnull String prefix) { - return create(Material.STONE_BUTTON, prefix + value).amount(Math.max(value, 1)); - } - - @Nonnull - public static ItemBuilder create(@Nonnull Material material, @Nonnull String name) { - return new ItemBuilder(material, getTitle(name)); - } - - @Nonnull - public static ItemBuilder create(@Nonnull Material material, @Nonnull Message message) { - ItemBuilder itemBuilder = new ItemBuilder(material, message); - return itemBuilder.setName(getTitle(message)); - } - - @Nonnull - private static String getTitle(@Nonnull Message message) { - return getTitle(message.asString()); - } - - @Nonnull - private static String getTitle(@Nonnull String text) { - return Message.forName("item-setting-info").asString(text); - } + private static final String ARROW_LEFT = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjAwNmVjMWVjYTJmMjY4NWY3MGU2NTQxMWNmZTg4MDhhMDg4ZjdjZjA4MDg3YWQ4ZWVjZTk2MTgzNjEwNzBlMyJ9fX0=", + ARROW_RIGHT = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZmY5ZTE5ZTVmMmNlMzQ4OGMyOTU4MmI2ZDI2MDE1MDA2MjZlOGRiMmE4OGNkMTgxNjQ0MzJmZWYyZTM0ZGU2YiJ9fX0="; + + @Nonnull + public static String getItemPrefix() { + return Message.forName("item-prefix").asString() + "§e"; + } + + @Nonnull + public static ItemBuilder navigateBack() { + return new SkullBuilder().setBase64Texture(ARROW_LEFT).setName(Message.forName("navigate-back")).hideAttributes(); + } + + @Nonnull + public static ItemBuilder navigateNext() { + return new SkullBuilder().setBase64Texture(ARROW_RIGHT).setName(Message.forName("navigate-next")).hideAttributes(); + } + + @Nonnull + public static ItemBuilder navigateBackMainMenu() { + return new ItemBuilder(Material.DARK_OAK_DOOR).setName(Message.forName("navigate-back")).hideAttributes(); + } + + @Nonnull + public static ItemBuilder status(boolean enabled) { + return enabled ? enabled() : disabled(); + } + + @Nonnull + public static ItemBuilder enabled() { + return new ItemBuilder(Material.LIME_DYE).setName(getTitle(Message.forName("enabled"))).hideAttributes(); + } + + @Nonnull + public static ItemBuilder disabled() { + return new ItemBuilder(MinecraftNameWrapper.RED_DYE).setName(getTitle(Message.forName("disabled"))).hideAttributes(); + } + + @Nonnull + public static ItemBuilder customize() { + return new ItemBuilder(MinecraftNameWrapper.SIGN).setName(getTitle(Message.forName("customize"))).hideAttributes(); + } + + @Nonnull + public static ItemBuilder value(int value) { + return value(value, "§e"); + } + + @Nonnull + public static ItemBuilder value(int value, @Nonnull String prefix) { + return create(Material.STONE_BUTTON, prefix + value).amount(Math.max(value, 1)); + } + + @Nonnull + public static ItemBuilder create(@Nonnull Material material, @Nonnull String name) { + return new ItemBuilder(material, getTitle(name)); + } + + @Nonnull + public static ItemBuilder create(@Nonnull Material material, @Nonnull Message message) { + ItemBuilder itemBuilder = new ItemBuilder(material, message); + return itemBuilder.setName(getTitle(message)); + } + + @Nonnull + private static String getTitle(@Nonnull Message message) { + return getTitle(message.asString()); + } + + @Nonnull + private static String getTitle(@Nonnull String text) { + return Message.forName("item-setting-info").asString(text); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index dead068e2..683ef1c80 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -22,414 +22,417 @@ import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.Base64; +import java.util.Collection; +import java.util.List; +import java.util.UUID; public class ItemBuilder extends net.anweisen.utilities.bukkit.utils.item.ItemBuilder { - public static final ItemStack BLOCKED_ITEM = new ItemBuilder(Material.BARRIER, "§cBlocked").build(); - - protected ItemDescription builtByItemDescription; - - public ItemBuilder(@Nonnull ItemStack item) { - super(item); - } - - public ItemBuilder(@Nonnull ItemStack item, @Nullable ItemMeta meta) { - super(item, meta); - } - - public ItemBuilder() { - this(Material.BARRIER, ItemDescription.empty()); - } - - public ItemBuilder(@Nonnull Material material) { - super(material); - } - - public ItemBuilder(@Nonnull Material material, @Nonnull Message message) { - this(material, message.asItemDescription()); - } - - public ItemBuilder(@Nonnull Material material, @Nonnull Message message, Object... args) { - this(material, message.asItemDescription(args)); - } - - public ItemBuilder(@Nonnull Material material, @Nonnull ItemDescription description) { - this(material); - applyFormat(description); - } - - public ItemBuilder(@Nonnull Material material, @Nonnull String name) { - super(material, name); - } - - public ItemBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { - super(material, name, lore); - } - - public ItemBuilder(@Nonnull Material material, @Nonnull String name, int amount) { - super(material, name, amount); - } - - @Nonnull - public ItemBuilder setLore(@Nonnull Message message) { - return setLore(message.asArray()); - } - - @Nonnull - public ItemBuilder setLore(@Nonnull List lore) { - return (ItemBuilder) super.setLore(lore); - } - - @Nonnull - public ItemBuilder setLore(@Nonnull String... lore) { - return (ItemBuilder) super.setLore(lore); - } - - @Nonnull - public ItemBuilder appendLore(@Nonnull String... lore) { - return (ItemBuilder) super.appendLore(lore); - } - - @Nonnull - public ItemBuilder appendLore(@Nonnull Collection lore) { - return (ItemBuilder) super.appendLore(lore); - } - - @Nonnull - public ItemBuilder setName(@Nullable String name) { - return (ItemBuilder) super.setName(name); - } - - @Nonnull - public ItemBuilder setName(@Nullable Object name) { - return (ItemBuilder) super.setName(name); - } - - @Nonnull - public ItemBuilder setName(@Nonnull String... content) { - return (ItemBuilder) super.setName(content); - } - - @Nonnull - public ItemBuilder appendName(@Nullable Object sequence) { - return (ItemBuilder) super.appendName(sequence); - } - - @Nonnull - public ItemBuilder name(@Nullable Object name) { - return (ItemBuilder) super.name(name); - } - - @Nonnull - public ItemBuilder name(@Nonnull String... content) { - return (ItemBuilder) super.name(content); - } - - @Nonnull - public ItemBuilder addEnchantment(@Nonnull Enchantment enchantment, int level) { - return (ItemBuilder) super.addEnchantment(enchantment, level); - } - - @Nonnull - public ItemBuilder enchant(@Nonnull Enchantment enchantment, int level) { - return (ItemBuilder) super.enchant(enchantment, level); - } - - @Nonnull - public ItemBuilder addFlag(@Nonnull ItemFlag... flags) { - return (ItemBuilder) super.addFlag(flags); - } - - @Nonnull - public ItemBuilder removeFlag(@Nonnull ItemFlag... flags) { - return (ItemBuilder) super.removeFlag(flags); - } - - @Nonnull - public ItemBuilder hideAttributes() { - return (ItemBuilder) super.hideAttributes(); - } - - @Nonnull - public ItemBuilder showAttributes() { - return (ItemBuilder) super.showAttributes(); - } - - @Nonnull - public ItemBuilder setUnbreakable(boolean unbreakable) { - return (ItemBuilder) super.setUnbreakable(unbreakable); - } - - @Nonnull - public ItemBuilder unbreakable() { - return (ItemBuilder) super.unbreakable(); - } - - @Nonnull - public ItemBuilder breakable() { - return (ItemBuilder) super.breakable(); - } - - @Nonnull - public ItemBuilder setAmount(int amount) { - return (ItemBuilder) super.setAmount(amount); - } - - @Nonnull - public ItemBuilder amount(int amount) { - return (ItemBuilder) super.amount(amount); - } - - @Nonnull - public ItemBuilder setDamage(int damage) { - return (ItemBuilder) super.setDamage(damage); - } - - @Nonnull - public ItemBuilder damage(int damage) { - return (ItemBuilder) super.damage(damage); - } - - @Nonnull - public ItemBuilder setType(@Nonnull Material material) { - return (ItemBuilder) super.setType(material); - } - - @Nonnull - public ItemBuilder applyFormat(@Nonnull ItemDescription description) { - builtByItemDescription = description; - setName(description.getName()); - setLore(description.getLore()); - return this; - } - - @Nullable - public ItemDescription getBuiltByItemDescription() { - return builtByItemDescription; - } - - @Override - public ItemBuilder clone() { - ItemBuilder builder = new ItemBuilder(item.clone(), getMeta().clone()); - builder.builtByItemDescription = builtByItemDescription; - return builder; - } - - public static class BannerBuilder extends ItemBuilder { - - public BannerBuilder(@Nonnull Material material) { - super(material); - } - - public BannerBuilder(@Nonnull Material material, @Nonnull Message message) { - super(material, message); - } - - public BannerBuilder(@Nonnull Material material, @Nonnull ItemDescription description) { - super(material, description); - } - - public BannerBuilder(@Nonnull Material material, @Nonnull String name) { - super(material, name); - } - - public BannerBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { - super(material, name, lore); - } - - public BannerBuilder(@Nonnull Material material, @Nonnull String name, int amount) { - super(material, name, amount); - } - - public BannerBuilder(@Nonnull ItemStack item) { - super(item); - } - - @Nonnull - public ItemBuilder.BannerBuilder addPattern(@Nonnull BannerPattern pattern, @Nonnull DyeColor color) { - return addPattern(pattern.getPatternType(), color); - } - - @Nonnull - public ItemBuilder.BannerBuilder addPattern(@Nonnull PatternType pattern, @Nonnull DyeColor color) { - getMeta().addPattern(new Pattern(color, pattern)); - return this; - } - - @Nonnull - @Override - public BannerMeta getMeta() { - return getCastedMeta(); - } - - } - - public static class SkullBuilder extends ItemBuilder { - - public SkullBuilder() { - super(Material.PLAYER_HEAD); - } - - public SkullBuilder(Message message) { - super(Material.PLAYER_HEAD, message); - } - - public SkullBuilder(String name, String... lore) { - super(Material.PLAYER_HEAD, name, lore); - } - - @NonNull - public ItemBuilder.SkullBuilder setOwner(@NonNull OfflinePlayer owner) { - getMeta().setOwningPlayer(owner); - return this; - } - - @NonNull - public ItemBuilder.SkullBuilder setOwner(@NonNull UUID uuid, @NonNull String name) { - PlayerProfile profile = Bukkit.createPlayerProfile(uuid, name); - getMeta().setOwnerProfile(profile); - return this; - } - - public ItemBuilder.SkullBuilder setTexture(@NonNull String textureUrl) { - UUID uuid = UUID.nameUUIDFromBytes(textureUrl.getBytes()); - - PlayerProfile profile = Bukkit.createPlayerProfile(uuid); - PlayerTextures texture = profile.getTextures(); - - try { - texture.setSkin(new URL(textureUrl)); - } catch (MalformedURLException e) { - throw new IllegalArgumentException("Invalid texture url", e); - } - - profile.setTextures(texture); - getMeta().setOwnerProfile(profile); - return this; - } - - public ItemBuilder.SkullBuilder setBase64Texture(@NonNull String base64Texture) { - String textureUrlJson = new String(Base64.getDecoder().decode(base64Texture), - StandardCharsets.UTF_8); - - String textureUrl = JsonParser.parseString(textureUrlJson) - .getAsJsonObject() - .get("textures").getAsJsonObject() - .get("SKIN").getAsJsonObject() - .get("url").getAsString(); - - return setTexture(textureUrl); - } - - @Nonnull - @Override - public SkullMeta getMeta() { - return getCastedMeta(); - } - - } - - public static class PotionBuilder extends ItemBuilder { - - public PotionBuilder(@Nonnull Material material) { - super(material); - } - - public PotionBuilder(@Nonnull Material material, @Nonnull Message message) { - super(material, message); - } - - public PotionBuilder(@Nonnull Material material, @Nonnull String name) { - super(material, name); - } - - public PotionBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { - super(material, name, lore); - } - - public PotionBuilder(@Nonnull Material material, @Nonnull String name, int amount) { - super(material, name, amount); - } - - public PotionBuilder(@Nonnull ItemStack item) { - super(item); - } - - @Nonnull - @CheckReturnValue - public static ItemBuilder createWaterBottle() { - return new ItemBuilder.PotionBuilder(Material.POTION).setColor(Color.BLUE).hideAttributes(); - } - - @Nonnull - public ItemBuilder.PotionBuilder addEffect(@Nonnull PotionEffect effect) { - getMeta().addCustomEffect(effect, true); - return this; - } - - @Nonnull - public ItemBuilder.PotionBuilder setColor(@Nonnull Color color) { - getMeta().setColor(color); - return this; - } - - @Nonnull - public ItemBuilder.PotionBuilder color(@Nonnull Color color) { - return setColor(color); - } - - @Nonnull - @Override - public PotionMeta getMeta() { - return getCastedMeta(); - } - - } - - public static class LeatherArmorBuilder extends ItemBuilder { - - public LeatherArmorBuilder(@Nonnull Material material) { - super(material); - } - - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull Message message) { - super(material, message); - } - - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name) { - super(material, name); - } - - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { - super(material, name, lore); - } - - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, int amount) { - super(material, name, amount); - } - - public LeatherArmorBuilder(@Nonnull ItemStack item) { - super(item); - } - - @Nonnull - public ItemBuilder.LeatherArmorBuilder setColor(@Nonnull Color color) { - getMeta().setColor(color); - return this; - } - - @Nonnull - public ItemBuilder.LeatherArmorBuilder color(@Nonnull Color color) { - return setColor(color); - } - - @Nonnull - @Override - public LeatherArmorMeta getMeta() { - return getCastedMeta(); - } - - } + public static final ItemStack BLOCKED_ITEM = new ItemBuilder(Material.BARRIER, "§cBlocked").build(); + + protected ItemDescription builtByItemDescription; + + public ItemBuilder(@Nonnull ItemStack item) { + super(item); + } + + public ItemBuilder(@Nonnull ItemStack item, @Nullable ItemMeta meta) { + super(item, meta); + } + + public ItemBuilder() { + this(Material.BARRIER, ItemDescription.empty()); + } + + public ItemBuilder(@Nonnull Material material) { + super(material); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull Message message) { + this(material, message.asItemDescription()); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull Message message, Object... args) { + this(material, message.asItemDescription(args)); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull ItemDescription description) { + this(material); + applyFormat(description); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + @Nonnull + public ItemBuilder setLore(@Nonnull Message message) { + return setLore(message.asArray()); + } + + @Nonnull + public ItemBuilder setLore(@Nonnull List lore) { + return (ItemBuilder) super.setLore(lore); + } + + @Nonnull + public ItemBuilder setLore(@Nonnull String... lore) { + return (ItemBuilder) super.setLore(lore); + } + + @Nonnull + public ItemBuilder appendLore(@Nonnull String... lore) { + return (ItemBuilder) super.appendLore(lore); + } + + @Nonnull + public ItemBuilder appendLore(@Nonnull Collection lore) { + return (ItemBuilder) super.appendLore(lore); + } + + @Nonnull + public ItemBuilder setName(@Nullable String name) { + return (ItemBuilder) super.setName(name); + } + + @Nonnull + public ItemBuilder setName(@Nullable Object name) { + return (ItemBuilder) super.setName(name); + } + + @Nonnull + public ItemBuilder setName(@Nonnull String... content) { + return (ItemBuilder) super.setName(content); + } + + @Nonnull + public ItemBuilder appendName(@Nullable Object sequence) { + return (ItemBuilder) super.appendName(sequence); + } + + @Nonnull + public ItemBuilder name(@Nullable Object name) { + return (ItemBuilder) super.name(name); + } + + @Nonnull + public ItemBuilder name(@Nonnull String... content) { + return (ItemBuilder) super.name(content); + } + + @Nonnull + public ItemBuilder addEnchantment(@Nonnull Enchantment enchantment, int level) { + return (ItemBuilder) super.addEnchantment(enchantment, level); + } + + @Nonnull + public ItemBuilder enchant(@Nonnull Enchantment enchantment, int level) { + return (ItemBuilder) super.enchant(enchantment, level); + } + + @Nonnull + public ItemBuilder addFlag(@Nonnull ItemFlag... flags) { + return (ItemBuilder) super.addFlag(flags); + } + + @Nonnull + public ItemBuilder removeFlag(@Nonnull ItemFlag... flags) { + return (ItemBuilder) super.removeFlag(flags); + } + + @Nonnull + public ItemBuilder hideAttributes() { + return (ItemBuilder) super.hideAttributes(); + } + + @Nonnull + public ItemBuilder showAttributes() { + return (ItemBuilder) super.showAttributes(); + } + + @Nonnull + public ItemBuilder setUnbreakable(boolean unbreakable) { + return (ItemBuilder) super.setUnbreakable(unbreakable); + } + + @Nonnull + public ItemBuilder unbreakable() { + return (ItemBuilder) super.unbreakable(); + } + + @Nonnull + public ItemBuilder breakable() { + return (ItemBuilder) super.breakable(); + } + + @Nonnull + public ItemBuilder setAmount(int amount) { + return (ItemBuilder) super.setAmount(amount); + } + + @Nonnull + public ItemBuilder amount(int amount) { + return (ItemBuilder) super.amount(amount); + } + + @Nonnull + public ItemBuilder setDamage(int damage) { + return (ItemBuilder) super.setDamage(damage); + } + + @Nonnull + public ItemBuilder damage(int damage) { + return (ItemBuilder) super.damage(damage); + } + + @Nonnull + public ItemBuilder setType(@Nonnull Material material) { + return (ItemBuilder) super.setType(material); + } + + @Nonnull + public ItemBuilder applyFormat(@Nonnull ItemDescription description) { + builtByItemDescription = description; + setName(description.getName()); + setLore(description.getLore()); + return this; + } + + @Nullable + public ItemDescription getBuiltByItemDescription() { + return builtByItemDescription; + } + + @Override + public ItemBuilder clone() { + ItemBuilder builder = new ItemBuilder(item.clone(), getMeta().clone()); + builder.builtByItemDescription = builtByItemDescription; + return builder; + } + + public static class BannerBuilder extends ItemBuilder { + + public BannerBuilder(@Nonnull Material material) { + super(material); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull Message message) { + super(material, message); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull ItemDescription description) { + super(material, description); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public BannerBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public ItemBuilder.BannerBuilder addPattern(@Nonnull BannerPattern pattern, @Nonnull DyeColor color) { + return addPattern(pattern.getPatternType(), color); + } + + @Nonnull + public ItemBuilder.BannerBuilder addPattern(@Nonnull PatternType pattern, @Nonnull DyeColor color) { + getMeta().addPattern(new Pattern(color, pattern)); + return this; + } + + @Nonnull + @Override + public BannerMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class SkullBuilder extends ItemBuilder { + + public SkullBuilder() { + super(Material.PLAYER_HEAD); + } + + public SkullBuilder(Message message) { + super(Material.PLAYER_HEAD, message); + } + + public SkullBuilder(String name, String... lore) { + super(Material.PLAYER_HEAD, name, lore); + } + + @NonNull + public ItemBuilder.SkullBuilder setOwner(@NonNull OfflinePlayer owner) { + getMeta().setOwningPlayer(owner); + return this; + } + + @NonNull + public ItemBuilder.SkullBuilder setOwner(@NonNull UUID uuid, @NonNull String name) { + PlayerProfile profile = Bukkit.createPlayerProfile(uuid, name); + getMeta().setOwnerProfile(profile); + return this; + } + + public ItemBuilder.SkullBuilder setTexture(@NonNull String textureUrl) { + UUID uuid = UUID.nameUUIDFromBytes(textureUrl.getBytes()); + + PlayerProfile profile = Bukkit.createPlayerProfile(uuid); + PlayerTextures texture = profile.getTextures(); + + try { + texture.setSkin(new URL(textureUrl)); + } catch (MalformedURLException e) { + throw new IllegalArgumentException("Invalid texture url", e); + } + + profile.setTextures(texture); + getMeta().setOwnerProfile(profile); + return this; + } + + public ItemBuilder.SkullBuilder setBase64Texture(@NonNull String base64Texture) { + String textureUrlJson = new String(Base64.getDecoder().decode(base64Texture), + StandardCharsets.UTF_8); + + String textureUrl = JsonParser.parseString(textureUrlJson) + .getAsJsonObject() + .get("textures").getAsJsonObject() + .get("SKIN").getAsJsonObject() + .get("url").getAsString(); + + return setTexture(textureUrl); + } + + @Nonnull + @Override + public SkullMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class PotionBuilder extends ItemBuilder { + + public PotionBuilder(@Nonnull Material material) { + super(material); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull Message message) { + super(material, message); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public PotionBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + @CheckReturnValue + public static ItemBuilder createWaterBottle() { + return new ItemBuilder.PotionBuilder(Material.POTION).setColor(Color.BLUE).hideAttributes(); + } + + @Nonnull + public ItemBuilder.PotionBuilder addEffect(@Nonnull PotionEffect effect) { + getMeta().addCustomEffect(effect, true); + return this; + } + + @Nonnull + public ItemBuilder.PotionBuilder setColor(@Nonnull Color color) { + getMeta().setColor(color); + return this; + } + + @Nonnull + public ItemBuilder.PotionBuilder color(@Nonnull Color color) { + return setColor(color); + } + + @Nonnull + @Override + public PotionMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class LeatherArmorBuilder extends ItemBuilder { + + public LeatherArmorBuilder(@Nonnull Material material) { + super(material); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull Message message) { + super(material, message); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public LeatherArmorBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public ItemBuilder.LeatherArmorBuilder setColor(@Nonnull Color color) { + getMeta().setColor(color); + return this; + } + + @Nonnull + public ItemBuilder.LeatherArmorBuilder color(@Nonnull Color color) { + return setColor(color); + } + + @Nonnull + @Override + public LeatherArmorMeta getMeta() { + return getCastedMeta(); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java index 42a6efc52..ce75b81eb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java @@ -11,107 +11,107 @@ public class ItemUtils { - @Nonnull - public static Material convertFoodToCookedFood(@Nonnull Material material) { - try { - return Material.valueOf("COOKED_" + material.name()); - } catch (Exception ex) { - return material; // No cooked material is available - } + @Nonnull + public static Material convertFoodToCookedFood(@Nonnull Material material) { + try { + return Material.valueOf("COOKED_" + material.name()); + } catch (Exception ex) { + return material; // No cooked material is available } + } - public static boolean isObtainableInSurvival(@Nonnull Material material) { - String name = material.name(); - if (BukkitReflectionUtils.isAir(material)) return false; - if (name.endsWith("_SPAWN_EGG")) return false; - if (name.startsWith("INFESTED_")) return false; - if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable - switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist - case "CHAIN_COMMAND_BLOCK": - case "REPEATING_COMMAND_BLOCK": - case "COMMAND_BLOCK": - case "COMMAND_BLOCK_MINECART": - case "JIGSAW": - case "STRUCTURE_BLOCK": - case "STRUCTURE_VOID": - case "BARRIER": - case "BEDROCK": - case "KNOWLEDGE_BOOK": - case "DEBUG_STICK": - case "END_PORTAL_FRAME": - case "END_PORTAL": - case "NETHER_PORTAL": - case "END_GATEWAY": - case "LAVA": - case "WATER": - case "LARGE_FERN": - case "TALL_GRASS": - case "TALL_SEAGRASS": - case "PATH_BLOCK": - case "CHORUS_PLANT": - case "PETRIFIED_OAK_SLAB": - case "FARMLAND": - case "PLAYER_HEAD": - case "GLOBE_BANNER_PATTERN": - case "SPAWNER": - case "AMETHYST_CLUSTER": - case "BUDDING_AMETHYST": - case "POWDER_SNOW": - case "LIGHT": - case "BUNDLE": - case "REINFORCED_DEEPSLATE": - case "FROGSPAWN": - return false; - } - - if (MinecraftVersion.current().isOlderThan(MinecraftVersion.V1_19)) { - return !name.equals("SCULK_SENSOR"); - } + public static boolean isObtainableInSurvival(@Nonnull Material material) { + String name = material.name(); + if (BukkitReflectionUtils.isAir(material)) return false; + if (name.endsWith("_SPAWN_EGG")) return false; + if (name.startsWith("INFESTED_")) return false; + if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable + switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist + case "CHAIN_COMMAND_BLOCK": + case "REPEATING_COMMAND_BLOCK": + case "COMMAND_BLOCK": + case "COMMAND_BLOCK_MINECART": + case "JIGSAW": + case "STRUCTURE_BLOCK": + case "STRUCTURE_VOID": + case "BARRIER": + case "BEDROCK": + case "KNOWLEDGE_BOOK": + case "DEBUG_STICK": + case "END_PORTAL_FRAME": + case "END_PORTAL": + case "NETHER_PORTAL": + case "END_GATEWAY": + case "LAVA": + case "WATER": + case "LARGE_FERN": + case "TALL_GRASS": + case "TALL_SEAGRASS": + case "PATH_BLOCK": + case "CHORUS_PLANT": + case "PETRIFIED_OAK_SLAB": + case "FARMLAND": + case "PLAYER_HEAD": + case "GLOBE_BANNER_PATTERN": + case "SPAWNER": + case "AMETHYST_CLUSTER": + case "BUDDING_AMETHYST": + case "POWDER_SNOW": + case "LIGHT": + case "BUNDLE": + case "REINFORCED_DEEPSLATE": + case "FROGSPAWN": + return false; + } - return true; + if (MinecraftVersion.current().isOlderThan(MinecraftVersion.V1_19)) { + return !name.equals("SCULK_SENSOR"); } - public static boolean blockIsAvailableInSurvival(@Nonnull Material material) { - if (!material.isBlock()) return false; - String name = material.name(); - if (BukkitReflectionUtils.isAir(material)) return false; - if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable - switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist - case "CHAIN_COMMAND_BLOCK": - case "REPEATING_COMMAND_BLOCK": - case "COMMAND_BLOCK": - case "COMMAND_BLOCK_MINECART": - case "JIGSAW": - case "STRUCTURE_BLOCK": - case "STRUCTURE_VOID": - case "BARRIER": - case "KNOWLEDGE_BOOK": - case "DEBUG_STICK": - case "END_PORTAL": - case "NETHER_PORTAL": - case "END_GATEWAY": - case "PETRIFIED_OAK_SLAB": - case "PLAYER_HEAD": - case "GLOBE_BANNER_PATTERN": - case "LIGHT": - case "BUNDLE": - return false; - } + return true; + } - return true; + public static boolean blockIsAvailableInSurvival(@Nonnull Material material) { + if (!material.isBlock()) return false; + String name = material.name(); + if (BukkitReflectionUtils.isAir(material)) return false; + if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable + switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist + case "CHAIN_COMMAND_BLOCK": + case "REPEATING_COMMAND_BLOCK": + case "COMMAND_BLOCK": + case "COMMAND_BLOCK_MINECART": + case "JIGSAW": + case "STRUCTURE_BLOCK": + case "STRUCTURE_VOID": + case "BARRIER": + case "KNOWLEDGE_BOOK": + case "DEBUG_STICK": + case "END_PORTAL": + case "NETHER_PORTAL": + case "END_GATEWAY": + case "PETRIFIED_OAK_SLAB": + case "PLAYER_HEAD": + case "GLOBE_BANNER_PATTERN": + case "LIGHT": + case "BUNDLE": + return false; } - public static void damageItem(@Nonnull ItemStack item) { - damageItem(item, 1); - } + return true; + } - public static void damageItem(@Nonnull ItemStack item, int amount) { - ItemMeta meta = item.getItemMeta(); - if (meta == null) return; - if (!(meta instanceof Damageable)) return; - Damageable damageable = (Damageable) meta; - damageable.setDamage(damageable.getDamage() + amount); - item.setItemMeta(meta); - } + public static void damageItem(@Nonnull ItemStack item) { + damageItem(item, 1); + } + + public static void damageItem(@Nonnull ItemStack item, int amount) { + ItemMeta meta = item.getItemMeta(); + if (meta == null) return; + if (!(meta instanceof Damageable)) return; + Damageable damageable = (Damageable) meta; + damageable.setDamage(damageable.getDamage() + amount); + item.setItemMeta(meta); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java index 43eaa118e..6f4382d40 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java @@ -8,72 +8,72 @@ public final class ConsolePrint { - private ConsolePrint() { - } + private ConsolePrint() { + } - public static void notSpigot() { - log(""); - log("============================================================================================="); - log(""); - log("Your server does NOT run an instance of spigot (Your server: " + Bukkit.getVersion() + ")"); - log("Please use an instance of spigot or paper to be able to use this plugin!"); - log(""); - log("Paper Download: https://papermc.io/downloads"); - log(""); - log("============================================================================================="); - log(""); - } + public static void notSpigot() { + log(""); + log("============================================================================================="); + log(""); + log("Your server does NOT run an instance of spigot (Your server: " + Bukkit.getVersion() + ")"); + log("Please use an instance of spigot or paper to be able to use this plugin!"); + log(""); + log("Paper Download: https://papermc.io/downloads"); + log(""); + log("============================================================================================="); + log(""); + } - public static void unknownLanguage(@Nullable String language) { - log(""); - log("Found unknown language '" + language + "'!"); - log("Defaulting to en (English)"); - log(""); - } + public static void unknownLanguage(@Nullable String language) { + log(""); + log("Found unknown language '" + language + "'!"); + log("Defaulting to en (English)"); + log(""); + } - public static void unableToGetLanguages() { - log(""); - log("No languages found to load"); - log("Is the server / plugin set up correctly?"); - log(""); - } + public static void unableToGetLanguages() { + log(""); + log("No languages found to load"); + log("Is the server / plugin set up correctly?"); + log(""); + } - public static void alreadyExecutingContentLoader() { - log(""); - log("Cannot load contents; Already loading contents?"); - log("Are you reloading too fast?"); - log(""); - } + public static void alreadyExecutingContentLoader() { + log(""); + log("Cannot load contents; Already loading contents?"); + log("Are you reloading too fast?"); + log(""); + } - public static void accessBlocked() { - log(" "); - log(" "); - log("██████╗░██╗░░░░░░█████╗░░█████╗░██╗░░██╗███████╗██████╗░"); - log("██╔══██╗██║░░░░░██╔══██╗██╔══██╗██║░██╔╝██╔════╝██╔══██╗"); - log("██████╦╝██║░░░░░██║░░██║██║░░╚═╝█████═╝░█████╗░░██║░░██║"); - log("██╔══██╗██║░░░░░██║░░██║██║░░██╗██╔═██╗░██╔══╝░░██║░░██║"); - log("██████╦╝███████╗╚█████╔╝╚█████╔╝██║░╚██╗███████╗██████╔╝"); - log("╚═════╝░╚══════╝░╚════╝░░╚════╝░╚═╝░░╚═╝╚══════╝╚═════╝░"); - log(" "); - log("Your server's access is blocked."); - log("For more information and support visit our discord server: https://discord.coding-area.net"); - log(" "); - log(" "); - } + public static void accessBlocked() { + log(" "); + log(" "); + log("██████╗░██╗░░░░░░█████╗░░█████╗░██╗░░██╗███████╗██████╗░"); + log("██╔══██╗██║░░░░░██╔══██╗██╔══██╗██║░██╔╝██╔════╝██╔══██╗"); + log("██████╦╝██║░░░░░██║░░██║██║░░╚═╝█████═╝░█████╗░░██║░░██║"); + log("██╔══██╗██║░░░░░██║░░██║██║░░██╗██╔═██╗░██╔══╝░░██║░░██║"); + log("██████╦╝███████╗╚█████╔╝╚█████╔╝██║░╚██╗███████╗██████╔╝"); + log("╚═════╝░╚══════╝░╚════╝░░╚════╝░╚═╝░░╚═╝╚══════╝╚═════╝░"); + log(" "); + log("Your server's access is blocked."); + log("For more information and support visit our discord server: https://discord.coding-area.net"); + log(" "); + log(" "); + } - public static void noMongoDependencies() { - log(""); - log("============================================================================================="); - log(""); - log("Cannot use MongoDB as database without the Challenges-MongoConnector dependency plugin."); - log("Please add this plugin in order to be able to access a mongodb database."); - log(""); - log("============================================================================================="); - log(""); - } + public static void noMongoDependencies() { + log(""); + log("============================================================================================="); + log(""); + log("Cannot use MongoDB as database without the Challenges-MongoConnector dependency plugin."); + log("Please add this plugin in order to be able to access a mongodb database."); + log(""); + log("============================================================================================="); + log(""); + } - private static void log(@Nonnull String message) { - Logger.error(message); - } + private static void log(@Nonnull String message) { + Logger.error(message); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java index e80deebf8..44db4456d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java @@ -4,20 +4,20 @@ public final class ArmorUtils { - private ArmorUtils() { - } + private ArmorUtils() { + } - public static Material[] getArmor() { - return new Material[]{ - Material.IRON_CHESTPLATE, Material.IRON_LEGGINGS, Material.IRON_BOOTS, Material.IRON_HELMET, - Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS, Material.DIAMOND_HELMET, - Material.GOLDEN_CHESTPLATE, Material.GOLDEN_LEGGINGS, Material.GOLDEN_BOOTS, Material.GOLDEN_HELMET, - Material.LEATHER_CHESTPLATE, Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS, Material.LEATHER_HELMET, - Material.CHAINMAIL_CHESTPLATE, Material.CHAINMAIL_LEGGINGS, Material.CHAINMAIL_BOOTS, Material.CHAINMAIL_HELMET, - Utils.getMaterial("NETHERITE_CHESTPLATE"), Utils.getMaterial("NETHERITE_LEGGINGS"), - Utils.getMaterial("NETHERITE_BOOTS"), Utils.getMaterial("NETHERITE_HELMET"), - Material.TURTLE_HELMET - }; - } + public static Material[] getArmor() { + return new Material[]{ + Material.IRON_CHESTPLATE, Material.IRON_LEGGINGS, Material.IRON_BOOTS, Material.IRON_HELMET, + Material.DIAMOND_CHESTPLATE, Material.DIAMOND_LEGGINGS, Material.DIAMOND_BOOTS, Material.DIAMOND_HELMET, + Material.GOLDEN_CHESTPLATE, Material.GOLDEN_LEGGINGS, Material.GOLDEN_BOOTS, Material.GOLDEN_HELMET, + Material.LEATHER_CHESTPLATE, Material.LEATHER_LEGGINGS, Material.LEATHER_BOOTS, Material.LEATHER_HELMET, + Material.CHAINMAIL_CHESTPLATE, Material.CHAINMAIL_LEGGINGS, Material.CHAINMAIL_BOOTS, Material.CHAINMAIL_HELMET, + Utils.getMaterial("NETHERITE_CHESTPLATE"), Utils.getMaterial("NETHERITE_LEGGINGS"), + Utils.getMaterial("NETHERITE_BOOTS"), Utils.getMaterial("NETHERITE_HELMET"), + Material.TURTLE_HELMET + }; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java index 071ef4ffc..dc533cbb8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java @@ -13,213 +13,213 @@ public final class BlockUtils { - private static final BlockFace[] faces = { - BlockFace.UP, BlockFace.DOWN, - BlockFace.NORTH, BlockFace.EAST, - BlockFace.SOUTH, BlockFace.WEST - }; - - private BlockUtils() { - } - - public static boolean isSameBlockLocation(@Nullable Location loc1, @Nullable Location loc2) { - if (loc1 == null || loc2 == null) return true; - if (loc1.getWorld() != loc2.getWorld()) return false; - return loc1.getBlockX() == loc2.getBlockX() - && loc1.getBlockY() == loc2.getBlockY() - && loc1.getBlockZ() == loc2.getBlockZ(); - } - - public static boolean isSameBlockLocationIgnoreHeight(@Nullable Location loc1, @Nullable Location loc2) { - if (loc1 == null || loc2 == null) return false; - if (loc1.getWorld() != loc2.getWorld()) return false; - return loc1.getBlockX() == loc2.getBlockX() - && loc1.getBlockZ() == loc2.getBlockZ(); - } - - public static boolean isSameLocation(@Nonnull Location loc1, @Nonnull Location loc2) { - if (loc1.getWorld() != loc2.getWorld()) return false; - return loc1.distance(loc2) < 0.1; - } - - public static boolean isSameLocationIgnoreHeight(@Nonnull Location loc1, @Nonnull Location loc2) { - if (loc1.getWorld() != loc2.getWorld()) return false; - return loc1.getX() == loc2.getX() - && loc1.getZ() == loc2.getZ(); - } - - public static boolean isSameChunk(@Nonnull Chunk chunk1, @Nonnull Chunk chunk2) { - if (chunk1.getWorld() != chunk2.getWorld()) return false; - return chunk1.getX() == chunk2.getX() && chunk1.getZ() == chunk2.getZ(); - } - - public static boolean isSameBlockIgnoreHeight(@Nullable Location loc1, @Nullable Location loc2) { - if (loc1 == null || loc2 == null) return false; - return loc1.getBlockX() == loc2.getBlockX() - && loc1.getBlockZ() == loc2.getBlockZ(); - } - - /** - * @param block middle block - * @return the block above, under, in the front, behind, to the left and to the right of the middle block - */ - @Nonnull - public static List getBlocksAroundBlock(@Nonnull Block block) { - List list = new ArrayList<>(); - for (BlockFace face : faces) { - list.add(block.getRelative(face)); - } - return list; - } - - public static Material getTerracotta(int subId) { - switch (subId) { - case 2: - return Material.ORANGE_TERRACOTTA; - case 3: - return Material.MAGENTA_TERRACOTTA; - case 4: - return Material.LIGHT_BLUE_TERRACOTTA; - case 5: - return Material.YELLOW_TERRACOTTA; - case 6: - return Material.LIME_TERRACOTTA; - case 7: - return Material.PINK_TERRACOTTA; - case 8: - return Material.GRAY_TERRACOTTA; - case 9: - return Material.LIGHT_GRAY_TERRACOTTA; - case 10: - return Material.CYAN_TERRACOTTA; - case 11: - return Material.PURPLE_TERRACOTTA; - case 12: - return Material.BLUE_TERRACOTTA; - case 13: - return Material.BROWN_TERRACOTTA; - case 14: - return Material.GREEN_TERRACOTTA; - case 15: - return Material.RED_TERRACOTTA; - case 16: - return Material.BLACK_TERRACOTTA; - default: - return Material.WHITE_TERRACOTTA; - } - } - - public static void createBlockPath(@Nullable Location from, @Nullable Location to, @Nonnull Material type) { - createBlockPath(from, to, type, true); - } - - public static void createBlockPath(@Nullable Location from, @Nullable Location to, @Nonnull Material type, boolean playSound) { - if (from == null || to == null) return; - if (isSameBlockLocationIgnoreHeight(from, to)) return; - - setBlockNatural(getBlockBelow(to), type, playSound); - } - - /** - * Sets the material of the block and breaks snow or other not solid blocks on top of it - * - * @param block the block of block to replace - * @param type the type to set as the block type - */ - public static void setBlockNatural(@Nullable Block block, @Nonnull Material type, boolean blockUpdate) { - setBlockNatural(block, type, blockUpdate, true); - } - - /** - * Sets the material of the block and breaks snow or other not solid blocks on top of it - * - * @param block the block of block to replace - * @param type the type to set as the block type - * @param playSound if a breaking sound for the block on top should be played - */ - public static void setBlockNatural(@Nullable Block block, @Nonnull Material type, boolean blockUpdate, boolean playSound) { - if (block == null || !block.getType().isSolid()) return; - - Block upperBlock = block.getLocation().add(0, 1, 0).getBlock(); - - if (!upperBlock.getType().isSolid()) { - upperBlock.breakNaturally(); - // TODO: PLAY THE RIGHT BREAKING SOUND FOR THE BLOCK - + private static final BlockFace[] faces = { + BlockFace.UP, BlockFace.DOWN, + BlockFace.NORTH, BlockFace.EAST, + BlockFace.SOUTH, BlockFace.WEST + }; + + private BlockUtils() { + } + + public static boolean isSameBlockLocation(@Nullable Location loc1, @Nullable Location loc2) { + if (loc1 == null || loc2 == null) return true; + if (loc1.getWorld() != loc2.getWorld()) return false; + return loc1.getBlockX() == loc2.getBlockX() + && loc1.getBlockY() == loc2.getBlockY() + && loc1.getBlockZ() == loc2.getBlockZ(); + } + + public static boolean isSameBlockLocationIgnoreHeight(@Nullable Location loc1, @Nullable Location loc2) { + if (loc1 == null || loc2 == null) return false; + if (loc1.getWorld() != loc2.getWorld()) return false; + return loc1.getBlockX() == loc2.getBlockX() + && loc1.getBlockZ() == loc2.getBlockZ(); + } + + public static boolean isSameLocation(@Nonnull Location loc1, @Nonnull Location loc2) { + if (loc1.getWorld() != loc2.getWorld()) return false; + return loc1.distance(loc2) < 0.1; + } + + public static boolean isSameLocationIgnoreHeight(@Nonnull Location loc1, @Nonnull Location loc2) { + if (loc1.getWorld() != loc2.getWorld()) return false; + return loc1.getX() == loc2.getX() + && loc1.getZ() == loc2.getZ(); + } + + public static boolean isSameChunk(@Nonnull Chunk chunk1, @Nonnull Chunk chunk2) { + if (chunk1.getWorld() != chunk2.getWorld()) return false; + return chunk1.getX() == chunk2.getX() && chunk1.getZ() == chunk2.getZ(); + } + + public static boolean isSameBlockIgnoreHeight(@Nullable Location loc1, @Nullable Location loc2) { + if (loc1 == null || loc2 == null) return false; + return loc1.getBlockX() == loc2.getBlockX() + && loc1.getBlockZ() == loc2.getBlockZ(); + } + + /** + * @param block middle block + * @return the block above, under, in the front, behind, to the left and to the right of the middle block + */ + @Nonnull + public static List getBlocksAroundBlock(@Nonnull Block block) { + List list = new ArrayList<>(); + for (BlockFace face : faces) { + list.add(block.getRelative(face)); + } + return list; + } + + public static Material getTerracotta(int subId) { + switch (subId) { + case 2: + return Material.ORANGE_TERRACOTTA; + case 3: + return Material.MAGENTA_TERRACOTTA; + case 4: + return Material.LIGHT_BLUE_TERRACOTTA; + case 5: + return Material.YELLOW_TERRACOTTA; + case 6: + return Material.LIME_TERRACOTTA; + case 7: + return Material.PINK_TERRACOTTA; + case 8: + return Material.GRAY_TERRACOTTA; + case 9: + return Material.LIGHT_GRAY_TERRACOTTA; + case 10: + return Material.CYAN_TERRACOTTA; + case 11: + return Material.PURPLE_TERRACOTTA; + case 12: + return Material.BLUE_TERRACOTTA; + case 13: + return Material.BROWN_TERRACOTTA; + case 14: + return Material.GREEN_TERRACOTTA; + case 15: + return Material.RED_TERRACOTTA; + case 16: + return Material.BLACK_TERRACOTTA; + default: + return Material.WHITE_TERRACOTTA; + } + } + + public static void createBlockPath(@Nullable Location from, @Nullable Location to, @Nonnull Material type) { + createBlockPath(from, to, type, true); + } + + public static void createBlockPath(@Nullable Location from, @Nullable Location to, @Nonnull Material type, boolean playSound) { + if (from == null || to == null) return; + if (isSameBlockLocationIgnoreHeight(from, to)) return; + + setBlockNatural(getBlockBelow(to), type, playSound); + } + + /** + * Sets the material of the block and breaks snow or other not solid blocks on top of it + * + * @param block the block of block to replace + * @param type the type to set as the block type + */ + public static void setBlockNatural(@Nullable Block block, @Nonnull Material type, boolean blockUpdate) { + setBlockNatural(block, type, blockUpdate, true); + } + + /** + * Sets the material of the block and breaks snow or other not solid blocks on top of it + * + * @param block the block of block to replace + * @param type the type to set as the block type + * @param playSound if a breaking sound for the block on top should be played + */ + public static void setBlockNatural(@Nullable Block block, @Nonnull Material type, boolean blockUpdate, boolean playSound) { + if (block == null || !block.getType().isSolid()) return; + + Block upperBlock = block.getLocation().add(0, 1, 0).getBlock(); + + if (!upperBlock.getType().isSolid()) { + upperBlock.breakNaturally(); + // TODO: PLAY THE RIGHT BREAKING SOUND FOR THE BLOCK + + } + + block.setType(type, blockUpdate); + } + + /** + * @param location the location to get the block below + * @return the block below the location + */ + @Nullable + public static Block getBlockBelow(@Nonnull Location location) { + return getBlockBelow(location, 0.1); + } + + /** + * @param location the location to get the block below + * @return the block below the location + */ + @Nullable + public static Block getBlockBelow(@Nonnull Location location, boolean ignoreNonSolid) { + return getBlockBelow(location, 0.1, ignoreNonSolid); + } + + /** + * @param location the location to get the block below + * @return the block below the location + */ + @Nullable + public static Block getBlockBelow(@Nonnull Location location, double offset) { + return getBlockBelow(location, offset, true); + } + + /** + * @param location the location to get the block below + * @return the block below the location + */ + @Nullable + public static Block getBlockBelow(@Nonnull Location location, double offset, boolean ignoreNonSolid) { + + Block block; + if (offset == -1) { + block = getBlockBelow(location, 0.1, ignoreNonSolid); + if (block == null) { + block = getBlockBelow(location, 1, ignoreNonSolid); + if (block == null) { + block = getBlockBelow(location, 1.5, ignoreNonSolid); } - - block.setType(type, blockUpdate); - } - - /** - * @param location the location to get the block below - * @return the block below the location - */ - @Nullable - public static Block getBlockBelow(@Nonnull Location location) { - return getBlockBelow(location, 0.1); - } - - /** - * @param location the location to get the block below - * @return the block below the location - */ - @Nullable - public static Block getBlockBelow(@Nonnull Location location, boolean ignoreNonSolid) { - return getBlockBelow(location, 0.1, ignoreNonSolid); - } - - /** - * @param location the location to get the block below - * @return the block below the location - */ - @Nullable - public static Block getBlockBelow(@Nonnull Location location, double offset) { - return getBlockBelow(location, offset, true); - } - - /** - * @param location the location to get the block below - * @return the block below the location - */ - @Nullable - public static Block getBlockBelow(@Nonnull Location location, double offset, boolean ignoreNonSolid) { - - Block block; - if (offset == -1) { - block = getBlockBelow(location, 0.1, ignoreNonSolid); - if (block == null) { - block = getBlockBelow(location, 1, ignoreNonSolid); - if (block == null) { - block = getBlockBelow(location, 1.5, ignoreNonSolid); - } - } - - } else { - block = location.clone().subtract(0, offset, 0).getBlock(); - } - - if (block == null) return null; - if (ignoreNonSolid && !block.getType().isSolid()) { - return null; - } - return block; - } - - public static boolean isEndItem(Material material) { - String name = material.name(); - return material == Material.ELYTRA || - name.contains("PURPUR") || - name.contains("SHULKER") || - name.contains("END"); - } - - public static boolean isTooHardToGet(Material material) { - String name = material.name(); - return name.contains("EXPOSED") || - name.contains("WEATHERED") || - name.contains("OXIDIZED") || - name.contains("BUD"); - } + } + + } else { + block = location.clone().subtract(0, offset, 0).getBlock(); + } + + if (block == null) return null; + if (ignoreNonSolid && !block.getType().isSolid()) { + return null; + } + return block; + } + + public static boolean isEndItem(Material material) { + String name = material.name(); + return material == Material.ELYTRA || + name.contains("PURPUR") || + name.contains("SHULKER") || + name.contains("END"); + } + + public static boolean isTooHardToGet(Material material) { + String name = material.name(); + return name.contains("EXPOSED") || + name.contains("WEATHERED") || + name.contains("OXIDIZED") || + name.contains("BUD"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java index 7ac2e0cd9..86d28fe59 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java @@ -12,148 +12,148 @@ public final class ColorConversions { - private static final Map colorsByChatColor = new HashMap<>(); - - static { - colorsByChatColor.put(ChatColor.BLACK, Color.decode("#000000")); - colorsByChatColor.put(ChatColor.DARK_BLUE, Color.decode("#0000A8")); - colorsByChatColor.put(ChatColor.DARK_GREEN, Color.decode("#00A800")); - colorsByChatColor.put(ChatColor.DARK_AQUA, Color.decode("#00A8A8")); - colorsByChatColor.put(ChatColor.DARK_RED, Color.decode("#A80000")); - colorsByChatColor.put(ChatColor.DARK_PURPLE, Color.decode("#A800A8")); - colorsByChatColor.put(ChatColor.GOLD, Color.decode("#FBA800")); - colorsByChatColor.put(ChatColor.GRAY, Color.decode("#A8A8A8")); - colorsByChatColor.put(ChatColor.DARK_GRAY, Color.decode("#545454")); - colorsByChatColor.put(ChatColor.BLUE, Color.decode("#5454FB")); - colorsByChatColor.put(ChatColor.GREEN, Color.decode("#54FB54")); - colorsByChatColor.put(ChatColor.AQUA, Color.decode("#54FBFB")); - colorsByChatColor.put(ChatColor.RED, Color.decode("#FB5454")); - colorsByChatColor.put(ChatColor.LIGHT_PURPLE, Color.decode("#FB54FB")); - colorsByChatColor.put(ChatColor.YELLOW, Color.decode("#FBFB54")); - colorsByChatColor.put(ChatColor.WHITE, Color.decode("#FBFBFB")); - } - - private ColorConversions() { - } - - @Nonnull - public static ChatColor convertDyeColorToChatColor(@Nonnull DyeColor color) { - switch (color) { - case RED: - return ChatColor.RED; - case BLUE: - return ChatColor.DARK_BLUE; - case CYAN: - return ChatColor.DARK_AQUA; - case GRAY: - return ChatColor.DARK_GRAY; - case LIME: - return ChatColor.GREEN; - case GREEN: - return ChatColor.DARK_GREEN; - case PURPLE: - return ChatColor.DARK_PURPLE; - case YELLOW: - return ChatColor.YELLOW; - case LIGHT_BLUE: - return ChatColor.BLUE; - case LIGHT_GRAY: - return ChatColor.GRAY; - case BLACK: - return ChatColor.BLACK; - case BROWN: - case ORANGE: - return ChatColor.GOLD; - case PINK: - case MAGENTA: - return ChatColor.LIGHT_PURPLE; - case WHITE: - default: - return ChatColor.WHITE; - } - } - - @Nonnull - public static Material convertDyeColorToMaterial(@Nonnull DyeColor color) { - switch (color) { - case YELLOW: - return MinecraftNameWrapper.YELLOW_DYE; - case RED: - return MinecraftNameWrapper.RED_DYE; - case GREEN: - return MinecraftNameWrapper.GREEN_DYE; - case BLACK: - return Material.INK_SAC; - case GRAY: - return Material.GRAY_DYE; - case LIGHT_GRAY: - return Material.LIGHT_GRAY_DYE; - case BLUE: - return Material.LAPIS_LAZULI; - case LIGHT_BLUE: - return Material.LIGHT_BLUE_DYE; - case MAGENTA: - return Material.MAGENTA_DYE; - case BROWN: - return Material.COCOA_BEANS; - case PURPLE: - return Material.PURPLE_DYE; - case ORANGE: - return Material.ORANGE_DYE; - case PINK: - return Material.PINK_DYE; - case LIME: - return Material.LIME_DYE; - case CYAN: - return Material.CYAN_DYE; - case WHITE: - default: - return Material.BONE_MEAL; - } - } - - @Nonnull - public static ChatColor convertAwtColorToChatColor(@Nonnull Color color) { - return colorsByChatColor.entrySet().stream() - .min((o1, o2) -> (int) ((calculateDifferenceBetweenColors(color, o1.getValue()) - calculateDifferenceBetweenColors(color, o2.getValue())) * 100)) - .orElseThrow(() -> new IllegalStateException("Could not find a ChatColor for the given input")) - .getKey(); - } - - @Nonnull - public static Color convertChatColorToAwtColor(@Nonnull ChatColor color) { - return Optional.ofNullable(colorsByChatColor.get(color)).orElseThrow(() -> new IllegalStateException("Could not find a color for ChatColor." + color.name())); - } - - @Nonnull - public static float[] convertAwtColorToHSB(@Nonnull Color color) { - return Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); - } - - public static double calculateDifferenceBetweenColors(@Nonnull Color color1, @Nonnull Color color2) { - - int diffRed = Math.abs(color1.getRed() - color2.getRed()); - int diffGreen = Math.abs(color1.getGreen() - color2.getGreen()); - int diffBlue = Math.abs(color1.getBlue() - color2.getBlue()); - - float pctDiffRed = (float) diffRed / 255f; - float pctDiffGreen = (float) diffGreen / 255f; - float pctDiffBlue = (float) diffBlue / 255f; - - return (pctDiffRed + pctDiffGreen + pctDiffBlue) / 3f * 100; - } - - public static boolean isValidColorCode(char code) { - for (ChatColor color : ChatColor.values()) { - if (color.isColor() && color.getChar() == code) - return true; - } - return false; - } - - public static boolean isValidColorCode(@Nonnull String code) { - if (code.length() != 1) return false; - return isValidColorCode(code.toCharArray()[0]); - } + private static final Map colorsByChatColor = new HashMap<>(); + + static { + colorsByChatColor.put(ChatColor.BLACK, Color.decode("#000000")); + colorsByChatColor.put(ChatColor.DARK_BLUE, Color.decode("#0000A8")); + colorsByChatColor.put(ChatColor.DARK_GREEN, Color.decode("#00A800")); + colorsByChatColor.put(ChatColor.DARK_AQUA, Color.decode("#00A8A8")); + colorsByChatColor.put(ChatColor.DARK_RED, Color.decode("#A80000")); + colorsByChatColor.put(ChatColor.DARK_PURPLE, Color.decode("#A800A8")); + colorsByChatColor.put(ChatColor.GOLD, Color.decode("#FBA800")); + colorsByChatColor.put(ChatColor.GRAY, Color.decode("#A8A8A8")); + colorsByChatColor.put(ChatColor.DARK_GRAY, Color.decode("#545454")); + colorsByChatColor.put(ChatColor.BLUE, Color.decode("#5454FB")); + colorsByChatColor.put(ChatColor.GREEN, Color.decode("#54FB54")); + colorsByChatColor.put(ChatColor.AQUA, Color.decode("#54FBFB")); + colorsByChatColor.put(ChatColor.RED, Color.decode("#FB5454")); + colorsByChatColor.put(ChatColor.LIGHT_PURPLE, Color.decode("#FB54FB")); + colorsByChatColor.put(ChatColor.YELLOW, Color.decode("#FBFB54")); + colorsByChatColor.put(ChatColor.WHITE, Color.decode("#FBFBFB")); + } + + private ColorConversions() { + } + + @Nonnull + public static ChatColor convertDyeColorToChatColor(@Nonnull DyeColor color) { + switch (color) { + case RED: + return ChatColor.RED; + case BLUE: + return ChatColor.DARK_BLUE; + case CYAN: + return ChatColor.DARK_AQUA; + case GRAY: + return ChatColor.DARK_GRAY; + case LIME: + return ChatColor.GREEN; + case GREEN: + return ChatColor.DARK_GREEN; + case PURPLE: + return ChatColor.DARK_PURPLE; + case YELLOW: + return ChatColor.YELLOW; + case LIGHT_BLUE: + return ChatColor.BLUE; + case LIGHT_GRAY: + return ChatColor.GRAY; + case BLACK: + return ChatColor.BLACK; + case BROWN: + case ORANGE: + return ChatColor.GOLD; + case PINK: + case MAGENTA: + return ChatColor.LIGHT_PURPLE; + case WHITE: + default: + return ChatColor.WHITE; + } + } + + @Nonnull + public static Material convertDyeColorToMaterial(@Nonnull DyeColor color) { + switch (color) { + case YELLOW: + return MinecraftNameWrapper.YELLOW_DYE; + case RED: + return MinecraftNameWrapper.RED_DYE; + case GREEN: + return MinecraftNameWrapper.GREEN_DYE; + case BLACK: + return Material.INK_SAC; + case GRAY: + return Material.GRAY_DYE; + case LIGHT_GRAY: + return Material.LIGHT_GRAY_DYE; + case BLUE: + return Material.LAPIS_LAZULI; + case LIGHT_BLUE: + return Material.LIGHT_BLUE_DYE; + case MAGENTA: + return Material.MAGENTA_DYE; + case BROWN: + return Material.COCOA_BEANS; + case PURPLE: + return Material.PURPLE_DYE; + case ORANGE: + return Material.ORANGE_DYE; + case PINK: + return Material.PINK_DYE; + case LIME: + return Material.LIME_DYE; + case CYAN: + return Material.CYAN_DYE; + case WHITE: + default: + return Material.BONE_MEAL; + } + } + + @Nonnull + public static ChatColor convertAwtColorToChatColor(@Nonnull Color color) { + return colorsByChatColor.entrySet().stream() + .min((o1, o2) -> (int) ((calculateDifferenceBetweenColors(color, o1.getValue()) - calculateDifferenceBetweenColors(color, o2.getValue())) * 100)) + .orElseThrow(() -> new IllegalStateException("Could not find a ChatColor for the given input")) + .getKey(); + } + + @Nonnull + public static Color convertChatColorToAwtColor(@Nonnull ChatColor color) { + return Optional.ofNullable(colorsByChatColor.get(color)).orElseThrow(() -> new IllegalStateException("Could not find a color for ChatColor." + color.name())); + } + + @Nonnull + public static float[] convertAwtColorToHSB(@Nonnull Color color) { + return Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); + } + + public static double calculateDifferenceBetweenColors(@Nonnull Color color1, @Nonnull Color color2) { + + int diffRed = Math.abs(color1.getRed() - color2.getRed()); + int diffGreen = Math.abs(color1.getGreen() - color2.getGreen()); + int diffBlue = Math.abs(color1.getBlue() - color2.getBlue()); + + float pctDiffRed = (float) diffRed / 255f; + float pctDiffGreen = (float) diffGreen / 255f; + float pctDiffBlue = (float) diffBlue / 255f; + + return (pctDiffRed + pctDiffGreen + pctDiffBlue) / 3f * 100; + } + + public static boolean isValidColorCode(char code) { + for (ChatColor color : ChatColor.values()) { + if (color.isColor() && color.getChar() == code) + return true; + } + return false; + } + + public static boolean isValidColorCode(@Nonnull String code) { + if (code.length() != 1) return false; + return isValidColorCode(code.toCharArray()[0]); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java index 34cdc714d..2d9965ee3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java @@ -16,79 +16,79 @@ public final class CommandHelper { - private CommandHelper() { - } + private CommandHelper() { + } - public static List getCompletions(CommandSender sender) { - LinkedList list = new LinkedList<>(); - Player player = sender instanceof Player ? ((Player) sender) : null; - Bukkit.getOnlinePlayers().forEach(player1 -> { - if (player == null || player.canSee(player1)) { - list.add(player1.getName()); - } - }); - list.addAll(Arrays.asList("@a", "@r", "@p", "@s")); - return list; - } + public static List getCompletions(CommandSender sender) { + LinkedList list = new LinkedList<>(); + Player player = sender instanceof Player ? ((Player) sender) : null; + Bukkit.getOnlinePlayers().forEach(player1 -> { + if (player == null || player.canSee(player1)) { + list.add(player1.getName()); + } + }); + list.addAll(Arrays.asList("@a", "@r", "@p", "@s")); + return list; + } - public static List getPlayers(@Nonnull CommandSender sender, @Nonnull String input) { - ArrayList list = new ArrayList<>(); - Location senderLocation = getSenderLocation(sender); + public static List getPlayers(@Nonnull CommandSender sender, @Nonnull String input) { + ArrayList list = new ArrayList<>(); + Location senderLocation = getSenderLocation(sender); - switch (input) { - case "@a": { - list.addAll(Bukkit.getOnlinePlayers()); - break; - } - case "@r": { - list.add(new ArrayList(Bukkit.getOnlinePlayers()).get(ThreadLocalRandom.current().nextInt(Bukkit.getOnlinePlayers().size()))); - break; - } - case "@p": { - if (senderLocation != null) { - Player nearestPlayer = getNearestPlayer(senderLocation); - if (nearestPlayer != null) list.add(nearestPlayer); - } - break; - } - case "@s": { - if (sender instanceof Player) list.add(((Player) sender)); - break; - } - default: { - Player player = Bukkit.getPlayer(input); - if (player != null) list.add(player); - } + switch (input) { + case "@a": { + list.addAll(Bukkit.getOnlinePlayers()); + break; + } + case "@r": { + list.add(new ArrayList(Bukkit.getOnlinePlayers()).get(ThreadLocalRandom.current().nextInt(Bukkit.getOnlinePlayers().size()))); + break; + } + case "@p": { + if (senderLocation != null) { + Player nearestPlayer = getNearestPlayer(senderLocation); + if (nearestPlayer != null) list.add(nearestPlayer); + } + break; + } + case "@s": { + if (sender instanceof Player) list.add(((Player) sender)); + break; + } + default: { + Player player = Bukkit.getPlayer(input); + if (player != null) list.add(player); + } - } + } - return list; - } + return list; + } - @Nullable - public static Location getSenderLocation(@Nonnull CommandSender sender) { - if (sender instanceof Player) return ((Player) sender).getLocation(); - if (sender instanceof BlockCommandSender) - return ((BlockCommandSender) sender).getBlock().getLocation(); - return null; - } + @Nullable + public static Location getSenderLocation(@Nonnull CommandSender sender) { + if (sender instanceof Player) return ((Player) sender).getLocation(); + if (sender instanceof BlockCommandSender) + return ((BlockCommandSender) sender).getBlock().getLocation(); + return null; + } - @Nullable - public static Player getNearestPlayer(@Nonnull Location location) { - if (location.getWorld() == null) return null; - Player currentPlayer = null; - double playersDistance = -1; + @Nullable + public static Player getNearestPlayer(@Nonnull Location location) { + if (location.getWorld() == null) return null; + Player currentPlayer = null; + double playersDistance = -1; - for (Player player : Bukkit.getOnlinePlayers()) { - if (location.getWorld() != player.getWorld()) continue; - double distance = location.distance(player.getLocation()); - if (playersDistance == -1 || distance < playersDistance) { - currentPlayer = player; - playersDistance = distance; - } - } + for (Player player : Bukkit.getOnlinePlayers()) { + if (location.getWorld() != player.getWorld()) continue; + double distance = location.distance(player.getLocation()); + if (playersDistance == -1 || distance < playersDistance) { + currentPlayer = player; + playersDistance = distance; + } + } - return currentPlayer; - } + return currentPlayer; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java index d4f1bb209..6bba078ef 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java @@ -15,71 +15,71 @@ public final class DatabaseHelper { - private static final Map cachedTextures = new HashMap<>(); - - private DatabaseHelper() { - } - - @Nullable - public static String getPlayerTextures(@Nonnull Player player) { - GameProfile profile = GameProfileUtils.getGameProfile(player); - PropertyMap properties = profile.getProperties(); - List textures = new ArrayList<>(properties.get("textures")); - return textures.isEmpty() ? null : textures.get(0).getValue(); - } - - public static void savePlayerData(@Nonnull Player player) { - try { - - String textures = getPlayerTextures(player); - if (textures != null) cachedTextures.put(player.getUniqueId(), textures); - - Challenges.getInstance().getDatabaseManager().getDatabase() - .insertOrUpdate("challenges") - .set("textures", textures) - .set("name", player.getName()) - .where("uuid", player.getUniqueId()) - .execute(); - - } catch (Exception ex) { - Logger.error("Unable to update textures for {} | {}", player.getName(), player.getUniqueId(), ex); - } - } - - @Nullable - public static String getTextures(@Nonnull UUID uuid) { - String cached = cachedTextures.get(uuid); - if (cached != null) return cached; - - Player player = Bukkit.getPlayer(uuid); - if (player != null) { - String textures = getPlayerTextures(player); - if (textures != null) { - cachedTextures.put(uuid, textures); - return textures; - } - } - - if (!Challenges.getInstance().getDatabaseManager().isConnected()) - return null; - - try { - String textures = Challenges.getInstance().getDatabaseManager().getDatabase() - .query("challenges") - .select("textures") - .where("uuid", uuid) - .execute().firstOrEmpty() - .getString("textures"); - cachedTextures.put(uuid, textures); - return textures; - } catch (Exception ex) { - Logger.error("Unable to get textures for {}", uuid, ex); - return null; - } - } - - public static void clearCache(@Nonnull UUID uuid) { - cachedTextures.remove(uuid); - } + private static final Map cachedTextures = new HashMap<>(); + + private DatabaseHelper() { + } + + @Nullable + public static String getPlayerTextures(@Nonnull Player player) { + GameProfile profile = GameProfileUtils.getGameProfile(player); + PropertyMap properties = profile.getProperties(); + List textures = new ArrayList<>(properties.get("textures")); + return textures.isEmpty() ? null : textures.get(0).getValue(); + } + + public static void savePlayerData(@Nonnull Player player) { + try { + + String textures = getPlayerTextures(player); + if (textures != null) cachedTextures.put(player.getUniqueId(), textures); + + Challenges.getInstance().getDatabaseManager().getDatabase() + .insertOrUpdate("challenges") + .set("textures", textures) + .set("name", player.getName()) + .where("uuid", player.getUniqueId()) + .execute(); + + } catch (Exception ex) { + Logger.error("Unable to update textures for {} | {}", player.getName(), player.getUniqueId(), ex); + } + } + + @Nullable + public static String getTextures(@Nonnull UUID uuid) { + String cached = cachedTextures.get(uuid); + if (cached != null) return cached; + + Player player = Bukkit.getPlayer(uuid); + if (player != null) { + String textures = getPlayerTextures(player); + if (textures != null) { + cachedTextures.put(uuid, textures); + return textures; + } + } + + if (!Challenges.getInstance().getDatabaseManager().isConnected()) + return null; + + try { + String textures = Challenges.getInstance().getDatabaseManager().getDatabase() + .query("challenges") + .select("textures") + .where("uuid", uuid) + .execute().firstOrEmpty() + .getString("textures"); + cachedTextures.put(uuid, textures); + return textures; + } catch (Exception ex) { + Logger.error("Unable to get textures for {}", uuid, ex); + return null; + } + } + + public static void clearCache(@Nonnull UUID uuid) { + cachedTextures.remove(uuid); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java index 8c1dd221e..54fe92a8a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java @@ -10,37 +10,37 @@ public final class EntityUtils { - private EntityUtils() { - } - - public static Vector getSucceedingVelocity(@Nonnull Vector vector) { - return new Vector(vector.getX(), getSucceedingVelocity(vector.getY()), vector.getX()); - } - - public static double getSucceedingVelocity(double currentYVelocity) { - return 0.98 * ((currentYVelocity) - 0.08); - } - - public static boolean isStandingOnBlock(@Nonnull Entity entity, Material block) { - for (int x = -1; x <= 1; x++) { - for (int z = -1; z <= 1; z++) { - for (int y = -1; y <= 1; y++) { - Material type = entity.getLocation().add(x, y, z).getBlock().getType(); - if (type == block) return true; - } - } - } - return false; - } - - @Nullable - public static Material getSpawnEgg(EntityType type) { - if (!type.isSpawnable() || !type.isAlive()) return null; - try { - return Material.valueOf(type.name() + "_SPAWN_EGG"); - } catch (Exception ex) { - return null; - } - } + private EntityUtils() { + } + + public static Vector getSucceedingVelocity(@Nonnull Vector vector) { + return new Vector(vector.getX(), getSucceedingVelocity(vector.getY()), vector.getX()); + } + + public static double getSucceedingVelocity(double currentYVelocity) { + return 0.98 * ((currentYVelocity) - 0.08); + } + + public static boolean isStandingOnBlock(@Nonnull Entity entity, Material block) { + for (int x = -1; x <= 1; x++) { + for (int z = -1; z <= 1; z++) { + for (int y = -1; y <= 1; y++) { + Material type = entity.getLocation().add(x, y, z).getBlock().getType(); + if (type == block) return true; + } + } + } + return false; + } + + @Nullable + public static Material getSpawnEgg(EntityType type) { + if (!type.isSpawnable() || !type.isAlive()) return null; + try { + return Material.valueOf(type.name() + "_SPAWN_EGG"); + } catch (Exception ex) { + return null; + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java index bacbadfe2..97dd467bb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java @@ -1,12 +1,13 @@ package net.codingarea.challenges.plugin.utils.misc; -import java.util.LinkedList; -import java.util.List; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.EntityType; +import java.util.LinkedList; +import java.util.List; + public class ExperimentalUtils { private static Material[] materials; @@ -27,7 +28,8 @@ private static void loadMaterials() { if (!material.isEnabledByFeature(Challenges.getInstance().getGameWorldStorage().getWorld(World.Environment.NORMAL))) { continue; } - } catch (NoSuchMethodError ignored) {} // only NoSuchMethodException + } catch (NoSuchMethodError ignored) { + } // only NoSuchMethodException materials.add(material); } @@ -49,7 +51,8 @@ private static void loadEntityTypes() { if (!type.isEnabledByFeature(Challenges.getInstance().getGameWorldStorage().getWorld(World.Environment.NORMAL))) { continue; } - } catch (NoSuchMethodError | IllegalArgumentException ignored) {} // only NoSuchMethodException + } catch (NoSuchMethodError | IllegalArgumentException ignored) { + } // only NoSuchMethodException entityTypes.add(type); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FontUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FontUtils.java index 760fc54d4..4ecf028e7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FontUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FontUtils.java @@ -6,40 +6,40 @@ public class FontUtils { - private static final char[] SMALL_CAPS_ALPHABET = "ᴀʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ".toCharArray(); + private static final char[] SMALL_CAPS_ALPHABET = "ᴀʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ".toCharArray(); - public static String[] toSmallCaps(String[] text) { - LinkedList strings = new LinkedList<>(); - for (String s : text) { - strings.add(toSmallCaps(s)); - } - return strings.toArray(new String[0]); - } + public static String[] toSmallCaps(String[] text) { + LinkedList strings = new LinkedList<>(); + for (String s : text) { + strings.add(toSmallCaps(s)); + } + return strings.toArray(new String[0]); + } - public static String toSmallCaps(String text) { - if (null == text) { - return null; - } - int length = text.length(); - StringBuilder smallCaps = new StringBuilder(length); - for (int i = 0; i < length; ++i) { - char c = text.charAt(i); - if (c >= 'a' && c <= 'z') { - if (i >= 1) { - char charBefore = text.charAt(i - 1); - if (charBefore == '§') { - if (ChatColor.getByChar(c) != null) { - smallCaps.append(c); - continue; - } - } - } - smallCaps.append(SMALL_CAPS_ALPHABET[c - 'a']); - } else { - smallCaps.append(c); - } - } - return smallCaps.toString(); - } + public static String toSmallCaps(String text) { + if (null == text) { + return null; + } + int length = text.length(); + StringBuilder smallCaps = new StringBuilder(length); + for (int i = 0; i < length; ++i) { + char c = text.charAt(i); + if (c >= 'a' && c <= 'z') { + if (i >= 1) { + char charBefore = text.charAt(i - 1); + if (charBefore == '§') { + if (ChatColor.getByChar(c) != null) { + smallCaps.append(c); + continue; + } + } + } + smallCaps.append(SMALL_CAPS_ALPHABET[c - 'a']); + } else { + smallCaps.append(c); + } + } + return smallCaps.toString(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java index f64928ea6..f81f27ba2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java @@ -13,34 +13,34 @@ public final class ImageUtils { - public static final char IMAGE_CHAR = '█'; - - private ImageUtils() { - } - - @Nullable - public static BufferedImage getImage(@Nonnull String url) throws IOException { - HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); - connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); - return ImageIO.read(connection.getInputStream()); - } - - public static BufferedImage getPlayerHead(@Nonnull Player player, int size) throws IOException { - String url = "https://crafatar.com/avatars/" + player.getUniqueId() + "?size=" + size + "&overlay"; - return getImage(url); - } - - public static String[] convertImageToText(@Nonnull BufferedImage image) { - String[] output = new String[image.getHeight()]; - for (int y = 0; y < output.length; y++) { - StringBuilder text = new StringBuilder(); - for (int x = 0; x < image.getWidth(); x++) { - text.append(ColorConversions.convertAwtColorToChatColor(new Color(image.getRGB(x, y)))) - .append(IMAGE_CHAR); - } - output[y] = text.toString(); - } - return output; - } + public static final char IMAGE_CHAR = '█'; + + private ImageUtils() { + } + + @Nullable + public static BufferedImage getImage(@Nonnull String url) throws IOException { + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); + return ImageIO.read(connection.getInputStream()); + } + + public static BufferedImage getPlayerHead(@Nonnull Player player, int size) throws IOException { + String url = "https://crafatar.com/avatars/" + player.getUniqueId() + "?size=" + size + "&overlay"; + return getImage(url); + } + + public static String[] convertImageToText(@Nonnull BufferedImage image) { + String[] output = new String[image.getHeight()]; + for (int y = 0; y < output.length; y++) { + StringBuilder text = new StringBuilder(); + for (int x = 0; x < image.getWidth(); x++) { + text.append(ColorConversions.convertAwtColorToChatColor(new Color(image.getRGB(x, y)))) + .append(IMAGE_CHAR); + } + output[y] = text.toString(); + } + return output; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java index b0e6af5f5..adbdcc26c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java @@ -25,201 +25,201 @@ public final class InventoryUtils { - private static final IRandom random; - private static final List items; - - static { - random = IRandom.create(); - items = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - items.removeIf(material -> !material.isItem()); - } - - private InventoryUtils() { - } - - public static void fillInventory(@Nonnull Inventory inventory, @Nullable ItemStack item) { - for (int i = 0; i < inventory.getSize(); i++) { - inventory.setItem(i, item); - } - } - - public static void fillInventory(@Nonnull Inventory inventory, @Nullable ItemStack item, @Nonnull int... slots) { - for (int i : slots) { - inventory.setItem(i, item); - } - } - - public static void setNavigationItemsToInventory(@Nonnull List inventories, @Nonnull int[] navigationSlots) { - setNavigationItemsToInventory(inventories, navigationSlots, true); - } - - public static void setNavigationItemsToInventory(@Nonnull List inventories, @Nonnull int[] navigationSlots, boolean goBackExit) { - setNavigationItems(inventories, navigationSlots, goBackExit, InventorySetter.INVENTORY); - } - - public static void setNavigationItemsToFrame(@Nonnull List frames, @Nonnull int[] navigationSlots) { - setNavigationItemsToFrame(frames, navigationSlots, true); - } - - public static void setNavigationItemsToFrame(@Nonnull List inventories, @Nonnull int[] navigationSlots, boolean goBackExit) { - setNavigationItems(inventories, navigationSlots, goBackExit, InventorySetter.FRAME); - } - - public static void setNavigationItemsToFrame(@Nonnull AnimationFrame frame, @Nonnull int[] navigationSlots, boolean goBackExit, int index, int size) { - setNavigationItems(frame, navigationSlots, goBackExit, InventorySetter.FRAME, index, size); - } - - public static void setNavigationItems(@Nonnull List inventories, @Nonnull int[] navigationSlots, boolean goBackExit, @Nonnull InventorySetter setter) { - for (int i = 0; i < inventories.size(); i++) { - setNavigationItems(inventories.get(i), navigationSlots, goBackExit, setter, i, inventories.size()); - } - } - - public static void setNavigationItems(@Nonnull I inventory, @Nonnull int[] navigationSlots, boolean goBackExit, @Nonnull InventorySetter setter, int index, int size) { - setNavigationItems(inventory, navigationSlots, goBackExit, setter, index, size, DefaultItem.navigateBack(), DefaultItem.navigateNext()); - } - - public static void setNavigationItems(@Nonnull I inventory, @Nonnull int[] navigationSlots, boolean goBackExit, @Nonnull InventorySetter setter, int index, int size, ItemBuilder navigateBack, ItemBuilder navigateNext) { - if (navigationSlots.length >= 1) { - ItemBuilder left = index == 0 && goBackExit ? DefaultItem.navigateBackMainMenu() : navigateBack; - setter.set(inventory, navigationSlots[0], left); - } - if (navigationSlots.length >= 2 && index < (size - 1)) - setter.set(inventory, navigationSlots[1], navigateNext); - } - - public static boolean isEmpty(@Nonnull Inventory inventory) { - for (ItemStack content : inventory.getContents()) { - if (content != null) return false; - } - return true; - } - - public static int getRandomEmptySlot(@Nonnull Inventory inventory) { - List emptySlots = new ArrayList<>(); - - for (int slot = 0; slot < inventory.getSize(); slot++) { - if (inventory.getItem(slot) == null) { - emptySlots.add(slot); - } - - } - - if (emptySlots.isEmpty()) return -1; - return emptySlots.get(ThreadLocalRandom.current().nextInt(emptySlots.size())); - } - - public static int getRandomFullSlot(@Nonnull Inventory inventory) { - List fullSlots = new ArrayList<>(); - - for (int slot = 0; slot < inventory.getSize(); slot++) { - ItemStack item = inventory.getItem(slot); - if (item != null && !item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { - fullSlots.add(slot); - } - } - - if (fullSlots.isEmpty()) return -1; - - return fullSlots.get(ThreadLocalRandom.current().nextInt(fullSlots.size())); - } - - public static int getRandomSlot(@Nonnull Inventory inventory) { - List slots = new ArrayList<>(); - - for (int slot = 0; slot < inventory.getSize(); slot++) { - ItemStack item = inventory.getItem(slot); - if (item != null && item.isSimilar(ItemBuilder.BLOCKED_ITEM)) continue; - slots.add(slot); - - } - - if (slots.isEmpty()) return -1; - return slots.get(ThreadLocalRandom.current().nextInt(slots.size())); - } - - public static void dropItemByPlayer(@Nonnull Location location, @Nonnull ItemStack itemStack) { - if (location.getWorld() == null) return; - Item droppedItem = location.getWorld().dropItem(location.clone().add(0, 1.4, 0), itemStack); - droppedItem.setVelocity(location.getDirection().multiply(0.4)); - } - - public static void dropOrGiveItem(@Nonnull Inventory inventory, @Nonnull Location location, @Nonnull Material material) { - dropOrGiveItem(inventory, location, new ItemStack(material)); - } - - public static void dropOrGiveItem(@Nonnull Inventory inventory, @Nonnull Location location, @Nonnull ItemStack itemStack) { - location = location.clone(); - if (inventory.firstEmpty() == -1) { - if (location.getWorld() == null) - location.setWorld(ChallengeAPI.getGameWorld(Environment.NORMAL)); - location.getWorld().dropItem(location, itemStack); - return; - } - inventory.addItem(itemStack); - } - - public static void removeRandomItem(@Nonnull Inventory inventory) { - int slot = InventoryUtils.getRandomFullSlot(inventory); - if (slot == -1) return; - inventory.setItem(slot, null); - } - - public static void giveItem(@Nonnull Player player, @Nonnull ItemStack itemStack) { - giveItem(player.getInventory(), player.getLocation(), itemStack); - } - - public static void giveItem(@Nonnull Inventory inventory, @Nonnull Location locationToDrop, @Nonnull ItemStack itemStack) { - if (inventory.firstEmpty() == -1) { - dropItemByPlayer(locationToDrop, itemStack); - return; - } - inventory.addItem(itemStack); - } - - public static ItemStack getRandomItem(boolean onlyOne, boolean respectMaxStackSize) { - Material material = random.choose(items); - int stackSize = onlyOne ? 1 : (respectMaxStackSize && material.getMaxStackSize() == 1 ? 1 : random.range(1, respectMaxStackSize ? material.getMaxStackSize() : 64)); - return new ItemStack(material, stackSize); - } - - /** - * @return if a navigation item was clicked - */ - public static boolean handleNavigationClicking(MenuGenerator generator, int[] navigationSlots, int page, MenuClickInfo info, Runnable onDoorClick) { - int pagesSwitching = info.isShiftClick() ? 5 : 1; - if (navigationSlots.length >= 1 && info.getSlot() == navigationSlots[0]) { - if (page <= 0) { - if (page == 0) { - onDoorClick.run(); - } else { - SoundSample.CLICK.play(info.getPlayer()); - } - return page == 0; - } else { - SoundSample.CLICK.play(info.getPlayer()); - generator.open(info.getPlayer(), Math.max(page - pagesSwitching, 0)); - return true; - } - } else if (navigationSlots.length >= 2 && info.getSlot() == navigationSlots[1]) { - SoundSample.CLICK.play(info.getPlayer()); - if (page < (generator.getInventories().size())) { - generator.open(info.getPlayer(), Math.min(page + pagesSwitching, generator.getInventories().size())); - return true; - } - return false; - } - return false; - } - - @FunctionalInterface - public interface InventorySetter { - - InventorySetter FRAME = AnimationFrame::setItem; - InventorySetter INVENTORY = (inventory, slot, item) -> inventory.setItem(slot, item.build()); - - void set(@Nonnull I inventory, int slot, @Nonnull ItemBuilder item); - - } + private static final IRandom random; + private static final List items; + + static { + random = IRandom.create(); + items = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + items.removeIf(material -> !material.isItem()); + } + + private InventoryUtils() { + } + + public static void fillInventory(@Nonnull Inventory inventory, @Nullable ItemStack item) { + for (int i = 0; i < inventory.getSize(); i++) { + inventory.setItem(i, item); + } + } + + public static void fillInventory(@Nonnull Inventory inventory, @Nullable ItemStack item, @Nonnull int... slots) { + for (int i : slots) { + inventory.setItem(i, item); + } + } + + public static void setNavigationItemsToInventory(@Nonnull List inventories, @Nonnull int[] navigationSlots) { + setNavigationItemsToInventory(inventories, navigationSlots, true); + } + + public static void setNavigationItemsToInventory(@Nonnull List inventories, @Nonnull int[] navigationSlots, boolean goBackExit) { + setNavigationItems(inventories, navigationSlots, goBackExit, InventorySetter.INVENTORY); + } + + public static void setNavigationItemsToFrame(@Nonnull List frames, @Nonnull int[] navigationSlots) { + setNavigationItemsToFrame(frames, navigationSlots, true); + } + + public static void setNavigationItemsToFrame(@Nonnull List inventories, @Nonnull int[] navigationSlots, boolean goBackExit) { + setNavigationItems(inventories, navigationSlots, goBackExit, InventorySetter.FRAME); + } + + public static void setNavigationItemsToFrame(@Nonnull AnimationFrame frame, @Nonnull int[] navigationSlots, boolean goBackExit, int index, int size) { + setNavigationItems(frame, navigationSlots, goBackExit, InventorySetter.FRAME, index, size); + } + + public static void setNavigationItems(@Nonnull List inventories, @Nonnull int[] navigationSlots, boolean goBackExit, @Nonnull InventorySetter setter) { + for (int i = 0; i < inventories.size(); i++) { + setNavigationItems(inventories.get(i), navigationSlots, goBackExit, setter, i, inventories.size()); + } + } + + public static void setNavigationItems(@Nonnull I inventory, @Nonnull int[] navigationSlots, boolean goBackExit, @Nonnull InventorySetter setter, int index, int size) { + setNavigationItems(inventory, navigationSlots, goBackExit, setter, index, size, DefaultItem.navigateBack(), DefaultItem.navigateNext()); + } + + public static void setNavigationItems(@Nonnull I inventory, @Nonnull int[] navigationSlots, boolean goBackExit, @Nonnull InventorySetter setter, int index, int size, ItemBuilder navigateBack, ItemBuilder navigateNext) { + if (navigationSlots.length >= 1) { + ItemBuilder left = index == 0 && goBackExit ? DefaultItem.navigateBackMainMenu() : navigateBack; + setter.set(inventory, navigationSlots[0], left); + } + if (navigationSlots.length >= 2 && index < (size - 1)) + setter.set(inventory, navigationSlots[1], navigateNext); + } + + public static boolean isEmpty(@Nonnull Inventory inventory) { + for (ItemStack content : inventory.getContents()) { + if (content != null) return false; + } + return true; + } + + public static int getRandomEmptySlot(@Nonnull Inventory inventory) { + List emptySlots = new ArrayList<>(); + + for (int slot = 0; slot < inventory.getSize(); slot++) { + if (inventory.getItem(slot) == null) { + emptySlots.add(slot); + } + + } + + if (emptySlots.isEmpty()) return -1; + return emptySlots.get(ThreadLocalRandom.current().nextInt(emptySlots.size())); + } + + public static int getRandomFullSlot(@Nonnull Inventory inventory) { + List fullSlots = new ArrayList<>(); + + for (int slot = 0; slot < inventory.getSize(); slot++) { + ItemStack item = inventory.getItem(slot); + if (item != null && !item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { + fullSlots.add(slot); + } + } + + if (fullSlots.isEmpty()) return -1; + + return fullSlots.get(ThreadLocalRandom.current().nextInt(fullSlots.size())); + } + + public static int getRandomSlot(@Nonnull Inventory inventory) { + List slots = new ArrayList<>(); + + for (int slot = 0; slot < inventory.getSize(); slot++) { + ItemStack item = inventory.getItem(slot); + if (item != null && item.isSimilar(ItemBuilder.BLOCKED_ITEM)) continue; + slots.add(slot); + + } + + if (slots.isEmpty()) return -1; + return slots.get(ThreadLocalRandom.current().nextInt(slots.size())); + } + + public static void dropItemByPlayer(@Nonnull Location location, @Nonnull ItemStack itemStack) { + if (location.getWorld() == null) return; + Item droppedItem = location.getWorld().dropItem(location.clone().add(0, 1.4, 0), itemStack); + droppedItem.setVelocity(location.getDirection().multiply(0.4)); + } + + public static void dropOrGiveItem(@Nonnull Inventory inventory, @Nonnull Location location, @Nonnull Material material) { + dropOrGiveItem(inventory, location, new ItemStack(material)); + } + + public static void dropOrGiveItem(@Nonnull Inventory inventory, @Nonnull Location location, @Nonnull ItemStack itemStack) { + location = location.clone(); + if (inventory.firstEmpty() == -1) { + if (location.getWorld() == null) + location.setWorld(ChallengeAPI.getGameWorld(Environment.NORMAL)); + location.getWorld().dropItem(location, itemStack); + return; + } + inventory.addItem(itemStack); + } + + public static void removeRandomItem(@Nonnull Inventory inventory) { + int slot = InventoryUtils.getRandomFullSlot(inventory); + if (slot == -1) return; + inventory.setItem(slot, null); + } + + public static void giveItem(@Nonnull Player player, @Nonnull ItemStack itemStack) { + giveItem(player.getInventory(), player.getLocation(), itemStack); + } + + public static void giveItem(@Nonnull Inventory inventory, @Nonnull Location locationToDrop, @Nonnull ItemStack itemStack) { + if (inventory.firstEmpty() == -1) { + dropItemByPlayer(locationToDrop, itemStack); + return; + } + inventory.addItem(itemStack); + } + + public static ItemStack getRandomItem(boolean onlyOne, boolean respectMaxStackSize) { + Material material = random.choose(items); + int stackSize = onlyOne ? 1 : (respectMaxStackSize && material.getMaxStackSize() == 1 ? 1 : random.range(1, respectMaxStackSize ? material.getMaxStackSize() : 64)); + return new ItemStack(material, stackSize); + } + + /** + * @return if a navigation item was clicked + */ + public static boolean handleNavigationClicking(MenuGenerator generator, int[] navigationSlots, int page, MenuClickInfo info, Runnable onDoorClick) { + int pagesSwitching = info.isShiftClick() ? 5 : 1; + if (navigationSlots.length >= 1 && info.getSlot() == navigationSlots[0]) { + if (page <= 0) { + if (page == 0) { + onDoorClick.run(); + } else { + SoundSample.CLICK.play(info.getPlayer()); + } + return page == 0; + } else { + SoundSample.CLICK.play(info.getPlayer()); + generator.open(info.getPlayer(), Math.max(page - pagesSwitching, 0)); + return true; + } + } else if (navigationSlots.length >= 2 && info.getSlot() == navigationSlots[1]) { + SoundSample.CLICK.play(info.getPlayer()); + if (page < (generator.getInventories().size())) { + generator.open(info.getPlayer(), Math.min(page + pagesSwitching, generator.getInventories().size())); + return true; + } + return false; + } + return false; + } + + @FunctionalInterface + public interface InventorySetter { + + InventorySetter FRAME = AnimationFrame::setItem; + InventorySetter INVENTORY = (inventory, slot, item) -> inventory.setItem(slot, item.build()); + + void set(@Nonnull I inventory, int slot, @Nonnull ItemBuilder item); + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java index f2a5bda15..21162ef90 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ListBuilder.java @@ -9,67 +9,67 @@ public final class ListBuilder { - private final List list = new ArrayList<>(); - - @SafeVarargs - public ListBuilder(T... t) { - list.addAll(Arrays.asList(t)); - } - - public ListBuilder fill(Consumer> consumer) { - consumer.accept(this); - return this; - } - - @SafeVarargs - public final ListBuilder addAll(T... t) { - return addAll(Arrays.asList(t)); - } - - public ListBuilder addAll(Collection collection) { - list.addAll(collection); - return this; - } - - @SafeVarargs - public final ListBuilder addAllIfNotContains(T... t) { - return addAllIfNotContains(Arrays.asList(t)); - } - - public ListBuilder addAllIfNotContains(Collection collection) { - for (T t : collection) { - if (!list.contains(t)) list.add(t); - } - return this; - } - - public ListBuilder add(T t) { - list.add(t); - return this; - } - - public ListBuilder addIfNotContains(T t) { - if (list.contains(t)) return this; - return add(t); - } - - public ListBuilder remove(T t) { - list.remove(t); - return this; - } - - public ListBuilder forEach(Consumer action) { - list.forEach(action); - return this; - } - - public ListBuilder removeIf(Predicate action) { - list.removeIf(action); - return this; - } - - public List build() { - return list; - } + private final List list = new ArrayList<>(); + + @SafeVarargs + public ListBuilder(T... t) { + list.addAll(Arrays.asList(t)); + } + + public ListBuilder fill(Consumer> consumer) { + consumer.accept(this); + return this; + } + + @SafeVarargs + public final ListBuilder addAll(T... t) { + return addAll(Arrays.asList(t)); + } + + public ListBuilder addAll(Collection collection) { + list.addAll(collection); + return this; + } + + @SafeVarargs + public final ListBuilder addAllIfNotContains(T... t) { + return addAllIfNotContains(Arrays.asList(t)); + } + + public ListBuilder addAllIfNotContains(Collection collection) { + for (T t : collection) { + if (!list.contains(t)) list.add(t); + } + return this; + } + + public ListBuilder add(T t) { + list.add(t); + return this; + } + + public ListBuilder addIfNotContains(T t) { + if (list.contains(t)) return this; + return add(t); + } + + public ListBuilder remove(T t) { + list.remove(t); + return this; + } + + public ListBuilder forEach(Consumer action) { + list.forEach(action); + return this; + } + + public ListBuilder removeIf(Predicate action) { + list.removeIf(action); + return this; + } + + public List build() { + return list; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java index 650d72cf1..5e8ff0de1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java @@ -8,39 +8,39 @@ public class MapUtils { - public static Map createStringMap(String... data) { - Map map = new HashMap<>(); - for (int i = 1; i < data.length; i += 2) { - String key = data[i - 1]; - String value = data[i]; - map.put(key, value); - } - return map; - } - - public static Map createStringArrayMap(String key, String... values) { - Map map = new HashMap<>(); - map.put(key, values); - return map; - } - - public static Map> createStringListMap(String key, String... values) { - Map> map = new HashMap<>(); - map.put(key, new ArrayList<>(Arrays.asList(values))); - return map; - } - - public static Map createSubSettingsMapFromDocument(Document document) { - if (document == null) return new HashMap<>(); - Map map = new HashMap<>(); - for (Entry entry : document.entrySet()) { - try { - map.put(entry.getKey(), document.getStringArray(entry.getKey())); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); - } - } - return map; - } + public static Map createStringMap(String... data) { + Map map = new HashMap<>(); + for (int i = 1; i < data.length; i += 2) { + String key = data[i - 1]; + String value = data[i]; + map.put(key, value); + } + return map; + } + + public static Map createStringArrayMap(String key, String... values) { + Map map = new HashMap<>(); + map.put(key, values); + return map; + } + + public static Map> createStringListMap(String key, String... values) { + Map> map = new HashMap<>(); + map.put(key, new ArrayList<>(Arrays.asList(values))); + return map; + } + + public static Map createSubSettingsMapFromDocument(Document document) { + if (document == null) return new HashMap<>(); + Map map = new HashMap<>(); + for (Entry entry : document.entrySet()) { + try { + map.put(entry.getKey(), document.getStringArray(entry.getKey())); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("", exception); + } + } + return map; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MemoryConverter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MemoryConverter.java index 51915d714..5be104fe1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MemoryConverter.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MemoryConverter.java @@ -2,10 +2,10 @@ public class MemoryConverter { - private static final long GIGABYTE = 1024L * 1024L * 1024L; + private static final long GIGABYTE = 1024L * 1024L * 1024L; - public static int getGB(long bytes) { - return (int) (bytes / GIGABYTE); - } + public static int getGB(long bytes) { + return (int) (bytes / GIGABYTE); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java index 6d167b4a0..4952998f1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.utils.misc; -import java.lang.reflect.Field; -import java.util.Arrays; -import javax.annotation.Nonnull; import net.anweisen.utilities.common.misc.ReflectionUtils; import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; import org.bukkit.Material; @@ -11,6 +8,10 @@ import org.bukkit.entity.EntityType; import org.bukkit.potion.PotionEffectType; +import javax.annotation.Nonnull; +import java.lang.reflect.Field; +import java.util.Arrays; + public class MinecraftNameWrapper { public static final Material GREEN_DYE = getItemByNames("CACTUS_GREEN", "GREEN_DYE"); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java index 4d2650c64..3d3e251a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java @@ -8,25 +8,25 @@ public final class NameHelper { - private NameHelper() { - } - - @Nonnull - public static String getName(@Nonnull OfflinePlayer player) { - CloudSupportManager cloudSupport = Challenges.getInstance().getCloudSupportManager(); - if (cloudSupport.isNameSupport() && cloudSupport.hasNameFor(player.getUniqueId())) { - if (player.isOnline() && player.getPlayer() != null) { - return cloudSupport.getColoredName(player.getPlayer()); - } else { - return cloudSupport.getColoredName(player.getUniqueId()); - } - } - - if (player.getName() == null) { - return ""; - } - - return player.getName(); - } + private NameHelper() { + } + + @Nonnull + public static String getName(@Nonnull OfflinePlayer player) { + CloudSupportManager cloudSupport = Challenges.getInstance().getCloudSupportManager(); + if (cloudSupport.isNameSupport() && cloudSupport.hasNameFor(player.getUniqueId())) { + if (player.isOnline() && player.getPlayer() != null) { + return cloudSupport.getColoredName(player.getPlayer()); + } else { + return cloudSupport.getColoredName(player.getUniqueId()); + } + } + + if (player.getName() == null) { + return ""; + } + + return player.getName(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java index a72079576..8d8d9d524 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java @@ -1,16 +1,8 @@ package net.codingarea.challenges.plugin.utils.misc; -import java.util.Objects; -import java.util.function.BiConsumer; -import javax.annotation.Nonnull; import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; import net.anweisen.utilities.common.collection.IRandom; -import org.bukkit.Bukkit; -import org.bukkit.Color; -import org.bukkit.Effect; -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.World; +import org.bukkit.*; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; @@ -18,98 +10,102 @@ import org.bukkit.util.Vector; import org.jetbrains.annotations.Nullable; +import javax.annotation.Nonnull; +import java.util.Objects; +import java.util.function.BiConsumer; + public final class ParticleUtils { - private static final IRandom iRandom = IRandom.create(); - - private ParticleUtils() { - } - - private static void spawnParticleCircle(@Nonnull Location location, int points, double radius, @Nonnull BiConsumer player) { - World world = location.getWorld(); - if (world == null) return; - - for (int i = 0; i < points; i++) { - double angle = 2 * Math.PI * i / points; - Location point = location.clone().add(radius * Math.sin(angle), 0.0d, radius * Math.cos(angle)); - player.accept(world, point); - } - } - - public static void spawnParticleCircle(@Nonnull Location location, @Nonnull Effect particle, int points, double radius) { - spawnParticleCircle(location, points, radius, (world, point) -> world.playEffect(point, particle, 1)); - } - - public static void spawnParticleCircle(@Nonnull Location location, @Nonnull Particle particle, int points, double radius) { - spawnParticleCircle(location, points, radius, (world, point) -> world.spawnParticle(particle, point, 1)); - } - - private static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnull Location location, int points, double radius, double height, @Nonnull BiConsumer player) { - for (double y = 0, i = 0; y < height; y += .25, i++) { - final double Y = y; - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { - spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, player); - }, (long) i); - } - } - - public static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Effect effect, int points, double radius, double height) { - spawnUpGoingParticleCircle(plugin, location, points, radius, height, (world, point) -> world.playEffect(point, effect, 1)); - } - - public static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Particle particle, int points, double radius, double height) { - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_20_5)) { - for (double y = 0, i = 0; y < height; y += .25, i++) { - final double Y = y; - - Color color = Color.fromRGB( - iRandom.range(0, 255), - iRandom.range(0, 255), - iRandom.range(0, 255) - ); - - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { - if (particle == Particle.ENTITY_EFFECT) { - spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, (world, loc) -> world.spawnParticle(particle, loc, 1, color)); - } else { - spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, (world, loc) -> world.spawnParticle(particle, loc, 1)); - } - }, (long) i); - } - } else { - spawnUpGoingParticleCircle(plugin, location, points, radius, height, (world, point) -> world.spawnParticle(particle, point, 1)); - } - } - - public static void spawnParticleCircleAroundEntity(@Nonnull JavaPlugin plugin, @Nonnull Entity entity) { - spawnParticleCircleAroundBoundingBox(plugin, entity.getLocation(), MinecraftNameWrapper.INSTANT_EFFECT, entity.getBoundingBox(), 0.25); - } - - public static void spawnParticleCircleAroundBoundingBox(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Particle particle, @Nonnull BoundingBox box, double height) { - spawnParticleCircleAroundRadius(plugin, location, particle, box.getWidthX(), height); - } - - public static void spawnParticleCircleAroundRadius(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Particle particle, double radius, double height) { - spawnUpGoingParticleCircle(plugin, location, particle, (int) (radius * 15), radius, height); - } - - public static void drawLine(@Nonnull Player player, @Nonnull Location point1, @Nonnull Location point2, @Nonnull Particle particle, @Nullable Particle.DustOptions dustOptions, int count, double space, int max) { - World world = point1.getWorld(); - if (!Objects.equals(world, point2.getWorld())) return; - double distance = point1.distance(point2); - Vector p1 = point1.toVector(); - Vector p2 = point2.toVector(); - Vector vector = p2.clone().subtract(p1).normalize().multiply(space); - double length = 0; - int current = 0; - for (; length < distance; p1.add(vector)) { - player.spawnParticle(particle, p1.getX(), p1.getY(), p1.getZ(), count, dustOptions); - length += space; - - current++; - if (current >= max) break; - } - - } + private static final IRandom iRandom = IRandom.create(); + + private ParticleUtils() { + } + + private static void spawnParticleCircle(@Nonnull Location location, int points, double radius, @Nonnull BiConsumer player) { + World world = location.getWorld(); + if (world == null) return; + + for (int i = 0; i < points; i++) { + double angle = 2 * Math.PI * i / points; + Location point = location.clone().add(radius * Math.sin(angle), 0.0d, radius * Math.cos(angle)); + player.accept(world, point); + } + } + + public static void spawnParticleCircle(@Nonnull Location location, @Nonnull Effect particle, int points, double radius) { + spawnParticleCircle(location, points, radius, (world, point) -> world.playEffect(point, particle, 1)); + } + + public static void spawnParticleCircle(@Nonnull Location location, @Nonnull Particle particle, int points, double radius) { + spawnParticleCircle(location, points, radius, (world, point) -> world.spawnParticle(particle, point, 1)); + } + + private static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnull Location location, int points, double radius, double height, @Nonnull BiConsumer player) { + for (double y = 0, i = 0; y < height; y += .25, i++) { + final double Y = y; + Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { + spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, player); + }, (long) i); + } + } + + public static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Effect effect, int points, double radius, double height) { + spawnUpGoingParticleCircle(plugin, location, points, radius, height, (world, point) -> world.playEffect(point, effect, 1)); + } + + public static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Particle particle, int points, double radius, double height) { + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_20_5)) { + for (double y = 0, i = 0; y < height; y += .25, i++) { + final double Y = y; + + Color color = Color.fromRGB( + iRandom.range(0, 255), + iRandom.range(0, 255), + iRandom.range(0, 255) + ); + + Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { + if (particle == Particle.ENTITY_EFFECT) { + spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, (world, loc) -> world.spawnParticle(particle, loc, 1, color)); + } else { + spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, (world, loc) -> world.spawnParticle(particle, loc, 1)); + } + }, (long) i); + } + } else { + spawnUpGoingParticleCircle(plugin, location, points, radius, height, (world, point) -> world.spawnParticle(particle, point, 1)); + } + } + + public static void spawnParticleCircleAroundEntity(@Nonnull JavaPlugin plugin, @Nonnull Entity entity) { + spawnParticleCircleAroundBoundingBox(plugin, entity.getLocation(), MinecraftNameWrapper.INSTANT_EFFECT, entity.getBoundingBox(), 0.25); + } + + public static void spawnParticleCircleAroundBoundingBox(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Particle particle, @Nonnull BoundingBox box, double height) { + spawnParticleCircleAroundRadius(plugin, location, particle, box.getWidthX(), height); + } + + public static void spawnParticleCircleAroundRadius(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Particle particle, double radius, double height) { + spawnUpGoingParticleCircle(plugin, location, particle, (int) (radius * 15), radius, height); + } + + public static void drawLine(@Nonnull Player player, @Nonnull Location point1, @Nonnull Location point2, @Nonnull Particle particle, @Nullable Particle.DustOptions dustOptions, int count, double space, int max) { + World world = point1.getWorld(); + if (!Objects.equals(world, point2.getWorld())) return; + double distance = point1.distance(point2); + Vector p1 = point1.toVector(); + Vector p2 = point2.toVector(); + Vector vector = p2.clone().subtract(p1).normalize().multiply(space); + double length = 0; + int current = 0; + for (; length < distance; p1.add(vector)) { + player.spawnParticle(particle, p1.getX(), p1.getY(), p1.getZ(), count, dustOptions); + length += space; + + current++; + if (current >= max) break; + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java index 33ae0e17b..96fad9239 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java @@ -10,59 +10,59 @@ public final class StatsHelper { - private StatsHelper() { - } + private StatsHelper() { + } - @Nonnull - public static int[] getSlots(int row) { - int[] slots = {1, 2, 3, 4, 5, 6, 7, 11, 12, 13, 14, 15}; - for (int i = 0; i < slots.length; i++) { - slots[i] += row * 9; - } - return slots; - } + @Nonnull + public static int[] getSlots(int row) { + int[] slots = {1, 2, 3, 4, 5, 6, 7, 11, 12, 13, 14, 15}; + for (int i = 0; i < slots.length; i++) { + slots[i] += row * 9; + } + return slots; + } - public static void setAccent(@Nonnull AnimatedInventory inventory, int row) { - inventory.createAndAdd().fill(ItemBuilder.FILL_ITEM); - int offset = row * 9; - inventory.cloneLastAndAdd().setAccent(offset, offset + 8); - inventory.cloneLastAndAdd().setAccent(offset + 1, offset + 7); - inventory.cloneLastAndAdd().setAccent(offset + 10, offset + 16); - inventory.cloneLastAndAdd().setAccent(offset + 11, offset + 15); - inventory.cloneLastAndAdd().setAccent(offset + 12, offset + 14); - } + public static void setAccent(@Nonnull AnimatedInventory inventory, int row) { + inventory.createAndAdd().fill(ItemBuilder.FILL_ITEM); + int offset = row * 9; + inventory.cloneLastAndAdd().setAccent(offset, offset + 8); + inventory.cloneLastAndAdd().setAccent(offset + 1, offset + 7); + inventory.cloneLastAndAdd().setAccent(offset + 10, offset + 16); + inventory.cloneLastAndAdd().setAccent(offset + 11, offset + 15); + inventory.cloneLastAndAdd().setAccent(offset + 12, offset + 14); + } - @Nonnull - public static Message getNameMessage(@Nonnull Statistic statistic) { - return Message.forName("stat-" + statistic.name().toLowerCase().replace('_', '-')); - } + @Nonnull + public static Message getNameMessage(@Nonnull Statistic statistic) { + return Message.forName("stat-" + statistic.name().toLowerCase().replace('_', '-')); + } - @Nonnull - public static Material getMaterial(@Nonnull Statistic statistic) { - switch (statistic) { - default: - return Material.PAPER; - case DEATHS: - return Material.STONE_SHOVEL; - case BLOCKS_MINED: - return Material.GOLDEN_PICKAXE; - case BLOCKS_PLACED: - return Material.DIRT; - case DAMAGE_DEALT: - return Material.STONE_SWORD; - case DAMAGE_TAKEN: - return Material.LEATHER_CHESTPLATE; - case ENTITY_KILLS: - return Material.IRON_SWORD; - case DRAGON_KILLED: - return Material.DRAGON_EGG; - case BLOCKS_TRAVELED: - return Material.MINECART; - case CHALLENGES_PLAYED: - return Material.GOLD_INGOT; - case JUMPS: - return Material.GOLDEN_BOOTS; - } - } + @Nonnull + public static Material getMaterial(@Nonnull Statistic statistic) { + switch (statistic) { + default: + return Material.PAPER; + case DEATHS: + return Material.STONE_SHOVEL; + case BLOCKS_MINED: + return Material.GOLDEN_PICKAXE; + case BLOCKS_PLACED: + return Material.DIRT; + case DAMAGE_DEALT: + return Material.STONE_SWORD; + case DAMAGE_TAKEN: + return Material.LEATHER_CHESTPLATE; + case ENTITY_KILLS: + return Material.IRON_SWORD; + case DRAGON_KILLED: + return Material.DRAGON_EGG; + case BLOCKS_TRAVELED: + return Material.MINECART; + case CHALLENGES_PLAYED: + return Material.GOLD_INGOT; + case JUMPS: + return Material.GOLDEN_BOOTS; + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StructureUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StructureUtils.java index a163910ab..a1c20de3d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StructureUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StructureUtils.java @@ -4,48 +4,48 @@ import org.bukkit.StructureType; public class StructureUtils { - public static Material getStructureIcon(StructureType structureType) { + public static Material getStructureIcon(StructureType structureType) { - switch (structureType.getName()) { - case "nether_fossil": - return Material.BONE_BLOCK; - case "jungle_pyramid": - return Material.LEVER; - case "monument": - return Material.SEA_LANTERN; - case "desert_pyramid": - return Material.SANDSTONE_STAIRS; - case "mineshaft": - return Material.RAIL; - case "ocean_ruin": - return Material.DROWNED_SPAWN_EGG; - case "bastion_remnant": - return Material.BLACKSTONE; - case "shipwreck": - return Material.OAK_BOAT; - case "fortress": - return Material.NETHER_BRICK_FENCE; - case "buried_treasure": - return Material.CHEST; - case "pillager_outpost": - return Material.CROSSBOW; - case "swamp_hut": - return Material.CAULDRON; - case "igloo": - return Material.SNOW_BLOCK; - case "village": - return Material.VILLAGER_SPAWN_EGG; - case "stronghold": - return Material.END_PORTAL_FRAME; - case "end_city": - return Material.PURPUR_PILLAR; - case "mansion": - return Material.TOTEM_OF_UNDYING; - case "ruined_portal": - return Material.CRYING_OBSIDIAN; - default: - return Material.STRUCTURE_VOID; - } + switch (structureType.getName()) { + case "nether_fossil": + return Material.BONE_BLOCK; + case "jungle_pyramid": + return Material.LEVER; + case "monument": + return Material.SEA_LANTERN; + case "desert_pyramid": + return Material.SANDSTONE_STAIRS; + case "mineshaft": + return Material.RAIL; + case "ocean_ruin": + return Material.DROWNED_SPAWN_EGG; + case "bastion_remnant": + return Material.BLACKSTONE; + case "shipwreck": + return Material.OAK_BOAT; + case "fortress": + return Material.NETHER_BRICK_FENCE; + case "buried_treasure": + return Material.CHEST; + case "pillager_outpost": + return Material.CROSSBOW; + case "swamp_hut": + return Material.CAULDRON; + case "igloo": + return Material.SNOW_BLOCK; + case "village": + return Material.VILLAGER_SPAWN_EGG; + case "stronghold": + return Material.END_PORTAL_FRAME; + case "end_city": + return Material.PURPUR_PILLAR; + case "mansion": + return Material.TOTEM_OF_UNDYING; + case "ruined_portal": + return Material.CRYING_OBSIDIAN; + default: + return Material.STRUCTURE_VOID; } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriConsumer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriConsumer.java index e5951b662..3cb89fbbc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriConsumer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriConsumer.java @@ -2,6 +2,6 @@ public interface TriConsumer { - void accept(A a, B b, C c); + void accept(A a, B b, C c); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriFunction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriFunction.java index 88021f775..5235277c9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriFunction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/TriFunction.java @@ -6,11 +6,11 @@ @FunctionalInterface public interface TriFunction { - R apply(A a, B b, C c); + R apply(A a, B b, C c); - default TriFunction andThen(Function after) { - Objects.requireNonNull(after); - return (A a, B b, C c) -> after.apply(apply(a, b, c)); - } + default TriFunction andThen(Function after) { + Objects.requireNonNull(after); + return (A a, B b, C c) -> after.apply(apply(a, b, c)); + } -} \ No newline at end of file +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java index 8ba0c86d2..c98b80ee8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java @@ -16,50 +16,50 @@ public final class Utils { - private Utils() { - } + private Utils() { + } - @Nonnull - public static List filterRecommendations(@Nonnull String argument, @Nonnull String... recommendations) { - argument = argument.toLowerCase(); - List list = new ArrayList<>(); - for (String current : recommendations) { - if (current.toLowerCase().startsWith(argument)) - list.add(current); - } - return list; - } + @Nonnull + public static List filterRecommendations(@Nonnull String argument, @Nonnull String... recommendations) { + argument = argument.toLowerCase(); + List list = new ArrayList<>(); + for (String current : recommendations) { + if (current.toLowerCase().startsWith(argument)) + list.add(current); + } + return list; + } - @Nonnull - public static UUID fetchUUID(@Nonnull String name) throws IOException { - String url = "https://api.mojang.com/users/profiles/minecraft/" + name; - String content = IOUtils.toString(new URL(url)); - Document document = Document.parseJson(content); - return Optional.ofNullable(matchUUID(document.getString("id"))).orElseThrow(IOException::new); - } + @Nonnull + public static UUID fetchUUID(@Nonnull String name) throws IOException { + String url = "https://api.mojang.com/users/profiles/minecraft/" + name; + String content = IOUtils.toString(new URL(url)); + Document document = Document.parseJson(content); + return Optional.ofNullable(matchUUID(document.getString("id"))).orElseThrow(IOException::new); + } - @Nullable - public static UUID matchUUID(@Nullable String uuid) { - if (uuid == null) return null; - Pattern pattern = Pattern.compile("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})"); - return UUID.fromString(pattern.matcher(uuid).replaceAll("$1-$2-$3-$4-$5")); - } + @Nullable + public static UUID matchUUID(@Nullable String uuid) { + if (uuid == null) return null; + Pattern pattern = Pattern.compile("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})"); + return UUID.fromString(pattern.matcher(uuid).replaceAll("$1-$2-$3-$4-$5")); + } - @Nullable - @CheckReturnValue - public static Material getMaterial(@Nullable String name) { - return ReflectionUtils.getEnumOrNull(name, Material.class); - } + @Nullable + @CheckReturnValue + public static Material getMaterial(@Nullable String name) { + return ReflectionUtils.getEnumOrNull(name, Material.class); + } - @Nullable - @CheckReturnValue - public static EntityType getEntityType(@Nullable String name) { - return ReflectionUtils.getEnumOrNull(name, EntityType.class); - } + @Nullable + @CheckReturnValue + public static EntityType getEntityType(@Nullable String name) { + return ReflectionUtils.getEnumOrNull(name, EntityType.class); + } - public static > void removeEnums(@Nonnull Collection collection, @Nonnull String... names) { - List nameList = Arrays.asList(names); - collection.removeIf(element -> nameList.contains(element.name())); - } + public static > void removeEnums(@Nonnull Collection collection, @Nonnull String... names) { + List nameList = Arrays.asList(names); + collection.removeIf(element -> nameList.contains(element.name())); + } } From b8f2c911657c637903e2f2a3ef71c7e99635208a Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 18 Apr 2025 10:52:12 +0200 Subject: [PATCH 051/119] style: reindent with 2 spaces --- language/files/de.json | 3728 ++++++++--------- language/files/en.json | 3638 ++++++++-------- language/languages.json | 4 +- .../mongoconnector/MongoConnector.java | 8 +- .../challenges/plugin/ChallengeAPI.java | 210 +- .../management/blocks/BlockDropManager.java | 276 +- .../challenges/ChallengeLoader.java | 582 ++- .../challenges/CustomChallengesLoader.java | 202 +- .../annotations/RequireVersion.java | 4 +- .../entities/GamestateSaveable.java | 6 +- .../plugin/management/cloud/CloudSupport.java | 16 +- .../management/cloud/CloudSupportManager.java | 256 +- .../cloud/support/CloudNet2Support.java | 68 +- .../management/database/DatabaseManager.java | 240 +- .../management/files/ConfigManager.java | 168 +- .../inventory/PlayerInventoryManager.java | 484 +-- .../menu/InventoryTitleManager.java | 92 +- .../plugin/management/menu/MenuType.java | 68 +- .../generator/ChallengeMenuGenerator.java | 444 +- .../menu/generator/MenuGenerator.java | 88 +- .../generator/MultiPageMenuGenerator.java | 76 +- .../menu/generator/ValueMenuGenerator.java | 142 +- .../categorised/CategorisedMenuGenerator.java | 334 +- .../categorised/SettingCategory.java | 68 +- .../implementation/TimerMenuGenerator.java | 386 +- .../CustomMainSettingsMenuGenerator.java | 140 +- .../custom/InfoMenuGenerator.java | 526 +-- .../custom/MainCustomMenuGenerator.java | 172 +- .../custom/SubSettingValueMenuGenerator.java | 58 +- .../scheduler/AbstractTaskConfig.java | 8 +- .../management/scheduler/ScheduleManager.java | 208 +- .../scheduler/ScheduledFunction.java | 71 +- .../scheduler/ScheduledTaskExecutor.java | 52 +- .../management/scheduler/TimerTaskConfig.java | 30 +- .../scheduler/TimerTaskExecutor.java | 38 +- .../policy/ChallengeStatusPolicy.java | 30 +- .../scheduler/policy/ExtraWorldPolicy.java | 22 +- .../scheduler/policy/FreshnessPolicy.java | 22 +- .../management/scheduler/policy/IPolicy.java | 8 +- .../scheduler/policy/PlayerCountPolicy.java | 24 +- .../scheduler/task/ScheduledTask.java | 26 +- .../management/scheduler/task/TimerTask.java | 22 +- .../scheduler/timer/ChallengeTimer.java | 386 +- .../scheduler/timer/TimerFormat.java | 104 +- .../scheduler/timer/TimerStatus.java | 4 +- .../management/server/ChallengeEndCause.java | 35 +- .../management/server/GameWorldStorage.java | 184 +- .../server/GeneratorWorldPortalManager.java | 80 +- .../management/server/ScoreboardManager.java | 154 +- .../management/server/ServerManager.java | 198 +- .../management/server/WorldManager.java | 626 +-- .../server/scoreboard/ChallengeBossBar.java | 254 +- .../scoreboard/ChallengeScoreboard.java | 250 +- .../plugin/management/stats/Statistic.java | 60 +- .../plugin/management/stats/StatsManager.java | 304 +- 55 files changed, 7811 insertions(+), 7873 deletions(-) diff --git a/language/files/de.json b/language/files/de.json index 4762dbaac..db6acbadb 100644 --- a/language/files/de.json +++ b/language/files/de.json @@ -1,1866 +1,1866 @@ { - "syntax": "Bitte nutze §e/{0}", - "reload": "Challenges Plugin wird neu geladen...", - "reload-failed": "Ein §cFehler §7ist während dem Reload aufgetreten", - "reload-success": "Challenges Plugin wurde §aerfolgreich §7neu geladen", - "player-command": "Dazu musst du ein Spieler sein!", - "no-permission": "Dazu hast du §ckeine §7Rechte", - "enabled": "§aAktiviert", - "disabled": "§cDeaktiviert", - "customize": "§6Anpassen", - "navigate-back": "§8« §7Zurück", - "navigate-next": "§8» §7Weiter", - "seconds": "Sekunden", - "second": "Sekunde", - "minutes": "Minuten", - "minute": "Minute", - "hours": "Stunden", - "hour": "Stunde", - "amplifier": "Stärke", - "open": "Öffnen", - "everyone": "§5Alle", - "player": "§6Aktiver Spieler", - "none": "Nichts", - "inventory-color": "§9", - "timer-counting-up": "§8» §7Timer zählt §ahoch", - "timer-counting-down": "§8» §7Timer zählt §crunter", - "timer-is-paused": "§8» §7Timer ist §cpausiert", - "timer-is-running": "§8» §7Timer ist §agestartet", - "confirm-reset": "Bestätige den Reset mit §e/{0}", - "no-fresh-reset": [ - "Der Server kann §cnicht resettet §7werden", - "Die Challenge wurde §cnoch nicht §7gestartet" - ], - "new-challenge": "§a§lNeu!", - "feature-disabled": "Diese Funktion ist derzeit §cdeaktiviert", - "challenge-disabled": "Diese Challenge ist derzeit §cdeaktiviert", - "stopped-message": "§8• §7Timer §c§lpaused §8•", - "count-up-message": "§8• §7Time: §a§l{0} §8•", - "count-down-message": "§8• §7Time: §c§l{0} §8•", - "timer-not-started": "Der Timer wurde noch §cnicht gestartet", - "timer-was-started": "Der Timer wurde §agestartet", - "timer-was-paused": "Der Timer wurde §cpausiert", - "timer-was-set": "Der Timer wurde auf §e§l{0} §7gesetzt", - "timer-already-started": "Der Timer §cläuft bereits", - "timer-already-paused": "Der Timer ist §cbereits pausiert", - "timer-mode-set-down": "Der Timer zählt nun §crunter", - "timer-mode-set-up": "Der Timer zählt nun §ahoch", - "no-database-connection": "Es gibt §ckeine §7Datenbankverbindung", - "fetching-data": "Daten werden abgerufen..", - "undefined": "undefiniert", - "no-such-material": "Dieses Material gibt es nicht", - "not-an-item": "§e{0} §7ist kein Item", - "no-such-entity": "Dieses Entity existiert nicht", - "not-alive": "§e{0} §7ist kein lebendes Entity", - "no-loot": "§e{0} §7hat keine Drops", - "deprecated-plugin-version": [ - " ", - "§7Ein neues Update ist verfügbar!", - "§7Download: §e§l{0}", - " " - ], - "deprecated-config-version": [ - "Deine Plugin Config ist §cveraltet §7(§c{1} §7< §a{0}§7)", - "Du kannst die alte Config löschen oder die fehlenden Einstellungen manuell hinzufügen" - ], - "missing-config-settings": "Folgende Einstellungen fehlen in der Config: §e{0}", - "missing-config-settings-separator": "§7, §e", - "no-missing-config-settings": [ - "§cEs fehlen keine Einstellungen in der Config.", - "§cDu kannst die Version ohne bedenken selbst auf §c§l{0} §cstellen." - ], - "unsuported-language": [ - "§cDiese Sprache §7(§e{0}§7) wird nicht unterstützt" - ], - "not-op":[ - "§7Um dieses Plugin zu nutzen, musst du die Berechtigung haben. Gib dir die Berechtigung in der Serverkonsole mit: /op [name]" - ], - "join-message": "§e{0} §7hat den Server §abetreten", - "quit-message": "§e{0} §7hat den Server §cverlassen", - "timer-paused-message": [ - "Der Timer ist noch §cpausiert", - "Nutze §e/timer resume §7um ihn zu starten" - ], - "cheats-detected": [ - "§e{0} §7hat §cgecheated", - "Es können §ckeine weiteren §7Statistiken gesammelt werden" - ], - "cheats-already-detected": [ - "Auf diesem Server wurde §cgecheated", - "Es können §ckeine weiteren §7Statistiken gesammelt werden" - ], - "custom_challenges-reset": "Die §eLokalen §7Challenges wurden §aerfolgreich zurückgesetzt", - "config-reset": "Die §eLokalen §7Einstellungen wurden §aerfolgreich zurückgesetzt", - "player-config-loaded": "Deine Einstellungen wurden §aerfolgreich geladen", - "player-config-saved": "Deine Einstellungen wurden §aerfolgreich gespeichert", - "player-config-reset": "Deine Einstellungen wurden §aerfolgreich zurückgesetzt", - "player-custom_challenges-loaded": "Deine Challenges wurden §aerfolgreich geladen", - "player-custom_challenges-saved": "Deine Challenges wurden §aerfolgreich gespeichert", - "player-custom_challenges-reset": "Deine Challenges wurden §aerfolgreich zurückgesetzt", - "item-prefix": "§8» ", - "item-setting-info": "§8➟ {0}", - "stat-dragon-killed": "Drachen getötet", - "stat-deaths": "Tode", - "stat-entity-kills": "Kills", - "stat-damage-dealt": "Schaden ausgeteilt", - "stat-damage-taken": "Schaden genommen", - "stat-blocks-mined": "Blöcke abgebaut", - "stat-blocks-placed": "Blöcke platziert", - "stat-blocks-traveled": "Blöcke gereist", - "stat-challenges-played": "Challenges gespielt", - "stat-jumps": "Sprünge", - "stats-of": "§8» §7Stats von §e{0}", - "stats-display": "§8» §7{0} §8(§e{1}. §7Platz§8)", - "stats-leaderboard-display": [ - "§8» §e{0}", - "§8§l┣ §7{1} §7{2}", - "§8§l┗ §e{3}. §7Platz" - ], - "position": "§e{4} §8- §7{0}, {1}, {2} §8(§e{3}§8) §8┃ §e{5}m", - "positions-disabled": "Positionen sind §cdeaktiviert", - "position-other-world": "Diese Position befindet sich in einer anderen Welt §8(§e{0}§8)", - "position-not-exists": "Die Position §e{0} §7existiert §cnicht", - "position-already-exists": "Die Position §e{0} §7existiert §cbereits", - "position-set": "§e{5} §7hat §e{4} §7{0}, {1}, {2} §8(§e{3}§8) §7erstellt", - "position-deleted": "§e{5} §7hat §e{4} §7{0}, {1}, {2} §8(§e{3}§8) §7gelöscht", - "no-positions": [ - "Es sind keine §ePositionen §7in dieser Welt gesetzt", - "Erstelle eine mit §e/{0}" - ], - "no-positions-global": [ - "Es sind keine §ePositionen §7gesetzt", - "Erstelle eine mit §e/{0}" - ], - "command-no-target": "Es wurde §ckein §7Spieler gefunden", - "command-heal-healed": "Du wurdest §ageheilt", - "command-heal-healed-others": "Du hast §e{0} Spieler §ageheilt", - "command-gamemode-gamemode-changed": "Du wurdest in den Gamemode §e{0} §7gesetzt", - "command-gamemode-gamemode-changed-others": "Du hast §e{1} Spieler §7in den Gamemode §e{0} §7gesetzt", - "command-village-search": "Es wird nach einem Dorf gesucht..", - "command-village-teleport": "Du wurdest in ein Dorf §ateleportiert", - "command-village-not-found": "Es wurde §ckein neues §7Dorf gefunden", - "command-weather-set-clear": "Wetter zu §eklar §7geändert", - "command-weather-set-rain": "Wetter zu §eregnerisch §7geändert", - "command-weather-set-thunder": "Wetter zu §estürmisch §7geändert", - "command-invsee-open": "Inventar von §e{0} §7geöffnet", - "command-enderchest-open": "Du hast deine §5Enderchest §7geöffnet", - "command-difficulty-change": "Schwierigkeit auf {0} §7geändert", - "command-difficulty-current": "Die derzeitige Schwierigkeit ist {0}", - "command-search-nothing": "§e{0} §7wird durch keinen speziellen Block gedroppt", - "command-search-result": "§e{0} §7droppt aus §e{1}", - "command-searchloot-disabled": "Die Entity Loot Randomizer Challenge ist aktuell §cdeaktiviert", - "command-searchloot-nothing": "Der Loot von §e{0} §7wird durch kein spezielles Entity gedroppt", - "command-searchloot-result": [ - "§e{0} §7droppt den Loot von §e{1}", - "Der Loot von §e{0} §7wird von §e{2} §7gedroppt" - ], - "command-time-set": "Die Zeit wurde auf §e{0} §7Ticks §8(§7ca. §e{1}§8) §7geändert", - "command-time-set-exact": "Die Zeit wurde auf §e{0} §8(§e{1} §7Ticks§8) §7geändert", - "command-time-query": [ - "§8» §7Derzeitige Ingamezeiten", - "Spielzeit §e{0} §7Ticks §8(§7Tag §e{1}§8)", - "Tageszeit §e{2} §7Ticks §8(§7ca. §e{3}§8)" - ], - "command-time-noon": "Mittag", - "command-time-night": "Nacht", - "command-time-midnight": "Mitternacht", - "command-time-day": "Tag", - "command-fly-enabled": "Du kannst §anun fliegen", - "command-fly-disabled": "Du kannst nun §cnicht mehr §7fliegen", - "command-fly-toggled-others": "Du hast §eFly §7für §e{0} §7Spieler verändert", - "command-feed-fed": "Dein Hunger wurde §agestillt", - "command-feed-others": "Du hast den Hunger von §e{0} §7Spieler *gestillt*", - "command-gamestate-reload": "Der Gamestate wurde §aneu geladen", - "command-gamestate-reset": "Der Gamestate wurde §azurückgesetzt", - "command-world-teleport": "Du wirst in die Welt §e{0} §7teleportiert", - "command-back-no-locations": "Du hast dich noch §cnicht §7teleportiert", - "command-back-teleported": "Du wurdest §e{0} §7Position zurück teleportiert", - "command-back-teleported-multiple": "Du wurdest §e{0} §7Positionen zurück teleportiert", - "command-result-no-battle-active": "Es ist aktuell §ckein §7Force-Battle aktiviert", - "command-god-mode-enabled": "Du bist nun im §aGod-Mode", - "command-god-mode-disabled": "Du bist nun §cnicht mehr im God-Mode", - "command-god-mode-toggled-others": "§e{0} §7Spieler sind jetzt im §eGod-Mode", - "traffic-light-challenge-fail": "§e{0} §7ist über §crot §7gegangen", - "player-damage-display": "§e{0} §7nahm §7{1} §7Schaden durch §e{2}", - "death-message": "§e{0} §7ist gestorben", - "death-message-cause": "§e{0} §7ist durch §e{1} §7gestorben", - "health-inverted": "Deine Herzen wurden §cinvertiert", - "exp-picked-up": "§e{0} §7hat §cXP §7aufgesammelt", - "unable-to-find-fortress": "Es konnte §ckeine Festung §7gefunden werden", - "unable-to-find-bastion": "Es konnte §ckeine Bastion §7gefunden werden", - "death-collected": "Todesgrund §e{0} §7wurde registriert", - "item-collected": "Item §e{0} §7wurde registriert", - "items-to-collect": "§7Items zu sammeln §8» §e{0}", - "backpacks-disabled": "Rucksäcke sind derzeit §cdeaktiviert", - "backpack-opened": "Du hast den {0} §7geöffnet", - "top-to-overworld": "Du wurdest zur §eOverworld §7teleportiert", - "top-to-surface": "Du wurdest zur §eOberfläche §7teleportiert", - "jnr-countdown": "Nächstes §6JumpAndRun §7in §e{0} Sekunden", - "jnr-countdown-one": "Nächstes §6JumpAndRun §7in §eeiner Sekunde", - "jnr-finished": "§e{0} §7hat das §6JumpAndRun §ageschafft", - "snake-failed": "§e{0} §7ist über die §9Linie §7getreten", - "only-dirt-failed": "§e{0} §7stand nicht auf Erde", - "no-mouse-move-failed": "§e{0} §7hat seine Maus bewegt", - "no-duped-items-failed": "§e{0} §7und §e{1} §7hatten beide §e{2} §7im Inventar", - "only-down-failed": "§e{0} §7ist einen Block nach oben gegangen", - "food-once-failed": "§e{0} §7ist an §e{1} §7erstickt", - "food-once-new-food-team": "§e{0} §7hat §e{1} §7gegessen", - "food-once-new-food": "§eDu §7hast §e{1} §7gegessen", - "sneak-damage-failed": "§e{0} §7ist geschlichen", - "jump-damage-failed": "§e{0} §7ist gesprungen", - "random-challenge-enabled": "Die Challenge §e{0} §7wurde §aaktiviert", - "all-items-skipped": "Item §e{0} §7geskippt", - "all-items-already-finished": "Es wurden bereits alle Items gefunden", - "all-items-found": "Das Item §e{0} §7wurde von §e{1} §7registriert", - "mob-kill": "§e{0} §7wurde besiegt §8(§e{1} §7/ §e{2}§8)", - "endergames-teleport": "Du wurdest mit §e{0} §7getauscht", - "force-height-fail": "§e{0} §7war auf der §cfalschen Höhe §8(§e{1}§8)", - "force-height-success": "Alle Spieler waren auf der §arichtigen Höhe", - "force-block-fail": "§e{0} §7war auf dem §cfalschen Block §8(§e{1}§8)", - "force-block-success": "Alle Spieler waren auf dem §arichtigen Block", - "force-biome-fail": "Das Biom §e{0} §7wurde §cnicht gefunden", - "force-biome-success": "§e{0} §7hat das Biom §e{1} §agefunden", - "force-mob-fail": "Das Mob §e{0} §7wurde §cnicht getötet", - "force-mob-success": "§e{0} §7hat das Mob §e{1} §agetötet", - "force-item-fail": "Das Item §e{0} §7wurde §cnicht gefunden", - "force-item-success": "§e{0} §7hat das Item §e{1} §agefunden", - "new-effect": "Effekt §e{0} §8➔ §e{1}", - "missing-items-inventory": "{0}Welches Item fehlt?", - "missing-items-inventory-open": "§8[§aGUI öffnen§8]", - "loops-cleared": "§e{0} §7Loops abgebrochen", - "stopped-moving": "§e{0} §7hat sich zu lange nicht bewegt", - "all-advancements-goal": "§7Advancements §8» §e{0}", - "Chalheight-reached": "§e{0} §7hat Höhe §e{1} §7erreicht!", - "race-goal-reached": "§e{0} §7hat das Ziel erreicht!", - "points-change": "§e{0} §7Punkte", - "force-item-battle-found": "Du hast §e{0} §7gefunden!", - "force-item-battle-new-item": "Item zu suchen: §e{0}", - "force-item-battle-leaderboard": "§8➜ §7Force Item Battle Leaderboard", - "force-mob-battle-killed": "Du hast §e{0} §7gefunden!", - "force-mob-battle-new-mob": "Mob zu suchen: §e{0}", - "force-mob-battle-leaderboard": "§8➜ §7Force Mob Battle Leaderboard", - "force-advancement-battle-completed": "Du hast §e{0} §7erzielt!", - "force-advancement-battle-new-advancement": "Nächstes Advancement: §e{0}", - "force-advancement-battle-leaderboard": "§8➜ §7Force Advancement Battle Leaderboard", - "force-block-battle-found": "Du hast §e{0} §7gefunden!", - "force-block-battle-new-block": "Block zu suchen: §e{0}", - "force-block-battle-leaderboard": "§8➜ §7Force Block Battle Leaderboard", - "force-battle-leaderboard-entry": "{0}#{1} §8» §e{2} §8┃ §e{3}", - "force-battle-block-target-display": "§eBlock: {0}", - "force-battle-item-target-display":"§eItem: {0}", - "force-battle-height-target-display": "§eHöhe: {0}", - "force-battle-mob-target-display": "§eMob: {0}", - "force-battle-biome-target-display": "§eBiom: {0}", - "force-battle-damage-target-display": "§eSchaden: §c{0} ❤", - "force-battle-advancement-target-display": "§eAdvancement: {0}", - "force-battle-position-target-display": "§ePosition: {0}", - "extreme-force-battle-new-height": "Höhe zu erreichen: §e{0}", - "extreme-force-battle-reached-height": "Du hast die Höhe §e{0} §7erreicht!", - "extreme-force-battle-new-biome": "Biom zu finden: §e{0}", - "extreme-force-battle-found-biome": "Du hast das Biom §e{0} §7gefunden!", - "extreme-force-battle-new-damage": "Schaden zu nehmen: §c{0} ❤", - "extreme-force-battle-took-damage": "Du hast §c{0} ❤ §7Schaden genommen!", - "extreme-force-battle-position": "§eX: {0} §8┃ §eZ: {1}", - "extreme-force-battle-new-position": "Position zu erreichen: §e{0}", - "extreme-force-battle-reached-position": "Du hast die Position §e{0} §7erreicht!", - "extreme-force-battle-leaderboard": "§8➜ §7Extreme Force Battle Leaderboard", - "force-biome-battle-leaderboard": "§8➜ §7Force Biome Battle Leaderboard", - "force-damage-battle-leaderboard": "§8➜ §7Force Damage Battle Leaderboard", - "force-height-battle-leaderboard": "§8➜ §7Force Height Battle Leaderboard", - "force-position-battle-leaderboard": "§8➜ §7Force Position Battle Leaderboard", - "random-event-speed": [ - "Sonic? Bist du es?", - "Woahh! Das ist aber schnell" - ], - "random-event-entities": [ - "Ist das hier ein Zoo?", - "Wo kommt ihr denn her?", - "Was macht ihr denn hier?" - ], - "random-event-hole": [ - "Du bist aber ganz schön tief gefallen", - "Von ganz oben nach ganz unten..", - "Wo kommt denn das Loch her?" - ], - "random-event-fly": [ - "Guten Flug :)", - "I believe I can fly..", - "So fühlt sich also fliegen an" - ], - "random-event-webs": [ - "Liegen die schon lange hier?" - ], - "random-event-ores": [ - "Wo sind denn die ganzen Erze hin?", - "Gibt es hier keine Erze?", - "Gab es hier mal Erze?" - ], - "random-event-sickness": [ - "Bist du etwa krank?", - "Was geht denn jetzt ab" - ], - "bossbar-timer-paused": "§8» §7Der Timer ist §cpausiert", - "bossbar-mob-transformation": "§8» §7Letzter Mob §8§l┃ §a{0}", - "bossbar-biome-time-left": "§8» §7Zeit übrig in §e{0} §8§l┃ §a{1}s", - "bossbar-height-time-left": "§8» §7Zeit übrig auf §e{0} §8§l┃ §a{1}s", - "bossbar-zero-hearts": "§8» §7Schutzzeit §8§l┃ §a{0}s", - "bossbar-random-challenge-waiting": "§8» §7Warten auf neue Challenge..", - "bossbar-random-challenge-current": "§8» §7Challenge §e{0}", - "bossbar-all-items-current-max": "§8» §f{0} §8┃ §7{1} §8/ §7{2}", - "bossbar-all-items-finished": "§8» §7Alle Items gefunden", - "bossbar-force-height-waiting": "§8» §7Warten auf nächste Höhe..", - "bossbar-force-height-instruction": "§8» §7Höhe §e{0} §8┃ §a{1}", - "bossbar-force-block-waiting": "§8» §7Warten auf nächsten Block..", - "bossbar-force-block-instruction": "§8» §7Block §e{0} §8┃ §a{1}", - "bossbar-force-biome-waiting": "§8» §7Warten auf nächstes Biom..", - "bossbar-force-biome-instruction": "§8» §7Biom §e{0} §8┃ §a{1}", - "bossbar-force-mob-waiting": "§8» §7Warten auf nächsten Mob..", - "bossbar-force-mob-instruction": "§8» §7Mob §e{0} §8┃ §a{1}", - "bossbar-force-item-waiting": "§8» §7Warten auf nächstes Item..", - "bossbar-force-item-instruction": "§8» §7Item §e{0} §8┃ §a{1}", - "bossbar-tsunami-water": "§8» §7Wasserhöhe: §9{0}", - "bossbar-tsunami-lava": "§8» §7Lavahöhe: §c{0}", - "bossbar-ice-floor": "§8» §fEisboden §8┃ {0}", - "bossbar-dont-stop-running": "§8» §7Bewege dich in §8┃ §e{0}", - "bossbar-five-hundred-blocks": "§8» §fBlöcke Gelaufen §8┃ §7{0} §8/ §7{1}", - "bossbar-level-border": "§8» §7Border Größe §8┃ §7{0}", - "bossbar-race-goal-info": "§8» §fZiel §8┃ §7X: {0} §8/ §7Z: {1} §8┃ §e{2} Blöcke", - "bossbar-race-goal": "§8» §fZiel §8┃ §7X: {0} §8/ §7Z: {1}", - "bossbar-first-at-height-goal": "§8» §fZiel §8┃ §7Y: {0}", - "bossbar-respawn-end": "§8» §5Respawnte Mobs im End §8┃ §e{0}", - "bossbar-kill-all-bosses": "§8» §cAlle Bosse §8┃ §e{0}/{1}", - "bossbar-kill-all-mobs": "§8» §cAlle Mobs §8┃ §e{0}/{1}", - "bossbar-kill-all-monster": "§8» §cAlle Monster §8┃ §e{0}/{1}", - "bossbar-chunk-deletion": "§8» §7Zeit übrig im Chunk §6{0}s", - "subtitle-time-seconds": "§e{0} §7Sekunden", - "subtitle-time-seconds-range": "§e{0}-{1} §7Sekunden", - "subtitle-time-minutes": "§e{0} §7Minuten", - "subtitle-launcher-description": "§7Stärke §e{0}", - "subtitle-blocks": "§e{0} §7Blöcke", - "subtitle-range-blocks": "§7Reichweite: §e{0} §7Blöcke", - "scoreboard-title": "§7» §f§lChallenge", - "scoreboard-leaderboard": "§e#{0} §8┃ §7{1} §8» §e{2}", - "your-place": "§7Dein Platz §8» §e{0}", - "server-reset": [ - "§8————————————————————", - " ", - "§8» §cServerreset", - " ", - "§7Reset durch §4§l{0}", - "§7Der Server startet nun §cneu", - " ", - "§8————————————————————" - ], - "challenge-end-timer-hit-zero": [ - " ", - "§cDie Challenge ist vorbei!", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-timer-hit-zero-winner": [ - " ", - "§cDie Challenge ist vorbei!", - "§7Gewinner: §e§l{1}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-reached": [ - " ", - "§7Die Challenge wurde beendet!", - "§7Zeit benötigt: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-reached-winner": [ - " ", - "§7Die Challenge wurde beendet!", - "§7Gewinner: §e§l{1}", - "§7Zeit benötigt: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-failed": [ - " ", - "§cDie Challenge ist vorbei! §6#FeelsBadMan ✞", - "§7Zeit verschwendet: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "title-timer-started": [ - " ", - "§8» §7Timer §afortgesetzt" - ], - "title-timer-paused": [ - " ", - "§8» §7Timer §cpausiert" - ], - "title-challenge-enabled": [ - "§e{0}", - "§2§l✔ §8┃ §aAktiviert" - ], - "title-challenge-disabled": [ - "§e{0}", - "§4✖ §8┃ §cDeaktiviert" - ], - "title-challenge-value-changed": [ - "§e{0}", - "§8» §e{1}" - ], - "title-pregame-movement-setting": [ - "§cWarte..", - "§8» §7Der Timer ist gestoppt.." - ], - "item-menu-start": "§8• §aStart Challenge §8┃ §e/start §8•", - "item-menu-challenges": "§8• §cChallenges §8┃ §e/challenge §8•", - "item-menu-timer": "§8• §5Timer §8┃ §e/timer §8•", - "item-menu-leaderboard": "§8• §6Leaderboard §8┃ §e/leaderboard §8•", - "item-menu-stats": "§8• §2Statistiken §8┃ §e/stats §8•", - "menu-title": "Menu", - "menu-timer": "§6Timer", - "menu-goal": "§5Ziel", - "menu-damage": "§7Schaden", - "menu-item_blocks": "§4Blöcke & Items", - "menu-challenges": "§cChallenges", - "menu-settings": "§eEinstellungen", - "menu-custom": "§aIndividuelle Challenges", - "lore-category-activated-count": "§7Aktiviert §8» §a{0}§8/§7{1}", - "lore-category-activated": "§7Aktiviert §8» §aJa", - "lore-category-deactivated": "§7Aktiviert §8» §cNein", - "category-misc_challenge": [ - "§9Miscellaneous", - "Challenges, die *keiner Kategorie*", - "zugeordnet werden können" - ], - "category-randomizer": [ - "§6Randomizer", - "Erlebe ein komplett", - "*durcheinandergebrachtes* Spiel" - ], - "category-limited_time": [ - "§aLimitierte Zeit", - "Du wirst bei verschiedenen", - "Faktoren *zeitlich eingeschränkt*" - ], - "category-force": [ - "§3Zwischenziele (Force)", - "Du musst *bestimmte Zwischenziele*", - "erfüllen, sonst stirbst du" - ], - "category-world": [ - "§4Weltveränderung", - "Die Welt wird nicht mehr", - "*wiedererkennbar* sein" - ], - "category-damage": [ - "§cSchaden", - "Neue *Schadens Regeln*" - ], - "category-effect": [ - "§5Effekte", - "Erlebe verrückte *Effekte*" - ], - "category-inventory": [ - "§6Inventory", - "Dein Inventar wird *verdreht*" - ], - "category-movement": [ - "§aBewegung", - "Du wirst in deinen Bewegungen *eingeschränkt*" - ], - "category-entities": [ - "§bEntities", - "Entities werden *verändert*" - ], - "category-extra_world": [ - "§aExtra Welt", - "Challenges, die in einer", - "*anderen Welt* spielen" - ], - "category-misc_goal": [ - "§9Miscellaneous", - "Ziele, die *keiner Kategorie*", - "zugeordnet werden können" - ], - "category-kill_entity": [ - "§cEntity töten", - "Töte *bestimmte Entities*,", - "um zu gewinnen" - ], - "category-score_points": [ - "§eMeiste Punkte", - "Erziele die *meisten Punkte* in", - "einem *bestimmten Bereich*." - ], - "category-fastest_time": [ - "§6Schnellste Zeit", - "Sei der *schnellste Spieler*, der", - "das Ziel erfüllt" - ], - "category-force_battle": [ - "§bForce Battles", - "Erfülle die *vorgegebenen Zwischenziele*,", - "um Punkte zu erhalten.", - " ", - "Der Spieler mit den *meisten Punkten* gewinnt." - ], - "item-time-seconds-description": "§8» §7Zeit: §e{0} §7Sekunden", - "item-time-seconds-range-description": "§8» §7Zeit: §e{0}-{1} §7Sekunden", - "item-time-minutes-description": "§8» §7Zeit: §e{0} §7Minuten", - "item-heart-damage-description": "§8» §7Schaden: §e{0} §c❤", - "item-heart-start-description": "§8» §7Start: §e{0} §c❤", - "item-max-health-description": "§8» §7Maximale Leben: §e{0} §c❤", - "item-chance-description": "§8» §7Chance: §e{0}%", - "item-launcher-description": "§8» §7Stärke: §e{0}", - "item-permanent-effect-target-player-description": "§8» §7Nur der aktive Spieler erhält den Effekt", - "item-permanent-effect-target-everyone-description": "§8» §7Alle erhalten den Effekt", - "item-blocks-description": "§8» §7Blöcke zu laufen: §e{0}", - "item-range-blocks-description": "§8» §7Reichweite: §e{0} §7Blöcke", - "item-force-battle-goal-jokers": [ - "§6Anzahl der Joker", - "Die *Anzahl* der *Joker*,", - "die jeder Spieler hat" - ], - "item-force-battle-show-scoreboard": [ - "§bScoreboard anzeigen" - ], - "item-force-battle-duped-targets": [ - "§cDoppelte Ziele", - "Ziele können *mehrfach* vorkommen" - ], - "item-force-position-battle-radius": [ - "§bRadius", - "Der *maximale Radius*, in dem sich die", - "Positionen befinden können" - ], - "item-language-setting": [ - "§bSprache", - "Setze die *Sprache*" - ], - "item-language-setting-german": "§fDeutsch", - "item-language-setting-english": "§fEnglish", - "item-difficulty-setting": [ - "§aSchwierigkeit", - "Stellt die *Schwierigkeitsstufe* ein" - ], - "item-one-life-setting": [ - "§cEin Teamleben", - "*Jeder* stirbt, wenn *einer stirbt*" - ], - "item-respawn-setting": [ - "§4Respawn", - "Wenn du *stirbst*, wirst du nicht zu einem *Zuschauer*" - ], - "item-death-message-setting": [ - "§6Todesnachrichten", - "Schaltet *Todesnachrichten* ein/aus" - ], - "item-death-message-setting-vanilla": "§6Vanilla", - "item-pvp-setting": [ - "§9PvP" - ], - "item-max-health-setting": [ - "§cMaximale Herzen", - "Stellt ein, wie viele", - "Herzen man hat" - ], - "item-soup-setting": [ - "§cSuppen Heilung", - "Wenn du eine *Pilzsuppe* benutzt,", - "wirst du um *4 Herzen* geheilt" - ], - "item-damage-setting": [ - "§cDamage Multiplier", - "Schaden, den du nimmst, wird *multipliziert*" - ], - "item-damage-display-setting": [ - "§eDamage Display", - "Es wird im Chat angezeigt,", - "wenn jemand *Schaden* bekommt" - ], - "item-health-display-setting": [ - "§cHealth Display", - "Die *Herzen* aller Spieler", - "werden in der *Tablist* angezeigt" - ], - "item-position-setting": [ - "§9Positions", - "Erlaubt es dir *Positionen*", - "mit */pos* zu *markieren*" - ], - "item-backpack-setting": [ - "§6Backpack", - "Erlaubt es dir, *deinen Backpack* oder den", - "*Team Backpack* mit */backpack* zu öffnen" - ], - "item-backpack-setting-team": "§5Team", - "item-backpack-setting-player": "§6Player", - "item-cut-clean-setting": [ - "§9CutClean", - "Verschiedene *Einstellungen*, die", - "das *Farmen* von Items *einfacher* machen" - ], - "menu-cut-clean-setting-settings": "CutClean", - "item-cut-clean-gold-setting": [ - "§6Gold", - "*Golderz* wird direkt zu *Goldbarren*" - ], - "item-cut-clean-iron-setting": [ - "§7Iron", - "*Eisenerz* wird direkt zu *Eisenbarren*" - ], - "item-cut-clean-coal-setting": [ - "§eCoal", - "*Kohleerz* wird direkt zu *Fackeln*" - ], - "item-cut-clean-flint-setting": [ - "§eFlint", - "*Gravel* droppt immer *Flint*" - ], - "item-cut-clean-vein-setting": [ - "§eOre Veins", - "*Erz Venen* werden direkt abgebaut" - ], - "item-cut-clean-inventory-setting": [ - "§6Direkt ins Inventar", - "*Items* werden, *anstatt gedroppt* zu werden,", - "*direkt* ins *Inventar* hinzugefügt" - ], - "item-cut-clean-food-setting": [ - "§cGebratenes Essen", - "*Rohes Fleisch* wird direkt zu *gebratenem Fleisch*" - ], - "item-glow-setting": [ - "§fPlayerglow", - "*Spieler* sind durch die *Wand* sichtbar" - ], - "no-hunger-setting": [ - "§cKein Hunger", - "Du bekommst keinen *Hunger*" - ], - "pregame-movement-setting": [ - "§6Pregame Movement", - "Du kannst dich *bewegen*, bevor", - "das Spiel *gestartet* hat" - ], - "item-no-hit-delay-setting": [ - "§fNoHitDelay", - "Nachdem du *Schaden* genommen hast,", - "kannst du *sofort* wieder Schaden *bekommen*" - ], - "item-timber-setting": [ - "§bTimber", - "Du kannst einen *Baum* zerstören,", - "indem du *einen Block* des Baumes abbaust" - ], - "item-timber-setting-logs": "§6Baumstämme", - "item-timber-setting-logs-and-leaves": "§6Baumstämme §7und §2Blätter", - "item-keep-inventory-setting": [ - "§5Keep Inventory", - "Du verlierst keine *Items*,", - "wenn du *stirbst*" - ], - "item-mob-griefing-setting": [ - "§5Mob Griefing", - "Monster können *nichts zerstören*" - ], - "item-no-item-damage-setting": [ - "§5Kein Itemschaden", - "*Items* sind *unzerstörbar*" - ], - "top-command-setting": [ - "§dTop Command", - "Mit */top* kannst du dich", - "zur *Oberfläche* oder in", - "die *Overworld* teleportieren" - ], - "item-fortress-spawn-setting": [ - "§cFestungs Spawn", - "Wenn du in den *Nether* gehst,", - "spawnst du immer in einer *Festung*" - ], - "item-bastion-spawn-setting": [ - "§cBastions Spawn", - "Wenn du in den *Nether* gehst,", - "spawnst du immer in einer *Bastion*" - ], - "item-no-offhand-setting": [ - "§6Keine Offhand", - "Die *zweite Hand* wird geblockt" - ], - "item-regeneration-setting": [ - "§cRegeneration", - "Stellt ein, *ob* und", - "*wie* man *regeneriert*" - ], - "item-regeneration-setting-not_natural": "§6Nicht natürlich", - "item-immediate-respawn-setting": [ - "§6Direkter Respawn", - "Wenn du stirbst, *respawnst* du *automatisch,*", - "ohne den *Death Screen* zu sehen" - ], - "item-slot-limit-setting": [ - "§4Inventar Slots", - "Stellt ein, wie viele *Inventar*", - "*Slots* nutzbar sind" - ], - "item-death-position-setting": [ - "§cDeath Position", - "Wenn du stirbst, wird mit */pos* ", - "eine *Position an deinem Todespunkt* erstellt" - ], - "item-enderchest-command-setting": [ - "§5Enderchest Command", - "Wenn du */ec* ausführst, öffnet", - "sich deine *Enderchest*" - ], - "item-split-health-setting": [ - "§cGeteilte Herzen", - "Stellt ein, ob sich *alle*", - "*Spieler* eine *Gesundheit teilen*" - ], - "item-old-pvp-setting": [ - "§b1.8 PvP", - "Das *alte 1.8 PvP System* wird genutzt", - "Es gibt keinen *Attack Cooldown*" - ], - "item-totem-save-setting": [ - "§6Challenge Tod Rettung", - "Wenn du durch eine Challenge *instant*", - "*stirbst*, können *Totems* dich retten" - ], - "item-traffic-light-challenge": [ - "§cAmpelchallenge", - "Die *Ampel* schaltet alle paar Minuten um", - "Wenn du bei *rot* gehst, stirbst du" - ], - "item-block-randomizer-challenge": [ - "§6Block Randomizer", - "Jeder *Block* droppt ein *zufälliges Item*" - ], - "item-crafting-randomizer-challenge": [ - "§6Crafting Randomizer", - "Wenn du *etwas craftest*, bekommst du ein *zufälliges Item*" - ], - "item-mob-randomizer-challenge": [ - "§6Mob Randomizer", - "Wenn ein *Entity* spawnt, spawnt ein *anderes*" - ], - "item-hotbar-randomizer-challenge": [ - "§6HotBar Randomizer", - "Alle *paar Minuten* erhält jeder Spieler *zufällige Items*" - ], - "item-damage-block-challenge": [ - "§4Schaden pro Block", - "Du bekommst *Schaden* durch", - "jeden *Block*, den du gehst" - ], - "item-hunger-block-challenge": [ - "§6Hunger pro Block", - "Du bekommst *Hunger* durch", - "jeden *Block*, den du gehst" - ], - "item-stone-sight-challenge": [ - "§fStein Blick", - "*Mobs*, denen du in die *Augen*", - "*schaust*, werden zu *Stein*" - ], - "item-no-mob-sight-challenge": [ - "§cMob Blick Schaden", - "Wenn du einen *Mob* in die *Augen*", - "*schaust*, erleidest du *Schaden*" - ], - "item-bedrock-path-challenge": [ - "§7Bedrock Path", - "*Unter dir* entsteht die", - "ganze Zeit *Bedrock*" - ], - "item-bedrock-walls-challenge": [ - "§7Bedrock Walls", - "Hinter dir *spawnen* riesige", - "*Wände* aus *Bedrock*" - ], - "item-surface-hole-challenge": [ - "§cSurface Hole", - "§7Hinter dir *verschwindet* der", - "*Boden* bis ins *Void*" - ], - "item-damage-inv-clear-challenge": [ - "§cDamage Inventory Clear", - "Die *Inventare* aller Spieler werden *geleert*,", - "wenn ein *Spieler* Schaden erleidet" - ], - "item-no-trading-challenge": [ - "§2Kein Handeln", - "Du kannst *nicht* mit", - "Villager *handeln*" - ], - "item-block-break-damage-challenge": [ - "§6Block Break Damage", - "Wenn du einen *Block abbaust*,", - "*erleidest* du die gesetze Anzahl *schaden*" - ], - "item-block-place-damage-challenge": [ - "§6Block Place Damage", - "Wenn du einen *Block plazierst*,", - "*erleidest* du die gesetze Anzahl *schaden*" - ], - "item-no-exp-challenge": [ - "§aKeine XP", - "Wenn du *XP* aufsammelst, stirbst du" - ], - "item-invert-health-challenge": [ - "§cInvert Health", - "Alle paar Minuten werden deine *Herzen invertiert*.", - "Wenn du *8 Herzen* hast,", - "hast du danach *2 Herzen* und umgekehrt." - ], - "item-jump-and-run-challenge": [ - "§6Jump and Run", - "Alle *paar Minuten* musst du ein random *Jump and Run* machen,", - "welches jedes Mal *schwieriger* wird" - ], - "item-randomized-hp-challenge": [ - "§4Randomized HP", - "Die *Leben* aller *Mobs*", - "sind *random*" - ], - "item-snake-challenge": [ - "§9Snake", - "*Jeder Spieler* zieht eine", - "tödliche Linie hinter sich her" - ], - "item-reversed-damage-challenge": [ - "§cReversed Damage", - "Wenn du Entities *schlägst* oder *abschießt*,", - "bekommst du den *gleichen Schaden*" - ], - "item-duped-spawning-challenge": [ - "§cDoppeltes Spawning", - "Wenn ein Monster *spawnt*,", - "spawnt es *zweimal*" - ], - "item-hydra-challenge": [ - "§5Hydra", - "Wenn du einen *Mob* tötest,", - "spawnen *zwei* neue" - ], - "item-hydra-plus-challenge": [ - "§cHydra Plus", - "Wenn du einen *Mob* tötest,", - "spawnen *doppelt* so viele", - "wie beim *vorherigen* mal", - " ", - "Maximum beträgt *512* Mobs gleichzeitig" - ], - "item-floor-lava-challenge": [ - "§6Der Boden ist Lava", - "Alle *Blöcke* unter dir verwandeln sich", - "erst zu *Magma* und dann zu *Lava*" - ], - "item-only-dirt-challenge": [ - "§cOnly Dirt", - "Wenn du nicht auf *Erde*", - "stehst, *stirbst* du" - ], - "item-food-once-challenge": [ - "§cFood Once", - "Du kannst jedes *Essen*", - "nur einmal *essen*" - ], - "item-food-once-challenge-player": "§6Spieler", - "item-food-once-challenge-everyone": "§5Jeder", - "item-chunk-deconstruction-challenge": [ - "§bChunk Deconstruction", - "*Chunks*, in denen sich Spieler befinden,", - "*bauen* sich von *oben* aus ab" - ], - "item-one-durability-challenge": [ - "§4Eine Haltbarkeit", - "*Items* gehen nach *einer* Benutzung *kaputt*" - ], - "item-low-drop-rate-challenge": [ - "§6Low Drop Chance", - "Die *Dropchance* jedes *Blockes* wird auf die", - "angegebene *Prozentzahl* gesetzt" - ], - "item-invisible-mobs-challenge": [ - "§fUnsichtbare Mobs", - "Alle *Mobs* haben einen", - "*Unsichtbarkeits* Effekt" - ], - "item-mob-transformation-challenge": [ - "§cMob Verwandlung", - "Wenn du einen Mob schlägst, *verwandelt* sich", - "dieser in den *letzen Mob*, den du *geschlagen* hast" - ], - "item-jump-entity-challenge": [ - "§2Jump Entity", - "Wenn du *springst*, *spawnt* ein", - "zufälliges *Entity*" - ], - "item-no-mouse-move-challenge": [ - "§cMausbewegung Schaden", - "Wenn du deinen *Blick bewegst*,", - "erleidest du den *gesetzen Schaden*" - ], - "item-no-duped-items-challenge": [ - "§6Keine Doppelten Items", - "Wenn *2 Spieler* das gleiche *Item* im", - "Inventar haben, *sterben* beide" - ], - "item-infection-challenge": [ - "§aInfection Challenge", - "Du musst *2 Blöcke* Abstand von allen ", - "*Mobs* halten oder du wirst *krank*" - ], - "item-only-down-challenge": [ - "§cNur nach unten", - "Wenn du *einen Block* nach", - "*oben* gehst, *stirbst* du" - ], - "item-advancement-damage-challenge": [ - "§cAdvancement Schaden", - "Du bekommst für jedes neue *Advancement*", - "die gesetze Anzahl *Schaden*" - ], - "item-all-blocks-disappear-challenge": [ - "§cAlle Blöcke verschwinden", - "Bei verschiedenen *Interaktionen*", - "verschwinden alle *Blöcke* im *Chunk*", - "eines *bestimmten Types*" - ], - "menu-all-blocks-disappear-challenge-settings": "Alle Blöcke verschwinden", - "item-all-blocks-disappear-break-challenge": [ - "§bBeim Abbauen", - "Wenn du einen Block *abbaust*, werden", - "*alle Blöcke* des *selben Types zerstört*" - ], - "item-all-blocks-disappear-place-challenge": [ - "§bBeim Platzieren", - "Wenn du einen Block *platzierst*, werden", - "*alle Blöcke* des *selben Types zerstört*" - ], - "item-water-allergy-challenge": [ - "§9Wasserallergie", - "Wenn du in *Wasser* bist,", - "*erleidest* du den gesetzen Schaden" - ], - "item-max-biome-time-challenge": [ - "§2Maximale Biom Zeit", - "Die *Zeit*, die du in jedem *Biom*", - "sein darfst, ist *begrenzt*" - ], - "item-max-height-time-challenge": [ - "§9Maximale Höhen Zeit", - "Die *Zeit*, die du auf jeder *Höhe*", - "sein darfst, ist *begrenzt*" - ], - "item-permanent-item-challenge": [ - "§cPermanente Items", - "*Items* können nicht gedroppt", - "oder *weggelegt* werden" - ], - "item-sneak-damage-challenge": [ - "§6Schaden pro Schleichen", - "Du *erleidest* den gesetzten", - "*Schaden*, wenn du *schleichst*" - ], - "item-jump-damage-challenge": [ - "§6Schaden pro Sprung", - "Du *erleidest* den gesetzen", - "*Schaden*, wenn du *springst*" - ], - "item-random-dropping-challenge": [ - "§cZufälliges Item Droppen", - "Alle paar Sekunden wird ein *zufälliges*", - "*Item* aus deinem Inventar *gedroppt*" - ], - "item-random-swapping-challenge": [ - "§cZufälliges Item Mischen", - "Alle paar Sekunden wird ein", - "*zufälliges Item* aus deinem Inventar", - "mit einem anderem *getauscht*" - ], - "item-random-removing-challenge": [ - "§cZufälliges Item Löschen", - "Alle paar Sekunden wird ein *zufälliges*", - "*Item* aus deinem Inventar *gelöscht*" - ], - "item-death-on-fall-challenge": [ - "§fTod bei Fallschaden", - "Wenn du *Fallschaden* erleidest,", - "*stirbst* du sofort" - ], - "item-zero-hearts-challenge": [ - "§6Null Herzen", - "Nach einer *Schutzzeit* musst du", - "dauerhaft Absorption bekommen" - ], - "item-random-effect-challenge": [ - "§6Random Effekte", - "Du bekommst in einem gesetzen *Intervall*", - "einen *zufälligen Trank Effekt*" - ], - "menu-random-effect-challenge-settings": "Random Effekte", - "item-random-effect-time-challenge": [ - "§6Intervall", - "Das *Intervall*, in dem man", - "einen *Effekt* erhält" - ], - "item-random-effect-length-challenge": [ - "§6Länge", - "Die *Länge*, die der", - "*Effekt* anhält" - ], - "item-random-effect-amplifier-challenge": [ - "§6Stärke", - "Die *Stärke*, die der", - "*Effekt* hat" - ], - "item-permanent-effect-on-damage-challenge": [ - "§6Permanente Effekte", - "Du bekommst immer, wenn du *Schaden*", - "erleidest, einen *zufälligen Effekt*" - ], - "item-random-challenge-challenge": [ - "§cRandom Challenge", - "In einem *gesetzten Intervall*", - "wird eine *Random Challenge* aktiviert" - ], - "item-anvil-rain-challenge": [ - "§cAmboss Regen", - "Vom *Himmel* fallen *Ambosse*" - ], - "menu-anvil-rain-challenge-settings": "Amboss Regen", - "item-anvil-rain-time-challenge": [ - "§6Intervall", - "Das *Intervall*, in", - "dem *Ambosse* spawnen" - ], - "item-anvil-rain-range-challenge": [ - "§6Range", - "Die *Reichweite*, in", - "der *Ambosse* spawnen" - ], - "item-anvil-rain-count-challenge": [ - "§6Anzahl", - "Die *Anzahl*, an *Ambossen*,", - "die in einem *Chunk* spawnen" - ], - "item-anvil-rain-damage-challenge": [ - "§6Schaden", - "Der *Schaden*, die", - "die *Ambosse* machen" - ], - "item-water-mlg-challenge": [ - "§bWater MLG", - "Du musst *immer wieder*", - "einen *Water MLG* absolvieren" - ], - "item-ender-games-challenge": [ - "§5Ender Games", - "Alle *paar Minuten* wirst du", - "mit einem *zufälligem Entity* aus", - "einem *200 Block* Radius *getauscht*" - ], - "item-random-event-challenge": [ - "§6Random Events", - "Alle *paar Minuten* wird eines von", - "*{0} random Events* aktiviert" - ], - "item-block-chunk-item-remove-challenge": [ - "§6Movement Item Remove", - "Es wird für jeden *Block* / *Chunk*,", - "den du dich *fortbewegst*, ein Item", - "aus deinem Inventar *gelöscht*" - ], - "item-block-chunk-item-remove-challenge-block": "§6Block", - "item-block-chunk-item-remove-challenge-chunk": "§6Chunk", - "item-higher-jumps-challenge": [ - "§aHigher Jumps", - "*Umso öfter* du springst,", - "*desto höher* springst du" - ], - "item-force-height-challenge": [ - "§eForce Height", - "Alle *paar Minuten* musst du auf", - "eine *bestimmte Höhe* oder du stirbst" - ], - "item-force-block-challenge": [ - "§6Force Block", - "Alle *paar Minuten* musst du auf", - "einen *bestimmten Block* oder du stirbst" - ], - "item-force-biome-challenge": [ - "§aForce Biome", - "Alle *paar Minuten* musst du in", - "ein *bestimmtes Biom* oder du stirbst", - "Je *seltener* das Biom ist, desto *mehr Zeit* hast du" - ], - "item-force-mob-challenge": [ - "§bForce Mob", - "Alle *paar Minuten* musst du", - "ein *bestimmtes Entity* killen oder du stirbst" - ], - "item-force-item-challenge": [ - "§6Force Item", - "Alle *paar Minuten* musst du", - "ein *bestimmtes Item* finden oder du stirbst" - ], - "item-random-item-challenge": [ - "§bRandom Items", - "Ein *zufälliger Spieler* erhält alle paar", - "*Sekunden* ein *zufälliges Item*" - ], - "item-always-running-challenge": [ - "§cAlways Running", - "Du kannst *nicht aufhören*, vorwärts zu laufen" - ], - "item-pickup-launch-challenge": [ - "§cPickup Boost", - "Wenn du ein *Item aufhebst*,", - "wirst du *in die Luft* geschleudert" - ], - "item-tsunami-challenge": [ - "§9Tsunami", - "In einem *gesetztem Intervall*", - "*steigt* das *Wasser* in der *Overworld*", - "und die *Lava* in im *Nether*", - " ", - "Sollte mit wenigen Personen gespielt werden!" - ], - "item-all-mobs-to-death-position-challenge": [ - "§cAlle Monster zum Todespunkt", - "Wenn ein *Mob* von einem Spieler", - "*getötet* wird, werden *alle* anderen", - "Monster vom *selben Typen* zum", - "*Todespunkt* teleportiert" - ], - "item-ice-floor-challenge": [ - "§bEisboden", - "Unter dir wird *Luft* zu einem", - "*3x3* Boden aus *Eis*" - ], - "item-blocks-disappear-time-challenge": [ - "§fBlöcke verschwinden nach Zeit", - "Blöcke, die du *platzierst*, *verschwinden*", - "nach ein *paar Sekunden* wieder" - ], - "item-missing-items-challenge": [ - "§9Items Fehlen", - "Alle paar Minuten *verschwindet* ein *Item* aus", - "deinem *Inventar* und du musst *erraten*, welches" - ], - "item-damage-item-challenge": [ - "§cSchaden pro Item", - "Wenn du ein *Item aufhebst* oder es", - "in deinem Inventar *anklickst* erleidest", - "du *0,5 ❤* multipliziert mit der Anzahl der Items" - ], - "item-damage-teleport-challenge": [ - "§cSchaden Random Teleport", - "Du wirst *zufällig teleportiert*,", - "wenn du *Schaden* erleidest" - ], - "item-loop-challenge": [ - "§6Wiederholungs Challenge", - "Verschiedene Aktionen *wiederholen* sich", - "unendlich oft, bis ein Spieler *schleicht*" - ], - "item-uncraft-challenge": [ - "§6Items craften sich zurück", - "Alle *Items* in deinem Inventar *craften*", - "sich alle paar Sekunden *zurück*" - ], - "item-freeze-challenge": [ - "§bFreeze Challenge", - "Für *jedes Herz*, das du *Schaden* erleidest, kannst", - "du dich für eine bestimmte Zeit *nicht bewegen*" - ], - "item-dont-stop-running-challenge": [ - "§9Nicht stehen bleiben", - "Du darfst nur eine bestimmte Zeit", - "*stehen bleiben* bevor du *stirbst*" - ], - "item-consume-launch-challenge": [ - "§cEssens Boost", - "Wenn du ein *Item isst*,", - "wirst du *in die Luft* geschleudert" - ], - "item-five-hundred-blocks-challenges": [ - "§5500 Blöcke", - "*Alle* 500 Blöcke, die du *läufst*,", - "bekommst du *64* eines *zufälliges Items*.", - "Es droppen *keine Items* von", - "*Blöcken* und *Entities* mehr." - ], - "item-level-border-challenges": [ - "§eLevel = Border", - "Die *Border-Größe* passt sich dem *Spieler*", - "mit den *meisten Leveln* an." - ], - "item-chunk-effect-challenge": [ - "§3Zufällige Chunk Effekte", - "In *jedem Chunk* bekommst du", - "einen *zufälligen Effekt*" - ], - "item-repeat-chunk-challenge": [ - "§2Wiederholende Chunks", - "Blöcke die *platziert oder zerstört* werden,", - "werden in *jedem Chunk* platziert / zerstört" - ], - "item-blocks-fly-challenge": [ - "§fBlöcke fliegen in die Luft", - "*Blöcke*, auf denen du *gelaufen* bist,", - "fliegen nach *einer Sekunde* in die *Luft*" - ], - "item-respawn-end-challenge": [ - "§5Mobs respawnen im End", - "Mobs, die *getötet werden*,", - "respawnen im *End*" - ], - "item-block-effect-challenge": [ - "§3Zufällige Block Effekte", - "Auf *jedem Block* bekommst du", - "einen *zufälligen Effekt*" - ], - "item-entity-effect-challenge": [ - "§5Mobs Haben Random Effekte", - "*Jedes Mob* hat einen zufälligen", - "Effekt auf *höchster Stufe*" - ], - "item-mob-damage-teleport-challenge": [ - "§5Mob Tausch Beim Schlagen", - "Jedes mal, wenn du einen *Mob schlägst*,", - "tauschst du mit einem *zufälligem Mob* die Position" - ], - "item-block-mob-challenge": [ - "§cMob Blöcke", - "Aus jedem abgebautem Block, *spawnt ein Mob*,", - "dass *getötet* werden muss, um den Block *zu erhalten*" - ], - "item-entity-loot-randomizer-challenge": [ - "§6Entity Loot Randomizer", - "Alle Mob Drops sind *zufällig vertauscht*." - ], - "item-no-shared-advancements-challenge": [ - "§2Keine Gleichen Advancements", - "Spieler dürfen *nicht* die *gleichen Advancements*", - "abschließen, sonst *stirbt* der *Spieler*" - ], - "item-chunk-deletion-challenge": [ - "§6Chunk Löschung", - "*Chunks*, in denen sich *Spieler* befinden,", - "werden nach gegebener *Zeit* komplett *gelöscht*" - ], - "item-delay-damage-description": [ - "§4Verzögerter Schaden", - "Der *schaden* von allen *Spielern* ist", - "zusammenaddiert und wird nach einer bestimmten *Zeit* hinzugefügt." - ], - "item-dragon-goal": [ - "§5Enderdrache", - "Töte den *Enderdrachen* um zu gewinnen" - ], - "item-wither-goal": [ - "§dWither", - "Töte einen *Wither* um zu gewinnen" - ], - "item-elder-guardian-goal": [ - "§bElder Guardian", - "Töte einen *Elder Guardian* um zu gewinnen" - ], - "item-warden-goal": [ - "§5Warden", - "Töte einen *Warden* um zu gewinnen" - ], - "item-iron-golem-goal": [ - "§bEisengolem", - "Töte einen *Eisengolem* um zu gewinnen" - ], - "item-snow-golem-goal": [ - "§bSchneemann", - "Töte einen *Schneemann* um zu gewinnen" - ], - "item-most-deaths-goal": [ - "§6Meiste Tode", - "Wer die meisten *verschiedenen Tode*", - "sammelt, *gewinnt*" - ], - "item-most-items-goal": [ - "§cMeisten Items", - "Wer die meisten *verschiedenen Items*", - "findet, *gewinnt*" - ], - "item-last-man-standing-goal": [ - "§cLast Man Standing", - "Wer *am Ende* noch *lebt*, gewinnt" - ], - "item-mine-most-blocks-goal": [ - "§eMeisten Blöcke", - "Wer die *meisten Blöcke* abbaut, gewinnt" - ], - "item-most-xp-goal": [ - "§aMeiste XP", - "Wer die meiste *XP sammelt*, gewinnt" - ], - "item-first-one-to-die-goal": [ - "§cErster Tod", - "Wer als *erstes stirbt*, gewinnt" - ], - "item-collect-wood-goal": [ - "§6Holzarten Sammeln", - "Wer als *erstes* alle *Holzarten*, die", - "*eingestellt* sind, gesammelt hat, gewinnt" - ], - "item-collect-wood-goal-overworld": "§aOverworld", - "item-collect-wood-goal-nether": "§cNether", - "item-collect-wood-goal-both": "§9Beide", - "item-all-bosses-goal": [ - "§bAlle Bosse", - "Es müssen *alle Bosse* einmal", - "*getötet* werden, um zu *gewinnen*" - ], - "item-all-bosses-new-goal": [ - "§5Alle Bosse (+ Warden)", - "Es müssen *alle Bosse* einmal", - "*getötet* werden, um zu *gewinnen*" - ], - "item-all-mobs-goal": [ - "§bAlle Mobs", - "Es müssen *alle Mobs* einmal", - "*getötet* werden, um zu *gewinnen*" - ], - "item-all-monster-goal": [ - "§bAlle Monster", - "Es müssen *alle Monster* einmal", - "*getötet* werden, um zu *gewinnen*" - ], - "item-all-items-goal": [ - "§2Alle Items", - "Finde *alle Items*, die es *in Minecraft gibt*" - ], - "item-finish-raid-goal": [ - "§6Raid Gewinnen", - "Der erste Spieler, der einen *Raid*", - "*abschließt*, gewinnt" - ], - "item-most-emeralds-goal": [ - "§2Meisten Emeralds", - "Der Spieler mit den *meisten*", - "*Emeralds* gewinnt" - ], - "item-all-advancements-goal": [ - "§6Alle Advancements", - "Der Spieler, der als erstes *alle*", - "Errungenschaften *erhalten hat*, gewinnt" - ], - "item-max-height-goal": [ - "§fMaximale Höhe", - "Der Spieler, der als *erstes* die", - "Höhe *{0}* erreicht hat, gewinnt" - ], - "item-min-height-goal": [ - "§fMinimale Höhe", - "Der Spieler, der als *erstes* die", - "Höhe *{0}* erreicht hat, gewinnt" - ], - "item-race-goal": [ - "§5Wettrennen", - "Der Spieler, der als *erstes* an", - "einer *zufälligen* Position ist, gewinnt" - ], - "item-most-ores-goal": [ - "§9Meiste Erze", - "Der Spieler, der am *meisten Erze*", - "*abgebaut* hat, gewinnt" - ], - "item-find-elytra-goal": [ - "§fElytra Finden", - "Der Spieler, der als *erstes*", - "eine *Elytra findet*, gewinnt" - ], - "item-eat-cake-goal": [ - "§fKuchen Essen", - "Der Spieler, der als *erstes*", - "einen *Kuchen isst*, gewinnt" - ], - "item-collect-horse-armor-goal": [ - "§bSammle Pferderüstungen", - "Der Spieler, der als *erstes*", - "*alle Pferderüstungen* hat, gewinnt" - ], - "item-collect-ice-goal": [ - "§bSammle Eisblöcke", - "Der Spieler, der als *erstes*", - "*alle Eisblöcke* und Schnee hat, gewinnt" - ], - "item-collect-swords-goal": [ - "§9Sammle Schwerter", - "Der Spieler, der als *erstes*", - "*alle Schwerter* hat, gewinnt" - ], - "item-collect-workstations-item": [ - "§6Sammle Arbeitsblöcke", - "Der Spieler, der als *erstes*", - "*alle Villager Arbeitsblöcke* hat, gewinnt" - ], - "item-eat-most-goal": [ - "§6Am Meisten Essen", - "Der Spieler, der am *meisten isst*, gewinnt" - ], - "item-force-item-battle-goal": [ - "§5Force Item Battle", - "Jeder Spieler bekommt ein *zufälliges Item*,", - "das er finden muss.", - "Wer am Ende die *meisten Items* hat, gewinnt" - ], - "menu-force-item-battle-goal-settings": "Force Item Battle", - "item-force-item-battle-goal-give-item": [ - "§bItem bei Skippen geben", - "Wenn ein Spieler ein Item *skippt*,", - "wird dieses in sein *Inventar hinzugefügt*" - ], - "item-force-mob-battle-goal": [ - "§bForce Mob Battle", - "Jeder Spieler bekommt ein *zufälliges Mob*,", - "das er töten muss." - ], - "menu-force-mob-battle-goal-settings": "Force Mob Battle", - "item-force-advancement-battle-goal": [ - "§6Force Advancement Battle", - "Jeder Spieler bekommt ein *zufälliges*", - "*Advancement*, welches er erreichen muss." - ], - "menu-force-advancement-battle-goal-settings": "Force Advancement Battle", - "item-force-block-battle-goal": [ - "§aForce Block Battle", - "Jeder Spieler bekommt einen *zufälligen*", - "*Block*, auf welchem er stehen muss" - ], - "menu-force-block-battle-goal-settings": "Force Block Battle", - "item-force-block-battle-goal-give-block": [ - "§bBlock bei Skippen geben", - "Wenn ein Spieler einen Block *skippt*,", - "wird dieser in sein *Inventar hinzugefügt*" - ], - "item-force-biome-battle-goal": [ - "§2Force Biome Battle", - "Jeder Spieler bekommt ein *zufälliges Biom*,", - "das er betreten muss" - ], - "menu-force-biome-battle-goal-settings": "Force Biome Battle", - "item-force-damage-battle-goal": [ - "§3Force Damage Battle", - "Jeder Spieler bekommt eine *zufällige Anzahl Schaden*,", - "die er *erhalten* muss" - ], - "menu-force-damage-battle-goal-settings": "Force Damage Battle", - "item-force-height-battle-goal": [ - "§6Force Height Battle", - "Jeder Spieler bekommt eine *zufällige Höhe*,", - "auf der er sich befinden muss." - ], - "menu-force-height-battle-goal-settings": "Force Height Battle", - "item-force-position-battle-goal": [ - "§aForce Position Battle", - "Jeder Spieler bekommt eine *zufällige Position*,", - "die er erreichen muss." - ], - "menu-force-position-battle-goal-settings": "Force Position Battle", - "item-extreme-force-battle-goal": [ - "§cExtreme Force Battle", - "Jeder Spieler bekommt ein *zufälliges Ziel*,", - "welches er erreichen muss" - ], - "menu-extreme-force-battle-goal-settings": "Extreme Force Battle", - "item-get-full-health-goal": [ - "§aRegeneriere Volle Leben", - "The first player to gain full health wins." - ], - "item-damage-rule-none": [ - "§6Genereller Schaden", - "Stellt ein, ob du Schaden bekommen kannst" - ], - "item-damage-rule-fire": [ - "§6Feuer Schaden", - "Stellt ein, ob du Schaden durch", - "*Lava* und *Feuer* bekommen kannst" - ], - "item-damage-rule-attack": [ - "§3Angriff Schaden", - "Stellt ein, ob du Schaden durch", - "*Nahkampfangriffe von Entities* bekommen kannst" - ], - "item-damage-rule-projectile": [ - "§6Projektil Schaden", - "Stellt ein, ob du Schaden durch", - "*Projektile* bekommen kannst" - ], - "item-damage-rule-fall": [ - "§fFallschaden", - "Stellt ein, ob du *Fallschaden* bekommen kannst" - ], - "item-damage-rule-explosion": [ - "§cExplosions Schaden", - "Stellt ein, ob du *Explosions Schaden* bekommen kannst" - ], - "item-damage-rule-drowning": [ - "§9Ertrink Schaden", - "Stellt ein, ob du Schaden durch", - "*Ertrinken* bekommen kannst" - ], - "item-damage-rule-block": [ - "§eBlock Schaden", - "Stellt ein, ob du Schaden durch", - "*Fallende Blöcke* bekommen kannst" - ], - "item-damage-rule-magic": [ - "§5Magie Schaden", - "Stellt ein, ob du Schaden durch", - "*Gift*, *Wither* und andere *Tränke* bekommen kannst" - ], - "item-damage-rule-freeze": [ - "§fFrost Schaden", - "Stellt ein, ob du Schaden durch", - "*Frost* bekommen kannst" - ], - "item-block-material": [ - "{0}", - "Stellt ein, ob *{1}*", - "genutzt werden *kann*" - ], - "custom-limit": "Du hast das Limit von §e{0} Challenges §7erreicht", - "custom-not-deleted": "Diese Challenge existiert noch nicht!", - "custom-saved": "§7Challenge wurde lokal §agespeichert", - "custom-saved-db": [ - "Um in §eDatenbank §7zu Speichern benutze §e/db save customs", - "§cAchtung: §7Alte Einstellungen werden dabei überschrieben!" - ], - "custom-no-changes": "Du hast an der Challenge §ckeine §7Änderungen gemacht", - "custom-name-info": "Schreibe den Namen der Challenge in den Chat", - "custom-command-info": [ - "Schreibe den Command den der Spieler ausführen soll §eohne / §7in den Chat", - "Erlaubte Commands: §e{0}", - "§cWeitere Commands können in der Config erlaubt werden" - ], - "custom-command-not-allowed": "Der Command §e{0} §7ist in der Config nicht als erlaubter Command angegeben", - "custom-chars-max_length": "Du hast die Maximale Anzahl von §e{0} Zeichen §7überschritten", - "custom-not-loaded": [ - " ", - "Es sind derzeit keine Custom Challenges geladen.", - "Du vermisst deine Challenges? §e/db load customs", - "Du hast Probleme beim Speichern?", - "Speichere vorm verlassen manuell §e/db save customs", - " " - ], - "custom-main-view-challenges": "§6Challenges Ansehen", - "custom-main-create-challenge": "§aChallenge Erstellen", - "custom-title-trigger": "Auslöser", - "custom-title-action": "Aktion", - "custom-title-view": "Gespeichert", - "custom-sub-finish": "§aFertig", - "item-custom-info-delete": [ - "§cLöschen", - "*Achtung* diese Aktion kann *nicht*", - "rückgängig gemacht werden" - ], - "item-custom-info-save": "§aSpeichern", - "item-custom-info-trigger": [ - "§cAuslöser", - "*Klicke* um einzustellen, was passieren", - "muss, damit die *Aktion* ausgeführt wird" - ], - "item-custom-info-action": [ - "§bAktion", - "*Klicke* um einzustellen, was passieren", - "soll, wenn der *Auslöser* erfüllt ist" - ], - "item-custom-info-material": [ - "§6Anzeige Item", - "*Klicke* um das Anzeigeitem zu ändern" - ], - "item-custom-info-name": [ - "§6Name", - "*Klicke* um den Namen über den Chat zu ändern", - "Maximale Zeichenanzahl: 50" - ], - "custom-info-currently": "§7Eingestellt §8» §e", - "custom-info-trigger": "§7Auslöser", - "custom-info-action": "§7Aktion", - "item-custom-trigger-jump": [ - "§aSpieler Springt" - ], - "item-custom-trigger-sneak": [ - "§aSpieler Schleicht" - ], - "item-custom-trigger-move_block": [ - "§6Spieler Läuft Einen Block" - ], - "item-custom-trigger-death": [ - "§cEntity Stirbt" - ], - "item-custom-trigger-damage": [ - "§cEntity Erleidet Schaden" - ], - "item-custom-trigger-damage-any": [ - "§aJeglicher Grund" - ], - "item-custom-trigger-damage_by_player": [ - "§cEntity Bekommt Schaden Von Spieler" - ], - "item-custom-trigger-intervall": [ - "§6Intervall" - ], - "item-custom-trigger-intervall-second": [ - "§6Jede Sekunde" - ], - "item-custom-trigger-intervall-seconds": [ - "§6Alle {0} Sekunden" - ], - "item-custom-trigger-intervall-minutes": [ - "§6Alle {0} Minuten" - ], - "item-custom-trigger-block_place": [ - "§aBlock Platziert" - ], - "item-custom-trigger-block_break": [ - "§cBlock Zerstört" - ], - "item-custom-trigger-consume_item": [ - "§2Item Konsumieren" - ], - "item-custom-trigger-pickup_item": [ - "§bItem Aufheben" - ], - "item-custom-trigger-drop_item": [ - "§9Spieler Droppt Item" - ], - "item-custom-trigger-advancement": [ - "§cSpieler Erhält Errungenschaft" - ], - "item-custom-trigger-hunger": [ - "§2Spieler Verliert Hunger" - ], - "item-custom-trigger-move_down": [ - "§6Block Nach Unten Bewegen" - ], - "item-custom-trigger-move_up": [ - "§6Block Nach Oben Bewegen" - ], - "item-custom-trigger-move_camera": [ - "§6Kamera Bewegen" - ], - "item-custom-trigger-stands_on_specific_block": [ - "§6Spieler Ist Auf Bestimmten Block" - ], - "item-custom-trigger-stands_not_on_specific_block": [ - "§6Spieler Ist Nicht Auf Bestimmten Block" - ], - "item-custom-trigger-gain_xp": [ - "§5Spieler Bekommt XP" - ], - "item-custom-trigger-level_up": [ - "§5Spieler Levelt Auf" - ], - "item-custom-trigger-item_craft": [ - "§6Spieler Craftet Item" - ], - "item-custom-trigger-in_liquid": [ - "§9Spieler In Flüssigkeit" - ], - "item-custom-trigger-get_item": [ - "§aItem bekommen", - "Aktion wird für *jedes* anklicken oder aufheben ausgeführt" - ], - "item-custom-action-cancel": [ - "§4Auslöser Abbrechen", - "Verhindert, dass der Auslöser ausgeführt wird.", - "Nicht abrechenbare Auslöser: *Springen*, *Sneaken*, *Töten*", - "*Advancement*, *Auf Leveln*, *In Flüssigkeit*" - ], - "item-custom-action-command": [ - "§4Command Ausführen", - "Lasse Spieler einen Command ausführen lassen", - "Die Commands werden für Spieler mit */execute as* von", - "der Konsole ausgeführt.", - "Erlaubte Commands werden in der Config eingestellt.", - "Der Spieler braucht *keine Rechte* auf den Command haben.", - "Spieler können *keine Plugin Commands* ausführen." - ], - "item-custom-action-kill": [ - "§4Töten", - "Töte Entities" - ], - "item-custom-action-damage": [ - "§cSchaden", - "Füge Entities Schaden zu" - ], - "item-custom-action-heal": [ - "§aHeilen", - "Heile Entities" - ], - "item-custom-action-hunger": [ - "§6Hunger", - "Füge Spielern Hunger hinzu" - ], - "item-custom-action-max_health": [ - "§cMaximale Leben Verändern", - "Verändere die Maximalen Leben von Spielern", - "Wird mit einem */gamestate reset* zurückgesetzt" - ], - "item-custom-action-max_health-offset": [ - "§cVeränderung", - "Wähle aus wie viele Leben verändert werden sollen" - ], - "item-custom-action-spawn_entity": [ - "§3Entity Spawnen", - "Spawne ein Entity bestimmten Types" - ], - "item-custom-action-random_mob": [ - "§6Zufälliges Entity", - "Spawne ein zufälliges Entity" - ], - "item-custom-action-random_item": [ - "§bZufälliges Item", - "Gebe Spielern zufällige Items" - ], - "item-custom-action-uncraft_inventory": [ - "§eInventar Zurück-Craften", - "Lasse das Inventar von Spielern Zurück-Craften" - ], - "item-custom-action-boost_in_air": [ - "§fIn Luft Schleudern", - "Schleudere Entities in die Luft" - ], - "item-custom-action-boost_in_air-strength": [ - "§fStärke" - ], - "item-custom-action-potion_effect": [ - "§dTrank Effekt", - "Gebe Entities einen bestimmten Trank Effekt" - ], - "item-custom-action-permanent_effect": [ - "§6Permanenten Trank Effekt", - "Füge Spieler einen Permanenten Effekt hinzu.", - "Die Aktion nutzt die Einstellungen", - "von der Permanenten Effekt Challenge." - ], - "item-custom-action-random_effect": [ - "§dZufälliger Trank Effekt", - "Gebe Entities einen zufälligen Trank Effekt" - ], - "item-custom-action-clear_inventory": [ - "§cInventar Leeren", - "Leere das Inventar von Spielern komplett" - ], - "item-custom-action-drop_random_item": [ - "§aItem Aus Inventar Droppen", - "Droppe ein Item aus dem Inventar auf den Boden" - ], - "item-custom-action-remove_random_item": [ - "§cItem Aus Inventar Entfernen", - "Entferne ein Item aus dem Inventar" - ], - "item-custom-action-swap_random_item": [ - "§6Items Im Inventar Tauschen", - "Tausche zwei Item im Inventar" - ], - "item-custom-action-freeze": [ - "§bFreeze", - "Friere Mobs Zeitweise ein.", - "Die Aktion nutzt die Einstellungen", - "von der Freeze On Damage Challenge." - ], - "item-custom-action-invert_health": [ - "§cInvert Health", - "Invertiere die Herzen eines Spielers.", - "Wenn du *8 Herzen* hast,", - "hast du danach *2 Herzen* und umgekehrt." - ], - "item-custom-action-water_mlg": [ - "§9Water MLG", - "Alle Spieler müssen einen Water MLG machen" - ], - "item-custom-action-jnr": [ - "§6Jump And Run", - "Ein zufälliger Spieler muss ein Jump And Run machen" - ], - "item-custom-action-win": [ - "§6Gewinnen", - "Die Challenge wird von *bestimmten Spielern* gewonnen" - ], - "item-custom-action-random_hotbar": [ - "§eZufällige Hotbar", - "Das Inventar wird geleert und der Spieler", - "bekommt zufällige Items in die HotBar" - ], - "item-custom-action-modify_border": [ - "§bWorld Border Verändern", - "Mache die Worldborder *größer* §7oder *kleiner*" - ], - "item-custom-action-modify_border-change": [ - "§dVeränderung" - ], - "item-custom-action-swap_mobs": [ - "§5Mobs tauschen", - "Tausche ein Mob mit einem zufälligen", - "anderem Mob aus der gleichen Welt" - ], - "item-custom-action-place_structure": [ - "§aStruktur Platzieren", - "Platziert eine Struktur" - ], - "item-custom-action-place_structure-random": "§bZufällige Struktur", - "item-custom-setting-target-current": [ - "§6Aktives Entity", - "Die Aktion wird für das *aktive Entity* ausgeführt" - ], - "item-custom-setting-target-every_mob": [ - "§4Alle Mobs", - "Die Aktion wird für *alle Mobs* ausgeführt" - ], - "item-custom-setting-target-every_mob_except_current": [ - "§4Alle Mobs Außer Aktives", - "Die Aktion wird für *alle Mobs*", - "*außer* das Aktive ausgeführt ausgeführt" - ], - "item-custom-setting-target-every_mob_except_players": [ - "§4Alle Mobs Außer Spieler", - "Die Aktion wird für *alle Mobs*", - "*außer* Spieler ausgeführt" - ], - "item-custom-setting-target-random_player": [ - "§5Zufälliger Spieler", - "Die Aktion wird für einen *zufälligen Spieler* ausgeführt" - ], - "item-custom-setting-target-every_player": [ - "§cAlle Spieler", - "Die Aktion wird für *jeden Spieler* ausgeführt" - ], - "item-custom-setting-target-current_player": [ - "§aAktiver Spieler", - "Die Aktion wird für den *aktiven Spieler* ausgeführt", - "§7§oWenn das Entity kein Spieler ist, wird nichts passieren" - ], - "item-custom-setting-target-console": [ - "§4Konsole", - "Die Aktion wird für die *Konsole* ausgeführt" - ], - "item-custom-setting-entity_type-any": "§cJegliches Entity", - "item-custom-setting-entity_type-player": "§aSpieler", - "item-custom-setting-block-any": "§2Jeglicher Block", - "item-custom-setting-item-any": "§2Jegliches Item", - "custom-subsetting-target_entity": "Ziel Entity", - "custom-subsetting-entity_type": "Entity Typ", - "custom-subsetting-liquid": "Flüssigkeit", - "custom-subsetting-time": "Zeit", - "custom-subsetting-damage_cause": "Schadens Art", - "custom-subsetting-amount": "Anzahl", - "custom-subsetting-value": "Werte Editor", - "custom-subsetting-health_offset": "Veränderung", - "custom-subsetting-length": "Länge", - "custom-subsetting-amplifier": "Stärke", - "custom-subsetting-change": "Veränderung", - "custom-subsetting-swap_targets": "Tausch Ziele" + "syntax": "Bitte nutze §e/{0}", + "reload": "Challenges Plugin wird neu geladen...", + "reload-failed": "Ein §cFehler §7ist während dem Reload aufgetreten", + "reload-success": "Challenges Plugin wurde §aerfolgreich §7neu geladen", + "player-command": "Dazu musst du ein Spieler sein!", + "no-permission": "Dazu hast du §ckeine §7Rechte", + "enabled": "§aAktiviert", + "disabled": "§cDeaktiviert", + "customize": "§6Anpassen", + "navigate-back": "§8« §7Zurück", + "navigate-next": "§8» §7Weiter", + "seconds": "Sekunden", + "second": "Sekunde", + "minutes": "Minuten", + "minute": "Minute", + "hours": "Stunden", + "hour": "Stunde", + "amplifier": "Stärke", + "open": "Öffnen", + "everyone": "§5Alle", + "player": "§6Aktiver Spieler", + "none": "Nichts", + "inventory-color": "§9", + "timer-counting-up": "§8» §7Timer zählt §ahoch", + "timer-counting-down": "§8» §7Timer zählt §crunter", + "timer-is-paused": "§8» §7Timer ist §cpausiert", + "timer-is-running": "§8» §7Timer ist §agestartet", + "confirm-reset": "Bestätige den Reset mit §e/{0}", + "no-fresh-reset": [ + "Der Server kann §cnicht resettet §7werden", + "Die Challenge wurde §cnoch nicht §7gestartet" + ], + "new-challenge": "§a§lNeu!", + "feature-disabled": "Diese Funktion ist derzeit §cdeaktiviert", + "challenge-disabled": "Diese Challenge ist derzeit §cdeaktiviert", + "stopped-message": "§8• §7Timer §c§lpaused §8•", + "count-up-message": "§8• §7Time: §a§l{0} §8•", + "count-down-message": "§8• §7Time: §c§l{0} §8•", + "timer-not-started": "Der Timer wurde noch §cnicht gestartet", + "timer-was-started": "Der Timer wurde §agestartet", + "timer-was-paused": "Der Timer wurde §cpausiert", + "timer-was-set": "Der Timer wurde auf §e§l{0} §7gesetzt", + "timer-already-started": "Der Timer §cläuft bereits", + "timer-already-paused": "Der Timer ist §cbereits pausiert", + "timer-mode-set-down": "Der Timer zählt nun §crunter", + "timer-mode-set-up": "Der Timer zählt nun §ahoch", + "no-database-connection": "Es gibt §ckeine §7Datenbankverbindung", + "fetching-data": "Daten werden abgerufen..", + "undefined": "undefiniert", + "no-such-material": "Dieses Material gibt es nicht", + "not-an-item": "§e{0} §7ist kein Item", + "no-such-entity": "Dieses Entity existiert nicht", + "not-alive": "§e{0} §7ist kein lebendes Entity", + "no-loot": "§e{0} §7hat keine Drops", + "deprecated-plugin-version": [ + " ", + "§7Ein neues Update ist verfügbar!", + "§7Download: §e§l{0}", + " " + ], + "deprecated-config-version": [ + "Deine Plugin Config ist §cveraltet §7(§c{1} §7< §a{0}§7)", + "Du kannst die alte Config löschen oder die fehlenden Einstellungen manuell hinzufügen" + ], + "missing-config-settings": "Folgende Einstellungen fehlen in der Config: §e{0}", + "missing-config-settings-separator": "§7, §e", + "no-missing-config-settings": [ + "§cEs fehlen keine Einstellungen in der Config.", + "§cDu kannst die Version ohne bedenken selbst auf §c§l{0} §cstellen." + ], + "unsuported-language": [ + "§cDiese Sprache §7(§e{0}§7) wird nicht unterstützt" + ], + "not-op": [ + "§7Um dieses Plugin zu nutzen, musst du die Berechtigung haben. Gib dir die Berechtigung in der Serverkonsole mit: /op [name]" + ], + "join-message": "§e{0} §7hat den Server §abetreten", + "quit-message": "§e{0} §7hat den Server §cverlassen", + "timer-paused-message": [ + "Der Timer ist noch §cpausiert", + "Nutze §e/timer resume §7um ihn zu starten" + ], + "cheats-detected": [ + "§e{0} §7hat §cgecheated", + "Es können §ckeine weiteren §7Statistiken gesammelt werden" + ], + "cheats-already-detected": [ + "Auf diesem Server wurde §cgecheated", + "Es können §ckeine weiteren §7Statistiken gesammelt werden" + ], + "custom_challenges-reset": "Die §eLokalen §7Challenges wurden §aerfolgreich zurückgesetzt", + "config-reset": "Die §eLokalen §7Einstellungen wurden §aerfolgreich zurückgesetzt", + "player-config-loaded": "Deine Einstellungen wurden §aerfolgreich geladen", + "player-config-saved": "Deine Einstellungen wurden §aerfolgreich gespeichert", + "player-config-reset": "Deine Einstellungen wurden §aerfolgreich zurückgesetzt", + "player-custom_challenges-loaded": "Deine Challenges wurden §aerfolgreich geladen", + "player-custom_challenges-saved": "Deine Challenges wurden §aerfolgreich gespeichert", + "player-custom_challenges-reset": "Deine Challenges wurden §aerfolgreich zurückgesetzt", + "item-prefix": "§8» ", + "item-setting-info": "§8➟ {0}", + "stat-dragon-killed": "Drachen getötet", + "stat-deaths": "Tode", + "stat-entity-kills": "Kills", + "stat-damage-dealt": "Schaden ausgeteilt", + "stat-damage-taken": "Schaden genommen", + "stat-blocks-mined": "Blöcke abgebaut", + "stat-blocks-placed": "Blöcke platziert", + "stat-blocks-traveled": "Blöcke gereist", + "stat-challenges-played": "Challenges gespielt", + "stat-jumps": "Sprünge", + "stats-of": "§8» §7Stats von §e{0}", + "stats-display": "§8» §7{0} §8(§e{1}. §7Platz§8)", + "stats-leaderboard-display": [ + "§8» §e{0}", + "§8§l┣ §7{1} §7{2}", + "§8§l┗ §e{3}. §7Platz" + ], + "position": "§e{4} §8- §7{0}, {1}, {2} §8(§e{3}§8) §8┃ §e{5}m", + "positions-disabled": "Positionen sind §cdeaktiviert", + "position-other-world": "Diese Position befindet sich in einer anderen Welt §8(§e{0}§8)", + "position-not-exists": "Die Position §e{0} §7existiert §cnicht", + "position-already-exists": "Die Position §e{0} §7existiert §cbereits", + "position-set": "§e{5} §7hat §e{4} §7{0}, {1}, {2} §8(§e{3}§8) §7erstellt", + "position-deleted": "§e{5} §7hat §e{4} §7{0}, {1}, {2} §8(§e{3}§8) §7gelöscht", + "no-positions": [ + "Es sind keine §ePositionen §7in dieser Welt gesetzt", + "Erstelle eine mit §e/{0}" + ], + "no-positions-global": [ + "Es sind keine §ePositionen §7gesetzt", + "Erstelle eine mit §e/{0}" + ], + "command-no-target": "Es wurde §ckein §7Spieler gefunden", + "command-heal-healed": "Du wurdest §ageheilt", + "command-heal-healed-others": "Du hast §e{0} Spieler §ageheilt", + "command-gamemode-gamemode-changed": "Du wurdest in den Gamemode §e{0} §7gesetzt", + "command-gamemode-gamemode-changed-others": "Du hast §e{1} Spieler §7in den Gamemode §e{0} §7gesetzt", + "command-village-search": "Es wird nach einem Dorf gesucht..", + "command-village-teleport": "Du wurdest in ein Dorf §ateleportiert", + "command-village-not-found": "Es wurde §ckein neues §7Dorf gefunden", + "command-weather-set-clear": "Wetter zu §eklar §7geändert", + "command-weather-set-rain": "Wetter zu §eregnerisch §7geändert", + "command-weather-set-thunder": "Wetter zu §estürmisch §7geändert", + "command-invsee-open": "Inventar von §e{0} §7geöffnet", + "command-enderchest-open": "Du hast deine §5Enderchest §7geöffnet", + "command-difficulty-change": "Schwierigkeit auf {0} §7geändert", + "command-difficulty-current": "Die derzeitige Schwierigkeit ist {0}", + "command-search-nothing": "§e{0} §7wird durch keinen speziellen Block gedroppt", + "command-search-result": "§e{0} §7droppt aus §e{1}", + "command-searchloot-disabled": "Die Entity Loot Randomizer Challenge ist aktuell §cdeaktiviert", + "command-searchloot-nothing": "Der Loot von §e{0} §7wird durch kein spezielles Entity gedroppt", + "command-searchloot-result": [ + "§e{0} §7droppt den Loot von §e{1}", + "Der Loot von §e{0} §7wird von §e{2} §7gedroppt" + ], + "command-time-set": "Die Zeit wurde auf §e{0} §7Ticks §8(§7ca. §e{1}§8) §7geändert", + "command-time-set-exact": "Die Zeit wurde auf §e{0} §8(§e{1} §7Ticks§8) §7geändert", + "command-time-query": [ + "§8» §7Derzeitige Ingamezeiten", + "Spielzeit §e{0} §7Ticks §8(§7Tag §e{1}§8)", + "Tageszeit §e{2} §7Ticks §8(§7ca. §e{3}§8)" + ], + "command-time-noon": "Mittag", + "command-time-night": "Nacht", + "command-time-midnight": "Mitternacht", + "command-time-day": "Tag", + "command-fly-enabled": "Du kannst §anun fliegen", + "command-fly-disabled": "Du kannst nun §cnicht mehr §7fliegen", + "command-fly-toggled-others": "Du hast §eFly §7für §e{0} §7Spieler verändert", + "command-feed-fed": "Dein Hunger wurde §agestillt", + "command-feed-others": "Du hast den Hunger von §e{0} §7Spieler *gestillt*", + "command-gamestate-reload": "Der Gamestate wurde §aneu geladen", + "command-gamestate-reset": "Der Gamestate wurde §azurückgesetzt", + "command-world-teleport": "Du wirst in die Welt §e{0} §7teleportiert", + "command-back-no-locations": "Du hast dich noch §cnicht §7teleportiert", + "command-back-teleported": "Du wurdest §e{0} §7Position zurück teleportiert", + "command-back-teleported-multiple": "Du wurdest §e{0} §7Positionen zurück teleportiert", + "command-result-no-battle-active": "Es ist aktuell §ckein §7Force-Battle aktiviert", + "command-god-mode-enabled": "Du bist nun im §aGod-Mode", + "command-god-mode-disabled": "Du bist nun §cnicht mehr im God-Mode", + "command-god-mode-toggled-others": "§e{0} §7Spieler sind jetzt im §eGod-Mode", + "traffic-light-challenge-fail": "§e{0} §7ist über §crot §7gegangen", + "player-damage-display": "§e{0} §7nahm §7{1} §7Schaden durch §e{2}", + "death-message": "§e{0} §7ist gestorben", + "death-message-cause": "§e{0} §7ist durch §e{1} §7gestorben", + "health-inverted": "Deine Herzen wurden §cinvertiert", + "exp-picked-up": "§e{0} §7hat §cXP §7aufgesammelt", + "unable-to-find-fortress": "Es konnte §ckeine Festung §7gefunden werden", + "unable-to-find-bastion": "Es konnte §ckeine Bastion §7gefunden werden", + "death-collected": "Todesgrund §e{0} §7wurde registriert", + "item-collected": "Item §e{0} §7wurde registriert", + "items-to-collect": "§7Items zu sammeln §8» §e{0}", + "backpacks-disabled": "Rucksäcke sind derzeit §cdeaktiviert", + "backpack-opened": "Du hast den {0} §7geöffnet", + "top-to-overworld": "Du wurdest zur §eOverworld §7teleportiert", + "top-to-surface": "Du wurdest zur §eOberfläche §7teleportiert", + "jnr-countdown": "Nächstes §6JumpAndRun §7in §e{0} Sekunden", + "jnr-countdown-one": "Nächstes §6JumpAndRun §7in §eeiner Sekunde", + "jnr-finished": "§e{0} §7hat das §6JumpAndRun §ageschafft", + "snake-failed": "§e{0} §7ist über die §9Linie §7getreten", + "only-dirt-failed": "§e{0} §7stand nicht auf Erde", + "no-mouse-move-failed": "§e{0} §7hat seine Maus bewegt", + "no-duped-items-failed": "§e{0} §7und §e{1} §7hatten beide §e{2} §7im Inventar", + "only-down-failed": "§e{0} §7ist einen Block nach oben gegangen", + "food-once-failed": "§e{0} §7ist an §e{1} §7erstickt", + "food-once-new-food-team": "§e{0} §7hat §e{1} §7gegessen", + "food-once-new-food": "§eDu §7hast §e{1} §7gegessen", + "sneak-damage-failed": "§e{0} §7ist geschlichen", + "jump-damage-failed": "§e{0} §7ist gesprungen", + "random-challenge-enabled": "Die Challenge §e{0} §7wurde §aaktiviert", + "all-items-skipped": "Item §e{0} §7geskippt", + "all-items-already-finished": "Es wurden bereits alle Items gefunden", + "all-items-found": "Das Item §e{0} §7wurde von §e{1} §7registriert", + "mob-kill": "§e{0} §7wurde besiegt §8(§e{1} §7/ §e{2}§8)", + "endergames-teleport": "Du wurdest mit §e{0} §7getauscht", + "force-height-fail": "§e{0} §7war auf der §cfalschen Höhe §8(§e{1}§8)", + "force-height-success": "Alle Spieler waren auf der §arichtigen Höhe", + "force-block-fail": "§e{0} §7war auf dem §cfalschen Block §8(§e{1}§8)", + "force-block-success": "Alle Spieler waren auf dem §arichtigen Block", + "force-biome-fail": "Das Biom §e{0} §7wurde §cnicht gefunden", + "force-biome-success": "§e{0} §7hat das Biom §e{1} §agefunden", + "force-mob-fail": "Das Mob §e{0} §7wurde §cnicht getötet", + "force-mob-success": "§e{0} §7hat das Mob §e{1} §agetötet", + "force-item-fail": "Das Item §e{0} §7wurde §cnicht gefunden", + "force-item-success": "§e{0} §7hat das Item §e{1} §agefunden", + "new-effect": "Effekt §e{0} §8➔ §e{1}", + "missing-items-inventory": "{0}Welches Item fehlt?", + "missing-items-inventory-open": "§8[§aGUI öffnen§8]", + "loops-cleared": "§e{0} §7Loops abgebrochen", + "stopped-moving": "§e{0} §7hat sich zu lange nicht bewegt", + "all-advancements-goal": "§7Advancements §8» §e{0}", + "Chalheight-reached": "§e{0} §7hat Höhe §e{1} §7erreicht!", + "race-goal-reached": "§e{0} §7hat das Ziel erreicht!", + "points-change": "§e{0} §7Punkte", + "force-item-battle-found": "Du hast §e{0} §7gefunden!", + "force-item-battle-new-item": "Item zu suchen: §e{0}", + "force-item-battle-leaderboard": "§8➜ §7Force Item Battle Leaderboard", + "force-mob-battle-killed": "Du hast §e{0} §7gefunden!", + "force-mob-battle-new-mob": "Mob zu suchen: §e{0}", + "force-mob-battle-leaderboard": "§8➜ §7Force Mob Battle Leaderboard", + "force-advancement-battle-completed": "Du hast §e{0} §7erzielt!", + "force-advancement-battle-new-advancement": "Nächstes Advancement: §e{0}", + "force-advancement-battle-leaderboard": "§8➜ §7Force Advancement Battle Leaderboard", + "force-block-battle-found": "Du hast §e{0} §7gefunden!", + "force-block-battle-new-block": "Block zu suchen: §e{0}", + "force-block-battle-leaderboard": "§8➜ §7Force Block Battle Leaderboard", + "force-battle-leaderboard-entry": "{0}#{1} §8» §e{2} §8┃ §e{3}", + "force-battle-block-target-display": "§eBlock: {0}", + "force-battle-item-target-display": "§eItem: {0}", + "force-battle-height-target-display": "§eHöhe: {0}", + "force-battle-mob-target-display": "§eMob: {0}", + "force-battle-biome-target-display": "§eBiom: {0}", + "force-battle-damage-target-display": "§eSchaden: §c{0} ❤", + "force-battle-advancement-target-display": "§eAdvancement: {0}", + "force-battle-position-target-display": "§ePosition: {0}", + "extreme-force-battle-new-height": "Höhe zu erreichen: §e{0}", + "extreme-force-battle-reached-height": "Du hast die Höhe §e{0} §7erreicht!", + "extreme-force-battle-new-biome": "Biom zu finden: §e{0}", + "extreme-force-battle-found-biome": "Du hast das Biom §e{0} §7gefunden!", + "extreme-force-battle-new-damage": "Schaden zu nehmen: §c{0} ❤", + "extreme-force-battle-took-damage": "Du hast §c{0} ❤ §7Schaden genommen!", + "extreme-force-battle-position": "§eX: {0} §8┃ §eZ: {1}", + "extreme-force-battle-new-position": "Position zu erreichen: §e{0}", + "extreme-force-battle-reached-position": "Du hast die Position §e{0} §7erreicht!", + "extreme-force-battle-leaderboard": "§8➜ §7Extreme Force Battle Leaderboard", + "force-biome-battle-leaderboard": "§8➜ §7Force Biome Battle Leaderboard", + "force-damage-battle-leaderboard": "§8➜ §7Force Damage Battle Leaderboard", + "force-height-battle-leaderboard": "§8➜ §7Force Height Battle Leaderboard", + "force-position-battle-leaderboard": "§8➜ §7Force Position Battle Leaderboard", + "random-event-speed": [ + "Sonic? Bist du es?", + "Woahh! Das ist aber schnell" + ], + "random-event-entities": [ + "Ist das hier ein Zoo?", + "Wo kommt ihr denn her?", + "Was macht ihr denn hier?" + ], + "random-event-hole": [ + "Du bist aber ganz schön tief gefallen", + "Von ganz oben nach ganz unten..", + "Wo kommt denn das Loch her?" + ], + "random-event-fly": [ + "Guten Flug :)", + "I believe I can fly..", + "So fühlt sich also fliegen an" + ], + "random-event-webs": [ + "Liegen die schon lange hier?" + ], + "random-event-ores": [ + "Wo sind denn die ganzen Erze hin?", + "Gibt es hier keine Erze?", + "Gab es hier mal Erze?" + ], + "random-event-sickness": [ + "Bist du etwa krank?", + "Was geht denn jetzt ab" + ], + "bossbar-timer-paused": "§8» §7Der Timer ist §cpausiert", + "bossbar-mob-transformation": "§8» §7Letzter Mob §8§l┃ §a{0}", + "bossbar-biome-time-left": "§8» §7Zeit übrig in §e{0} §8§l┃ §a{1}s", + "bossbar-height-time-left": "§8» §7Zeit übrig auf §e{0} §8§l┃ §a{1}s", + "bossbar-zero-hearts": "§8» §7Schutzzeit §8§l┃ §a{0}s", + "bossbar-random-challenge-waiting": "§8» §7Warten auf neue Challenge..", + "bossbar-random-challenge-current": "§8» §7Challenge §e{0}", + "bossbar-all-items-current-max": "§8» §f{0} §8┃ §7{1} §8/ §7{2}", + "bossbar-all-items-finished": "§8» §7Alle Items gefunden", + "bossbar-force-height-waiting": "§8» §7Warten auf nächste Höhe..", + "bossbar-force-height-instruction": "§8» §7Höhe §e{0} §8┃ §a{1}", + "bossbar-force-block-waiting": "§8» §7Warten auf nächsten Block..", + "bossbar-force-block-instruction": "§8» §7Block §e{0} §8┃ §a{1}", + "bossbar-force-biome-waiting": "§8» §7Warten auf nächstes Biom..", + "bossbar-force-biome-instruction": "§8» §7Biom §e{0} §8┃ §a{1}", + "bossbar-force-mob-waiting": "§8» §7Warten auf nächsten Mob..", + "bossbar-force-mob-instruction": "§8» §7Mob §e{0} §8┃ §a{1}", + "bossbar-force-item-waiting": "§8» §7Warten auf nächstes Item..", + "bossbar-force-item-instruction": "§8» §7Item §e{0} §8┃ §a{1}", + "bossbar-tsunami-water": "§8» §7Wasserhöhe: §9{0}", + "bossbar-tsunami-lava": "§8» §7Lavahöhe: §c{0}", + "bossbar-ice-floor": "§8» §fEisboden §8┃ {0}", + "bossbar-dont-stop-running": "§8» §7Bewege dich in §8┃ §e{0}", + "bossbar-five-hundred-blocks": "§8» §fBlöcke Gelaufen §8┃ §7{0} §8/ §7{1}", + "bossbar-level-border": "§8» §7Border Größe §8┃ §7{0}", + "bossbar-race-goal-info": "§8» §fZiel §8┃ §7X: {0} §8/ §7Z: {1} §8┃ §e{2} Blöcke", + "bossbar-race-goal": "§8» §fZiel §8┃ §7X: {0} §8/ §7Z: {1}", + "bossbar-first-at-height-goal": "§8» §fZiel §8┃ §7Y: {0}", + "bossbar-respawn-end": "§8» §5Respawnte Mobs im End §8┃ §e{0}", + "bossbar-kill-all-bosses": "§8» §cAlle Bosse §8┃ §e{0}/{1}", + "bossbar-kill-all-mobs": "§8» §cAlle Mobs §8┃ §e{0}/{1}", + "bossbar-kill-all-monster": "§8» §cAlle Monster §8┃ §e{0}/{1}", + "bossbar-chunk-deletion": "§8» §7Zeit übrig im Chunk §6{0}s", + "subtitle-time-seconds": "§e{0} §7Sekunden", + "subtitle-time-seconds-range": "§e{0}-{1} §7Sekunden", + "subtitle-time-minutes": "§e{0} §7Minuten", + "subtitle-launcher-description": "§7Stärke §e{0}", + "subtitle-blocks": "§e{0} §7Blöcke", + "subtitle-range-blocks": "§7Reichweite: §e{0} §7Blöcke", + "scoreboard-title": "§7» §f§lChallenge", + "scoreboard-leaderboard": "§e#{0} §8┃ §7{1} §8» §e{2}", + "your-place": "§7Dein Platz §8» §e{0}", + "server-reset": [ + "§8————————————————————", + " ", + "§8» §cServerreset", + " ", + "§7Reset durch §4§l{0}", + "§7Der Server startet nun §cneu", + " ", + "§8————————————————————" + ], + "challenge-end-timer-hit-zero": [ + " ", + "§cDie Challenge ist vorbei!", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-timer-hit-zero-winner": [ + " ", + "§cDie Challenge ist vorbei!", + "§7Gewinner: §e§l{1}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-reached": [ + " ", + "§7Die Challenge wurde beendet!", + "§7Zeit benötigt: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-reached-winner": [ + " ", + "§7Die Challenge wurde beendet!", + "§7Gewinner: §e§l{1}", + "§7Zeit benötigt: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-failed": [ + " ", + "§cDie Challenge ist vorbei! §6#FeelsBadMan ✞", + "§7Zeit verschwendet: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "title-timer-started": [ + " ", + "§8» §7Timer §afortgesetzt" + ], + "title-timer-paused": [ + " ", + "§8» §7Timer §cpausiert" + ], + "title-challenge-enabled": [ + "§e{0}", + "§2§l✔ §8┃ §aAktiviert" + ], + "title-challenge-disabled": [ + "§e{0}", + "§4✖ §8┃ §cDeaktiviert" + ], + "title-challenge-value-changed": [ + "§e{0}", + "§8» §e{1}" + ], + "title-pregame-movement-setting": [ + "§cWarte..", + "§8» §7Der Timer ist gestoppt.." + ], + "item-menu-start": "§8• §aStart Challenge §8┃ §e/start §8•", + "item-menu-challenges": "§8• §cChallenges §8┃ §e/challenge §8•", + "item-menu-timer": "§8• §5Timer §8┃ §e/timer §8•", + "item-menu-leaderboard": "§8• §6Leaderboard §8┃ §e/leaderboard §8•", + "item-menu-stats": "§8• §2Statistiken §8┃ §e/stats §8•", + "menu-title": "Menu", + "menu-timer": "§6Timer", + "menu-goal": "§5Ziel", + "menu-damage": "§7Schaden", + "menu-item_blocks": "§4Blöcke & Items", + "menu-challenges": "§cChallenges", + "menu-settings": "§eEinstellungen", + "menu-custom": "§aIndividuelle Challenges", + "lore-category-activated-count": "§7Aktiviert §8» §a{0}§8/§7{1}", + "lore-category-activated": "§7Aktiviert §8» §aJa", + "lore-category-deactivated": "§7Aktiviert §8» §cNein", + "category-misc_challenge": [ + "§9Miscellaneous", + "Challenges, die *keiner Kategorie*", + "zugeordnet werden können" + ], + "category-randomizer": [ + "§6Randomizer", + "Erlebe ein komplett", + "*durcheinandergebrachtes* Spiel" + ], + "category-limited_time": [ + "§aLimitierte Zeit", + "Du wirst bei verschiedenen", + "Faktoren *zeitlich eingeschränkt*" + ], + "category-force": [ + "§3Zwischenziele (Force)", + "Du musst *bestimmte Zwischenziele*", + "erfüllen, sonst stirbst du" + ], + "category-world": [ + "§4Weltveränderung", + "Die Welt wird nicht mehr", + "*wiedererkennbar* sein" + ], + "category-damage": [ + "§cSchaden", + "Neue *Schadens Regeln*" + ], + "category-effect": [ + "§5Effekte", + "Erlebe verrückte *Effekte*" + ], + "category-inventory": [ + "§6Inventory", + "Dein Inventar wird *verdreht*" + ], + "category-movement": [ + "§aBewegung", + "Du wirst in deinen Bewegungen *eingeschränkt*" + ], + "category-entities": [ + "§bEntities", + "Entities werden *verändert*" + ], + "category-extra_world": [ + "§aExtra Welt", + "Challenges, die in einer", + "*anderen Welt* spielen" + ], + "category-misc_goal": [ + "§9Miscellaneous", + "Ziele, die *keiner Kategorie*", + "zugeordnet werden können" + ], + "category-kill_entity": [ + "§cEntity töten", + "Töte *bestimmte Entities*,", + "um zu gewinnen" + ], + "category-score_points": [ + "§eMeiste Punkte", + "Erziele die *meisten Punkte* in", + "einem *bestimmten Bereich*." + ], + "category-fastest_time": [ + "§6Schnellste Zeit", + "Sei der *schnellste Spieler*, der", + "das Ziel erfüllt" + ], + "category-force_battle": [ + "§bForce Battles", + "Erfülle die *vorgegebenen Zwischenziele*,", + "um Punkte zu erhalten.", + " ", + "Der Spieler mit den *meisten Punkten* gewinnt." + ], + "item-time-seconds-description": "§8» §7Zeit: §e{0} §7Sekunden", + "item-time-seconds-range-description": "§8» §7Zeit: §e{0}-{1} §7Sekunden", + "item-time-minutes-description": "§8» §7Zeit: §e{0} §7Minuten", + "item-heart-damage-description": "§8» §7Schaden: §e{0} §c❤", + "item-heart-start-description": "§8» §7Start: §e{0} §c❤", + "item-max-health-description": "§8» §7Maximale Leben: §e{0} §c❤", + "item-chance-description": "§8» §7Chance: §e{0}%", + "item-launcher-description": "§8» §7Stärke: §e{0}", + "item-permanent-effect-target-player-description": "§8» §7Nur der aktive Spieler erhält den Effekt", + "item-permanent-effect-target-everyone-description": "§8» §7Alle erhalten den Effekt", + "item-blocks-description": "§8» §7Blöcke zu laufen: §e{0}", + "item-range-blocks-description": "§8» §7Reichweite: §e{0} §7Blöcke", + "item-force-battle-goal-jokers": [ + "§6Anzahl der Joker", + "Die *Anzahl* der *Joker*,", + "die jeder Spieler hat" + ], + "item-force-battle-show-scoreboard": [ + "§bScoreboard anzeigen" + ], + "item-force-battle-duped-targets": [ + "§cDoppelte Ziele", + "Ziele können *mehrfach* vorkommen" + ], + "item-force-position-battle-radius": [ + "§bRadius", + "Der *maximale Radius*, in dem sich die", + "Positionen befinden können" + ], + "item-language-setting": [ + "§bSprache", + "Setze die *Sprache*" + ], + "item-language-setting-german": "§fDeutsch", + "item-language-setting-english": "§fEnglish", + "item-difficulty-setting": [ + "§aSchwierigkeit", + "Stellt die *Schwierigkeitsstufe* ein" + ], + "item-one-life-setting": [ + "§cEin Teamleben", + "*Jeder* stirbt, wenn *einer stirbt*" + ], + "item-respawn-setting": [ + "§4Respawn", + "Wenn du *stirbst*, wirst du nicht zu einem *Zuschauer*" + ], + "item-death-message-setting": [ + "§6Todesnachrichten", + "Schaltet *Todesnachrichten* ein/aus" + ], + "item-death-message-setting-vanilla": "§6Vanilla", + "item-pvp-setting": [ + "§9PvP" + ], + "item-max-health-setting": [ + "§cMaximale Herzen", + "Stellt ein, wie viele", + "Herzen man hat" + ], + "item-soup-setting": [ + "§cSuppen Heilung", + "Wenn du eine *Pilzsuppe* benutzt,", + "wirst du um *4 Herzen* geheilt" + ], + "item-damage-setting": [ + "§cDamage Multiplier", + "Schaden, den du nimmst, wird *multipliziert*" + ], + "item-damage-display-setting": [ + "§eDamage Display", + "Es wird im Chat angezeigt,", + "wenn jemand *Schaden* bekommt" + ], + "item-health-display-setting": [ + "§cHealth Display", + "Die *Herzen* aller Spieler", + "werden in der *Tablist* angezeigt" + ], + "item-position-setting": [ + "§9Positions", + "Erlaubt es dir *Positionen*", + "mit */pos* zu *markieren*" + ], + "item-backpack-setting": [ + "§6Backpack", + "Erlaubt es dir, *deinen Backpack* oder den", + "*Team Backpack* mit */backpack* zu öffnen" + ], + "item-backpack-setting-team": "§5Team", + "item-backpack-setting-player": "§6Player", + "item-cut-clean-setting": [ + "§9CutClean", + "Verschiedene *Einstellungen*, die", + "das *Farmen* von Items *einfacher* machen" + ], + "menu-cut-clean-setting-settings": "CutClean", + "item-cut-clean-gold-setting": [ + "§6Gold", + "*Golderz* wird direkt zu *Goldbarren*" + ], + "item-cut-clean-iron-setting": [ + "§7Iron", + "*Eisenerz* wird direkt zu *Eisenbarren*" + ], + "item-cut-clean-coal-setting": [ + "§eCoal", + "*Kohleerz* wird direkt zu *Fackeln*" + ], + "item-cut-clean-flint-setting": [ + "§eFlint", + "*Gravel* droppt immer *Flint*" + ], + "item-cut-clean-vein-setting": [ + "§eOre Veins", + "*Erz Venen* werden direkt abgebaut" + ], + "item-cut-clean-inventory-setting": [ + "§6Direkt ins Inventar", + "*Items* werden, *anstatt gedroppt* zu werden,", + "*direkt* ins *Inventar* hinzugefügt" + ], + "item-cut-clean-food-setting": [ + "§cGebratenes Essen", + "*Rohes Fleisch* wird direkt zu *gebratenem Fleisch*" + ], + "item-glow-setting": [ + "§fPlayerglow", + "*Spieler* sind durch die *Wand* sichtbar" + ], + "no-hunger-setting": [ + "§cKein Hunger", + "Du bekommst keinen *Hunger*" + ], + "pregame-movement-setting": [ + "§6Pregame Movement", + "Du kannst dich *bewegen*, bevor", + "das Spiel *gestartet* hat" + ], + "item-no-hit-delay-setting": [ + "§fNoHitDelay", + "Nachdem du *Schaden* genommen hast,", + "kannst du *sofort* wieder Schaden *bekommen*" + ], + "item-timber-setting": [ + "§bTimber", + "Du kannst einen *Baum* zerstören,", + "indem du *einen Block* des Baumes abbaust" + ], + "item-timber-setting-logs": "§6Baumstämme", + "item-timber-setting-logs-and-leaves": "§6Baumstämme §7und §2Blätter", + "item-keep-inventory-setting": [ + "§5Keep Inventory", + "Du verlierst keine *Items*,", + "wenn du *stirbst*" + ], + "item-mob-griefing-setting": [ + "§5Mob Griefing", + "Monster können *nichts zerstören*" + ], + "item-no-item-damage-setting": [ + "§5Kein Itemschaden", + "*Items* sind *unzerstörbar*" + ], + "top-command-setting": [ + "§dTop Command", + "Mit */top* kannst du dich", + "zur *Oberfläche* oder in", + "die *Overworld* teleportieren" + ], + "item-fortress-spawn-setting": [ + "§cFestungs Spawn", + "Wenn du in den *Nether* gehst,", + "spawnst du immer in einer *Festung*" + ], + "item-bastion-spawn-setting": [ + "§cBastions Spawn", + "Wenn du in den *Nether* gehst,", + "spawnst du immer in einer *Bastion*" + ], + "item-no-offhand-setting": [ + "§6Keine Offhand", + "Die *zweite Hand* wird geblockt" + ], + "item-regeneration-setting": [ + "§cRegeneration", + "Stellt ein, *ob* und", + "*wie* man *regeneriert*" + ], + "item-regeneration-setting-not_natural": "§6Nicht natürlich", + "item-immediate-respawn-setting": [ + "§6Direkter Respawn", + "Wenn du stirbst, *respawnst* du *automatisch,*", + "ohne den *Death Screen* zu sehen" + ], + "item-slot-limit-setting": [ + "§4Inventar Slots", + "Stellt ein, wie viele *Inventar*", + "*Slots* nutzbar sind" + ], + "item-death-position-setting": [ + "§cDeath Position", + "Wenn du stirbst, wird mit */pos* ", + "eine *Position an deinem Todespunkt* erstellt" + ], + "item-enderchest-command-setting": [ + "§5Enderchest Command", + "Wenn du */ec* ausführst, öffnet", + "sich deine *Enderchest*" + ], + "item-split-health-setting": [ + "§cGeteilte Herzen", + "Stellt ein, ob sich *alle*", + "*Spieler* eine *Gesundheit teilen*" + ], + "item-old-pvp-setting": [ + "§b1.8 PvP", + "Das *alte 1.8 PvP System* wird genutzt", + "Es gibt keinen *Attack Cooldown*" + ], + "item-totem-save-setting": [ + "§6Challenge Tod Rettung", + "Wenn du durch eine Challenge *instant*", + "*stirbst*, können *Totems* dich retten" + ], + "item-traffic-light-challenge": [ + "§cAmpelchallenge", + "Die *Ampel* schaltet alle paar Minuten um", + "Wenn du bei *rot* gehst, stirbst du" + ], + "item-block-randomizer-challenge": [ + "§6Block Randomizer", + "Jeder *Block* droppt ein *zufälliges Item*" + ], + "item-crafting-randomizer-challenge": [ + "§6Crafting Randomizer", + "Wenn du *etwas craftest*, bekommst du ein *zufälliges Item*" + ], + "item-mob-randomizer-challenge": [ + "§6Mob Randomizer", + "Wenn ein *Entity* spawnt, spawnt ein *anderes*" + ], + "item-hotbar-randomizer-challenge": [ + "§6HotBar Randomizer", + "Alle *paar Minuten* erhält jeder Spieler *zufällige Items*" + ], + "item-damage-block-challenge": [ + "§4Schaden pro Block", + "Du bekommst *Schaden* durch", + "jeden *Block*, den du gehst" + ], + "item-hunger-block-challenge": [ + "§6Hunger pro Block", + "Du bekommst *Hunger* durch", + "jeden *Block*, den du gehst" + ], + "item-stone-sight-challenge": [ + "§fStein Blick", + "*Mobs*, denen du in die *Augen*", + "*schaust*, werden zu *Stein*" + ], + "item-no-mob-sight-challenge": [ + "§cMob Blick Schaden", + "Wenn du einen *Mob* in die *Augen*", + "*schaust*, erleidest du *Schaden*" + ], + "item-bedrock-path-challenge": [ + "§7Bedrock Path", + "*Unter dir* entsteht die", + "ganze Zeit *Bedrock*" + ], + "item-bedrock-walls-challenge": [ + "§7Bedrock Walls", + "Hinter dir *spawnen* riesige", + "*Wände* aus *Bedrock*" + ], + "item-surface-hole-challenge": [ + "§cSurface Hole", + "§7Hinter dir *verschwindet* der", + "*Boden* bis ins *Void*" + ], + "item-damage-inv-clear-challenge": [ + "§cDamage Inventory Clear", + "Die *Inventare* aller Spieler werden *geleert*,", + "wenn ein *Spieler* Schaden erleidet" + ], + "item-no-trading-challenge": [ + "§2Kein Handeln", + "Du kannst *nicht* mit", + "Villager *handeln*" + ], + "item-block-break-damage-challenge": [ + "§6Block Break Damage", + "Wenn du einen *Block abbaust*,", + "*erleidest* du die gesetze Anzahl *schaden*" + ], + "item-block-place-damage-challenge": [ + "§6Block Place Damage", + "Wenn du einen *Block plazierst*,", + "*erleidest* du die gesetze Anzahl *schaden*" + ], + "item-no-exp-challenge": [ + "§aKeine XP", + "Wenn du *XP* aufsammelst, stirbst du" + ], + "item-invert-health-challenge": [ + "§cInvert Health", + "Alle paar Minuten werden deine *Herzen invertiert*.", + "Wenn du *8 Herzen* hast,", + "hast du danach *2 Herzen* und umgekehrt." + ], + "item-jump-and-run-challenge": [ + "§6Jump and Run", + "Alle *paar Minuten* musst du ein random *Jump and Run* machen,", + "welches jedes Mal *schwieriger* wird" + ], + "item-randomized-hp-challenge": [ + "§4Randomized HP", + "Die *Leben* aller *Mobs*", + "sind *random*" + ], + "item-snake-challenge": [ + "§9Snake", + "*Jeder Spieler* zieht eine", + "tödliche Linie hinter sich her" + ], + "item-reversed-damage-challenge": [ + "§cReversed Damage", + "Wenn du Entities *schlägst* oder *abschießt*,", + "bekommst du den *gleichen Schaden*" + ], + "item-duped-spawning-challenge": [ + "§cDoppeltes Spawning", + "Wenn ein Monster *spawnt*,", + "spawnt es *zweimal*" + ], + "item-hydra-challenge": [ + "§5Hydra", + "Wenn du einen *Mob* tötest,", + "spawnen *zwei* neue" + ], + "item-hydra-plus-challenge": [ + "§cHydra Plus", + "Wenn du einen *Mob* tötest,", + "spawnen *doppelt* so viele", + "wie beim *vorherigen* mal", + " ", + "Maximum beträgt *512* Mobs gleichzeitig" + ], + "item-floor-lava-challenge": [ + "§6Der Boden ist Lava", + "Alle *Blöcke* unter dir verwandeln sich", + "erst zu *Magma* und dann zu *Lava*" + ], + "item-only-dirt-challenge": [ + "§cOnly Dirt", + "Wenn du nicht auf *Erde*", + "stehst, *stirbst* du" + ], + "item-food-once-challenge": [ + "§cFood Once", + "Du kannst jedes *Essen*", + "nur einmal *essen*" + ], + "item-food-once-challenge-player": "§6Spieler", + "item-food-once-challenge-everyone": "§5Jeder", + "item-chunk-deconstruction-challenge": [ + "§bChunk Deconstruction", + "*Chunks*, in denen sich Spieler befinden,", + "*bauen* sich von *oben* aus ab" + ], + "item-one-durability-challenge": [ + "§4Eine Haltbarkeit", + "*Items* gehen nach *einer* Benutzung *kaputt*" + ], + "item-low-drop-rate-challenge": [ + "§6Low Drop Chance", + "Die *Dropchance* jedes *Blockes* wird auf die", + "angegebene *Prozentzahl* gesetzt" + ], + "item-invisible-mobs-challenge": [ + "§fUnsichtbare Mobs", + "Alle *Mobs* haben einen", + "*Unsichtbarkeits* Effekt" + ], + "item-mob-transformation-challenge": [ + "§cMob Verwandlung", + "Wenn du einen Mob schlägst, *verwandelt* sich", + "dieser in den *letzen Mob*, den du *geschlagen* hast" + ], + "item-jump-entity-challenge": [ + "§2Jump Entity", + "Wenn du *springst*, *spawnt* ein", + "zufälliges *Entity*" + ], + "item-no-mouse-move-challenge": [ + "§cMausbewegung Schaden", + "Wenn du deinen *Blick bewegst*,", + "erleidest du den *gesetzen Schaden*" + ], + "item-no-duped-items-challenge": [ + "§6Keine Doppelten Items", + "Wenn *2 Spieler* das gleiche *Item* im", + "Inventar haben, *sterben* beide" + ], + "item-infection-challenge": [ + "§aInfection Challenge", + "Du musst *2 Blöcke* Abstand von allen ", + "*Mobs* halten oder du wirst *krank*" + ], + "item-only-down-challenge": [ + "§cNur nach unten", + "Wenn du *einen Block* nach", + "*oben* gehst, *stirbst* du" + ], + "item-advancement-damage-challenge": [ + "§cAdvancement Schaden", + "Du bekommst für jedes neue *Advancement*", + "die gesetze Anzahl *Schaden*" + ], + "item-all-blocks-disappear-challenge": [ + "§cAlle Blöcke verschwinden", + "Bei verschiedenen *Interaktionen*", + "verschwinden alle *Blöcke* im *Chunk*", + "eines *bestimmten Types*" + ], + "menu-all-blocks-disappear-challenge-settings": "Alle Blöcke verschwinden", + "item-all-blocks-disappear-break-challenge": [ + "§bBeim Abbauen", + "Wenn du einen Block *abbaust*, werden", + "*alle Blöcke* des *selben Types zerstört*" + ], + "item-all-blocks-disappear-place-challenge": [ + "§bBeim Platzieren", + "Wenn du einen Block *platzierst*, werden", + "*alle Blöcke* des *selben Types zerstört*" + ], + "item-water-allergy-challenge": [ + "§9Wasserallergie", + "Wenn du in *Wasser* bist,", + "*erleidest* du den gesetzen Schaden" + ], + "item-max-biome-time-challenge": [ + "§2Maximale Biom Zeit", + "Die *Zeit*, die du in jedem *Biom*", + "sein darfst, ist *begrenzt*" + ], + "item-max-height-time-challenge": [ + "§9Maximale Höhen Zeit", + "Die *Zeit*, die du auf jeder *Höhe*", + "sein darfst, ist *begrenzt*" + ], + "item-permanent-item-challenge": [ + "§cPermanente Items", + "*Items* können nicht gedroppt", + "oder *weggelegt* werden" + ], + "item-sneak-damage-challenge": [ + "§6Schaden pro Schleichen", + "Du *erleidest* den gesetzten", + "*Schaden*, wenn du *schleichst*" + ], + "item-jump-damage-challenge": [ + "§6Schaden pro Sprung", + "Du *erleidest* den gesetzen", + "*Schaden*, wenn du *springst*" + ], + "item-random-dropping-challenge": [ + "§cZufälliges Item Droppen", + "Alle paar Sekunden wird ein *zufälliges*", + "*Item* aus deinem Inventar *gedroppt*" + ], + "item-random-swapping-challenge": [ + "§cZufälliges Item Mischen", + "Alle paar Sekunden wird ein", + "*zufälliges Item* aus deinem Inventar", + "mit einem anderem *getauscht*" + ], + "item-random-removing-challenge": [ + "§cZufälliges Item Löschen", + "Alle paar Sekunden wird ein *zufälliges*", + "*Item* aus deinem Inventar *gelöscht*" + ], + "item-death-on-fall-challenge": [ + "§fTod bei Fallschaden", + "Wenn du *Fallschaden* erleidest,", + "*stirbst* du sofort" + ], + "item-zero-hearts-challenge": [ + "§6Null Herzen", + "Nach einer *Schutzzeit* musst du", + "dauerhaft Absorption bekommen" + ], + "item-random-effect-challenge": [ + "§6Random Effekte", + "Du bekommst in einem gesetzen *Intervall*", + "einen *zufälligen Trank Effekt*" + ], + "menu-random-effect-challenge-settings": "Random Effekte", + "item-random-effect-time-challenge": [ + "§6Intervall", + "Das *Intervall*, in dem man", + "einen *Effekt* erhält" + ], + "item-random-effect-length-challenge": [ + "§6Länge", + "Die *Länge*, die der", + "*Effekt* anhält" + ], + "item-random-effect-amplifier-challenge": [ + "§6Stärke", + "Die *Stärke*, die der", + "*Effekt* hat" + ], + "item-permanent-effect-on-damage-challenge": [ + "§6Permanente Effekte", + "Du bekommst immer, wenn du *Schaden*", + "erleidest, einen *zufälligen Effekt*" + ], + "item-random-challenge-challenge": [ + "§cRandom Challenge", + "In einem *gesetzten Intervall*", + "wird eine *Random Challenge* aktiviert" + ], + "item-anvil-rain-challenge": [ + "§cAmboss Regen", + "Vom *Himmel* fallen *Ambosse*" + ], + "menu-anvil-rain-challenge-settings": "Amboss Regen", + "item-anvil-rain-time-challenge": [ + "§6Intervall", + "Das *Intervall*, in", + "dem *Ambosse* spawnen" + ], + "item-anvil-rain-range-challenge": [ + "§6Range", + "Die *Reichweite*, in", + "der *Ambosse* spawnen" + ], + "item-anvil-rain-count-challenge": [ + "§6Anzahl", + "Die *Anzahl*, an *Ambossen*,", + "die in einem *Chunk* spawnen" + ], + "item-anvil-rain-damage-challenge": [ + "§6Schaden", + "Der *Schaden*, die", + "die *Ambosse* machen" + ], + "item-water-mlg-challenge": [ + "§bWater MLG", + "Du musst *immer wieder*", + "einen *Water MLG* absolvieren" + ], + "item-ender-games-challenge": [ + "§5Ender Games", + "Alle *paar Minuten* wirst du", + "mit einem *zufälligem Entity* aus", + "einem *200 Block* Radius *getauscht*" + ], + "item-random-event-challenge": [ + "§6Random Events", + "Alle *paar Minuten* wird eines von", + "*{0} random Events* aktiviert" + ], + "item-block-chunk-item-remove-challenge": [ + "§6Movement Item Remove", + "Es wird für jeden *Block* / *Chunk*,", + "den du dich *fortbewegst*, ein Item", + "aus deinem Inventar *gelöscht*" + ], + "item-block-chunk-item-remove-challenge-block": "§6Block", + "item-block-chunk-item-remove-challenge-chunk": "§6Chunk", + "item-higher-jumps-challenge": [ + "§aHigher Jumps", + "*Umso öfter* du springst,", + "*desto höher* springst du" + ], + "item-force-height-challenge": [ + "§eForce Height", + "Alle *paar Minuten* musst du auf", + "eine *bestimmte Höhe* oder du stirbst" + ], + "item-force-block-challenge": [ + "§6Force Block", + "Alle *paar Minuten* musst du auf", + "einen *bestimmten Block* oder du stirbst" + ], + "item-force-biome-challenge": [ + "§aForce Biome", + "Alle *paar Minuten* musst du in", + "ein *bestimmtes Biom* oder du stirbst", + "Je *seltener* das Biom ist, desto *mehr Zeit* hast du" + ], + "item-force-mob-challenge": [ + "§bForce Mob", + "Alle *paar Minuten* musst du", + "ein *bestimmtes Entity* killen oder du stirbst" + ], + "item-force-item-challenge": [ + "§6Force Item", + "Alle *paar Minuten* musst du", + "ein *bestimmtes Item* finden oder du stirbst" + ], + "item-random-item-challenge": [ + "§bRandom Items", + "Ein *zufälliger Spieler* erhält alle paar", + "*Sekunden* ein *zufälliges Item*" + ], + "item-always-running-challenge": [ + "§cAlways Running", + "Du kannst *nicht aufhören*, vorwärts zu laufen" + ], + "item-pickup-launch-challenge": [ + "§cPickup Boost", + "Wenn du ein *Item aufhebst*,", + "wirst du *in die Luft* geschleudert" + ], + "item-tsunami-challenge": [ + "§9Tsunami", + "In einem *gesetztem Intervall*", + "*steigt* das *Wasser* in der *Overworld*", + "und die *Lava* in im *Nether*", + " ", + "Sollte mit wenigen Personen gespielt werden!" + ], + "item-all-mobs-to-death-position-challenge": [ + "§cAlle Monster zum Todespunkt", + "Wenn ein *Mob* von einem Spieler", + "*getötet* wird, werden *alle* anderen", + "Monster vom *selben Typen* zum", + "*Todespunkt* teleportiert" + ], + "item-ice-floor-challenge": [ + "§bEisboden", + "Unter dir wird *Luft* zu einem", + "*3x3* Boden aus *Eis*" + ], + "item-blocks-disappear-time-challenge": [ + "§fBlöcke verschwinden nach Zeit", + "Blöcke, die du *platzierst*, *verschwinden*", + "nach ein *paar Sekunden* wieder" + ], + "item-missing-items-challenge": [ + "§9Items Fehlen", + "Alle paar Minuten *verschwindet* ein *Item* aus", + "deinem *Inventar* und du musst *erraten*, welches" + ], + "item-damage-item-challenge": [ + "§cSchaden pro Item", + "Wenn du ein *Item aufhebst* oder es", + "in deinem Inventar *anklickst* erleidest", + "du *0,5 ❤* multipliziert mit der Anzahl der Items" + ], + "item-damage-teleport-challenge": [ + "§cSchaden Random Teleport", + "Du wirst *zufällig teleportiert*,", + "wenn du *Schaden* erleidest" + ], + "item-loop-challenge": [ + "§6Wiederholungs Challenge", + "Verschiedene Aktionen *wiederholen* sich", + "unendlich oft, bis ein Spieler *schleicht*" + ], + "item-uncraft-challenge": [ + "§6Items craften sich zurück", + "Alle *Items* in deinem Inventar *craften*", + "sich alle paar Sekunden *zurück*" + ], + "item-freeze-challenge": [ + "§bFreeze Challenge", + "Für *jedes Herz*, das du *Schaden* erleidest, kannst", + "du dich für eine bestimmte Zeit *nicht bewegen*" + ], + "item-dont-stop-running-challenge": [ + "§9Nicht stehen bleiben", + "Du darfst nur eine bestimmte Zeit", + "*stehen bleiben* bevor du *stirbst*" + ], + "item-consume-launch-challenge": [ + "§cEssens Boost", + "Wenn du ein *Item isst*,", + "wirst du *in die Luft* geschleudert" + ], + "item-five-hundred-blocks-challenges": [ + "§5500 Blöcke", + "*Alle* 500 Blöcke, die du *läufst*,", + "bekommst du *64* eines *zufälliges Items*.", + "Es droppen *keine Items* von", + "*Blöcken* und *Entities* mehr." + ], + "item-level-border-challenges": [ + "§eLevel = Border", + "Die *Border-Größe* passt sich dem *Spieler*", + "mit den *meisten Leveln* an." + ], + "item-chunk-effect-challenge": [ + "§3Zufällige Chunk Effekte", + "In *jedem Chunk* bekommst du", + "einen *zufälligen Effekt*" + ], + "item-repeat-chunk-challenge": [ + "§2Wiederholende Chunks", + "Blöcke die *platziert oder zerstört* werden,", + "werden in *jedem Chunk* platziert / zerstört" + ], + "item-blocks-fly-challenge": [ + "§fBlöcke fliegen in die Luft", + "*Blöcke*, auf denen du *gelaufen* bist,", + "fliegen nach *einer Sekunde* in die *Luft*" + ], + "item-respawn-end-challenge": [ + "§5Mobs respawnen im End", + "Mobs, die *getötet werden*,", + "respawnen im *End*" + ], + "item-block-effect-challenge": [ + "§3Zufällige Block Effekte", + "Auf *jedem Block* bekommst du", + "einen *zufälligen Effekt*" + ], + "item-entity-effect-challenge": [ + "§5Mobs Haben Random Effekte", + "*Jedes Mob* hat einen zufälligen", + "Effekt auf *höchster Stufe*" + ], + "item-mob-damage-teleport-challenge": [ + "§5Mob Tausch Beim Schlagen", + "Jedes mal, wenn du einen *Mob schlägst*,", + "tauschst du mit einem *zufälligem Mob* die Position" + ], + "item-block-mob-challenge": [ + "§cMob Blöcke", + "Aus jedem abgebautem Block, *spawnt ein Mob*,", + "dass *getötet* werden muss, um den Block *zu erhalten*" + ], + "item-entity-loot-randomizer-challenge": [ + "§6Entity Loot Randomizer", + "Alle Mob Drops sind *zufällig vertauscht*." + ], + "item-no-shared-advancements-challenge": [ + "§2Keine Gleichen Advancements", + "Spieler dürfen *nicht* die *gleichen Advancements*", + "abschließen, sonst *stirbt* der *Spieler*" + ], + "item-chunk-deletion-challenge": [ + "§6Chunk Löschung", + "*Chunks*, in denen sich *Spieler* befinden,", + "werden nach gegebener *Zeit* komplett *gelöscht*" + ], + "item-delay-damage-description": [ + "§4Verzögerter Schaden", + "Der *schaden* von allen *Spielern* ist", + "zusammenaddiert und wird nach einer bestimmten *Zeit* hinzugefügt." + ], + "item-dragon-goal": [ + "§5Enderdrache", + "Töte den *Enderdrachen* um zu gewinnen" + ], + "item-wither-goal": [ + "§dWither", + "Töte einen *Wither* um zu gewinnen" + ], + "item-elder-guardian-goal": [ + "§bElder Guardian", + "Töte einen *Elder Guardian* um zu gewinnen" + ], + "item-warden-goal": [ + "§5Warden", + "Töte einen *Warden* um zu gewinnen" + ], + "item-iron-golem-goal": [ + "§bEisengolem", + "Töte einen *Eisengolem* um zu gewinnen" + ], + "item-snow-golem-goal": [ + "§bSchneemann", + "Töte einen *Schneemann* um zu gewinnen" + ], + "item-most-deaths-goal": [ + "§6Meiste Tode", + "Wer die meisten *verschiedenen Tode*", + "sammelt, *gewinnt*" + ], + "item-most-items-goal": [ + "§cMeisten Items", + "Wer die meisten *verschiedenen Items*", + "findet, *gewinnt*" + ], + "item-last-man-standing-goal": [ + "§cLast Man Standing", + "Wer *am Ende* noch *lebt*, gewinnt" + ], + "item-mine-most-blocks-goal": [ + "§eMeisten Blöcke", + "Wer die *meisten Blöcke* abbaut, gewinnt" + ], + "item-most-xp-goal": [ + "§aMeiste XP", + "Wer die meiste *XP sammelt*, gewinnt" + ], + "item-first-one-to-die-goal": [ + "§cErster Tod", + "Wer als *erstes stirbt*, gewinnt" + ], + "item-collect-wood-goal": [ + "§6Holzarten Sammeln", + "Wer als *erstes* alle *Holzarten*, die", + "*eingestellt* sind, gesammelt hat, gewinnt" + ], + "item-collect-wood-goal-overworld": "§aOverworld", + "item-collect-wood-goal-nether": "§cNether", + "item-collect-wood-goal-both": "§9Beide", + "item-all-bosses-goal": [ + "§bAlle Bosse", + "Es müssen *alle Bosse* einmal", + "*getötet* werden, um zu *gewinnen*" + ], + "item-all-bosses-new-goal": [ + "§5Alle Bosse (+ Warden)", + "Es müssen *alle Bosse* einmal", + "*getötet* werden, um zu *gewinnen*" + ], + "item-all-mobs-goal": [ + "§bAlle Mobs", + "Es müssen *alle Mobs* einmal", + "*getötet* werden, um zu *gewinnen*" + ], + "item-all-monster-goal": [ + "§bAlle Monster", + "Es müssen *alle Monster* einmal", + "*getötet* werden, um zu *gewinnen*" + ], + "item-all-items-goal": [ + "§2Alle Items", + "Finde *alle Items*, die es *in Minecraft gibt*" + ], + "item-finish-raid-goal": [ + "§6Raid Gewinnen", + "Der erste Spieler, der einen *Raid*", + "*abschließt*, gewinnt" + ], + "item-most-emeralds-goal": [ + "§2Meisten Emeralds", + "Der Spieler mit den *meisten*", + "*Emeralds* gewinnt" + ], + "item-all-advancements-goal": [ + "§6Alle Advancements", + "Der Spieler, der als erstes *alle*", + "Errungenschaften *erhalten hat*, gewinnt" + ], + "item-max-height-goal": [ + "§fMaximale Höhe", + "Der Spieler, der als *erstes* die", + "Höhe *{0}* erreicht hat, gewinnt" + ], + "item-min-height-goal": [ + "§fMinimale Höhe", + "Der Spieler, der als *erstes* die", + "Höhe *{0}* erreicht hat, gewinnt" + ], + "item-race-goal": [ + "§5Wettrennen", + "Der Spieler, der als *erstes* an", + "einer *zufälligen* Position ist, gewinnt" + ], + "item-most-ores-goal": [ + "§9Meiste Erze", + "Der Spieler, der am *meisten Erze*", + "*abgebaut* hat, gewinnt" + ], + "item-find-elytra-goal": [ + "§fElytra Finden", + "Der Spieler, der als *erstes*", + "eine *Elytra findet*, gewinnt" + ], + "item-eat-cake-goal": [ + "§fKuchen Essen", + "Der Spieler, der als *erstes*", + "einen *Kuchen isst*, gewinnt" + ], + "item-collect-horse-armor-goal": [ + "§bSammle Pferderüstungen", + "Der Spieler, der als *erstes*", + "*alle Pferderüstungen* hat, gewinnt" + ], + "item-collect-ice-goal": [ + "§bSammle Eisblöcke", + "Der Spieler, der als *erstes*", + "*alle Eisblöcke* und Schnee hat, gewinnt" + ], + "item-collect-swords-goal": [ + "§9Sammle Schwerter", + "Der Spieler, der als *erstes*", + "*alle Schwerter* hat, gewinnt" + ], + "item-collect-workstations-item": [ + "§6Sammle Arbeitsblöcke", + "Der Spieler, der als *erstes*", + "*alle Villager Arbeitsblöcke* hat, gewinnt" + ], + "item-eat-most-goal": [ + "§6Am Meisten Essen", + "Der Spieler, der am *meisten isst*, gewinnt" + ], + "item-force-item-battle-goal": [ + "§5Force Item Battle", + "Jeder Spieler bekommt ein *zufälliges Item*,", + "das er finden muss.", + "Wer am Ende die *meisten Items* hat, gewinnt" + ], + "menu-force-item-battle-goal-settings": "Force Item Battle", + "item-force-item-battle-goal-give-item": [ + "§bItem bei Skippen geben", + "Wenn ein Spieler ein Item *skippt*,", + "wird dieses in sein *Inventar hinzugefügt*" + ], + "item-force-mob-battle-goal": [ + "§bForce Mob Battle", + "Jeder Spieler bekommt ein *zufälliges Mob*,", + "das er töten muss." + ], + "menu-force-mob-battle-goal-settings": "Force Mob Battle", + "item-force-advancement-battle-goal": [ + "§6Force Advancement Battle", + "Jeder Spieler bekommt ein *zufälliges*", + "*Advancement*, welches er erreichen muss." + ], + "menu-force-advancement-battle-goal-settings": "Force Advancement Battle", + "item-force-block-battle-goal": [ + "§aForce Block Battle", + "Jeder Spieler bekommt einen *zufälligen*", + "*Block*, auf welchem er stehen muss" + ], + "menu-force-block-battle-goal-settings": "Force Block Battle", + "item-force-block-battle-goal-give-block": [ + "§bBlock bei Skippen geben", + "Wenn ein Spieler einen Block *skippt*,", + "wird dieser in sein *Inventar hinzugefügt*" + ], + "item-force-biome-battle-goal": [ + "§2Force Biome Battle", + "Jeder Spieler bekommt ein *zufälliges Biom*,", + "das er betreten muss" + ], + "menu-force-biome-battle-goal-settings": "Force Biome Battle", + "item-force-damage-battle-goal": [ + "§3Force Damage Battle", + "Jeder Spieler bekommt eine *zufällige Anzahl Schaden*,", + "die er *erhalten* muss" + ], + "menu-force-damage-battle-goal-settings": "Force Damage Battle", + "item-force-height-battle-goal": [ + "§6Force Height Battle", + "Jeder Spieler bekommt eine *zufällige Höhe*,", + "auf der er sich befinden muss." + ], + "menu-force-height-battle-goal-settings": "Force Height Battle", + "item-force-position-battle-goal": [ + "§aForce Position Battle", + "Jeder Spieler bekommt eine *zufällige Position*,", + "die er erreichen muss." + ], + "menu-force-position-battle-goal-settings": "Force Position Battle", + "item-extreme-force-battle-goal": [ + "§cExtreme Force Battle", + "Jeder Spieler bekommt ein *zufälliges Ziel*,", + "welches er erreichen muss" + ], + "menu-extreme-force-battle-goal-settings": "Extreme Force Battle", + "item-get-full-health-goal": [ + "§aRegeneriere Volle Leben", + "The first player to gain full health wins." + ], + "item-damage-rule-none": [ + "§6Genereller Schaden", + "Stellt ein, ob du Schaden bekommen kannst" + ], + "item-damage-rule-fire": [ + "§6Feuer Schaden", + "Stellt ein, ob du Schaden durch", + "*Lava* und *Feuer* bekommen kannst" + ], + "item-damage-rule-attack": [ + "§3Angriff Schaden", + "Stellt ein, ob du Schaden durch", + "*Nahkampfangriffe von Entities* bekommen kannst" + ], + "item-damage-rule-projectile": [ + "§6Projektil Schaden", + "Stellt ein, ob du Schaden durch", + "*Projektile* bekommen kannst" + ], + "item-damage-rule-fall": [ + "§fFallschaden", + "Stellt ein, ob du *Fallschaden* bekommen kannst" + ], + "item-damage-rule-explosion": [ + "§cExplosions Schaden", + "Stellt ein, ob du *Explosions Schaden* bekommen kannst" + ], + "item-damage-rule-drowning": [ + "§9Ertrink Schaden", + "Stellt ein, ob du Schaden durch", + "*Ertrinken* bekommen kannst" + ], + "item-damage-rule-block": [ + "§eBlock Schaden", + "Stellt ein, ob du Schaden durch", + "*Fallende Blöcke* bekommen kannst" + ], + "item-damage-rule-magic": [ + "§5Magie Schaden", + "Stellt ein, ob du Schaden durch", + "*Gift*, *Wither* und andere *Tränke* bekommen kannst" + ], + "item-damage-rule-freeze": [ + "§fFrost Schaden", + "Stellt ein, ob du Schaden durch", + "*Frost* bekommen kannst" + ], + "item-block-material": [ + "{0}", + "Stellt ein, ob *{1}*", + "genutzt werden *kann*" + ], + "custom-limit": "Du hast das Limit von §e{0} Challenges §7erreicht", + "custom-not-deleted": "Diese Challenge existiert noch nicht!", + "custom-saved": "§7Challenge wurde lokal §agespeichert", + "custom-saved-db": [ + "Um in §eDatenbank §7zu Speichern benutze §e/db save customs", + "§cAchtung: §7Alte Einstellungen werden dabei überschrieben!" + ], + "custom-no-changes": "Du hast an der Challenge §ckeine §7Änderungen gemacht", + "custom-name-info": "Schreibe den Namen der Challenge in den Chat", + "custom-command-info": [ + "Schreibe den Command den der Spieler ausführen soll §eohne / §7in den Chat", + "Erlaubte Commands: §e{0}", + "§cWeitere Commands können in der Config erlaubt werden" + ], + "custom-command-not-allowed": "Der Command §e{0} §7ist in der Config nicht als erlaubter Command angegeben", + "custom-chars-max_length": "Du hast die Maximale Anzahl von §e{0} Zeichen §7überschritten", + "custom-not-loaded": [ + " ", + "Es sind derzeit keine Custom Challenges geladen.", + "Du vermisst deine Challenges? §e/db load customs", + "Du hast Probleme beim Speichern?", + "Speichere vorm verlassen manuell §e/db save customs", + " " + ], + "custom-main-view-challenges": "§6Challenges Ansehen", + "custom-main-create-challenge": "§aChallenge Erstellen", + "custom-title-trigger": "Auslöser", + "custom-title-action": "Aktion", + "custom-title-view": "Gespeichert", + "custom-sub-finish": "§aFertig", + "item-custom-info-delete": [ + "§cLöschen", + "*Achtung* diese Aktion kann *nicht*", + "rückgängig gemacht werden" + ], + "item-custom-info-save": "§aSpeichern", + "item-custom-info-trigger": [ + "§cAuslöser", + "*Klicke* um einzustellen, was passieren", + "muss, damit die *Aktion* ausgeführt wird" + ], + "item-custom-info-action": [ + "§bAktion", + "*Klicke* um einzustellen, was passieren", + "soll, wenn der *Auslöser* erfüllt ist" + ], + "item-custom-info-material": [ + "§6Anzeige Item", + "*Klicke* um das Anzeigeitem zu ändern" + ], + "item-custom-info-name": [ + "§6Name", + "*Klicke* um den Namen über den Chat zu ändern", + "Maximale Zeichenanzahl: 50" + ], + "custom-info-currently": "§7Eingestellt §8» §e", + "custom-info-trigger": "§7Auslöser", + "custom-info-action": "§7Aktion", + "item-custom-trigger-jump": [ + "§aSpieler Springt" + ], + "item-custom-trigger-sneak": [ + "§aSpieler Schleicht" + ], + "item-custom-trigger-move_block": [ + "§6Spieler Läuft Einen Block" + ], + "item-custom-trigger-death": [ + "§cEntity Stirbt" + ], + "item-custom-trigger-damage": [ + "§cEntity Erleidet Schaden" + ], + "item-custom-trigger-damage-any": [ + "§aJeglicher Grund" + ], + "item-custom-trigger-damage_by_player": [ + "§cEntity Bekommt Schaden Von Spieler" + ], + "item-custom-trigger-intervall": [ + "§6Intervall" + ], + "item-custom-trigger-intervall-second": [ + "§6Jede Sekunde" + ], + "item-custom-trigger-intervall-seconds": [ + "§6Alle {0} Sekunden" + ], + "item-custom-trigger-intervall-minutes": [ + "§6Alle {0} Minuten" + ], + "item-custom-trigger-block_place": [ + "§aBlock Platziert" + ], + "item-custom-trigger-block_break": [ + "§cBlock Zerstört" + ], + "item-custom-trigger-consume_item": [ + "§2Item Konsumieren" + ], + "item-custom-trigger-pickup_item": [ + "§bItem Aufheben" + ], + "item-custom-trigger-drop_item": [ + "§9Spieler Droppt Item" + ], + "item-custom-trigger-advancement": [ + "§cSpieler Erhält Errungenschaft" + ], + "item-custom-trigger-hunger": [ + "§2Spieler Verliert Hunger" + ], + "item-custom-trigger-move_down": [ + "§6Block Nach Unten Bewegen" + ], + "item-custom-trigger-move_up": [ + "§6Block Nach Oben Bewegen" + ], + "item-custom-trigger-move_camera": [ + "§6Kamera Bewegen" + ], + "item-custom-trigger-stands_on_specific_block": [ + "§6Spieler Ist Auf Bestimmten Block" + ], + "item-custom-trigger-stands_not_on_specific_block": [ + "§6Spieler Ist Nicht Auf Bestimmten Block" + ], + "item-custom-trigger-gain_xp": [ + "§5Spieler Bekommt XP" + ], + "item-custom-trigger-level_up": [ + "§5Spieler Levelt Auf" + ], + "item-custom-trigger-item_craft": [ + "§6Spieler Craftet Item" + ], + "item-custom-trigger-in_liquid": [ + "§9Spieler In Flüssigkeit" + ], + "item-custom-trigger-get_item": [ + "§aItem bekommen", + "Aktion wird für *jedes* anklicken oder aufheben ausgeführt" + ], + "item-custom-action-cancel": [ + "§4Auslöser Abbrechen", + "Verhindert, dass der Auslöser ausgeführt wird.", + "Nicht abrechenbare Auslöser: *Springen*, *Sneaken*, *Töten*", + "*Advancement*, *Auf Leveln*, *In Flüssigkeit*" + ], + "item-custom-action-command": [ + "§4Command Ausführen", + "Lasse Spieler einen Command ausführen lassen", + "Die Commands werden für Spieler mit */execute as* von", + "der Konsole ausgeführt.", + "Erlaubte Commands werden in der Config eingestellt.", + "Der Spieler braucht *keine Rechte* auf den Command haben.", + "Spieler können *keine Plugin Commands* ausführen." + ], + "item-custom-action-kill": [ + "§4Töten", + "Töte Entities" + ], + "item-custom-action-damage": [ + "§cSchaden", + "Füge Entities Schaden zu" + ], + "item-custom-action-heal": [ + "§aHeilen", + "Heile Entities" + ], + "item-custom-action-hunger": [ + "§6Hunger", + "Füge Spielern Hunger hinzu" + ], + "item-custom-action-max_health": [ + "§cMaximale Leben Verändern", + "Verändere die Maximalen Leben von Spielern", + "Wird mit einem */gamestate reset* zurückgesetzt" + ], + "item-custom-action-max_health-offset": [ + "§cVeränderung", + "Wähle aus wie viele Leben verändert werden sollen" + ], + "item-custom-action-spawn_entity": [ + "§3Entity Spawnen", + "Spawne ein Entity bestimmten Types" + ], + "item-custom-action-random_mob": [ + "§6Zufälliges Entity", + "Spawne ein zufälliges Entity" + ], + "item-custom-action-random_item": [ + "§bZufälliges Item", + "Gebe Spielern zufällige Items" + ], + "item-custom-action-uncraft_inventory": [ + "§eInventar Zurück-Craften", + "Lasse das Inventar von Spielern Zurück-Craften" + ], + "item-custom-action-boost_in_air": [ + "§fIn Luft Schleudern", + "Schleudere Entities in die Luft" + ], + "item-custom-action-boost_in_air-strength": [ + "§fStärke" + ], + "item-custom-action-potion_effect": [ + "§dTrank Effekt", + "Gebe Entities einen bestimmten Trank Effekt" + ], + "item-custom-action-permanent_effect": [ + "§6Permanenten Trank Effekt", + "Füge Spieler einen Permanenten Effekt hinzu.", + "Die Aktion nutzt die Einstellungen", + "von der Permanenten Effekt Challenge." + ], + "item-custom-action-random_effect": [ + "§dZufälliger Trank Effekt", + "Gebe Entities einen zufälligen Trank Effekt" + ], + "item-custom-action-clear_inventory": [ + "§cInventar Leeren", + "Leere das Inventar von Spielern komplett" + ], + "item-custom-action-drop_random_item": [ + "§aItem Aus Inventar Droppen", + "Droppe ein Item aus dem Inventar auf den Boden" + ], + "item-custom-action-remove_random_item": [ + "§cItem Aus Inventar Entfernen", + "Entferne ein Item aus dem Inventar" + ], + "item-custom-action-swap_random_item": [ + "§6Items Im Inventar Tauschen", + "Tausche zwei Item im Inventar" + ], + "item-custom-action-freeze": [ + "§bFreeze", + "Friere Mobs Zeitweise ein.", + "Die Aktion nutzt die Einstellungen", + "von der Freeze On Damage Challenge." + ], + "item-custom-action-invert_health": [ + "§cInvert Health", + "Invertiere die Herzen eines Spielers.", + "Wenn du *8 Herzen* hast,", + "hast du danach *2 Herzen* und umgekehrt." + ], + "item-custom-action-water_mlg": [ + "§9Water MLG", + "Alle Spieler müssen einen Water MLG machen" + ], + "item-custom-action-jnr": [ + "§6Jump And Run", + "Ein zufälliger Spieler muss ein Jump And Run machen" + ], + "item-custom-action-win": [ + "§6Gewinnen", + "Die Challenge wird von *bestimmten Spielern* gewonnen" + ], + "item-custom-action-random_hotbar": [ + "§eZufällige Hotbar", + "Das Inventar wird geleert und der Spieler", + "bekommt zufällige Items in die HotBar" + ], + "item-custom-action-modify_border": [ + "§bWorld Border Verändern", + "Mache die Worldborder *größer* §7oder *kleiner*" + ], + "item-custom-action-modify_border-change": [ + "§dVeränderung" + ], + "item-custom-action-swap_mobs": [ + "§5Mobs tauschen", + "Tausche ein Mob mit einem zufälligen", + "anderem Mob aus der gleichen Welt" + ], + "item-custom-action-place_structure": [ + "§aStruktur Platzieren", + "Platziert eine Struktur" + ], + "item-custom-action-place_structure-random": "§bZufällige Struktur", + "item-custom-setting-target-current": [ + "§6Aktives Entity", + "Die Aktion wird für das *aktive Entity* ausgeführt" + ], + "item-custom-setting-target-every_mob": [ + "§4Alle Mobs", + "Die Aktion wird für *alle Mobs* ausgeführt" + ], + "item-custom-setting-target-every_mob_except_current": [ + "§4Alle Mobs Außer Aktives", + "Die Aktion wird für *alle Mobs*", + "*außer* das Aktive ausgeführt ausgeführt" + ], + "item-custom-setting-target-every_mob_except_players": [ + "§4Alle Mobs Außer Spieler", + "Die Aktion wird für *alle Mobs*", + "*außer* Spieler ausgeführt" + ], + "item-custom-setting-target-random_player": [ + "§5Zufälliger Spieler", + "Die Aktion wird für einen *zufälligen Spieler* ausgeführt" + ], + "item-custom-setting-target-every_player": [ + "§cAlle Spieler", + "Die Aktion wird für *jeden Spieler* ausgeführt" + ], + "item-custom-setting-target-current_player": [ + "§aAktiver Spieler", + "Die Aktion wird für den *aktiven Spieler* ausgeführt", + "§7§oWenn das Entity kein Spieler ist, wird nichts passieren" + ], + "item-custom-setting-target-console": [ + "§4Konsole", + "Die Aktion wird für die *Konsole* ausgeführt" + ], + "item-custom-setting-entity_type-any": "§cJegliches Entity", + "item-custom-setting-entity_type-player": "§aSpieler", + "item-custom-setting-block-any": "§2Jeglicher Block", + "item-custom-setting-item-any": "§2Jegliches Item", + "custom-subsetting-target_entity": "Ziel Entity", + "custom-subsetting-entity_type": "Entity Typ", + "custom-subsetting-liquid": "Flüssigkeit", + "custom-subsetting-time": "Zeit", + "custom-subsetting-damage_cause": "Schadens Art", + "custom-subsetting-amount": "Anzahl", + "custom-subsetting-value": "Werte Editor", + "custom-subsetting-health_offset": "Veränderung", + "custom-subsetting-length": "Länge", + "custom-subsetting-amplifier": "Stärke", + "custom-subsetting-change": "Veränderung", + "custom-subsetting-swap_targets": "Tausch Ziele" } diff --git a/language/files/en.json b/language/files/en.json index 9b7e2344d..57e13303d 100644 --- a/language/files/en.json +++ b/language/files/en.json @@ -1,1821 +1,1821 @@ { - "syntax": "Please use §e/{0}", - "reload": "Challenges Plugin is reloading...", - "reload-failed": "An §cerror &7occurred while reloading the plugin", - "reload-success": "Challenges Plugin §asuccessfully §7reloaded", - "player-command": "You must be a player!", - "no-permission": "You §cdon't §7have permissions to do this", - "enabled": "§aActivated", - "disabled": "§cDeactivated", - "customize": "§6Customize", - "navigate-back": "§8« §7Back", - "navigate-next": "§8» §7Next", - "seconds": "seconds", - "second": "second", - "minutes": "minutes", - "minute": "minute", - "hours": "hours", - "hour": "hour", - "amplifier": "amplifier", - "open": "Open", - "everyone": "§5Everyone", - "player": "§6Active player", - "none": "None", - "inventory-color": "§9", - "timer-counting-up": "§8» §7Timer counting §aup", - "timer-counting-down": "§8» §7Timer counting §cdown", - "timer-is-paused": "§8» §7Timer §cpaused", - "timer-is-running": "§8» §7Timer §astarted", - "confirm-reset": "Confirm reset with §e/{0}", - "no-fresh-reset": [ - "The Server §ccan't §7be reset yet", - "The Challenge §chasn't been §7started" - ], - "new-challenge": "§a§lNew!", - "feature-disabled": "This function is currently §cdeactivated", - "challenge-disabled": "This challenge is currently §cdeactivated", - "stopped-message": "§8• §7Timer §c§lpaused §8•", - "count-up-message": "§8• §7Time: §a§l{0} §8•", - "count-down-message": "§8• §7Time: §c§l{0} §8•", - "timer-not-started": "The timer §chasn't been started", - "timer-was-started": "The timer has been §astarted", - "timer-was-paused": "The timer has been §cpaused", - "timer-was-set": "The timer has ben set on §e§l{0}", - "timer-already-started": "The timer is §calready running", - "timer-already-paused": "The timer is §calready paused", - "timer-mode-set-down": "The timer is counting §cdown", - "timer-mode-set-up": "The timer is counting §aup", - "no-database-connection": "There is §cno §7database connection", - "fetching-data": "Data is being retrieved..", - "undefined": "undefined", - "no-such-material": "This material doesn't exist", - "not-an-item": "§e{0} §7is not an item", - "no-such-entity": "This entity doesn't exist", - "not-alive": "§e{0} §7is not a living entity", - "no-loot": "§e{0} §7doesn't have any drops", - "deprecated-plugin-version": [ - " ", - "An update for the plugin is available", - "Download: §e{0}", - " " - ], - "deprecated-config-version": [ - "The plugin config version is §coutdated §7(§c{1} §7< §a{0}§7)", - "You can either manually add all missing settings or delete the old one" - ], - "missing-config-settings": "There are missing config settings: §e{0}", - "missing-config-settings-separator": "§7, §e", - "no-missing-config-settings": [ - "§cThere are no missing config settings.", - "§cYou can manually update it to §c§l{0}" - ], - "unsuported-language": [ - "§cThe language §7(§e{0}§7) is not supported" - ], - "not-op":[ - "§7To use this plugin you need to have permissions. Give yourself permissions in the Server Console with: /op [name]" - ], - "join-message": "§e{0} §7has §ajoined §7the server", - "quit-message": "§e{0} §7has §cleft §7the server", - "timer-paused-message": [ - "The timer is §cpaused", - "Use §e/timer resume §7to start it" - ], - "cheats-detected": [ - "§e{0} §7has §ccheated", - "§cNo §7further statistics can be collected" - ], - "cheats-already-detected": [ - "On this server has been §ccheated", - "§cNo §7further statistics can be collected" - ], - "custom_challenges-reset": "The §elokal §7settings were reset §asuccessfully", - "config-reset": "The §elocal §7settings were reset §asuccessfully", - "player-config-loaded": "Your settings have been loaded §asuccessfully", - "player-config-saved": "Your settings have been saved §asuccessfully", - "player-config-reset": "Your settings were reset §asuccessfully", - "player-custom_challenges-loaded": "Your challenges have been loaded §asuccessfully", - "player-custom_challenges-saved": "Your challenges have been saved §asuccessfully", - "player-custom_challenges-reset": "Your challenges were §asuccessfully §7reset", - "item-prefix": "§8» ", - "item-setting-info": "§8➟ {0}", - "stat-dragon-killed": "Dragons killed", - "stat-deaths": "Deaths", - "stat-entity-kills": "Kills", - "stat-damage-dealt": "Damage dealt", - "stat-damage-taken": "Damage taken", - "stat-blocks-mined": "Blocks destroyed", - "stat-blocks-placed": "Blocks placed", - "stat-blocks-traveled": "Blocks travelled", - "stat-challenges-played": "Challenges played", - "stat-jumps": "Jumps", - "stats-of": "§8» §7Stats of §e{0}", - "stats-display": "§8» §7{0} §8(§e{1}. §7Platz§8)", - "stats-leaderboard-display": [ - "§8» §e{0}", - "§8§l┣ §7{1} §7{2}", - "§8§l┗ §e{3}. §7Place" - ], - "position": "§e{4} §8- §7{0}, {1}, {2} §8(§e{3}§8) §8┃ §e{5}m", - "positions-disabled": "Positions are §cdeactivated", - "position-other-world": "This position is in another world §8(§e{0}§8)", - "position-not-exists": "The position §e{0} §cdoesn't §7exist", - "position-already-exists": "The position {0} §calready §7exist", - "position-set": "§e{5} §7created position §e{4} §7{0}, {1}, {2} §8(§e{3}§8)", - "position-deleted": "§e{5} §7deleted §e{4} §7{0}, {1}, {2} §8(§e{3}§8)", - "no-positions": [ - "There are no §epositions §7set in this world", - "Create on with §e/{0}" - ], - "no-positions-global": [ - "There are no §epositions §7set", - "Create on with §e/{0}" - ], - "command-no-target": "§cNo §7players has been found", - "command-heal-healed": "You have been §ahealed", - "command-heal-healed-others": "You healed §e{0} player/s", - "command-gamemode-gamemode-changed": "Your gamemode has been changed to §e{0}", - "command-gamemode-gamemode-changed-others": "The gamemode of §e{1} §7player/s has been changed to §e{0}", - "command-village-search": "A village is being searched..", - "command-village-teleport": "You have been §ateleported to a village", - "command-village-not-found": "§cNo §7new village was found", - "command-weather-set-clear": "Weather was changed to §eclear", - "command-weather-set-rain": "Weather was changed to §erainy", - "command-weather-set-thunder": "Weather was changed to §ethundery", - "command-invsee-open": "Inventory of §e{0} §7opened", - "command-enderchest-open": "You opened your §5Enderchest", - "command-difficulty-change": "Difficulty changed to {0}", - "command-difficulty-current": "Current difficulty is {0}", - "command-search-nothing": "§e{0} §7is not dropped by any special block", - "command-search-result": "§e{0} §7drops from §e{1}", - "command-searchloot-disabled": "The entity loot randomizer challenge is currently §cdeactivated", - "command-searchloot-nothing": "The loot of §e{0} §7isn't dropped by any specific entity", - "command-searchloot-result": [ - "§e{0} §7drops the loot of §e{1}", - "The loot of §e{0} §7is dropped by §e{2}" - ], - "command-time-set": "Time was changed to §e{0} §7Ticks §8(§7ca. §e{1}§8)", - "command-time-set-exact": "Time was changed to §e{0} §8(§e{1} §7Ticks§8)", - "command-time-query": [ - "§8» §7Current ingame times", - "Playtime §e{0} §7Ticks §8(§7Tag §e{1}§8)", - "Time of day §e{2} §7Ticks §8(§7ca. §e{3}§8)" - ], - "command-time-noon": "Noon", - "command-time-night": "Night", - "command-time-midnight": "Midnight", - "command-time-day": "Day", - "command-fly-enabled": "You can fly §anow", - "command-fly-disabled": "You can §cno longer §7fly", - "command-fly-toggled-others": "You toggled §efly §7for §e{0} §7player/s", - "command-feed-fed": "Your appetite was §esated", - "command-feed-others": "You satiated the appetite of §e{0} §7player/s", - "command-gamestate-reload": "The gamestate was §areloaded", - "command-gamestate-reset": "The gamestate was §areset", - "command-world-teleport": "You'll be teleported into the §e{0}", - "command-back-no-locations": "You §cweren't §7teleported yet", - "command-back-teleported": "You were teleported §e{0} §7location back", - "command-back-teleported-multiple": "You were teleported §e{0} §7locations back", - "command-result-no-battle-active": "There is currently §cno §7Force Battle enabled", - "command-god-mode-enabled": "You are now in §aGod mode", - "command-god-mode-disabled": "You are §cno longer in God mode", - "command-god-mode-toggled-others": "§e{0} §7players are now in §eGod mode", - "traffic-light-challenge-fail": "§e{0} §7went over §cred", - "player-damage-display": "§e{0} §7took §7{1} §7damage by §e{2}", - "death-message": "§e{0} §7died", - "death-message-cause": "§e{0} §7died by §e{1}", - "health-inverted": "Your hearts have been §cinverted", - "exp-picked-up": "§e{0} §7collected §cEXP", - "unable-to-find-fortress": "§cNo fortress §7could be found", - "unable-to-find-bastion": "§cNo bastion §7could be found", - "death-collected": "Death reason §e{0} §7registered", - "item-collected": "Item §e{0} §7registered", - "items-to-collect": "§7Items to collect §8» §e{0}", - "backpacks-disabled": "Backpacks are currently §cdeactivated", - "backpack-opened": "You opened the {0}", - "top-to-overworld": "You have been teleported to the §eoverworld", - "top-to-surface": "You have been teleported to the §etop", - "jnr-countdown": "Next §6JumpAndRun §7in §e{0} seconds", - "jnr-countdown-one": "Next §6JumpAndRun §7in §eone second", - "jnr-finished": "§e{0} §afinished §7the §6JumpAndRun", - "snake-failed": "§e{0} §7stepped over the §9line", - "only-dirt-failed": "§e{0} §7did not stand on dirt", - "no-mouse-move-failed": "§e{0} §7moved his mouse", - "no-duped-items-failed": "§e{0} §7and §e{1} §7both had §e{2} §7in their inventory", - "only-down-failed": "§e{0} §7went up one block", - "food-once-failed": "§e{0} §7suffocated by §e{1}", - "food-once-new-food-team": "§e{0} §7ate §e{1}", - "food-once-new-food": "§eYou §7ate §e{1}", - "sneak-damage-failed": "§e{0} §7sneaked", - "jump-damage-failed": "§e{0} §7jumped", - "random-challenge-enabled": "The challenge §e{0} §7has been §aactivated", - "all-items-skipped": "Item §e{0} §7skipped", - "all-items-already-finished": "All items has been already found", - "all-items-found": "Item §e{0} §7registered by §e{1}", - "mob-kill": "§e{0} §ehas been killed §8(§e{1} §7/ §e{2}§8)", - "endergames-teleport": "Swapped with §e{0}", - "force-height-fail": "§e{0} §7was on the §cwrong §7height §8(§e{1}§8)", - "force-height-success": "All players were on the §aright §7height", - "force-block-fail": "§e{0} §7was on the §cwrong §7block §8(§e{1}§8)", - "force-block-success": "All players were on the §aright §7block", - "force-biome-fail": "The biome §e{0} §chasn't been found", - "force-biome-success": "§e{0} §7found the biome §e{1}", - "force-mob-fail": "The mob §e{0} §chasn't been killed", - "force-mob-success": "§e{0} §7killed the mob §e{1}", - "force-item-fail": "Item §e{0} §chasn't been found", - "force-item-success": "§e{0} §afound §7the item §e{1}", - "new-effect": "Effect §e{0} §8➔ §e{1}", - "missing-items-inventory": "{0}Which item is missing?", - "missing-items-inventory-open": "§8[§aOpen GUI§8]", - "loops-cleared": "§e{0} §7Loops cancelled", - "stopped-moving": "§e{0} §7hasn't moved for too long", - "all-advancements-goal": "§7Advancements §8» §e{0}", - "height-reached": "§e{0} §7reached §eY = {1} §7first!", - "race-goal-reached": "§e{0} §7reached the goal!", - "points-change": "§e{0} §7Points", - "force-item-battle-found": "You've found §e{0}!", - "force-item-battle-new-item": "Item to find: §e{0}", - "force-item-battle-leaderboard": "§8➜ §7Force Item Battle Leaderboard", - "force-mob-battle-killed": "You've killed §e{0}!", - "force-mob-battle-new-mob": "Mob to kill: §e{0}", - "force-mob-battle-leaderboard": "§8➜ §7Force Mob Battle Leaderboard", - "force-advancement-battle-completed": "You've completed §e{0}!", - "force-advancement-battle-new-advancement": "Nächstes Advancement: §e{0}", - "force-advancement-battle-leaderboard": "§8➜ §7Force Advancement Battle Leaderboard", - "force-block-battle-found": "You've found §e{0}!", - "force-block-battle-new-block": "Block to find: §e{0}", - "force-block-battle-leaderboard": "§8➜ §7Force Block Battle Leaderboard", - "force-battle-leaderboard-entry": "{0}#{1} §8» §e{2} §8┃ §e{3}", - "force-battle-block-target-display": "§eBlock: {0}", - "force-battle-item-target-display":"§eItem: {0}", - "force-battle-height-target-display": "§eHeight: {0}", - "force-battle-mob-target-display": "§eMob: {0}", - "force-battle-biome-target-display": "§eBiome: {0}", - "force-battle-damage-target-display": "§eDamage: §c{0} ❤", - "force-battle-advancement-target-display": "§eAdvancement: {0}", - "force-battle-position-target-display": "§ePosition: {0}", - "extreme-force-battle-new-height": "Height to reach: §e{0}", - "extreme-force-battle-reached-height": "You've reached height §e{0}!", - "extreme-force-battle-new-biome": "Biome to find: §e{0}", - "extreme-force-battle-found-biome": "You've found the biome §e{0}!", - "extreme-force-battle-new-damage": "Damage to take: §c{0} ❤", - "extreme-force-battle-took-damage": "You took §c{0} ❤ §7damage!", - "extreme-force-battle-position": "§eX: {0} §8┃ §eZ: {1}", - "extreme-force-battle-new-position": "Position to reach: §e{0}", - "extreme-force-battle-reached-position": "You've reached the position §e{0}!", - "extreme-force-battle-leaderboard": "§8➜ §7Extreme Force Battle Leaderboard", - "force-biome-battle-leaderboard": "§8➜ §7Force Biome Battle Leaderboard", - "force-damage-battle-leaderboard": "§8➜ §7Force Damage Battle Leaderboard", - "force-height-battle-leaderboard": "§8➜ §7Force Height Battle Leaderboard", - "force-position-battle-leaderboard": "§8➜ §7Force Position Battle Leaderboard", - "random-event-speed": [ - "Sonic? Is it you?", - "Woahh! That's fast" - ], - "random-event-entities": [ - "Is this a zoo?", - "Where did this come from?", - "What are you doing here?" - ], - "random-event-hole": [ - "But you fell pretty deep", - "From the very top to the very bottom..", - "Where did this hole come from?" - ], - "random-event-fly": [ - "Good flight :)", - "I believe I can fly..", - "So this is what flying feels like" - ], - "random-event-webs": [ - "Have they been here for a long time?" - ], - "random-event-ores": [ - "Where did all the ores go?", - "Aren't there any ores here?", - "Was there any ore here??" - ], - "random-event-sickness": [ - "Are you sick??", - "What's going on now?!" - ], - "bossbar-timer-paused": "§8» §7The timer is §cpaused", - "bossbar-mob-transformation": "§8» §7Last mob §8§l┃ §a{0}", - "bossbar-biome-time-left": "§8» §7Time left in §e{0} §8§l┃ §a{1}s", - "bossbar-height-time-left": "§8» §7Time left on §e{0} §8§l┃ §a{1}s", - "bossbar-zero-hearts": "§8» §7Protection time §8§l┃ §a{0}s", - "bossbar-random-challenge-waiting": "§8» §7Waiting for new challenge..", - "bossbar-random-challenge-current": "§8» §7Challenge §e{0}", - "bossbar-all-items-current-max": "§8» §f{0} §8┃ §7{1} §8/ §7{2}", - "bossbar-all-items-finished": "§8» §7All items found", - "bossbar-force-height-waiting": "§8» §7Waiting for next height..", - "bossbar-force-height-instruction": "§8» §7Height §e{0} §8┃ §a{1}", - "bossbar-force-block-waiting": "§8» §7Waiting for next block..", - "bossbar-force-block-instruction": "§8» §7Block §e{0} §8┃ §a{1}", - "bossbar-force-biome-waiting": "§8» §7Waiting for next biome..", - "bossbar-force-biome-instruction": "§8» §7Biome §e{0} §8┃ §a{1}", - "bossbar-force-mob-waiting": "§8» §7Waiting for next mob..", - "bossbar-force-mob-instruction": "§8» §7Mob §e{0} §8┃ §a{1}", - "bossbar-force-item-waiting": "§8» §7Waiting for next item..", - "bossbar-force-item-instruction": "§8» §7Item §e{0} §8┃ §a{1}", - "bossbar-tsunami-water": "§8» §7Waterheight: §9{0}", - "bossbar-tsunami-lava": "§8» §7Lavaheight: §c{0}", - "bossbar-ice-floor": "§8» §bIce floor §8┃ {0}", - "bossbar-dont-stop-running": "§8» §7Move in §8┃ §e{0}", - "bossbar-five-hundred-blocks": "§8» §fBlocks Walked §8┃ §7{0} §8/ §7{1}", - "bossbar-level-border": "§8» §7Border size §8┃ §7{0}", - "bossbar-race-goal-info": "§8» §fGoal §8┃ §7X: {0} §8/ §7Z: {1} §8┃ §e{2} Blocks", - "bossbar-race-goal": "§8» §fGoal §8┃ §7X: {0} §8/ §7Z: {1}", - "bossbar-first-at-height-goal": "§8» §fGoal §8┃ §7Y: {0}", - "bossbar-respawn-end": "§8» §5Respawned Mobs in End §8┃ §e{0}", - "bossbar-kill-all-bosses": "§8» §cAll Bosses §8┃ §e{0}/{1}", - "bossbar-kill-all-mobs": "§8» §cAll Mobs §8┃ §e{0}/{1}", - "bossbar-kill-all-monster": "§8» §cAll Monsters §8┃ §e{0}/{1}", - "bossbar-chunk-deletion": "§8» §7Time left in chunk §6{0}s", - "subtitle-time-seconds": "§e{0} §7seconds", - "subtitle-time-seconds-range": "§e{0}-{1} §7seconds", - "subtitle-time-minutes": "§e{0} §7minutes", - "subtitle-launcher-description": "§7Power §e{0}", - "subtitle-blocks": "§e{0} §7Blocks", - "subtitle-range-blocks": "§eRange: §e{0} §7Blöcke", - "scoreboard-title": "§7» §f§lChallenge", - "scoreboard-leaderboard": "§e#{0} §8┃ §7{1} §8» §e{2}", - "your-place": "§7Your place §8» §e{0}", - "server-reset": [ - "§8————————————————————", - " ", - "§8» §cServer reset", - " ", - "§7Reset by §4§l{0}", - "§7The server is §crestarting", - " ", - "§8————————————————————" - ], - "challenge-end-timer-hit-zero": [ - " ", - "§cThe challenge is over!", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-timer-hit-zero-winner": [ - " ", - "§cThe challenge is over!", - "§7Gewinner: §e§l{1}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-reached": [ - " ", - "§7The challenge was ended!", - "§7Time needed: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-reached-winner": [ - " ", - "§7The challenge was ended!", - "§7Winner: §e§l{1}", - "§7Time needed: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-failed": [ - " ", - "§cThe challenge is over! §6#FeelsBadMan ✞", - "§7Time wasted: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "title-timer-started": [ - " ", - "§8» §7Timer §acontinued" - ], - "title-timer-paused": [ - " ", - "§8» §7Timer §cpaused" - ], - "title-challenge-enabled": [ - "§e{0}", - "§2§l✔ §8┃ §aActivated" - ], - "title-challenge-disabled": [ - "§e{0}", - "§4✖ §8┃ §cDeactivated" - ], - "title-challenge-value-changed": [ - "§e{0}", - "§8» §e{1}" - ], - "title-pregame-movement-setting": [ - "§cWarte..", - "§8» §7Timer is stopped.." - ], - "item-menu-start": "§8• §aStart Challenge §8┃ §e/start §8•", - "item-menu-challenges": "§8• §cChallenges §8┃ §e/challenge §8•", - "item-menu-timer": "§8• §5Timer §8┃ §e/timer §8•", - "item-menu-leaderboard": "§8• §6Leaderboard §8┃ §e/leaderboard §8•", - "item-menu-stats": "§8• §2Statistics §8┃ §e/stats §8•", - "menu-title": "Menu", - "menu-timer": "§6Timer", - "menu-goal": "§5Goal", - "menu-damage": "§7Schaden", - "menu-item_blocks": "§4Blocks & Items", - "menu-challenges": "§cChallenges", - "menu-settings": "§eSettings", - "menu-custom": "§aCustom Challenges", - "lore-category-activated-count": "§7Activated §8» §a{0}§8/§7{1}", - "lore-category-activated": "§7Activated §8» §aYes", - "lore-category-deactivated": "§7Activated §8» §cNo", - "category-misc_challenge": [ - "§9Miscellaneous", - "Challenges that *couldn't be*", - "*assigned* with a category" - ], - "category-randomizer": [ - "§6Randomizer", - "Experience a *randomized gameplay*" - ], - "category-limited_time": [ - "§aLimited Time", - "Some things are timely restricted" - ], - "category-force": [ - "§3Force", - "You have to fulfill specific", - "*intermediate goals* to survive" - ], - "category-world": [ - "§4World Change", - "The world will be *modified* significant" - ], - "category-damage": [ - "§cSchaden", - "New *damage rules*" - ], - "category-effect": [ - "§5Effekte", - "Have fun with *lots of effects*" - ], - "category-inventory": [ - "§6Inventory", - "You'll have problems managing *your inventory*" - ], - "category-movement": [ - "§aBewegung", - "You're *restricted in your movements*" - ], - "category-entities": [ - "§bEntities", - "Entities will be *modified*" - ], - "category-extra_world": [ - "§aExtra Welt", - "Challenges that will *send*", - "you to *another world*" - ], - "category-misc_goal": [ - "§9Miscellaneous", - "Goals that *couldn't be*", - "*assigned* with a category" - ], - "category-kill_entity": [ - "§cEntities töten", - "Kill *specific entities* to win" - ], - "category-score_points": [ - "§eBest Score", - "Get the best score *to win*" - ], - "category-fastest_time": [ - "§6Fastest Time", - "Be the fastest *to win*" - ], - "category-force_battle": [ - "§bForce Battles", - "Fulfill the given *intermediate goals*", - "to earn points.", - " ", - "The player with the *most points* wins." - ], - "item-time-seconds-description": "§8» §7Time: §e{0} §7seconds", - "item-time-seconds-range-description": "§8» §7Time: §e{0}-{1} §7Sekunden", - "item-time-minutes-description": "§8» §7Time: §e{0} §7minutes", - "item-heart-damage-description": "§8» §7Damage: §e{0} §c❤", - "item-heart-start-description": "§8» §7Start: §e{0} §c❤", - "item-max-health-description": "§8» §7Max health: §e{0} §c❤", - "item-chance-description": "§8» §7Chance: §e{0}%", - "item-launcher-description": "§8» §7Strength: §e{0}", - "item-permanent-effect-target-player-description": "§8» §7Only the active players gets the effect", - "item-permanent-effect-target-everyone-description": "§8» §7All players are getting the effect", - "item-blocks-description": "§8» Blocks to walk: §e{0}", - "item-range-blocks-description": "§8» §7Range: §e{0} §7Block", - "item-force-battle-goal-jokers": [ - "§6Number of jokers", - "The *amount* of *jokers*", - "hat every player has" - ], - "item-force-battle-show-scoreboard": [ - "§bShow Scoreboard" - ], - "item-force-battle-duped-targets": [ - "§cDuped Targets", - "Targets can occur *multiple times*" - ], - "item-force-position-battle-radius": [ - "§bRadius", - "The *maximum radius*, in which the", - "positions will be located" - ], - "item-difficulty-setting": [ - "§aDifficulty", - "Sets the *Difficulty*" - ], - "item-language-setting": [ - "§bLanguage", - "Sets the *Language*" - ], - "item-language-setting-german": "§fDeutsch", - "item-language-setting-english": "§fEnglish", - "item-one-life-setting": [ - "§cOne Teamlife", - "*Everyone* dies when *one player dies*" - ], - "item-respawn-setting": [ - "§4Respawn", - "When you *die*, you won't be a *spectator*" - ], - "item-death-message-setting": [ - "§6Death messages", - "Toggles *death messages*" - ], - "item-death-message-setting-vanilla": "§6Vanilla", - "item-pvp-setting": [ - "§9PvP" - ], - "item-max-health-setting": [ - "§cMax health", - "Sets the *max health*", - "for *all players*" - ], - "item-soup-setting": [ - "§cSoup healing", - "When you use a *mushroom soup*", - "you will be healed for *4 hearts*" - ], - "item-damage-setting": [ - "§cDamage Multiplier", - "Damage you take will be *multiplied*" - ], - "item-damage-display-setting": [ - "§eDamage Display", - "It will be displayed in the *chat*", - "when anybody takes *damage*" - ], - "item-health-display-setting": [ - "§cHealth Display", - "The *hearts* of all players", - "will be showed in the *tablist*" - ], - "item-position-setting": [ - "§9Positions", - "Allows you to mark *positions*", - "with */pos*" - ], - "item-backpack-setting": [ - "§6Backpack", - "Allows you to open *your backpack* or", - "the *team backpack* with */backpack*" - ], - "item-backpack-setting-team": "§5Team", - "item-backpack-setting-player": "§6Player", - "item-cut-clean-setting": [ - "§9CutClean", - "Different *settings* to simplify", - "the *farming* of items" - ], - "menu-cut-clean-setting-settings": "CutClean", - "item-cut-clean-gold-setting": [ - "§6Gold", - "*Gold ore* will be directly dropped as *Gold ingot*" - ], - "item-cut-clean-iron-setting": [ - "§7Iron", - "*Iron ore* will be directly dropped as *Iron ingot*" - ], - "item-cut-clean-coal-setting": [ - "§eCoal", - "*Coal* will be directly dropped as *torches*" - ], - "item-cut-clean-flint-setting": [ - "§eFlint", - "*Gravel* will always drop *flint*" - ], - "item-cut-clean-vein-setting": [ - "§eOre Veins", - "*Ore veins* will be directly destroyed" - ], - "item-cut-clean-inventory-setting": [ - "§6Direct Into Inventory", - "*Items* will be put *directly* into your", - "*inventory* instead of dropping" - ], - "item-cut-clean-food-setting": [ - "§cCooked Food", - "*Raw meat* will be directly dropped as *cooked meat*" - ], - "item-glow-setting": [ - "§fPlayer Glow", - "*Players* are visible through *walls*" - ], - "no-hunger-setting": [ - "§cNo Hunger", - "You don't get *hungry*" - ], - "pregame-movement-setting": [ - "§6Pregame Movement", - "You can *move* before", - "the game has been *started*" - ], - "item-no-hit-delay-setting": [ - "§fNoHitDelay", - "After you've *taken* damage", - "you can *get* damage *immediately* again" - ], - "item-timber-setting": [ - "§bTimber", - "You can destroy a *tree*", - "by breaking down *a single block* of the tree" - ], - "item-timber-setting-logs": "§6Logs", - "item-timber-setting-logs-and-leaves": "§6Logs §7and §2Leaves", - "item-keep-inventory-setting": [ - "§5Keep Inventory", - "You don't lose any *items*", - "when you die" - ], - "item-mob-griefing-setting": [ - "§5Mob Griefing", - "Monsters *can't destroy* anything" - ], - "item-no-item-damage-setting": [ - "§5No Item Damage", - "*Items* are *unbreakable*" - ], - "top-command-setting": [ - "§dTop Command", - "You can *teleport* to the *top*", - "of the world or to the *overworld*", - "with /top" - ], - "item-fortress-spawn-setting": [ - "§cFortress Spawn", - "When you go into the *nether*", - "you will always spawn in a *fortress*" - ], - "item-bastion-spawn-setting": [ - "§cBastion Spawn", - "When you go into the *nether*", - "you will always spawn in a *bastion*" - ], - "item-no-offhand-setting": [ - "§6No Offhand", - "The *second hand* will be blocked" - ], - "item-regeneration-setting": [ - "§cRegeneration", - "Sets *whether* and", - "*how* to *regenerate*" - ], - "item-regeneration-setting-not_natural": "§6Not Natural", - "item-immediate-respawn-setting": [ - "§6Direct Respawn", - "When you *die* you *respawn* automatically", - "*without* seeing the *death screen*" - ], - "item-slot-limit-setting": [ - "§4Inventory Slots", - "Sets how many *inventory*", - "*slots* are useable" - ], - "item-death-position-setting": [ - "§cDeath Position", - "When you die, */pos* creates", - "a position at your death point" - ], - "item-enderchest-command-setting": [ - "§5Enderchest Command", - "When you execute */ec*,", - "your *Enderchest* opens" - ], - "item-split-health-setting": [ - "§cSplit Health", - "Sets whether *all players*", - "share the same *health*" - ], - "item-old-pvp-setting": [ - "§b1.8 PvP", - "The *old 1.8 PvP System* will be used", - "There will be no *attack damage cooldown*" - ], - "item-totem-save-setting": [ - "§6Challenge Death Rescue", - "If you *instant die* from a *challenge*", - "*totems* can *rescue* you" - ], - "item-traffic-light-challenge": [ - "§cTraffic Light Challenge", - "The *traffic light* switches every few minutes.", - "If you go on *red*, you die" - ], - "item-block-randomizer-challenge": [ - "§6Block Randomizer", - "Each *block* drops a *random item*" - ], - "item-crafting-randomizer-challenge": [ - "§6Crafting Randomizer", - "If you *craft* something you will get another *random item*" - ], - "item-mob-randomizer-challenge": [ - "§6Mob Randomizer", - "When an *Entity* spawns, it spawns *twice*" - ], - "item-hotbar-randomizer-challenge": [ - "§6HotBar Randomizer", - "Every *few minutes* every player gets *random items*" - ], - "item-damage-block-challenge": [ - "§4Damage per Block", - "You take *damage* for", - "every *block* you walk" - ], - "item-hunger-block-challenge": [ - "§6Hunger per Block", - "You lose *food* for", - "every *block* you walk" - ], - "item-stone-sight-challenge": [ - "§fStone Sight", - "*Mobs* that you look in the", - "*eyes* turn to stone" - ], - "item-no-mob-sight-challenge": [ - "§cMob Sight Damage", - "When you look into the *eyes* of an", - "*entity*, you get *damage*" - ], - "item-bedrock-path-challenge": [ - "§7Bedrock Path", - "*Bedrock *generates* under you*", - "the whole time" - ], - "item-bedrock-walls-challenge": [ - "§7Bedrock Walls", - "Huge *walls of bedrock*", - "are *generating* behind you" - ], - "item-surface-hole-challenge": [ - "§cSurface Hole", - "The *floor* is disappearing", - "to *void* behind you" - ], - "item-damage-inv-clear-challenge": [ - "§cDamage Inventory Clear", - "Player *inventories* are *cleared*", - "when a *player* takes damage" - ], - "item-no-trading-challenge": [ - "§2No Trading", - "You *cannot* trade", - "with villagers" - ], - "item-block-break-damage-challenge": [ - "§6Block Break Damage", - "If you *break* a *block*, you", - "will *take* the set amount of *damage*" - ], - "item-block-place-damage-challenge": [ - "§6Block Place Damage", - "If you *place* a *block*, you", - "will *take* the set amount of *damage*" - ], - "item-no-exp-challenge": [ - "§aNo EXP", - "If you pickup *EXP* you die" - ], - "item-invert-health-challenge": [ - "§cInvert Health", - "Every few minutes the *hearts are inverted*.", - "If you have *8 hearts*, you will have *2 hearts*", - "and the other way around" - ], - "item-jump-and-run-challenge": [ - "§6Jump and Run", - "Every *few minutes* you have to do a random", - "*jump and run* which gets *harder* every time" - ], - "item-randomized-hp-challenge": [ - "§4Randomized HP", - "The *health* of all mobs", - "is randomized" - ], - "item-snake-challenge": [ - "§9Snake", - "Each player draws a *deadly line*", - "behind them" - ], - "item-reversed-damage-challenge": [ - "§cReversed Damage", - "If you deal damage to entites", - "you take the same damage" - ], - "item-duped-spawning-challenge": [ - "§cDuped Spawning", - "If a mob *spawns*", - "it spawns *two times*" - ], - "item-hydra-challenge": [ - "§5Hydra", - "If you *kill* a mob", - "*two new* are spawning" - ], - "item-hydra-plus-challenge": [ - "§cHydra Plus", - "If you kill a *mob* it", - "spawns *twice* as many", - "times as the *previous* time", - " ", - "Maximum are *512* Mobs each time" - ], - "item-floor-lava-challenge": [ - "§6The Floor Is Lava", - "*Blocks* below you transform first", - "to *magma* and then to *lava*" - ], - "item-only-dirt-challenge": [ - "§cOnly Dirt", - "You must stay on *dirt*", - "otherwise you will *die*" - ], - "item-food-once-challenge": [ - "§cFood Once", - "Each *food* can be*", - "*eaten* only once" - ], - "item-food-once-challenge-player": "§6Player", - "item-food-once-challenge-everyone": "§5Everyone", - "item-chunk-deconstruction-challenge": [ - "§bChunk Deconstruction", - "*Chunks* that players are in", - "*break* down from *above*" - ], - "item-one-durability-challenge": [ - "§4One Durability", - "Items are *destroyed* after one *use*" - ], - "item-low-drop-rate-challenge": [ - "§6Low Drop Chance", - "The *drop chance* of each *block*", - "will be set to the defined *percentage*" - ], - "item-invisible-mobs-challenge": [ - "§fInvisible Mobs", - "All *Mobs* have an", - "*invisibility* effect" - ], - "item-mob-transformation-challenge": [ - "§cMob Transformation", - "When you hit a mob, it *turns*", - "into the last mob *you* hit" - ], - "item-jump-entity-challenge": [ - "§2Jump Entity", - "A *random entity* spawns", - "everytime you *jump*" - ], - "item-no-mouse-move-challenge": [ - "§cMouse Movement Damage", - "You take *damage* everytime", - "you *move* your *view*" - ], - "item-no-duped-items-challenge": [ - "§6No Duped Items", - "Players are *not allowed* to have", - "the *same item* in their *inventories*", - "at the same time" - ], - "item-infection-challenge": [ - "§aInfection Challenge", - "You have to keep *2 blocks* away", - "from all *mobs* or you will *get* sick" - ], - "item-only-down-challenge": [ - "§cOnly Down", - "If you go *up* by *a block*, you *die*" - ], - "item-advancement-damage-challenge": [ - "§cAdvancement Damage", - "You *take* the set amount of *damage*", - "for every new *advancement*" - ], - "item-all-blocks-disappear-challenge": [ - "§cAll Blocks Disappear", - "With different *interactions* all", - "*blocks* of a certain type", - "disappear in the same chunk" - ], - "menu-all-blocks-disappear-challenge-settings": "All blocks disappear", - "item-all-blocks-disappear-break-challenge": [ - "§bBy breaking", - "If you *break* a *block* all blocks", - "of the same types disappear" - ], - "item-all-blocks-disappear-place-challenge": [ - "§bBy Placing", - "If you *place* a *block* all blocks", - "of the same types disappear" - ], - "item-water-allergy-challenge": [ - "§9Water Allergy", - "You *take* the set amount of *damage*", - "while you are in *water*" - ], - "item-max-biome-time-challenge": [ - "§2Max Biome Time", - "The *time* that you may spend", - "in every *biome* is limited" - ], - "item-max-height-time-challenge": [ - "§9Max Biome Time", - "The *time* that you may spend", - "on every *height* is limited" - ], - "item-permanent-item-challenge": [ - "§cPermanent Items", - "*Items* cannot be dropped", - "or put *away*" - ], - "item-sneak-damage-challenge": [ - "§6Damage per Sneak", - "You *take* the set amount", - "of *damage* if you *sneak*" - ], - "item-jump-damage-challenge": [ - "§6Damage per Jump", - "You *take* the set amount", - "of *damage* if you *jump*" - ], - "item-random-dropping-challenge": [ - "§cRandom Item Dropping", - "Every few seconds a *random item*", - "will be *dropped* from your *inventory*" - ], - "item-random-swapping-challenge": [ - "§cRandom Item Swapping", - "Every few seconds a *random item*", - "will be *swapped* with *another item*", - "in your *inventory*" - ], - "item-random-removing-challenge": [ - "§cRandom Item Removing", - "Every few seconds a *random item*", - "will be *removed* from your *inventory*" - ], - "item-death-on-fall-challenge": [ - "§fDeath On Fall Damage", - "You *die instantly*, when", - "you take *fall damage*" - ], - "item-zero-hearts-challenge": [ - "§6Zero Hearts", - "After a *protection time* you have to", - "get *absorption permanently* else you will die" - ], - "item-random-effect-challenge": [ - "§6Random Effects", - "You get a *random potion effect*", - "in a set *interval*" - ], - "menu-random-effect-challenge-settings": "Random Effects", - "item-random-effect-time-challenge": [ - "§6Interval", - "The *interval* you get the *effect* in" - ], - "item-random-effect-length-challenge": [ - "§6Length", - "The *length* you have the *effect*" - ], - "item-random-effect-amplifier-challenge": [ - "§6Amplifier", - "The *amplifier* the effect has" - ], - "item-permanent-effect-on-damage-challenge": [ - "§6Permanent Effects", - "Everytime you *take damage* you get", - "a random *permanent potion effect*" - ], - "item-random-challenge-challenge": [ - "§cRandom Challenge", - "In a set *interval* a random", - "*challenge* will be *activated*" - ], - "item-anvil-rain-challenge": [ - "§cAnvil Rain", - "*Anvils* are falling from the *sky*" - ], - "menu-anvil-rain-challenge-settings": "Anvil Rain", - "item-anvil-rain-time-challenge": [ - "§6Interval", - "The *interval*, the *anvils* are spawning in" - ], - "item-anvil-rain-range-challenge": [ - "§6Range", - "The *range* of chunks, the *anvils* are spawning in" - ], - "item-anvil-rain-count-challenge": [ - "§6Amount", - "The *amount* of anvils that", - "are spawning in one chunk" - ], - "item-anvil-rain-damage-challenge": [ - "§6Damage", - "The *damage* you take from an *anvil*" - ], - "item-water-mlg-challenge": [ - "§bWater MLG", - "You have to do a *Water MLG*", - "over and over again" - ], - "item-ender-games-challenge": [ - "§5Ender Games", - "Every *few minutes* you will be", - "*swapped* with a *random entity*", - "in a *200 blocks* range" - ], - "item-random-event-challenge": [ - "§6Random Events", - "Every *few minutes* one of", - "*{0} random Events* will be activated" - ], - "item-block-chunk-item-remove-challenge": [ - "§6Movement Item Remove", - "A random item will be removed from", - "your inventory for every", - "*block* / *chunk* you walk" - ], - "item-block-chunk-item-remove-challenge-block": "§6Block", - "item-block-chunk-item-remove-challenge-chunk": "§6Chunk", - "item-higher-jumps-challenge": [ - "§aHigher Jumps", - "The more *you jump*, the *higher* you jump" - ], - "item-force-height-challenge": [ - "§eForce Height", - "Every *few minutes* you have to be", - "on a *certain height*, else you die" - ], - "item-force-block-challenge": [ - "§6Force Block", - "Every *few minutes* you have to be", - "on a *certain block*, else you die" - ], - "item-force-biome-challenge": [ - "§aForce Biome", - "Every *few minutes* you have to be", - "in a *certain biome*, else you die", - "The *rarer* the biome, the *more time* you have" - ], - "item-force-mob-challenge": [ - "§bForce Mob", - "Every *few minutes* you have to", - "*kill* a *certain mob*, else you die" - ], - "item-force-item-challenge": [ - "§6Force Item", - "Every *few minutes* you have to get", - "a *certain item*, else you die" - ], - "item-random-item-challenge": [ - "§bRandom Items", - "A *random player* gets a *random item*", - "every *few seconds*" - ], - "item-always-running-challenge": [ - "§cAlways Running", - "You *cannot stop* to *walk forwards*" - ], - "item-pickup-launch-challenge": [ - "§cPickup Boost", - "When you *pick up* an *item*", - "you will be *launched* into the air" - ], - "item-tsunami-challenge": [ - "§9Tsunami", - "In a *set interval* ", - "the water rises in the *Overworld*", - "and the *lava* in the nether", - " ", - "Should be played with a *few people*!" - ], - "item-all-mobs-to-death-position-challenge": [ - "§cAll Mobs To Death Point", - "If a *Mob* gets *killed* by a player", - "all mobs of the *same type* will be", - "*teleported* to its *death point*" - ], - "item-ice-floor-challenge": [ - "§bIce Floor", - "*Air* will be replaced in a", - "*3x3* area with *packed ice*" - ], - "item-blocks-disappear-time-challenge": [ - "§fBlocks Disappear After Time", - "Placed *blocks*, will *disappear*", - "after a *few seconds*" - ], - "item-missing-items-challenge": [ - "§9Items Missing", - "Every few minutes a *random item disappears* from", - "your *inventory* and you have to *guess* which it was" - ], - "item-damage-item-challenge": [ - "§cDamage Per Item", - "When you *pickup* or *click* an item", - "in your *inventory* you take the", - "*amount* of the items as *damage*" - ], - "item-damage-teleport-challenge": [ - "§cRandom Teleport On Damage", - "You'll be teleported randomly", - "when you take damage" - ], - "item-loop-challenge": [ - "§6Loop Challenge", - "Certain actions are *looped*", - "until a player *sneaks*" - ], - "item-uncraft-challenge": [ - "§6Items Crafting Back", - "*Items* in your inventory are", - "*crafting* back all few seconds" - ], - "item-freeze-challenge": [ - "§bFreeze Challenge", - "For each heart of *damage*, you'll be", - "*frozen* for a certain time" - ], - "item-dont-stop-running-challenge": [ - "§9Dont stop running", - "You are only allowed to stand *still*", - "a certain *time* before you *die*" - ], - "item-consume-launch-challenge": [ - "§cConsume Boost", - "When you *eat* an *item*", - "you will be *launched* into the air" - ], - "item-five-hundred-blocks-challenges": [ - "§5500 Blocks", - "*Every 500 Blocks walked* players", - "will get a *64 stack* of a random item.", - "*Blocks* and *Entities* won't *drop* any items." - ], - "item-level-border-challenges": [ - "§eLevel = Border", - "The *border size* adjusts to *the player*", - "with the *most levels*." - ], - "item-chunk-effect-challenge": [ - "§3Random Chunk Effects", - "In *each chunk* you'll get", - "a random *potion effect*" - ], - "item-repeat-chunk-challenge": [ - "§2Repeated Chunk", - "Blocks that are *placed or destroyed*", - "will be placed / destroyed in *every chunk*" - ], - "item-blocks-fly-challenge": [ - "§fBlocks Fly in Air", - "*Blocks* you've *walked* on fly", - "into the air after *one second*" - ], - "item-respawn-end-challenge": [ - "§5Mobs Respawn In End", - "*Killed mobs* respawn in *end dimension*" - ], - "item-block-effect-challenge": [ - "§3Random Block Effects", - "On *each block* you'll get", - "a random *potion effect*" - ], - "item-entity-effect-challenge": [ - "§5Mobs Got Random Effects", - "*Every Mob* has a random", - "potion effect with *max amplifier*" - ], - "item-block-mob-challenge": [ - "§cMob Blocks", - "A *random mob* spawns out of *every broken block*", - "and to *get the block* you have to *kill it*" - ], - "item-entity-loot-randomizer-challenge": [ - "§6Entity Loot Randomizer", - "All mob drops are *randomly swapped*." - ], - "item-no-shared-advancements-challenge": [ - "§2No Shared Advancements", - "You're *not allowed* to get *advancements* someone else", - "*already did*. Else *you'll die*." - ], - "item-chunk-deletion-challenge": [ - "§6Chunk Deletion", - "*Chunks* that players are in *delete*", - "completely after the given *time*" - ], - "item-delay-damage-description": [ - "§4Damage delay", - "All *damage* from all *players* is", - "added up and dealt after *5 minutes*." - ], - "item-dragon-goal": [ - "§5Ender Dragon", - "Kill the *Ender Dragon* to win" - ], - "item-wither-goal": [ - "§dWither", - "Kill a *Wither* to win" - ], - "item-iron-golem-goal": [ - "§bIron Golem", - "Kill an *Iron Golem* to win" - ], - "item-snow-golem-goal": [ - "§bSnowman", - "Kill a *Snowman* to win" - ], - "item-elder-guardian-goal": [ - "§bElder Guardian", - "Kill an *Elder Guardian* to win" - ], - "item-warden-goal": [ - "§5Warden", - "Kill an *Warden* to win" - ], - "item-most-deaths-goal": [ - "§6Most Deaths", - "Who *collects* the most *different deaths* wins" - ], - "item-most-items-goal": [ - "§cMost Items", - "Who *collects* the most *different items* wins" - ], - "item-last-man-standing-goal": [ - "§cLast Man Standing", - "Who survived until the end wins" - ], - "item-mine-most-blocks-goal": [ - "§eMost Blocks", - "Who *breaks* the most *blocks* wins" - ], - "item-most-xp-goal": [ - "§aMost XP", - "Who *collects* the most *EXP* wins" - ], - "item-first-one-to-die-goal": [ - "§cFirst Death", - "Who *dies* first wins" - ], - "item-collect-wood-goal": [ - "§6Collect Wood", - "Who first collected all types of wood set wins" - ], - "item-collect-wood-goal-overworld": "§aOverworld", - "item-collect-wood-goal-nether": "§cNether", - "item-collect-wood-goal-both": "§9Both", - "item-all-bosses-goal": [ - "§bAll Bosses", - "Each boss must has to be killed once to win" - ], - "item-all-bosses-new-goal": [ - "§5All Bosses (+ Warden)", - "Each boss must has to be killed once to win" - ], - "item-all-mobs-goal": [ - "§bAll Mobs", - "Each mob has to be killed once to win" - ], - "item-all-monster-goal": [ - "§bAll Monsters", - "Each monster has to be killed once to win" - ], - "item-all-items-goal": [ - "§2All Items", - "Find *all items* that are in *Minecraft*" - ], - "item-finish-raid-goal": [ - "§6Finish Raid", - "The first player that *finishes* a *raid* wins" - ], - "item-most-emeralds-goal": [ - "§2Most Emeralds", - "The player with the *most*", - "*emeralds* wins" - ], - "item-all-advancements-goal": [ - "§6All Advancements", - "The first player that *gets* all *advancements* wins" - ], - "item-max-height-goal": [ - "§fMaximum Height", - "The *first* player to reach", - "*Y = {0}* wins" - ], - "item-min-height-goal": [ - "§fMinimum Height", - "The *first* player to reach", - "*Y = {0}* wins" - ], - "item-race-goal": [ - "§5Race", - "The *first* player to *reach* a", - "*random* location in the overworld wins" - ], - "item-most-ores-goal": [ - "§9Most Ores", - "The player that mines the most ores wins" - ], - "item-find-elytra-goal": [ - "§fFind Elytra", - "The *player* that finds an elytra *wins*" - ], - "item-eat-cake-goal": [ - "§fEat Cake", - "The player that *eats a cake* first *wins*" - ], - "item-collect-horse-armor-goal": [ - "§bCollect Horse Armor", - "The player that *collects* every", - "horse armor first *wins*" - ], - "item-collect-ice-goal": [ - "§bCollect Ice Blocks", - "The player that *collects* every", - "ice blocks and snow first *wins*" - ], - "item-collect-swords-goal": [ - "§9Collect Swords", - "The player that *collects* every", - "sword first *wins*" - ], - "item-collect-workstations-item": [ - "§6Collect Workstations", - "The player that *collects* every", - "villager workstation first *wins*" - ], - "item-eat-most-goal": [ - "§6Eat most", - "The player that fills the mods hunger bars *wins*" - ], - "item-force-item-battle-goal": [ - "§5Force Item Battle", - "Each player gets *a random item* that", - "he has *to find*.", - "The player that *found* the *most items*, wins." - ], - "menu-force-item-battle-goal-settings": "Force Item Battle", - "item-force-item-battle-goal-give-item": [ - "§bGive Item On Skip", - "If a player *skips* an item,", - "they will *receive* it" - ], - "item-force-mob-battle-goal": [ - "§bForce Mob Battle", - "Each player gets *a random mob* that", - "he has to *kill*.", - "The player that *killed* the *most mobs*, wins." - ], - "item-force-advancement-battle-goal": [ - "§6Force Advancement Battle", - "Each player gets a *random advancement*,", - "that he has to complete." - ], - "menu-force-mob-battle-goal-settings": "Force Mob Battle", - "item-get-full-health-goal": [ - "§aGet Full Health", - "The first player to gain full health wins." - ], - "menu-force-advancement-battle-goal-settings": "Force Advancement Battle", - "item-force-block-battle-goal": [ - "§aForce Block Battle", - "Every player gets a *random*", - "*block*, on which he has to stand" - ], - "menu-force-block-battle-goal-settings": "Force Block Battle", - "item-force-block-battle-goal-give-block": [ - "§bGive Block On Skip", - "If a player *skips* a block,", - "they will *receive* it" - ], - "item-force-biome-battle-goal": [ - "§2Force Biome Battle", - "Each player gets a *random biome*,", - "that he has to *enter*." - ], - "menu-force-biome-battle-goal-settings": "Force Biome Battle", - "item-force-damage-battle-goal": [ - "§3Force Damage Battle", - "Each player gets a *random damage amount*,", - "that he has to *take*." - ], - "menu-force-damage-battle-goal-settings": "Force Damage Battle", - "item-force-height-battle-goal": [ - "§6Force Height Battle", - "Each player gets a *random height*,", - "that he has to *reach*." - ], - "menu-force-height-battle-goal-settings": "Force Height Battle", - "item-force-position-battle-goal": [ - "§aForce Position Battle", - "Each player gets a *random position*,", - "that he has to *reach*." - ], - "menu-force-position-battle-goal-settings": "Force Position Battle", - "item-extreme-force-battle-goal": [ - "§cExtreme Force Battle", - "Each player gets a *random target*,", - "that he has to reach." - ], - "menu-extreme-force-battle-goal-settings": "Extreme Force Battle", - "item-damage-rule-none": [ - "§6General Damage", - "Sets whether you can get damage or not" - ], - "item-damage-rule-fire": [ - "§6Fire Damage", - "Sets whether you get *damage* from *Fire* and *Lava*" - ], - "item-damage-rule-attack": [ - "§3Attack Damage", - "Sets whether you get *damage* from *Melee Attacks* of entites" - ], - "item-damage-rule-projectile": [ - "§6Projectile Damage", - "Sets whether you get *damage* from *Projectiles*" - ], - "item-damage-rule-fall": [ - "§fFall Damage", - "Sets whether you get *damage* from *Fall Damage" - ], - "item-damage-rule-explosion": [ - "§cExplosion Damage", - "Sets whether you get *damage* from *Explosions" - ], - "item-damage-rule-drowning": [ - "§9Drowning Damage", - "Sets whether you get *damage* from *Drowning" - ], - "item-damage-rule-block": [ - "§eBlock Damage", - "Sets whether you get *damage* from *Falling Blocks" - ], - "item-damage-rule-magic": [ - "§5Magic Damage", - "Sets whether you get *damage* from", - "*Poison, Wither or other Potions" - ], - "item-damage-rule-freeze": [ - "§cFreeze Damage", - "Sets whether you get *damage* from *Freezing*" - ], - "item-block-material": [ - "{0}", - "Sets whether *{1}* can be used" - ], - "custom-limit": "You've reached the limit of §e{0} challenges", - "custom-not-deleted": "Challenge doesn't exist yet!", - "custom-saved": "§7Challenge §asaved §7locally", - "custom-saved-db": [ - "To save it in your database use §e/db save customs", - "§cWarning: §7Old challenges will be overwritten!" - ], - "custom-no-changes": "You haven't made any changes", - "custom-name-info": "Type the new name into the chat", - "custom-command-info": [ - "Type the command §ewithout / §7in chat", - "Allowed commands: §e{0}", - "§cOther commands can be allowed in the config" - ], - "custom-command-not-allowed": "Command §e{0} §7is not set as allowed command in config", - "custom-chars-max_length": "You've reached the limit of {0} characters", - "custom-not-loaded": [ - " ", - "There are no currently loaded challenges.", - "You're missing your challenges? §e/db load customs", - "You've got problems with saving them?", - "Save your challenges before leaving with §e/db save customs", - " " - ], - "custom-main-view-challenges": "§6View Challenges", - "custom-main-create-challenge": "§aCreate Challenge", - "custom-title-trigger": "Trigger", - "custom-title-action": "Action", - "custom-title-view": "View", - "custom-sub-finish": "§aFinished", - "item-custom-info-delete": [ - "§cDelete", - "*Warning* This Action cannot be made *undone*" - ], - "item-custom-info-save": "§aSave", - "item-custom-info-trigger": [ - "§cTrigger", - "*Click here* to set what has to be happening", - "for the *action* to execute" - ], - "item-custom-info-action": [ - "§bAction", - "*Click here* to set what should happen", - "once the *trigger* is met" - ], - "item-custom-info-material": [ - "§6Display Item", - "*Click here* to change the display item" - ], - "item-custom-info-name": [ - "§6Name", - "*Click here* to change the name via chat", - "Max Characters: 50" - ], - "custom-info-currently": "§7Set §8» §e", - "custom-info-trigger": "§7Trigger", - "custom-info-action": "§7Action", - "item-custom-trigger-jump": [ - "§aPlayer Jumps" - ], - "item-custom-trigger-sneak": [ - "§aPlayer Sneaks" - ], - "item-custom-trigger-move_block": [ - "§6Player Walks A Block" - ], - "item-custom-trigger-death": [ - "§cEntity Dies" - ], - "item-custom-trigger-damage": [ - "§cEntity Takes Damage" - ], - "item-custom-trigger-damage-any": [ - "§aAny Cause" - ], - "item-custom-trigger-damage_by_player": [ - "§cEntity Takes Damage By Player" - ], - "item-custom-trigger-intervall": [ - "§6Interval" - ], - "item-custom-trigger-intervall-second": [ - "§6Each Second" - ], - "item-custom-trigger-intervall-seconds": [ - "§6Every {0} Seconds" - ], - "item-custom-trigger-intervall-minutes": [ - "§6Every {0} Minutes" - ], - "item-custom-trigger-block_place": [ - "§aBlock Placed" - ], - "item-custom-trigger-block_break": [ - "§cBlock Destroyed" - ], - "item-custom-trigger-consume_item": [ - "§2Consume Item" - ], - "item-custom-trigger-pickup_item": [ - "§bPickup Item" - ], - "item-custom-trigger-drop_item": [ - "§9Player Dropped Item" - ], - "item-custom-trigger-advancement": [ - "§cPlayer Gets Advancement" - ], - "item-custom-trigger-hunger": [ - "§2Player Looses Hunger" - ], - "item-custom-trigger-move_down": [ - "§6Player Moves Block Down" - ], - "item-custom-trigger-move_up": [ - "§6Player Moves Block Up" - ], - "item-custom-trigger-move_camera": [ - "§6Moves Camera" - ], - "item-custom-trigger-stands_on_specific_block": [ - "§6Player Is On Specific Block" - ], - "item-custom-trigger-stands_not_on_specific_block": [ - "§6Player Is Not On Specific Block" - ], - "item-custom-trigger-gain_xp": [ - "§5Player Gets XP" - ], - "item-custom-trigger-level_up": [ - "§5Player Gets Level" - ], - "item-custom-trigger-item_craft": [ - "§6Player Crafts Item" - ], - "item-custom-trigger-in_liquid": [ - "§9Player Is In Liquid" - ], - "item-custom-trigger-get_item": [ - "§aGet Item", - "Action will be executed *every time*", - "item is clicked or picked up" - ], - "item-custom-action-cancel": [ - "§4Cancel Trigger", - "Prevent that the trigger will be executed", - "Non preventable Trigger: *Jump*, *Sneak*, *Death*", - "*Advancement*, *Level Up*, *In Liquid*" - ], - "item-custom-action-command": [ - "§4Execute Command", - "Make players execute commands.", - "Commands are executed for players via */execute as*.", - "Allowed commands can be set in plugin config.", - "The player doesn't need the *permission* to the commands.", - "Player aren't able to execute *plugin commands*." - ], - "item-custom-action-kill": [ - "§4Kill", - "Kill entities" - ], - "item-custom-action-damage": [ - "§cDamage", - "Hurt entities" - ], - "item-custom-action-heal": [ - "§aHeal", - "Restore entity health" - ], - "item-custom-action-hunger": [ - "§6Hunger", - "Make Entities get hunger" - ], - "item-custom-action-max_health": [ - "§cChange Max Health", - "Modify the max health of players.", - "Will be reset with */gamestate reset*" - ], - "item-custom-action-max_health-offset": [ - "§cHealth Change", - "Choose how the max health should be changed" - ], - "item-custom-action-spawn_entity": [ - "§3Spawn Entity", - "Spawn an entity with a specific type" - ], - "item-custom-action-random_mob": [ - "§6Random Entity", - "Spawn a random entity" - ], - "item-custom-action-random_item": [ - "§bRandom Item", - "Give random items to players" - ], - "item-custom-action-uncraft_inventory": [ - "§eUncraft Inventory", - "Make players inventories uncraft" - ], - "item-custom-action-boost_in_air": [ - "§fBoost In Air", - "Boost entities into the air" - ], - "item-custom-action-boost_in_air-strength": [ - "§fAmplifier" - ], - "item-custom-action-potion_effect": [ - "§dPotion Effect", - "Add a potion effect to entities" - ], - "item-custom-action-permanent_effect": [ - "§6Permanent Potion Effect", - "Add a permanent potion effect to players.", - "Uses the settings of the permanent effect challenge." - ], - "item-custom-action-random_effect": [ - "§dRandom Potion Effect", - "Add a random potion effect to entities" - ], - "item-custom-action-clear_inventory": [ - "§cClear Inventory", - "Clear the inventory of players" - ], - "item-custom-action-drop_random_item": [ - "§aDrop Item From Inventory", - "Drop a random item from the inventory onto the floor" - ], - "item-custom-action-remove_random_item": [ - "§cRemove Item From Inventory", - "Remove a random item from the inventory" - ], - "item-custom-action-swap_random_item": [ - "§6Swap Items In Inventory", - "Swap two items in the inventory" - ], - "item-custom-action-freeze": [ - "§bFreeze", - "Temporarily freeze mobs", - "Uses the settings of the freeze challenge" - ], - "item-custom-action-invert_health": [ - "§cInvert Health", - "Invert the current health of players" - ], - "item-custom-action-water_mlg": [ - "§9Water MLG", - "All players have to do a water mlg to survive" - ], - "item-custom-action-jnr": [ - "§6Jump And Run", - "A random player has to a a jump and run", - "that gets longer everytime" - ], - "item-custom-action-win": [ - "§6Win", - "The challenge will be won *by specific players*" - ], - "item-custom-action-random_hotbar": [ - "§eRandom Hotbar", - "The inventory is emptied and the player", - "gets a full hotbar of random items" - ], - "item-custom-action-modify_border": [ - "§bModify World Border", - "Make the world border *bigger* or *tinier*" - ], - "item-custom-action-modify_border-change": [ - "§dChange" - ], - "item-custom-action-swap_mobs": [ - "§5Swap mobs", - "Swap a mob with another of the same world" - ], - "item-custom-action-place_structure": [ - "§aPlace Structure", - "Places a structure" - ], - "item-custom-action-place_structure-random": "§bRandom structure", - "item-custom-setting-target-current": [ - "§6Current Entity", - "The action will be executed for the *current entity*" - ], - "item-custom-setting-target-every_mob": [ - "§4Every Mob", - "The action will be executed for *every mob*" - ], - "item-custom-setting-target-every_mob_except_current": [ - "§4Every Mob Except Current", - "The action will be executed for *every mob*", - "*except* the current one" - ], - "item-custom-setting-target-every_mob_except_players": [ - "§4Every Mob Except Players", - "The action will be executed for *every mob except players*" - ], - "item-custom-setting-target-random_player": [ - "§5Random Player", - "The action will be executed for a *random player*" - ], - "item-custom-setting-target-every_player": [ - "§cEvery Player", - "The action will be executed for *every player*" - ], - "item-custom-setting-target-current_player": [ - "§aCurrent Player", - "The action will be executed for the *active player*.", - "§7§oIf the current entity is not a player nothing will be happen" - ], - "item-custom-setting-target-console": [ - "§4Console", - "The action will be executed for the *console*" - ], - "item-custom-setting-entity_type-any": "§cAny Entity", - "item-custom-setting-entity_type-player": "§aPlayer", - "item-custom-setting-block-any": "§2Any Block", - "item-custom-setting-item-any": "§2Any Item", - "custom-subsetting-target_entity": "Target Entity", - "custom-subsetting-entity_type": "Entity Type", - "custom-subsetting-liquid": "Liquid", - "custom-subsetting-time": "Time", - "custom-subsetting-damage_cause": "Damage Cause", - "custom-subsetting-amount": "Amount", - "custom-subsetting-value": "Value Editor", - "custom-subsetting-health_offset": "Change", - "custom-subsetting-length": "Length", - "custom-subsetting-amplifier": "Amplifier", - "custom-subsetting-change": "Change", - "custom-subsetting-swap_targets": "Swap Targets" + "syntax": "Please use §e/{0}", + "reload": "Challenges Plugin is reloading...", + "reload-failed": "An §cerror &7occurred while reloading the plugin", + "reload-success": "Challenges Plugin §asuccessfully §7reloaded", + "player-command": "You must be a player!", + "no-permission": "You §cdon't §7have permissions to do this", + "enabled": "§aActivated", + "disabled": "§cDeactivated", + "customize": "§6Customize", + "navigate-back": "§8« §7Back", + "navigate-next": "§8» §7Next", + "seconds": "seconds", + "second": "second", + "minutes": "minutes", + "minute": "minute", + "hours": "hours", + "hour": "hour", + "amplifier": "amplifier", + "open": "Open", + "everyone": "§5Everyone", + "player": "§6Active player", + "none": "None", + "inventory-color": "§9", + "timer-counting-up": "§8» §7Timer counting §aup", + "timer-counting-down": "§8» §7Timer counting §cdown", + "timer-is-paused": "§8» §7Timer §cpaused", + "timer-is-running": "§8» §7Timer §astarted", + "confirm-reset": "Confirm reset with §e/{0}", + "no-fresh-reset": [ + "The Server §ccan't §7be reset yet", + "The Challenge §chasn't been §7started" + ], + "new-challenge": "§a§lNew!", + "feature-disabled": "This function is currently §cdeactivated", + "challenge-disabled": "This challenge is currently §cdeactivated", + "stopped-message": "§8• §7Timer §c§lpaused §8•", + "count-up-message": "§8• §7Time: §a§l{0} §8•", + "count-down-message": "§8• §7Time: §c§l{0} §8•", + "timer-not-started": "The timer §chasn't been started", + "timer-was-started": "The timer has been §astarted", + "timer-was-paused": "The timer has been §cpaused", + "timer-was-set": "The timer has ben set on §e§l{0}", + "timer-already-started": "The timer is §calready running", + "timer-already-paused": "The timer is §calready paused", + "timer-mode-set-down": "The timer is counting §cdown", + "timer-mode-set-up": "The timer is counting §aup", + "no-database-connection": "There is §cno §7database connection", + "fetching-data": "Data is being retrieved..", + "undefined": "undefined", + "no-such-material": "This material doesn't exist", + "not-an-item": "§e{0} §7is not an item", + "no-such-entity": "This entity doesn't exist", + "not-alive": "§e{0} §7is not a living entity", + "no-loot": "§e{0} §7doesn't have any drops", + "deprecated-plugin-version": [ + " ", + "An update for the plugin is available", + "Download: §e{0}", + " " + ], + "deprecated-config-version": [ + "The plugin config version is §coutdated §7(§c{1} §7< §a{0}§7)", + "You can either manually add all missing settings or delete the old one" + ], + "missing-config-settings": "There are missing config settings: §e{0}", + "missing-config-settings-separator": "§7, §e", + "no-missing-config-settings": [ + "§cThere are no missing config settings.", + "§cYou can manually update it to §c§l{0}" + ], + "unsuported-language": [ + "§cThe language §7(§e{0}§7) is not supported" + ], + "not-op": [ + "§7To use this plugin you need to have permissions. Give yourself permissions in the Server Console with: /op [name]" + ], + "join-message": "§e{0} §7has §ajoined §7the server", + "quit-message": "§e{0} §7has §cleft §7the server", + "timer-paused-message": [ + "The timer is §cpaused", + "Use §e/timer resume §7to start it" + ], + "cheats-detected": [ + "§e{0} §7has §ccheated", + "§cNo §7further statistics can be collected" + ], + "cheats-already-detected": [ + "On this server has been §ccheated", + "§cNo §7further statistics can be collected" + ], + "custom_challenges-reset": "The §elokal §7settings were reset §asuccessfully", + "config-reset": "The §elocal §7settings were reset §asuccessfully", + "player-config-loaded": "Your settings have been loaded §asuccessfully", + "player-config-saved": "Your settings have been saved §asuccessfully", + "player-config-reset": "Your settings were reset §asuccessfully", + "player-custom_challenges-loaded": "Your challenges have been loaded §asuccessfully", + "player-custom_challenges-saved": "Your challenges have been saved §asuccessfully", + "player-custom_challenges-reset": "Your challenges were §asuccessfully §7reset", + "item-prefix": "§8» ", + "item-setting-info": "§8➟ {0}", + "stat-dragon-killed": "Dragons killed", + "stat-deaths": "Deaths", + "stat-entity-kills": "Kills", + "stat-damage-dealt": "Damage dealt", + "stat-damage-taken": "Damage taken", + "stat-blocks-mined": "Blocks destroyed", + "stat-blocks-placed": "Blocks placed", + "stat-blocks-traveled": "Blocks travelled", + "stat-challenges-played": "Challenges played", + "stat-jumps": "Jumps", + "stats-of": "§8» §7Stats of §e{0}", + "stats-display": "§8» §7{0} §8(§e{1}. §7Platz§8)", + "stats-leaderboard-display": [ + "§8» §e{0}", + "§8§l┣ §7{1} §7{2}", + "§8§l┗ §e{3}. §7Place" + ], + "position": "§e{4} §8- §7{0}, {1}, {2} §8(§e{3}§8) §8┃ §e{5}m", + "positions-disabled": "Positions are §cdeactivated", + "position-other-world": "This position is in another world §8(§e{0}§8)", + "position-not-exists": "The position §e{0} §cdoesn't §7exist", + "position-already-exists": "The position {0} §calready §7exist", + "position-set": "§e{5} §7created position §e{4} §7{0}, {1}, {2} §8(§e{3}§8)", + "position-deleted": "§e{5} §7deleted §e{4} §7{0}, {1}, {2} §8(§e{3}§8)", + "no-positions": [ + "There are no §epositions §7set in this world", + "Create on with §e/{0}" + ], + "no-positions-global": [ + "There are no §epositions §7set", + "Create on with §e/{0}" + ], + "command-no-target": "§cNo §7players has been found", + "command-heal-healed": "You have been §ahealed", + "command-heal-healed-others": "You healed §e{0} player/s", + "command-gamemode-gamemode-changed": "Your gamemode has been changed to §e{0}", + "command-gamemode-gamemode-changed-others": "The gamemode of §e{1} §7player/s has been changed to §e{0}", + "command-village-search": "A village is being searched..", + "command-village-teleport": "You have been §ateleported to a village", + "command-village-not-found": "§cNo §7new village was found", + "command-weather-set-clear": "Weather was changed to §eclear", + "command-weather-set-rain": "Weather was changed to §erainy", + "command-weather-set-thunder": "Weather was changed to §ethundery", + "command-invsee-open": "Inventory of §e{0} §7opened", + "command-enderchest-open": "You opened your §5Enderchest", + "command-difficulty-change": "Difficulty changed to {0}", + "command-difficulty-current": "Current difficulty is {0}", + "command-search-nothing": "§e{0} §7is not dropped by any special block", + "command-search-result": "§e{0} §7drops from §e{1}", + "command-searchloot-disabled": "The entity loot randomizer challenge is currently §cdeactivated", + "command-searchloot-nothing": "The loot of §e{0} §7isn't dropped by any specific entity", + "command-searchloot-result": [ + "§e{0} §7drops the loot of §e{1}", + "The loot of §e{0} §7is dropped by §e{2}" + ], + "command-time-set": "Time was changed to §e{0} §7Ticks §8(§7ca. §e{1}§8)", + "command-time-set-exact": "Time was changed to §e{0} §8(§e{1} §7Ticks§8)", + "command-time-query": [ + "§8» §7Current ingame times", + "Playtime §e{0} §7Ticks §8(§7Tag §e{1}§8)", + "Time of day §e{2} §7Ticks §8(§7ca. §e{3}§8)" + ], + "command-time-noon": "Noon", + "command-time-night": "Night", + "command-time-midnight": "Midnight", + "command-time-day": "Day", + "command-fly-enabled": "You can fly §anow", + "command-fly-disabled": "You can §cno longer §7fly", + "command-fly-toggled-others": "You toggled §efly §7for §e{0} §7player/s", + "command-feed-fed": "Your appetite was §esated", + "command-feed-others": "You satiated the appetite of §e{0} §7player/s", + "command-gamestate-reload": "The gamestate was §areloaded", + "command-gamestate-reset": "The gamestate was §areset", + "command-world-teleport": "You'll be teleported into the §e{0}", + "command-back-no-locations": "You §cweren't §7teleported yet", + "command-back-teleported": "You were teleported §e{0} §7location back", + "command-back-teleported-multiple": "You were teleported §e{0} §7locations back", + "command-result-no-battle-active": "There is currently §cno §7Force Battle enabled", + "command-god-mode-enabled": "You are now in §aGod mode", + "command-god-mode-disabled": "You are §cno longer in God mode", + "command-god-mode-toggled-others": "§e{0} §7players are now in §eGod mode", + "traffic-light-challenge-fail": "§e{0} §7went over §cred", + "player-damage-display": "§e{0} §7took §7{1} §7damage by §e{2}", + "death-message": "§e{0} §7died", + "death-message-cause": "§e{0} §7died by §e{1}", + "health-inverted": "Your hearts have been §cinverted", + "exp-picked-up": "§e{0} §7collected §cEXP", + "unable-to-find-fortress": "§cNo fortress §7could be found", + "unable-to-find-bastion": "§cNo bastion §7could be found", + "death-collected": "Death reason §e{0} §7registered", + "item-collected": "Item §e{0} §7registered", + "items-to-collect": "§7Items to collect §8» §e{0}", + "backpacks-disabled": "Backpacks are currently §cdeactivated", + "backpack-opened": "You opened the {0}", + "top-to-overworld": "You have been teleported to the §eoverworld", + "top-to-surface": "You have been teleported to the §etop", + "jnr-countdown": "Next §6JumpAndRun §7in §e{0} seconds", + "jnr-countdown-one": "Next §6JumpAndRun §7in §eone second", + "jnr-finished": "§e{0} §afinished §7the §6JumpAndRun", + "snake-failed": "§e{0} §7stepped over the §9line", + "only-dirt-failed": "§e{0} §7did not stand on dirt", + "no-mouse-move-failed": "§e{0} §7moved his mouse", + "no-duped-items-failed": "§e{0} §7and §e{1} §7both had §e{2} §7in their inventory", + "only-down-failed": "§e{0} §7went up one block", + "food-once-failed": "§e{0} §7suffocated by §e{1}", + "food-once-new-food-team": "§e{0} §7ate §e{1}", + "food-once-new-food": "§eYou §7ate §e{1}", + "sneak-damage-failed": "§e{0} §7sneaked", + "jump-damage-failed": "§e{0} §7jumped", + "random-challenge-enabled": "The challenge §e{0} §7has been §aactivated", + "all-items-skipped": "Item §e{0} §7skipped", + "all-items-already-finished": "All items has been already found", + "all-items-found": "Item §e{0} §7registered by §e{1}", + "mob-kill": "§e{0} §ehas been killed §8(§e{1} §7/ §e{2}§8)", + "endergames-teleport": "Swapped with §e{0}", + "force-height-fail": "§e{0} §7was on the §cwrong §7height §8(§e{1}§8)", + "force-height-success": "All players were on the §aright §7height", + "force-block-fail": "§e{0} §7was on the §cwrong §7block §8(§e{1}§8)", + "force-block-success": "All players were on the §aright §7block", + "force-biome-fail": "The biome §e{0} §chasn't been found", + "force-biome-success": "§e{0} §7found the biome §e{1}", + "force-mob-fail": "The mob §e{0} §chasn't been killed", + "force-mob-success": "§e{0} §7killed the mob §e{1}", + "force-item-fail": "Item §e{0} §chasn't been found", + "force-item-success": "§e{0} §afound §7the item §e{1}", + "new-effect": "Effect §e{0} §8➔ §e{1}", + "missing-items-inventory": "{0}Which item is missing?", + "missing-items-inventory-open": "§8[§aOpen GUI§8]", + "loops-cleared": "§e{0} §7Loops cancelled", + "stopped-moving": "§e{0} §7hasn't moved for too long", + "all-advancements-goal": "§7Advancements §8» §e{0}", + "height-reached": "§e{0} §7reached §eY = {1} §7first!", + "race-goal-reached": "§e{0} §7reached the goal!", + "points-change": "§e{0} §7Points", + "force-item-battle-found": "You've found §e{0}!", + "force-item-battle-new-item": "Item to find: §e{0}", + "force-item-battle-leaderboard": "§8➜ §7Force Item Battle Leaderboard", + "force-mob-battle-killed": "You've killed §e{0}!", + "force-mob-battle-new-mob": "Mob to kill: §e{0}", + "force-mob-battle-leaderboard": "§8➜ §7Force Mob Battle Leaderboard", + "force-advancement-battle-completed": "You've completed §e{0}!", + "force-advancement-battle-new-advancement": "Nächstes Advancement: §e{0}", + "force-advancement-battle-leaderboard": "§8➜ §7Force Advancement Battle Leaderboard", + "force-block-battle-found": "You've found §e{0}!", + "force-block-battle-new-block": "Block to find: §e{0}", + "force-block-battle-leaderboard": "§8➜ §7Force Block Battle Leaderboard", + "force-battle-leaderboard-entry": "{0}#{1} §8» §e{2} §8┃ §e{3}", + "force-battle-block-target-display": "§eBlock: {0}", + "force-battle-item-target-display": "§eItem: {0}", + "force-battle-height-target-display": "§eHeight: {0}", + "force-battle-mob-target-display": "§eMob: {0}", + "force-battle-biome-target-display": "§eBiome: {0}", + "force-battle-damage-target-display": "§eDamage: §c{0} ❤", + "force-battle-advancement-target-display": "§eAdvancement: {0}", + "force-battle-position-target-display": "§ePosition: {0}", + "extreme-force-battle-new-height": "Height to reach: §e{0}", + "extreme-force-battle-reached-height": "You've reached height §e{0}!", + "extreme-force-battle-new-biome": "Biome to find: §e{0}", + "extreme-force-battle-found-biome": "You've found the biome §e{0}!", + "extreme-force-battle-new-damage": "Damage to take: §c{0} ❤", + "extreme-force-battle-took-damage": "You took §c{0} ❤ §7damage!", + "extreme-force-battle-position": "§eX: {0} §8┃ §eZ: {1}", + "extreme-force-battle-new-position": "Position to reach: §e{0}", + "extreme-force-battle-reached-position": "You've reached the position §e{0}!", + "extreme-force-battle-leaderboard": "§8➜ §7Extreme Force Battle Leaderboard", + "force-biome-battle-leaderboard": "§8➜ §7Force Biome Battle Leaderboard", + "force-damage-battle-leaderboard": "§8➜ §7Force Damage Battle Leaderboard", + "force-height-battle-leaderboard": "§8➜ §7Force Height Battle Leaderboard", + "force-position-battle-leaderboard": "§8➜ §7Force Position Battle Leaderboard", + "random-event-speed": [ + "Sonic? Is it you?", + "Woahh! That's fast" + ], + "random-event-entities": [ + "Is this a zoo?", + "Where did this come from?", + "What are you doing here?" + ], + "random-event-hole": [ + "But you fell pretty deep", + "From the very top to the very bottom..", + "Where did this hole come from?" + ], + "random-event-fly": [ + "Good flight :)", + "I believe I can fly..", + "So this is what flying feels like" + ], + "random-event-webs": [ + "Have they been here for a long time?" + ], + "random-event-ores": [ + "Where did all the ores go?", + "Aren't there any ores here?", + "Was there any ore here??" + ], + "random-event-sickness": [ + "Are you sick??", + "What's going on now?!" + ], + "bossbar-timer-paused": "§8» §7The timer is §cpaused", + "bossbar-mob-transformation": "§8» §7Last mob §8§l┃ §a{0}", + "bossbar-biome-time-left": "§8» §7Time left in §e{0} §8§l┃ §a{1}s", + "bossbar-height-time-left": "§8» §7Time left on §e{0} §8§l┃ §a{1}s", + "bossbar-zero-hearts": "§8» §7Protection time §8§l┃ §a{0}s", + "bossbar-random-challenge-waiting": "§8» §7Waiting for new challenge..", + "bossbar-random-challenge-current": "§8» §7Challenge §e{0}", + "bossbar-all-items-current-max": "§8» §f{0} §8┃ §7{1} §8/ §7{2}", + "bossbar-all-items-finished": "§8» §7All items found", + "bossbar-force-height-waiting": "§8» §7Waiting for next height..", + "bossbar-force-height-instruction": "§8» §7Height §e{0} §8┃ §a{1}", + "bossbar-force-block-waiting": "§8» §7Waiting for next block..", + "bossbar-force-block-instruction": "§8» §7Block §e{0} §8┃ §a{1}", + "bossbar-force-biome-waiting": "§8» §7Waiting for next biome..", + "bossbar-force-biome-instruction": "§8» §7Biome §e{0} §8┃ §a{1}", + "bossbar-force-mob-waiting": "§8» §7Waiting for next mob..", + "bossbar-force-mob-instruction": "§8» §7Mob §e{0} §8┃ §a{1}", + "bossbar-force-item-waiting": "§8» §7Waiting for next item..", + "bossbar-force-item-instruction": "§8» §7Item §e{0} §8┃ §a{1}", + "bossbar-tsunami-water": "§8» §7Waterheight: §9{0}", + "bossbar-tsunami-lava": "§8» §7Lavaheight: §c{0}", + "bossbar-ice-floor": "§8» §bIce floor §8┃ {0}", + "bossbar-dont-stop-running": "§8» §7Move in §8┃ §e{0}", + "bossbar-five-hundred-blocks": "§8» §fBlocks Walked §8┃ §7{0} §8/ §7{1}", + "bossbar-level-border": "§8» §7Border size §8┃ §7{0}", + "bossbar-race-goal-info": "§8» §fGoal §8┃ §7X: {0} §8/ §7Z: {1} §8┃ §e{2} Blocks", + "bossbar-race-goal": "§8» §fGoal §8┃ §7X: {0} §8/ §7Z: {1}", + "bossbar-first-at-height-goal": "§8» §fGoal §8┃ §7Y: {0}", + "bossbar-respawn-end": "§8» §5Respawned Mobs in End §8┃ §e{0}", + "bossbar-kill-all-bosses": "§8» §cAll Bosses §8┃ §e{0}/{1}", + "bossbar-kill-all-mobs": "§8» §cAll Mobs §8┃ §e{0}/{1}", + "bossbar-kill-all-monster": "§8» §cAll Monsters §8┃ §e{0}/{1}", + "bossbar-chunk-deletion": "§8» §7Time left in chunk §6{0}s", + "subtitle-time-seconds": "§e{0} §7seconds", + "subtitle-time-seconds-range": "§e{0}-{1} §7seconds", + "subtitle-time-minutes": "§e{0} §7minutes", + "subtitle-launcher-description": "§7Power §e{0}", + "subtitle-blocks": "§e{0} §7Blocks", + "subtitle-range-blocks": "§eRange: §e{0} §7Blöcke", + "scoreboard-title": "§7» §f§lChallenge", + "scoreboard-leaderboard": "§e#{0} §8┃ §7{1} §8» §e{2}", + "your-place": "§7Your place §8» §e{0}", + "server-reset": [ + "§8————————————————————", + " ", + "§8» §cServer reset", + " ", + "§7Reset by §4§l{0}", + "§7The server is §crestarting", + " ", + "§8————————————————————" + ], + "challenge-end-timer-hit-zero": [ + " ", + "§cThe challenge is over!", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-timer-hit-zero-winner": [ + " ", + "§cThe challenge is over!", + "§7Gewinner: §e§l{1}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-reached": [ + " ", + "§7The challenge was ended!", + "§7Time needed: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-reached-winner": [ + " ", + "§7The challenge was ended!", + "§7Winner: §e§l{1}", + "§7Time needed: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-failed": [ + " ", + "§cThe challenge is over! §6#FeelsBadMan ✞", + "§7Time wasted: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "title-timer-started": [ + " ", + "§8» §7Timer §acontinued" + ], + "title-timer-paused": [ + " ", + "§8» §7Timer §cpaused" + ], + "title-challenge-enabled": [ + "§e{0}", + "§2§l✔ §8┃ §aActivated" + ], + "title-challenge-disabled": [ + "§e{0}", + "§4✖ §8┃ §cDeactivated" + ], + "title-challenge-value-changed": [ + "§e{0}", + "§8» §e{1}" + ], + "title-pregame-movement-setting": [ + "§cWarte..", + "§8» §7Timer is stopped.." + ], + "item-menu-start": "§8• §aStart Challenge §8┃ §e/start §8•", + "item-menu-challenges": "§8• §cChallenges §8┃ §e/challenge §8•", + "item-menu-timer": "§8• §5Timer §8┃ §e/timer §8•", + "item-menu-leaderboard": "§8• §6Leaderboard §8┃ §e/leaderboard §8•", + "item-menu-stats": "§8• §2Statistics §8┃ §e/stats §8•", + "menu-title": "Menu", + "menu-timer": "§6Timer", + "menu-goal": "§5Goal", + "menu-damage": "§7Schaden", + "menu-item_blocks": "§4Blocks & Items", + "menu-challenges": "§cChallenges", + "menu-settings": "§eSettings", + "menu-custom": "§aCustom Challenges", + "lore-category-activated-count": "§7Activated §8» §a{0}§8/§7{1}", + "lore-category-activated": "§7Activated §8» §aYes", + "lore-category-deactivated": "§7Activated §8» §cNo", + "category-misc_challenge": [ + "§9Miscellaneous", + "Challenges that *couldn't be*", + "*assigned* with a category" + ], + "category-randomizer": [ + "§6Randomizer", + "Experience a *randomized gameplay*" + ], + "category-limited_time": [ + "§aLimited Time", + "Some things are timely restricted" + ], + "category-force": [ + "§3Force", + "You have to fulfill specific", + "*intermediate goals* to survive" + ], + "category-world": [ + "§4World Change", + "The world will be *modified* significant" + ], + "category-damage": [ + "§cSchaden", + "New *damage rules*" + ], + "category-effect": [ + "§5Effekte", + "Have fun with *lots of effects*" + ], + "category-inventory": [ + "§6Inventory", + "You'll have problems managing *your inventory*" + ], + "category-movement": [ + "§aBewegung", + "You're *restricted in your movements*" + ], + "category-entities": [ + "§bEntities", + "Entities will be *modified*" + ], + "category-extra_world": [ + "§aExtra Welt", + "Challenges that will *send*", + "you to *another world*" + ], + "category-misc_goal": [ + "§9Miscellaneous", + "Goals that *couldn't be*", + "*assigned* with a category" + ], + "category-kill_entity": [ + "§cEntities töten", + "Kill *specific entities* to win" + ], + "category-score_points": [ + "§eBest Score", + "Get the best score *to win*" + ], + "category-fastest_time": [ + "§6Fastest Time", + "Be the fastest *to win*" + ], + "category-force_battle": [ + "§bForce Battles", + "Fulfill the given *intermediate goals*", + "to earn points.", + " ", + "The player with the *most points* wins." + ], + "item-time-seconds-description": "§8» §7Time: §e{0} §7seconds", + "item-time-seconds-range-description": "§8» §7Time: §e{0}-{1} §7Sekunden", + "item-time-minutes-description": "§8» §7Time: §e{0} §7minutes", + "item-heart-damage-description": "§8» §7Damage: §e{0} §c❤", + "item-heart-start-description": "§8» §7Start: §e{0} §c❤", + "item-max-health-description": "§8» §7Max health: §e{0} §c❤", + "item-chance-description": "§8» §7Chance: §e{0}%", + "item-launcher-description": "§8» §7Strength: §e{0}", + "item-permanent-effect-target-player-description": "§8» §7Only the active players gets the effect", + "item-permanent-effect-target-everyone-description": "§8» §7All players are getting the effect", + "item-blocks-description": "§8» Blocks to walk: §e{0}", + "item-range-blocks-description": "§8» §7Range: §e{0} §7Block", + "item-force-battle-goal-jokers": [ + "§6Number of jokers", + "The *amount* of *jokers*", + "hat every player has" + ], + "item-force-battle-show-scoreboard": [ + "§bShow Scoreboard" + ], + "item-force-battle-duped-targets": [ + "§cDuped Targets", + "Targets can occur *multiple times*" + ], + "item-force-position-battle-radius": [ + "§bRadius", + "The *maximum radius*, in which the", + "positions will be located" + ], + "item-difficulty-setting": [ + "§aDifficulty", + "Sets the *Difficulty*" + ], + "item-language-setting": [ + "§bLanguage", + "Sets the *Language*" + ], + "item-language-setting-german": "§fDeutsch", + "item-language-setting-english": "§fEnglish", + "item-one-life-setting": [ + "§cOne Teamlife", + "*Everyone* dies when *one player dies*" + ], + "item-respawn-setting": [ + "§4Respawn", + "When you *die*, you won't be a *spectator*" + ], + "item-death-message-setting": [ + "§6Death messages", + "Toggles *death messages*" + ], + "item-death-message-setting-vanilla": "§6Vanilla", + "item-pvp-setting": [ + "§9PvP" + ], + "item-max-health-setting": [ + "§cMax health", + "Sets the *max health*", + "for *all players*" + ], + "item-soup-setting": [ + "§cSoup healing", + "When you use a *mushroom soup*", + "you will be healed for *4 hearts*" + ], + "item-damage-setting": [ + "§cDamage Multiplier", + "Damage you take will be *multiplied*" + ], + "item-damage-display-setting": [ + "§eDamage Display", + "It will be displayed in the *chat*", + "when anybody takes *damage*" + ], + "item-health-display-setting": [ + "§cHealth Display", + "The *hearts* of all players", + "will be showed in the *tablist*" + ], + "item-position-setting": [ + "§9Positions", + "Allows you to mark *positions*", + "with */pos*" + ], + "item-backpack-setting": [ + "§6Backpack", + "Allows you to open *your backpack* or", + "the *team backpack* with */backpack*" + ], + "item-backpack-setting-team": "§5Team", + "item-backpack-setting-player": "§6Player", + "item-cut-clean-setting": [ + "§9CutClean", + "Different *settings* to simplify", + "the *farming* of items" + ], + "menu-cut-clean-setting-settings": "CutClean", + "item-cut-clean-gold-setting": [ + "§6Gold", + "*Gold ore* will be directly dropped as *Gold ingot*" + ], + "item-cut-clean-iron-setting": [ + "§7Iron", + "*Iron ore* will be directly dropped as *Iron ingot*" + ], + "item-cut-clean-coal-setting": [ + "§eCoal", + "*Coal* will be directly dropped as *torches*" + ], + "item-cut-clean-flint-setting": [ + "§eFlint", + "*Gravel* will always drop *flint*" + ], + "item-cut-clean-vein-setting": [ + "§eOre Veins", + "*Ore veins* will be directly destroyed" + ], + "item-cut-clean-inventory-setting": [ + "§6Direct Into Inventory", + "*Items* will be put *directly* into your", + "*inventory* instead of dropping" + ], + "item-cut-clean-food-setting": [ + "§cCooked Food", + "*Raw meat* will be directly dropped as *cooked meat*" + ], + "item-glow-setting": [ + "§fPlayer Glow", + "*Players* are visible through *walls*" + ], + "no-hunger-setting": [ + "§cNo Hunger", + "You don't get *hungry*" + ], + "pregame-movement-setting": [ + "§6Pregame Movement", + "You can *move* before", + "the game has been *started*" + ], + "item-no-hit-delay-setting": [ + "§fNoHitDelay", + "After you've *taken* damage", + "you can *get* damage *immediately* again" + ], + "item-timber-setting": [ + "§bTimber", + "You can destroy a *tree*", + "by breaking down *a single block* of the tree" + ], + "item-timber-setting-logs": "§6Logs", + "item-timber-setting-logs-and-leaves": "§6Logs §7and §2Leaves", + "item-keep-inventory-setting": [ + "§5Keep Inventory", + "You don't lose any *items*", + "when you die" + ], + "item-mob-griefing-setting": [ + "§5Mob Griefing", + "Monsters *can't destroy* anything" + ], + "item-no-item-damage-setting": [ + "§5No Item Damage", + "*Items* are *unbreakable*" + ], + "top-command-setting": [ + "§dTop Command", + "You can *teleport* to the *top*", + "of the world or to the *overworld*", + "with /top" + ], + "item-fortress-spawn-setting": [ + "§cFortress Spawn", + "When you go into the *nether*", + "you will always spawn in a *fortress*" + ], + "item-bastion-spawn-setting": [ + "§cBastion Spawn", + "When you go into the *nether*", + "you will always spawn in a *bastion*" + ], + "item-no-offhand-setting": [ + "§6No Offhand", + "The *second hand* will be blocked" + ], + "item-regeneration-setting": [ + "§cRegeneration", + "Sets *whether* and", + "*how* to *regenerate*" + ], + "item-regeneration-setting-not_natural": "§6Not Natural", + "item-immediate-respawn-setting": [ + "§6Direct Respawn", + "When you *die* you *respawn* automatically", + "*without* seeing the *death screen*" + ], + "item-slot-limit-setting": [ + "§4Inventory Slots", + "Sets how many *inventory*", + "*slots* are useable" + ], + "item-death-position-setting": [ + "§cDeath Position", + "When you die, */pos* creates", + "a position at your death point" + ], + "item-enderchest-command-setting": [ + "§5Enderchest Command", + "When you execute */ec*,", + "your *Enderchest* opens" + ], + "item-split-health-setting": [ + "§cSplit Health", + "Sets whether *all players*", + "share the same *health*" + ], + "item-old-pvp-setting": [ + "§b1.8 PvP", + "The *old 1.8 PvP System* will be used", + "There will be no *attack damage cooldown*" + ], + "item-totem-save-setting": [ + "§6Challenge Death Rescue", + "If you *instant die* from a *challenge*", + "*totems* can *rescue* you" + ], + "item-traffic-light-challenge": [ + "§cTraffic Light Challenge", + "The *traffic light* switches every few minutes.", + "If you go on *red*, you die" + ], + "item-block-randomizer-challenge": [ + "§6Block Randomizer", + "Each *block* drops a *random item*" + ], + "item-crafting-randomizer-challenge": [ + "§6Crafting Randomizer", + "If you *craft* something you will get another *random item*" + ], + "item-mob-randomizer-challenge": [ + "§6Mob Randomizer", + "When an *Entity* spawns, it spawns *twice*" + ], + "item-hotbar-randomizer-challenge": [ + "§6HotBar Randomizer", + "Every *few minutes* every player gets *random items*" + ], + "item-damage-block-challenge": [ + "§4Damage per Block", + "You take *damage* for", + "every *block* you walk" + ], + "item-hunger-block-challenge": [ + "§6Hunger per Block", + "You lose *food* for", + "every *block* you walk" + ], + "item-stone-sight-challenge": [ + "§fStone Sight", + "*Mobs* that you look in the", + "*eyes* turn to stone" + ], + "item-no-mob-sight-challenge": [ + "§cMob Sight Damage", + "When you look into the *eyes* of an", + "*entity*, you get *damage*" + ], + "item-bedrock-path-challenge": [ + "§7Bedrock Path", + "*Bedrock *generates* under you*", + "the whole time" + ], + "item-bedrock-walls-challenge": [ + "§7Bedrock Walls", + "Huge *walls of bedrock*", + "are *generating* behind you" + ], + "item-surface-hole-challenge": [ + "§cSurface Hole", + "The *floor* is disappearing", + "to *void* behind you" + ], + "item-damage-inv-clear-challenge": [ + "§cDamage Inventory Clear", + "Player *inventories* are *cleared*", + "when a *player* takes damage" + ], + "item-no-trading-challenge": [ + "§2No Trading", + "You *cannot* trade", + "with villagers" + ], + "item-block-break-damage-challenge": [ + "§6Block Break Damage", + "If you *break* a *block*, you", + "will *take* the set amount of *damage*" + ], + "item-block-place-damage-challenge": [ + "§6Block Place Damage", + "If you *place* a *block*, you", + "will *take* the set amount of *damage*" + ], + "item-no-exp-challenge": [ + "§aNo EXP", + "If you pickup *EXP* you die" + ], + "item-invert-health-challenge": [ + "§cInvert Health", + "Every few minutes the *hearts are inverted*.", + "If you have *8 hearts*, you will have *2 hearts*", + "and the other way around" + ], + "item-jump-and-run-challenge": [ + "§6Jump and Run", + "Every *few minutes* you have to do a random", + "*jump and run* which gets *harder* every time" + ], + "item-randomized-hp-challenge": [ + "§4Randomized HP", + "The *health* of all mobs", + "is randomized" + ], + "item-snake-challenge": [ + "§9Snake", + "Each player draws a *deadly line*", + "behind them" + ], + "item-reversed-damage-challenge": [ + "§cReversed Damage", + "If you deal damage to entites", + "you take the same damage" + ], + "item-duped-spawning-challenge": [ + "§cDuped Spawning", + "If a mob *spawns*", + "it spawns *two times*" + ], + "item-hydra-challenge": [ + "§5Hydra", + "If you *kill* a mob", + "*two new* are spawning" + ], + "item-hydra-plus-challenge": [ + "§cHydra Plus", + "If you kill a *mob* it", + "spawns *twice* as many", + "times as the *previous* time", + " ", + "Maximum are *512* Mobs each time" + ], + "item-floor-lava-challenge": [ + "§6The Floor Is Lava", + "*Blocks* below you transform first", + "to *magma* and then to *lava*" + ], + "item-only-dirt-challenge": [ + "§cOnly Dirt", + "You must stay on *dirt*", + "otherwise you will *die*" + ], + "item-food-once-challenge": [ + "§cFood Once", + "Each *food* can be*", + "*eaten* only once" + ], + "item-food-once-challenge-player": "§6Player", + "item-food-once-challenge-everyone": "§5Everyone", + "item-chunk-deconstruction-challenge": [ + "§bChunk Deconstruction", + "*Chunks* that players are in", + "*break* down from *above*" + ], + "item-one-durability-challenge": [ + "§4One Durability", + "Items are *destroyed* after one *use*" + ], + "item-low-drop-rate-challenge": [ + "§6Low Drop Chance", + "The *drop chance* of each *block*", + "will be set to the defined *percentage*" + ], + "item-invisible-mobs-challenge": [ + "§fInvisible Mobs", + "All *Mobs* have an", + "*invisibility* effect" + ], + "item-mob-transformation-challenge": [ + "§cMob Transformation", + "When you hit a mob, it *turns*", + "into the last mob *you* hit" + ], + "item-jump-entity-challenge": [ + "§2Jump Entity", + "A *random entity* spawns", + "everytime you *jump*" + ], + "item-no-mouse-move-challenge": [ + "§cMouse Movement Damage", + "You take *damage* everytime", + "you *move* your *view*" + ], + "item-no-duped-items-challenge": [ + "§6No Duped Items", + "Players are *not allowed* to have", + "the *same item* in their *inventories*", + "at the same time" + ], + "item-infection-challenge": [ + "§aInfection Challenge", + "You have to keep *2 blocks* away", + "from all *mobs* or you will *get* sick" + ], + "item-only-down-challenge": [ + "§cOnly Down", + "If you go *up* by *a block*, you *die*" + ], + "item-advancement-damage-challenge": [ + "§cAdvancement Damage", + "You *take* the set amount of *damage*", + "for every new *advancement*" + ], + "item-all-blocks-disappear-challenge": [ + "§cAll Blocks Disappear", + "With different *interactions* all", + "*blocks* of a certain type", + "disappear in the same chunk" + ], + "menu-all-blocks-disappear-challenge-settings": "All blocks disappear", + "item-all-blocks-disappear-break-challenge": [ + "§bBy breaking", + "If you *break* a *block* all blocks", + "of the same types disappear" + ], + "item-all-blocks-disappear-place-challenge": [ + "§bBy Placing", + "If you *place* a *block* all blocks", + "of the same types disappear" + ], + "item-water-allergy-challenge": [ + "§9Water Allergy", + "You *take* the set amount of *damage*", + "while you are in *water*" + ], + "item-max-biome-time-challenge": [ + "§2Max Biome Time", + "The *time* that you may spend", + "in every *biome* is limited" + ], + "item-max-height-time-challenge": [ + "§9Max Biome Time", + "The *time* that you may spend", + "on every *height* is limited" + ], + "item-permanent-item-challenge": [ + "§cPermanent Items", + "*Items* cannot be dropped", + "or put *away*" + ], + "item-sneak-damage-challenge": [ + "§6Damage per Sneak", + "You *take* the set amount", + "of *damage* if you *sneak*" + ], + "item-jump-damage-challenge": [ + "§6Damage per Jump", + "You *take* the set amount", + "of *damage* if you *jump*" + ], + "item-random-dropping-challenge": [ + "§cRandom Item Dropping", + "Every few seconds a *random item*", + "will be *dropped* from your *inventory*" + ], + "item-random-swapping-challenge": [ + "§cRandom Item Swapping", + "Every few seconds a *random item*", + "will be *swapped* with *another item*", + "in your *inventory*" + ], + "item-random-removing-challenge": [ + "§cRandom Item Removing", + "Every few seconds a *random item*", + "will be *removed* from your *inventory*" + ], + "item-death-on-fall-challenge": [ + "§fDeath On Fall Damage", + "You *die instantly*, when", + "you take *fall damage*" + ], + "item-zero-hearts-challenge": [ + "§6Zero Hearts", + "After a *protection time* you have to", + "get *absorption permanently* else you will die" + ], + "item-random-effect-challenge": [ + "§6Random Effects", + "You get a *random potion effect*", + "in a set *interval*" + ], + "menu-random-effect-challenge-settings": "Random Effects", + "item-random-effect-time-challenge": [ + "§6Interval", + "The *interval* you get the *effect* in" + ], + "item-random-effect-length-challenge": [ + "§6Length", + "The *length* you have the *effect*" + ], + "item-random-effect-amplifier-challenge": [ + "§6Amplifier", + "The *amplifier* the effect has" + ], + "item-permanent-effect-on-damage-challenge": [ + "§6Permanent Effects", + "Everytime you *take damage* you get", + "a random *permanent potion effect*" + ], + "item-random-challenge-challenge": [ + "§cRandom Challenge", + "In a set *interval* a random", + "*challenge* will be *activated*" + ], + "item-anvil-rain-challenge": [ + "§cAnvil Rain", + "*Anvils* are falling from the *sky*" + ], + "menu-anvil-rain-challenge-settings": "Anvil Rain", + "item-anvil-rain-time-challenge": [ + "§6Interval", + "The *interval*, the *anvils* are spawning in" + ], + "item-anvil-rain-range-challenge": [ + "§6Range", + "The *range* of chunks, the *anvils* are spawning in" + ], + "item-anvil-rain-count-challenge": [ + "§6Amount", + "The *amount* of anvils that", + "are spawning in one chunk" + ], + "item-anvil-rain-damage-challenge": [ + "§6Damage", + "The *damage* you take from an *anvil*" + ], + "item-water-mlg-challenge": [ + "§bWater MLG", + "You have to do a *Water MLG*", + "over and over again" + ], + "item-ender-games-challenge": [ + "§5Ender Games", + "Every *few minutes* you will be", + "*swapped* with a *random entity*", + "in a *200 blocks* range" + ], + "item-random-event-challenge": [ + "§6Random Events", + "Every *few minutes* one of", + "*{0} random Events* will be activated" + ], + "item-block-chunk-item-remove-challenge": [ + "§6Movement Item Remove", + "A random item will be removed from", + "your inventory for every", + "*block* / *chunk* you walk" + ], + "item-block-chunk-item-remove-challenge-block": "§6Block", + "item-block-chunk-item-remove-challenge-chunk": "§6Chunk", + "item-higher-jumps-challenge": [ + "§aHigher Jumps", + "The more *you jump*, the *higher* you jump" + ], + "item-force-height-challenge": [ + "§eForce Height", + "Every *few minutes* you have to be", + "on a *certain height*, else you die" + ], + "item-force-block-challenge": [ + "§6Force Block", + "Every *few minutes* you have to be", + "on a *certain block*, else you die" + ], + "item-force-biome-challenge": [ + "§aForce Biome", + "Every *few minutes* you have to be", + "in a *certain biome*, else you die", + "The *rarer* the biome, the *more time* you have" + ], + "item-force-mob-challenge": [ + "§bForce Mob", + "Every *few minutes* you have to", + "*kill* a *certain mob*, else you die" + ], + "item-force-item-challenge": [ + "§6Force Item", + "Every *few minutes* you have to get", + "a *certain item*, else you die" + ], + "item-random-item-challenge": [ + "§bRandom Items", + "A *random player* gets a *random item*", + "every *few seconds*" + ], + "item-always-running-challenge": [ + "§cAlways Running", + "You *cannot stop* to *walk forwards*" + ], + "item-pickup-launch-challenge": [ + "§cPickup Boost", + "When you *pick up* an *item*", + "you will be *launched* into the air" + ], + "item-tsunami-challenge": [ + "§9Tsunami", + "In a *set interval* ", + "the water rises in the *Overworld*", + "and the *lava* in the nether", + " ", + "Should be played with a *few people*!" + ], + "item-all-mobs-to-death-position-challenge": [ + "§cAll Mobs To Death Point", + "If a *Mob* gets *killed* by a player", + "all mobs of the *same type* will be", + "*teleported* to its *death point*" + ], + "item-ice-floor-challenge": [ + "§bIce Floor", + "*Air* will be replaced in a", + "*3x3* area with *packed ice*" + ], + "item-blocks-disappear-time-challenge": [ + "§fBlocks Disappear After Time", + "Placed *blocks*, will *disappear*", + "after a *few seconds*" + ], + "item-missing-items-challenge": [ + "§9Items Missing", + "Every few minutes a *random item disappears* from", + "your *inventory* and you have to *guess* which it was" + ], + "item-damage-item-challenge": [ + "§cDamage Per Item", + "When you *pickup* or *click* an item", + "in your *inventory* you take the", + "*amount* of the items as *damage*" + ], + "item-damage-teleport-challenge": [ + "§cRandom Teleport On Damage", + "You'll be teleported randomly", + "when you take damage" + ], + "item-loop-challenge": [ + "§6Loop Challenge", + "Certain actions are *looped*", + "until a player *sneaks*" + ], + "item-uncraft-challenge": [ + "§6Items Crafting Back", + "*Items* in your inventory are", + "*crafting* back all few seconds" + ], + "item-freeze-challenge": [ + "§bFreeze Challenge", + "For each heart of *damage*, you'll be", + "*frozen* for a certain time" + ], + "item-dont-stop-running-challenge": [ + "§9Dont stop running", + "You are only allowed to stand *still*", + "a certain *time* before you *die*" + ], + "item-consume-launch-challenge": [ + "§cConsume Boost", + "When you *eat* an *item*", + "you will be *launched* into the air" + ], + "item-five-hundred-blocks-challenges": [ + "§5500 Blocks", + "*Every 500 Blocks walked* players", + "will get a *64 stack* of a random item.", + "*Blocks* and *Entities* won't *drop* any items." + ], + "item-level-border-challenges": [ + "§eLevel = Border", + "The *border size* adjusts to *the player*", + "with the *most levels*." + ], + "item-chunk-effect-challenge": [ + "§3Random Chunk Effects", + "In *each chunk* you'll get", + "a random *potion effect*" + ], + "item-repeat-chunk-challenge": [ + "§2Repeated Chunk", + "Blocks that are *placed or destroyed*", + "will be placed / destroyed in *every chunk*" + ], + "item-blocks-fly-challenge": [ + "§fBlocks Fly in Air", + "*Blocks* you've *walked* on fly", + "into the air after *one second*" + ], + "item-respawn-end-challenge": [ + "§5Mobs Respawn In End", + "*Killed mobs* respawn in *end dimension*" + ], + "item-block-effect-challenge": [ + "§3Random Block Effects", + "On *each block* you'll get", + "a random *potion effect*" + ], + "item-entity-effect-challenge": [ + "§5Mobs Got Random Effects", + "*Every Mob* has a random", + "potion effect with *max amplifier*" + ], + "item-block-mob-challenge": [ + "§cMob Blocks", + "A *random mob* spawns out of *every broken block*", + "and to *get the block* you have to *kill it*" + ], + "item-entity-loot-randomizer-challenge": [ + "§6Entity Loot Randomizer", + "All mob drops are *randomly swapped*." + ], + "item-no-shared-advancements-challenge": [ + "§2No Shared Advancements", + "You're *not allowed* to get *advancements* someone else", + "*already did*. Else *you'll die*." + ], + "item-chunk-deletion-challenge": [ + "§6Chunk Deletion", + "*Chunks* that players are in *delete*", + "completely after the given *time*" + ], + "item-delay-damage-description": [ + "§4Damage delay", + "All *damage* from all *players* is", + "added up and dealt after *5 minutes*." + ], + "item-dragon-goal": [ + "§5Ender Dragon", + "Kill the *Ender Dragon* to win" + ], + "item-wither-goal": [ + "§dWither", + "Kill a *Wither* to win" + ], + "item-iron-golem-goal": [ + "§bIron Golem", + "Kill an *Iron Golem* to win" + ], + "item-snow-golem-goal": [ + "§bSnowman", + "Kill a *Snowman* to win" + ], + "item-elder-guardian-goal": [ + "§bElder Guardian", + "Kill an *Elder Guardian* to win" + ], + "item-warden-goal": [ + "§5Warden", + "Kill an *Warden* to win" + ], + "item-most-deaths-goal": [ + "§6Most Deaths", + "Who *collects* the most *different deaths* wins" + ], + "item-most-items-goal": [ + "§cMost Items", + "Who *collects* the most *different items* wins" + ], + "item-last-man-standing-goal": [ + "§cLast Man Standing", + "Who survived until the end wins" + ], + "item-mine-most-blocks-goal": [ + "§eMost Blocks", + "Who *breaks* the most *blocks* wins" + ], + "item-most-xp-goal": [ + "§aMost XP", + "Who *collects* the most *EXP* wins" + ], + "item-first-one-to-die-goal": [ + "§cFirst Death", + "Who *dies* first wins" + ], + "item-collect-wood-goal": [ + "§6Collect Wood", + "Who first collected all types of wood set wins" + ], + "item-collect-wood-goal-overworld": "§aOverworld", + "item-collect-wood-goal-nether": "§cNether", + "item-collect-wood-goal-both": "§9Both", + "item-all-bosses-goal": [ + "§bAll Bosses", + "Each boss must has to be killed once to win" + ], + "item-all-bosses-new-goal": [ + "§5All Bosses (+ Warden)", + "Each boss must has to be killed once to win" + ], + "item-all-mobs-goal": [ + "§bAll Mobs", + "Each mob has to be killed once to win" + ], + "item-all-monster-goal": [ + "§bAll Monsters", + "Each monster has to be killed once to win" + ], + "item-all-items-goal": [ + "§2All Items", + "Find *all items* that are in *Minecraft*" + ], + "item-finish-raid-goal": [ + "§6Finish Raid", + "The first player that *finishes* a *raid* wins" + ], + "item-most-emeralds-goal": [ + "§2Most Emeralds", + "The player with the *most*", + "*emeralds* wins" + ], + "item-all-advancements-goal": [ + "§6All Advancements", + "The first player that *gets* all *advancements* wins" + ], + "item-max-height-goal": [ + "§fMaximum Height", + "The *first* player to reach", + "*Y = {0}* wins" + ], + "item-min-height-goal": [ + "§fMinimum Height", + "The *first* player to reach", + "*Y = {0}* wins" + ], + "item-race-goal": [ + "§5Race", + "The *first* player to *reach* a", + "*random* location in the overworld wins" + ], + "item-most-ores-goal": [ + "§9Most Ores", + "The player that mines the most ores wins" + ], + "item-find-elytra-goal": [ + "§fFind Elytra", + "The *player* that finds an elytra *wins*" + ], + "item-eat-cake-goal": [ + "§fEat Cake", + "The player that *eats a cake* first *wins*" + ], + "item-collect-horse-armor-goal": [ + "§bCollect Horse Armor", + "The player that *collects* every", + "horse armor first *wins*" + ], + "item-collect-ice-goal": [ + "§bCollect Ice Blocks", + "The player that *collects* every", + "ice blocks and snow first *wins*" + ], + "item-collect-swords-goal": [ + "§9Collect Swords", + "The player that *collects* every", + "sword first *wins*" + ], + "item-collect-workstations-item": [ + "§6Collect Workstations", + "The player that *collects* every", + "villager workstation first *wins*" + ], + "item-eat-most-goal": [ + "§6Eat most", + "The player that fills the mods hunger bars *wins*" + ], + "item-force-item-battle-goal": [ + "§5Force Item Battle", + "Each player gets *a random item* that", + "he has *to find*.", + "The player that *found* the *most items*, wins." + ], + "menu-force-item-battle-goal-settings": "Force Item Battle", + "item-force-item-battle-goal-give-item": [ + "§bGive Item On Skip", + "If a player *skips* an item,", + "they will *receive* it" + ], + "item-force-mob-battle-goal": [ + "§bForce Mob Battle", + "Each player gets *a random mob* that", + "he has to *kill*.", + "The player that *killed* the *most mobs*, wins." + ], + "item-force-advancement-battle-goal": [ + "§6Force Advancement Battle", + "Each player gets a *random advancement*,", + "that he has to complete." + ], + "menu-force-mob-battle-goal-settings": "Force Mob Battle", + "item-get-full-health-goal": [ + "§aGet Full Health", + "The first player to gain full health wins." + ], + "menu-force-advancement-battle-goal-settings": "Force Advancement Battle", + "item-force-block-battle-goal": [ + "§aForce Block Battle", + "Every player gets a *random*", + "*block*, on which he has to stand" + ], + "menu-force-block-battle-goal-settings": "Force Block Battle", + "item-force-block-battle-goal-give-block": [ + "§bGive Block On Skip", + "If a player *skips* a block,", + "they will *receive* it" + ], + "item-force-biome-battle-goal": [ + "§2Force Biome Battle", + "Each player gets a *random biome*,", + "that he has to *enter*." + ], + "menu-force-biome-battle-goal-settings": "Force Biome Battle", + "item-force-damage-battle-goal": [ + "§3Force Damage Battle", + "Each player gets a *random damage amount*,", + "that he has to *take*." + ], + "menu-force-damage-battle-goal-settings": "Force Damage Battle", + "item-force-height-battle-goal": [ + "§6Force Height Battle", + "Each player gets a *random height*,", + "that he has to *reach*." + ], + "menu-force-height-battle-goal-settings": "Force Height Battle", + "item-force-position-battle-goal": [ + "§aForce Position Battle", + "Each player gets a *random position*,", + "that he has to *reach*." + ], + "menu-force-position-battle-goal-settings": "Force Position Battle", + "item-extreme-force-battle-goal": [ + "§cExtreme Force Battle", + "Each player gets a *random target*,", + "that he has to reach." + ], + "menu-extreme-force-battle-goal-settings": "Extreme Force Battle", + "item-damage-rule-none": [ + "§6General Damage", + "Sets whether you can get damage or not" + ], + "item-damage-rule-fire": [ + "§6Fire Damage", + "Sets whether you get *damage* from *Fire* and *Lava*" + ], + "item-damage-rule-attack": [ + "§3Attack Damage", + "Sets whether you get *damage* from *Melee Attacks* of entites" + ], + "item-damage-rule-projectile": [ + "§6Projectile Damage", + "Sets whether you get *damage* from *Projectiles*" + ], + "item-damage-rule-fall": [ + "§fFall Damage", + "Sets whether you get *damage* from *Fall Damage" + ], + "item-damage-rule-explosion": [ + "§cExplosion Damage", + "Sets whether you get *damage* from *Explosions" + ], + "item-damage-rule-drowning": [ + "§9Drowning Damage", + "Sets whether you get *damage* from *Drowning" + ], + "item-damage-rule-block": [ + "§eBlock Damage", + "Sets whether you get *damage* from *Falling Blocks" + ], + "item-damage-rule-magic": [ + "§5Magic Damage", + "Sets whether you get *damage* from", + "*Poison, Wither or other Potions" + ], + "item-damage-rule-freeze": [ + "§cFreeze Damage", + "Sets whether you get *damage* from *Freezing*" + ], + "item-block-material": [ + "{0}", + "Sets whether *{1}* can be used" + ], + "custom-limit": "You've reached the limit of §e{0} challenges", + "custom-not-deleted": "Challenge doesn't exist yet!", + "custom-saved": "§7Challenge §asaved §7locally", + "custom-saved-db": [ + "To save it in your database use §e/db save customs", + "§cWarning: §7Old challenges will be overwritten!" + ], + "custom-no-changes": "You haven't made any changes", + "custom-name-info": "Type the new name into the chat", + "custom-command-info": [ + "Type the command §ewithout / §7in chat", + "Allowed commands: §e{0}", + "§cOther commands can be allowed in the config" + ], + "custom-command-not-allowed": "Command §e{0} §7is not set as allowed command in config", + "custom-chars-max_length": "You've reached the limit of {0} characters", + "custom-not-loaded": [ + " ", + "There are no currently loaded challenges.", + "You're missing your challenges? §e/db load customs", + "You've got problems with saving them?", + "Save your challenges before leaving with §e/db save customs", + " " + ], + "custom-main-view-challenges": "§6View Challenges", + "custom-main-create-challenge": "§aCreate Challenge", + "custom-title-trigger": "Trigger", + "custom-title-action": "Action", + "custom-title-view": "View", + "custom-sub-finish": "§aFinished", + "item-custom-info-delete": [ + "§cDelete", + "*Warning* This Action cannot be made *undone*" + ], + "item-custom-info-save": "§aSave", + "item-custom-info-trigger": [ + "§cTrigger", + "*Click here* to set what has to be happening", + "for the *action* to execute" + ], + "item-custom-info-action": [ + "§bAction", + "*Click here* to set what should happen", + "once the *trigger* is met" + ], + "item-custom-info-material": [ + "§6Display Item", + "*Click here* to change the display item" + ], + "item-custom-info-name": [ + "§6Name", + "*Click here* to change the name via chat", + "Max Characters: 50" + ], + "custom-info-currently": "§7Set §8» §e", + "custom-info-trigger": "§7Trigger", + "custom-info-action": "§7Action", + "item-custom-trigger-jump": [ + "§aPlayer Jumps" + ], + "item-custom-trigger-sneak": [ + "§aPlayer Sneaks" + ], + "item-custom-trigger-move_block": [ + "§6Player Walks A Block" + ], + "item-custom-trigger-death": [ + "§cEntity Dies" + ], + "item-custom-trigger-damage": [ + "§cEntity Takes Damage" + ], + "item-custom-trigger-damage-any": [ + "§aAny Cause" + ], + "item-custom-trigger-damage_by_player": [ + "§cEntity Takes Damage By Player" + ], + "item-custom-trigger-intervall": [ + "§6Interval" + ], + "item-custom-trigger-intervall-second": [ + "§6Each Second" + ], + "item-custom-trigger-intervall-seconds": [ + "§6Every {0} Seconds" + ], + "item-custom-trigger-intervall-minutes": [ + "§6Every {0} Minutes" + ], + "item-custom-trigger-block_place": [ + "§aBlock Placed" + ], + "item-custom-trigger-block_break": [ + "§cBlock Destroyed" + ], + "item-custom-trigger-consume_item": [ + "§2Consume Item" + ], + "item-custom-trigger-pickup_item": [ + "§bPickup Item" + ], + "item-custom-trigger-drop_item": [ + "§9Player Dropped Item" + ], + "item-custom-trigger-advancement": [ + "§cPlayer Gets Advancement" + ], + "item-custom-trigger-hunger": [ + "§2Player Looses Hunger" + ], + "item-custom-trigger-move_down": [ + "§6Player Moves Block Down" + ], + "item-custom-trigger-move_up": [ + "§6Player Moves Block Up" + ], + "item-custom-trigger-move_camera": [ + "§6Moves Camera" + ], + "item-custom-trigger-stands_on_specific_block": [ + "§6Player Is On Specific Block" + ], + "item-custom-trigger-stands_not_on_specific_block": [ + "§6Player Is Not On Specific Block" + ], + "item-custom-trigger-gain_xp": [ + "§5Player Gets XP" + ], + "item-custom-trigger-level_up": [ + "§5Player Gets Level" + ], + "item-custom-trigger-item_craft": [ + "§6Player Crafts Item" + ], + "item-custom-trigger-in_liquid": [ + "§9Player Is In Liquid" + ], + "item-custom-trigger-get_item": [ + "§aGet Item", + "Action will be executed *every time*", + "item is clicked or picked up" + ], + "item-custom-action-cancel": [ + "§4Cancel Trigger", + "Prevent that the trigger will be executed", + "Non preventable Trigger: *Jump*, *Sneak*, *Death*", + "*Advancement*, *Level Up*, *In Liquid*" + ], + "item-custom-action-command": [ + "§4Execute Command", + "Make players execute commands.", + "Commands are executed for players via */execute as*.", + "Allowed commands can be set in plugin config.", + "The player doesn't need the *permission* to the commands.", + "Player aren't able to execute *plugin commands*." + ], + "item-custom-action-kill": [ + "§4Kill", + "Kill entities" + ], + "item-custom-action-damage": [ + "§cDamage", + "Hurt entities" + ], + "item-custom-action-heal": [ + "§aHeal", + "Restore entity health" + ], + "item-custom-action-hunger": [ + "§6Hunger", + "Make Entities get hunger" + ], + "item-custom-action-max_health": [ + "§cChange Max Health", + "Modify the max health of players.", + "Will be reset with */gamestate reset*" + ], + "item-custom-action-max_health-offset": [ + "§cHealth Change", + "Choose how the max health should be changed" + ], + "item-custom-action-spawn_entity": [ + "§3Spawn Entity", + "Spawn an entity with a specific type" + ], + "item-custom-action-random_mob": [ + "§6Random Entity", + "Spawn a random entity" + ], + "item-custom-action-random_item": [ + "§bRandom Item", + "Give random items to players" + ], + "item-custom-action-uncraft_inventory": [ + "§eUncraft Inventory", + "Make players inventories uncraft" + ], + "item-custom-action-boost_in_air": [ + "§fBoost In Air", + "Boost entities into the air" + ], + "item-custom-action-boost_in_air-strength": [ + "§fAmplifier" + ], + "item-custom-action-potion_effect": [ + "§dPotion Effect", + "Add a potion effect to entities" + ], + "item-custom-action-permanent_effect": [ + "§6Permanent Potion Effect", + "Add a permanent potion effect to players.", + "Uses the settings of the permanent effect challenge." + ], + "item-custom-action-random_effect": [ + "§dRandom Potion Effect", + "Add a random potion effect to entities" + ], + "item-custom-action-clear_inventory": [ + "§cClear Inventory", + "Clear the inventory of players" + ], + "item-custom-action-drop_random_item": [ + "§aDrop Item From Inventory", + "Drop a random item from the inventory onto the floor" + ], + "item-custom-action-remove_random_item": [ + "§cRemove Item From Inventory", + "Remove a random item from the inventory" + ], + "item-custom-action-swap_random_item": [ + "§6Swap Items In Inventory", + "Swap two items in the inventory" + ], + "item-custom-action-freeze": [ + "§bFreeze", + "Temporarily freeze mobs", + "Uses the settings of the freeze challenge" + ], + "item-custom-action-invert_health": [ + "§cInvert Health", + "Invert the current health of players" + ], + "item-custom-action-water_mlg": [ + "§9Water MLG", + "All players have to do a water mlg to survive" + ], + "item-custom-action-jnr": [ + "§6Jump And Run", + "A random player has to a a jump and run", + "that gets longer everytime" + ], + "item-custom-action-win": [ + "§6Win", + "The challenge will be won *by specific players*" + ], + "item-custom-action-random_hotbar": [ + "§eRandom Hotbar", + "The inventory is emptied and the player", + "gets a full hotbar of random items" + ], + "item-custom-action-modify_border": [ + "§bModify World Border", + "Make the world border *bigger* or *tinier*" + ], + "item-custom-action-modify_border-change": [ + "§dChange" + ], + "item-custom-action-swap_mobs": [ + "§5Swap mobs", + "Swap a mob with another of the same world" + ], + "item-custom-action-place_structure": [ + "§aPlace Structure", + "Places a structure" + ], + "item-custom-action-place_structure-random": "§bRandom structure", + "item-custom-setting-target-current": [ + "§6Current Entity", + "The action will be executed for the *current entity*" + ], + "item-custom-setting-target-every_mob": [ + "§4Every Mob", + "The action will be executed for *every mob*" + ], + "item-custom-setting-target-every_mob_except_current": [ + "§4Every Mob Except Current", + "The action will be executed for *every mob*", + "*except* the current one" + ], + "item-custom-setting-target-every_mob_except_players": [ + "§4Every Mob Except Players", + "The action will be executed for *every mob except players*" + ], + "item-custom-setting-target-random_player": [ + "§5Random Player", + "The action will be executed for a *random player*" + ], + "item-custom-setting-target-every_player": [ + "§cEvery Player", + "The action will be executed for *every player*" + ], + "item-custom-setting-target-current_player": [ + "§aCurrent Player", + "The action will be executed for the *active player*.", + "§7§oIf the current entity is not a player nothing will be happen" + ], + "item-custom-setting-target-console": [ + "§4Console", + "The action will be executed for the *console*" + ], + "item-custom-setting-entity_type-any": "§cAny Entity", + "item-custom-setting-entity_type-player": "§aPlayer", + "item-custom-setting-block-any": "§2Any Block", + "item-custom-setting-item-any": "§2Any Item", + "custom-subsetting-target_entity": "Target Entity", + "custom-subsetting-entity_type": "Entity Type", + "custom-subsetting-liquid": "Liquid", + "custom-subsetting-time": "Time", + "custom-subsetting-damage_cause": "Damage Cause", + "custom-subsetting-amount": "Amount", + "custom-subsetting-value": "Value Editor", + "custom-subsetting-health_offset": "Change", + "custom-subsetting-length": "Length", + "custom-subsetting-amplifier": "Amplifier", + "custom-subsetting-change": "Change", + "custom-subsetting-swap_targets": "Swap Targets" } diff --git a/language/languages.json b/language/languages.json index 2758e52e6..3d81dfd05 100644 --- a/language/languages.json +++ b/language/languages.json @@ -1,4 +1,4 @@ [ - "en", - "de" + "en", + "de" ] diff --git a/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java b/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java index 1277a6e1f..745bf6468 100644 --- a/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java +++ b/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java @@ -7,9 +7,9 @@ public final class MongoConnector extends JavaPlugin { - @Override - public void onLoad() { - Challenges.getInstance().getDatabaseManager().registerDatabase("mongodb", MongoDBDatabase.class, this); - } + @Override + public void onLoad() { + Challenges.getInstance().getDatabaseManager().registerDatabase("mongodb", MongoDBDatabase.class, this); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java b/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java index 309c8efa2..c4323fb08 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java @@ -18,110 +18,110 @@ public final class ChallengeAPI { - private ChallengeAPI() { - } - - public static boolean isStarted() { - return Challenges.getInstance().getChallengeTimer().isStarted(); - } - - public static boolean isPaused() { - return Challenges.getInstance().getChallengeTimer().isPaused(); - } - - public static TimerStatus getTimerStatus() { - return Challenges.getInstance().getChallengeTimer().getStatus(); - } - - public static void pauseTimer() { - Challenges.getInstance().getChallengeTimer().pause(true); - } - - public static void pauseTimer(boolean playInGameEffects) { - Challenges.getInstance().getChallengeTimer().pause(playInGameEffects); - } - - public static void resumeTimer() { - Challenges.getInstance().getChallengeTimer().resume(); - } - - public static void resetTimer() { - Challenges.getInstance().getChallengeTimer().reset(); - } - - public static void endChallenge(@Nonnull ChallengeEndCause endCause) { - Challenges.getInstance().getServerManager().endChallenge(endCause, null); - } - - public static void endChallenge(@Nonnull ChallengeEndCause endCause, Supplier> winnerGetter) { - Challenges.getInstance().getServerManager().endChallenge(endCause, winnerGetter); - } - - - public static boolean isWorldInUse() { - return Challenges.getInstance().getWorldManager().isWorldInUse(); - } - - public static boolean isFresh() { - return Challenges.getInstance().getServerManager().isFresh(); - } - - public static void registerScheduler(@Nonnull Object... scheduler) { - Challenges.getInstance().getScheduler().register(scheduler); - } - - public static void subscribeLoader(@Nonnull Class classOfLoader, @Nonnull Runnable action) { - Challenges.getInstance().getLoaderRegistry().subscribe(classOfLoader, action); - } - - @Nonnull - public static List getCustomDrops(@Nonnull Material block) { - return Challenges.getInstance().getBlockDropManager().getCustomDrops(block); - } - - public static boolean getDropChance(@Nonnull Material block) { - return Challenges.getInstance().getBlockDropManager().getDropChance(block).getAsBoolean(); - } - - public static boolean getItemsDirectIntoInventory() { - return Challenges.getInstance().getBlockDropManager().isItemsDirectIntoInventory(); - } - - @Nonnull - public static String formatTime(long seconds) { - return Challenges.getInstance().getChallengeTimer().getFormat().format(seconds); - } - - /** - * @return all players that aren't ignored by the plugin - */ - @Nonnull - public static List getIngamePlayers() { - List list = new ArrayList<>(); - for (Player player : Bukkit.getOnlinePlayers()) { - if (!AbstractChallenge.ignorePlayer(player)) { - list.add(player); - } - } - return list; - } - - public static List getGameWorlds() { - return Challenges.getInstance().getGameWorldStorage().getGameWorlds(); - } - - public static World getGameWorld(@Nullable Environment environment) { - return Challenges.getInstance().getGameWorldStorage().getWorld(environment); - } - - public static boolean isPlayerInGameWorld(@Nonnull Environment environment) { - World world = getGameWorld(environment); - for (Player player : world.getPlayers()) { - if (!AbstractChallenge.ignorePlayer(player)) { - return true; - } - } - return false; - } + private ChallengeAPI() { + } + + public static boolean isStarted() { + return Challenges.getInstance().getChallengeTimer().isStarted(); + } + + public static boolean isPaused() { + return Challenges.getInstance().getChallengeTimer().isPaused(); + } + + public static TimerStatus getTimerStatus() { + return Challenges.getInstance().getChallengeTimer().getStatus(); + } + + public static void pauseTimer() { + Challenges.getInstance().getChallengeTimer().pause(true); + } + + public static void pauseTimer(boolean playInGameEffects) { + Challenges.getInstance().getChallengeTimer().pause(playInGameEffects); + } + + public static void resumeTimer() { + Challenges.getInstance().getChallengeTimer().resume(); + } + + public static void resetTimer() { + Challenges.getInstance().getChallengeTimer().reset(); + } + + public static void endChallenge(@Nonnull ChallengeEndCause endCause) { + Challenges.getInstance().getServerManager().endChallenge(endCause, null); + } + + public static void endChallenge(@Nonnull ChallengeEndCause endCause, Supplier> winnerGetter) { + Challenges.getInstance().getServerManager().endChallenge(endCause, winnerGetter); + } + + + public static boolean isWorldInUse() { + return Challenges.getInstance().getWorldManager().isWorldInUse(); + } + + public static boolean isFresh() { + return Challenges.getInstance().getServerManager().isFresh(); + } + + public static void registerScheduler(@Nonnull Object... scheduler) { + Challenges.getInstance().getScheduler().register(scheduler); + } + + public static void subscribeLoader(@Nonnull Class classOfLoader, @Nonnull Runnable action) { + Challenges.getInstance().getLoaderRegistry().subscribe(classOfLoader, action); + } + + @Nonnull + public static List getCustomDrops(@Nonnull Material block) { + return Challenges.getInstance().getBlockDropManager().getCustomDrops(block); + } + + public static boolean getDropChance(@Nonnull Material block) { + return Challenges.getInstance().getBlockDropManager().getDropChance(block).getAsBoolean(); + } + + public static boolean getItemsDirectIntoInventory() { + return Challenges.getInstance().getBlockDropManager().isItemsDirectIntoInventory(); + } + + @Nonnull + public static String formatTime(long seconds) { + return Challenges.getInstance().getChallengeTimer().getFormat().format(seconds); + } + + /** + * @return all players that aren't ignored by the plugin + */ + @Nonnull + public static List getIngamePlayers() { + List list = new ArrayList<>(); + for (Player player : Bukkit.getOnlinePlayers()) { + if (!AbstractChallenge.ignorePlayer(player)) { + list.add(player); + } + } + return list; + } + + public static List getGameWorlds() { + return Challenges.getInstance().getGameWorldStorage().getGameWorlds(); + } + + public static World getGameWorld(@Nullable Environment environment) { + return Challenges.getInstance().getGameWorldStorage().getWorld(environment); + } + + public static boolean isPlayerInGameWorld(@Nonnull Environment environment) { + World world = getGameWorld(environment); + for (Player player : world.getPlayers()) { + if (!AbstractChallenge.ignorePlayer(player)) { + return true; + } + } + return false; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java index fcc6ca530..8f639b03f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java @@ -17,151 +17,151 @@ public final class BlockDropManager { - private final Map drops = new HashMap<>(); - private final Map chance = new HashMap<>(); - private SubSetting directInventorySetting; - - @Nonnull - public Collection getDrops(@Nonnull Block block) { - if (!getDropChance(block.getType()).getAsBoolean()) return new ArrayList<>(); - List customDrops = getCustomDrops(block.getType()); - if (!customDrops.isEmpty()) - return customDrops.stream().map(ItemStack::new).collect(Collectors.toList()); - return block.getDrops(); - } - - @Nonnull - public Collection getDrops(@Nonnull Block block, @Nullable ItemStack tool) { - if (!getDropChance(block.getType()).getAsBoolean()) return new ArrayList<>(); - List customDrops = getCustomDrops(block.getType()); - if (!customDrops.isEmpty()) - return customDrops.stream().map(ItemStack::new).collect(Collectors.toList()); - return block.getDrops(tool); - } - - @Nonnull - public List getCustomDrops(@Nonnull Material block) { - RegisteredDrops option = drops.get(block); - if (option == null) return new ArrayList<>(); - return option.getFirst().orElse(new ArrayList<>()); - } - - public void setCustomDrops(@Nonnull Material block, @Nonnull Material item, byte priority) { - setCustomDrops(block, Collections.singletonList(item), priority); - } - - public void setCustomDrops(@Nonnull Material block, @Nonnull List items, byte priority) { - Logger.debug("Setting block drop for {} to {} at priority {}", block, items, priority); - - RegisteredDrops option = this.drops.computeIfAbsent(block, key -> new RegisteredDrops()); - option.setOption(priority, items); - } - - public void resetCustomDrop(@Nonnull Material block, byte priority) { - Logger.debug("Resetting block drop for {} at priority {}", block, priority); - - RegisteredDrops option = drops.get(block); - if (option == null) return; - - option.resetOption(priority); - if (option.isEmpty()) drops.remove(block); - } - - public void resetCustomDrops(byte priority) { - Logger.debug("Resetting block drops at priority {}", priority); - - List remove = new ArrayList<>(); - for (Entry entry : drops.entrySet()) { - - RegisteredDrops option = entry.getValue(); - option.resetOption(priority); - if (option.isEmpty()) remove.add(entry.getKey()); - } - - remove.forEach(drops::remove); - } - - @Nonnull - public BooleanSupplier getDropChance(@Nonnull Material block) { - RegisteredChance option = chance.get(block); - if (option == null) return () -> true; - return option.getFirst().orElse(() -> true); - } - - public void setDropChance(@Nonnull Material block, byte priority, @Nonnull BooleanSupplier chance) { - Logger.debug("Setting block drop chance for {} at priority {}", block, priority); - - RegisteredChance option = this.chance.computeIfAbsent(block, key -> new RegisteredChance()); - option.setOption(priority, chance); - } - - public void resetDropChance(byte priority) { - Logger.debug("Resetting block drop chance at priority " + priority); - - List remove = new ArrayList<>(); - for (Entry entry : chance.entrySet()) { - - RegisteredChance option = entry.getValue(); - option.resetOption(priority); - if (option.isEmpty()) remove.add(entry.getKey()); - } - - remove.forEach(drops::remove); - } - - @Nonnull - public Map getRegisteredDrops() { - return Collections.unmodifiableMap(drops); - } - - public boolean isItemsDirectIntoInventory() { - if (directInventorySetting == null) - directInventorySetting = AbstractChallenge.getFirstInstance(CutCleanSetting.class).getSetting("items->inventory"); - return directInventorySetting.isEnabled(); - } - - public static final class DropPriority { - - public static final byte - CUT_CLEAN = 10, - RANDOMIZER = 5, - CHANCE = -128; - - private DropPriority() { - } - } - - private static abstract class RegisteredOptions { + private final Map drops = new HashMap<>(); + private final Map chance = new HashMap<>(); + private SubSetting directInventorySetting; + + @Nonnull + public Collection getDrops(@Nonnull Block block) { + if (!getDropChance(block.getType()).getAsBoolean()) return new ArrayList<>(); + List customDrops = getCustomDrops(block.getType()); + if (!customDrops.isEmpty()) + return customDrops.stream().map(ItemStack::new).collect(Collectors.toList()); + return block.getDrops(); + } + + @Nonnull + public Collection getDrops(@Nonnull Block block, @Nullable ItemStack tool) { + if (!getDropChance(block.getType()).getAsBoolean()) return new ArrayList<>(); + List customDrops = getCustomDrops(block.getType()); + if (!customDrops.isEmpty()) + return customDrops.stream().map(ItemStack::new).collect(Collectors.toList()); + return block.getDrops(tool); + } + + @Nonnull + public List getCustomDrops(@Nonnull Material block) { + RegisteredDrops option = drops.get(block); + if (option == null) return new ArrayList<>(); + return option.getFirst().orElse(new ArrayList<>()); + } + + public void setCustomDrops(@Nonnull Material block, @Nonnull Material item, byte priority) { + setCustomDrops(block, Collections.singletonList(item), priority); + } + + public void setCustomDrops(@Nonnull Material block, @Nonnull List items, byte priority) { + Logger.debug("Setting block drop for {} to {} at priority {}", block, items, priority); + + RegisteredDrops option = this.drops.computeIfAbsent(block, key -> new RegisteredDrops()); + option.setOption(priority, items); + } + + public void resetCustomDrop(@Nonnull Material block, byte priority) { + Logger.debug("Resetting block drop for {} at priority {}", block, priority); + + RegisteredDrops option = drops.get(block); + if (option == null) return; + + option.resetOption(priority); + if (option.isEmpty()) drops.remove(block); + } + + public void resetCustomDrops(byte priority) { + Logger.debug("Resetting block drops at priority {}", priority); + + List remove = new ArrayList<>(); + for (Entry entry : drops.entrySet()) { + + RegisteredDrops option = entry.getValue(); + option.resetOption(priority); + if (option.isEmpty()) remove.add(entry.getKey()); + } + + remove.forEach(drops::remove); + } + + @Nonnull + public BooleanSupplier getDropChance(@Nonnull Material block) { + RegisteredChance option = chance.get(block); + if (option == null) return () -> true; + return option.getFirst().orElse(() -> true); + } + + public void setDropChance(@Nonnull Material block, byte priority, @Nonnull BooleanSupplier chance) { + Logger.debug("Setting block drop chance for {} at priority {}", block, priority); + + RegisteredChance option = this.chance.computeIfAbsent(block, key -> new RegisteredChance()); + option.setOption(priority, chance); + } + + public void resetDropChance(byte priority) { + Logger.debug("Resetting block drop chance at priority " + priority); + + List remove = new ArrayList<>(); + for (Entry entry : chance.entrySet()) { + + RegisteredChance option = entry.getValue(); + option.resetOption(priority); + if (option.isEmpty()) remove.add(entry.getKey()); + } + + remove.forEach(drops::remove); + } + + @Nonnull + public Map getRegisteredDrops() { + return Collections.unmodifiableMap(drops); + } + + public boolean isItemsDirectIntoInventory() { + if (directInventorySetting == null) + directInventorySetting = AbstractChallenge.getFirstInstance(CutCleanSetting.class).getSetting("items->inventory"); + return directInventorySetting.isEnabled(); + } + + public static final class DropPriority { + + public static final byte + CUT_CLEAN = 10, + RANDOMIZER = 5, + CHANCE = -128; + + private DropPriority() { + } + } + + private static abstract class RegisteredOptions { - private final SortedMap optionByPriority = new TreeMap<>(Collections.reverseOrder()); + private final SortedMap optionByPriority = new TreeMap<>(Collections.reverseOrder()); - public void setOption(byte priority, @Nonnull T option) { - optionByPriority.put(priority, option); - } + public void setOption(byte priority, @Nonnull T option) { + optionByPriority.put(priority, option); + } - public void resetOption(byte priority) { - optionByPriority.remove(priority); - } + public void resetOption(byte priority) { + optionByPriority.remove(priority); + } - @Nonnull - public Optional getFirst() { - return optionByPriority.values().stream().findFirst(); - } + @Nonnull + public Optional getFirst() { + return optionByPriority.values().stream().findFirst(); + } - public boolean isEmpty() { - return optionByPriority.isEmpty(); - } + public boolean isEmpty() { + return optionByPriority.isEmpty(); + } - } + } - public static class RegisteredDrops extends RegisteredOptions> { - private RegisteredDrops() { - } - } + public static class RegisteredDrops extends RegisteredOptions> { + private RegisteredDrops() { + } + } - public static class RegisteredChance extends RegisteredOptions { - private RegisteredChance() { - } - } + public static class RegisteredChance extends RegisteredOptions { + private RegisteredChance() { + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java index 9d46c150a..adafa7d83 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java @@ -3,86 +3,18 @@ import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.*; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.BlockEffectChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.ChunkRandomEffectChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.EntityRandomEffectChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.InfectionChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.PermanentEffectOnDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.RandomPotionEffectChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.AllMobsToDeathPoint; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.BlockMobsChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.DupedSpawningChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.HydraNormalChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.HydraPlusChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.InvisibleMobsChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.MobSightDamageChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.MobTransformationChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.MobsRespawnInEndChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.NewEntityOnJumpChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.StoneSightChallenge; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.*; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.entities.*; import net.codingarea.challenges.plugin.challenges.implementation.challenge.extraworld.JumpAndRunChallenge; import net.codingarea.challenges.plugin.challenges.implementation.challenge.extraworld.WaterMLGChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.force.ForceBiomeChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.force.ForceBlockChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.force.ForceHeightChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.force.ForceItemChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.force.ForceMobChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.DamageInventoryClearChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.MissingItemsChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.MovementItemRemovingChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.NoDupedItemsChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.PermanentItemChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.PickupItemLaunchChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.UncraftItemsChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.EnderGamesChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.FoodLaunchChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.FoodOnceChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.InvertHealthChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.LowDropRateChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.NoExpChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.NoSharedAdvancementsChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.NoTradingChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.OneDurabilityChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.AlwaysRunningChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.DontStopRunningChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.FiveHundredBlocksChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.HigherJumpsChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.HungerPerBlockChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.MoveMouseDamage; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.OnlyDirtChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.OnlyDownChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.TrafficLightChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.BlockRandomizerChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.CraftingRandomizerChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.EntityLootRandomizerChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.HotBarRandomizerChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.MobRandomizerChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomChallengeChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomEventChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomItemChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomItemDroppingChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomItemRemovingChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomItemSwappingChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomTeleportOnHitChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomizedHPChallenge; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.force.*; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.*; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.*; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.*; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.*; import net.codingarea.challenges.plugin.challenges.implementation.challenge.time.MaxBiomeTimeChallenge; import net.codingarea.challenges.plugin.challenges.implementation.challenge.time.MaxHeightTimeChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.AllBlocksDisappearChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.AnvilRainChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.BedrockPathChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.BedrockWallChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.BlockFlyInAirChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.BlocksDisappearAfterTimeChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.ChunkDeconstructionChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.ChunkDeletionChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.FloorIsLavaChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.IceFloorChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.LevelBorderChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.LoopChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.RepeatInChunkChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.SnakeChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.SurfaceHoleChallenge; -import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.TsunamiChallenge; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.world.*; import net.codingarea.challenges.plugin.challenges.implementation.goal.*; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.*; import net.codingarea.challenges.plugin.challenges.implementation.setting.*; @@ -96,254 +28,254 @@ */ public final class ChallengeLoader extends ModuleChallengeLoader { - public ChallengeLoader() { - super(Challenges.getInstance()); - } - - public void enable() { - - // Settings - registerWithCommand(DifficultySetting.class, "difficulty"); - register(RegenerationSetting.class); - register(OneTeamLifeSetting.class); - register(RespawnSetting.class); - register(SplitHealthSetting.class); - register(DamageDisplaySetting.class); - register(LanguageSetting.class); - - register(PregameMovementSetting.class); - register(DeathMessageSetting.class); - register(HealthDisplaySetting.class); - registerWithCommand(PositionSetting.class, "position"); - register(DeathPositionSetting.class); - register(PlayerGlowSetting.class); - register(NoHungerSetting.class); - - register(NoItemDamageSetting.class); - register(MobGriefingSetting.class); - register(KeepInventorySetting.class); - registerWithCommand(BackpackSetting.class, "backpack"); - registerWithCommand(EnderChestCommandSetting.class, "enderchest"); - register(TimberSetting.class); - register(PvPSetting.class); - - register(NoHitDelaySetting.class); - registerWithCommand(TopCommandSetting.class, "top"); - register(MaxHealthSetting.class); - register(DamageMultiplierModifier.class); - register(CutCleanSetting.class); - register(FortressSpawnSetting.class); - register(BastionSpawnSetting.class); - - register(NoOffhandSetting.class); - register(ImmediateRespawnSetting.class); - - register(SlotLimitSetting.class); - register(OldPvPSetting.class); - register(TotemSaveDeathSetting.class); - register(SoupSetting.class); - - - // Challenges - - // Randomizer - register(RandomChallengeChallenge.class); - register(RandomizedHPChallenge.class); - register(BlockRandomizerChallenge.class); - register(CraftingRandomizerChallenge.class); - register(HotBarRandomizerChallenge.class); - registerWithCommand(EntityLootRandomizerChallenge.class, "searchloot"); - register(MobRandomizerChallenge.class); - register(RandomItemDroppingChallenge.class); - register(RandomItemRemovingChallenge.class); - register(RandomItemSwappingChallenge.class); - register(RandomItemChallenge.class); - register(RandomEventChallenge.class); - register(RandomTeleportOnHitChallenge.class); - - // Force - register(ForceHeightChallenge.class); - register(ForceBlockChallenge.class); - register(ForceMobChallenge.class); - register(ForceItemChallenge.class); - register(ForceBiomeChallenge.class); - - // Entities - register(HydraNormalChallenge.class); - register(HydraPlusChallenge.class); - register(DupedSpawningChallenge.class); - register(NewEntityOnJumpChallenge.class); - register(InvisibleMobsChallenge.class); - register(StoneSightChallenge.class); - register(MobSightDamageChallenge.class); - register(AllMobsToDeathPoint.class); - register(MobsRespawnInEndChallenge.class); - register(MobTransformationChallenge.class); - register(BlockMobsChallenge.class); - - // Damage - register(DamagePerBlockChallenge.class); - register(SneakDamageChallenge.class); - register(JumpDamageChallenge.class); - register(BlockBreakDamageChallenge.class); - register(BlockPlaceDamageChallenge.class); - register(AdvancementDamageChallenge.class); - register(DamagePerItemChallenge.class); - register(WaterAllergyChallenge.class); - register(DeathOnFallChallenge.class); - register(ReversedDamageChallenge.class); - register(FreezeChallenge.class); - register(DelayDamageChallenge.class); - - // Effect - register(ChunkRandomEffectChallenge.class); - register(BlockEffectChallenge.class); - register(EntityRandomEffectChallenge.class); - register(RandomPotionEffectChallenge.class); - register(PermanentEffectOnDamageChallenge.class); - register(InfectionChallenge.class); - - // World - register(SurfaceHoleChallenge.class); - register(BedrockWallChallenge.class); - register(BedrockPathChallenge.class); - register(FloorIsLavaChallenge.class); - register(ChunkDeconstructionChallenge.class); - register(AllBlocksDisappearChallenge.class); - register(AnvilRainChallenge.class); - register(TsunamiChallenge.class); - register(RepeatInChunkChallenge.class); - register(SnakeChallenge.class); - register(BlockFlyInAirChallenge.class); - register(BlocksDisappearAfterTimeChallenge.class); - register(LoopChallenge.class); - register(IceFloorChallenge.class); - register(LevelBorderChallenge.class); - register(ChunkDeletionChallenge.class); - - // Inventory - register(PermanentItemChallenge.class); - register(NoDupedItemsChallenge.class); - register(DamageInventoryClearChallenge.class); - register(UncraftItemsChallenge.class); - registerWithCommand(MissingItemsChallenge.class, "openmissingitems"); - register(PickupItemLaunchChallenge.class); - register(MovementItemRemovingChallenge.class); - - // Movement - register(TrafficLightChallenge.class); - register(HungerPerBlockChallenge.class); - register(OnlyDownChallenge.class); - register(OnlyDirtChallenge.class); - register(HigherJumpsChallenge.class); - register(AlwaysRunningChallenge.class); - register(DontStopRunningChallenge.class); - register(MoveMouseDamage.class); - register(FiveHundredBlocksChallenge.class); - - // Limited Time - register(MaxBiomeTimeChallenge.class); - register(MaxHeightTimeChallenge.class); - - // Custom World - register(WaterMLGChallenge.class); - register(JumpAndRunChallenge.class); - - // Misc - register(OneDurabilityChallenge.class); - register(NoTradingChallenge.class); - register(NoExpChallenge.class); - register(FoodOnceChallenge.class); - register(FoodLaunchChallenge.class); - register(LowDropRateChallenge.class); - register(EnderGamesChallenge.class); - register(InvertHealthChallenge.class); - register(NoSharedAdvancementsChallenge.class); - - - // Goal - - // Kill - register(KillEnderDragonGoal.class); - register(KillWitherGoal.class); - register(KillElderGuardianGoal.class); - register(KillWardenGoal.class); - register(KillAllBossesGoal.class); - register(KillAllBossesNewGoal.class); - register(KillIronGolemGoal.class); - register(KillSnowGolemGoal.class); - register(KillAllMobsGoal.class); - register(KillAllMonsterGoal.class); - - // Score Points - register(CollectMostDeathsGoal.class); - register(CollectMostItemsGoal.class); - register(MineMostBlocksGoal.class); - register(CollectMostExpGoal.class); - register(MostEmeraldsGoal.class); - register(MostOresGoal.class); - register(EatMostGoal.class); - - // Fastest Time - register(FirstOneToDieGoal.class); - register(CollectWoodGoal.class); - register(FinishRaidGoal.class); - register(AllAdvancementGoal.class); - register(MaxHeightGoal.class); - register(MinHeightGoal.class); - register(RaceGoal.class); - register(FindElytraGoal.class); - register(EatCakeGoal.class); - register(CollectHorseAmorGoal.class); - register(CollectIceBlocksGoal.class); - register(CollectSwordsGoal.class); - register(CollectWorkstationsGoal.class); - register(GetFullHealthGoal.class); - - // Force battle - register(ForceItemBattleGoal.class); - register(ForceMobBattleGoal.class); - register(ForceAdvancementBattleGoal.class); - register(ForceBlockBattleGoal.class); - register(ForceBiomeBattleGoal.class); - register(ForceDamageBattleGoal.class); - register(ForceHeightBattleGoal.class); - register(ForcePositionBattleGoal.class); - register(ExtremeForceBattleGoal.class); - - // Misc - register(LastManStandingGoal.class); - registerWithCommand(CollectAllItemsGoal.class, "skipitem"); - - - // Damage Rules - registerDamageRule("none", Material.TOTEM_OF_UNDYING, DamageCause.values()); - registerDamageRule("fire", Material.LAVA_BUCKET, DamageCause.FIRE, DamageCause.FIRE_TICK, DamageCause.LAVA, DamageCause.HOT_FLOOR); - registerDamageRule("attack", Material.DIAMOND_SWORD, DamageCause.ENTITY_ATTACK, DamageCause.ENTITY_SWEEP_ATTACK, DamageCause.ENTITY_EXPLOSION, DamageCause.THORNS); - registerDamageRule("projectile", Material.ARROW, DamageCause.PROJECTILE); - registerDamageRule("fall", Material.FEATHER, DamageCause.FALL); - registerDamageRule("explosion", Material.TNT, DamageCause.ENTITY_EXPLOSION, DamageCause.BLOCK_EXPLOSION); - registerDamageRule("drowning", PotionBuilder.createWaterBottle(), DamageCause.DROWNING); - registerDamageRule("block", Material.SAND, DamageCause.FALLING_BLOCK, DamageCause.SUFFOCATION, DamageCause.CONTACT); - registerDamageRule("magic", Material.BREWING_STAND, DamageCause.MAGIC, DamageCause.POISON, DamageCause.WITHER); - - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_17)) { - registerDamageRule("freeze", Material.POWDER_SNOW_BUCKET, DamageCause.FREEZE); - } - - // Material Rules - registerMaterialRule("§cArmor", "Armor", ArmorUtils.getArmor()); - registerMaterialRule("§6Golden Apple", "Golden Apple", Material.GOLDEN_APPLE, Material.ENCHANTED_GOLDEN_APPLE); - registerMaterialRule("§6Crafting Table", "Crafting Table", Material.CRAFTING_TABLE); - registerMaterialRule("§6Chest", "Chest", Material.CHEST); - registerMaterialRule("§cFurnace", "Furnace", Material.FURNACE, Material.FURNACE_MINECART); - registerMaterialRule("§5Enchanting Table", "Enchanting Table", Material.ENCHANTING_TABLE); - registerMaterialRule("§cAnvil", "Anvil", Material.ANVIL, Material.CHIPPED_ANVIL, Material.DAMAGED_ANVIL); - registerMaterialRule("§dBrewing Stand", "Brewing Stand", Material.BREWING_STAND); - registerMaterialRule("§cBow", "Bow", Material.BOW); - registerMaterialRule("§fSnowball", "Snowball", Material.SNOWBALL); - registerMaterialRule("§cFlint and Steel", "Flint and Steel", Material.FLINT_AND_STEEL); - registerMaterialRule("§cBucket", "Bucket", Material.BUCKET); - } + public ChallengeLoader() { + super(Challenges.getInstance()); + } + + public void enable() { + + // Settings + registerWithCommand(DifficultySetting.class, "difficulty"); + register(RegenerationSetting.class); + register(OneTeamLifeSetting.class); + register(RespawnSetting.class); + register(SplitHealthSetting.class); + register(DamageDisplaySetting.class); + register(LanguageSetting.class); + + register(PregameMovementSetting.class); + register(DeathMessageSetting.class); + register(HealthDisplaySetting.class); + registerWithCommand(PositionSetting.class, "position"); + register(DeathPositionSetting.class); + register(PlayerGlowSetting.class); + register(NoHungerSetting.class); + + register(NoItemDamageSetting.class); + register(MobGriefingSetting.class); + register(KeepInventorySetting.class); + registerWithCommand(BackpackSetting.class, "backpack"); + registerWithCommand(EnderChestCommandSetting.class, "enderchest"); + register(TimberSetting.class); + register(PvPSetting.class); + + register(NoHitDelaySetting.class); + registerWithCommand(TopCommandSetting.class, "top"); + register(MaxHealthSetting.class); + register(DamageMultiplierModifier.class); + register(CutCleanSetting.class); + register(FortressSpawnSetting.class); + register(BastionSpawnSetting.class); + + register(NoOffhandSetting.class); + register(ImmediateRespawnSetting.class); + + register(SlotLimitSetting.class); + register(OldPvPSetting.class); + register(TotemSaveDeathSetting.class); + register(SoupSetting.class); + + + // Challenges + + // Randomizer + register(RandomChallengeChallenge.class); + register(RandomizedHPChallenge.class); + register(BlockRandomizerChallenge.class); + register(CraftingRandomizerChallenge.class); + register(HotBarRandomizerChallenge.class); + registerWithCommand(EntityLootRandomizerChallenge.class, "searchloot"); + register(MobRandomizerChallenge.class); + register(RandomItemDroppingChallenge.class); + register(RandomItemRemovingChallenge.class); + register(RandomItemSwappingChallenge.class); + register(RandomItemChallenge.class); + register(RandomEventChallenge.class); + register(RandomTeleportOnHitChallenge.class); + + // Force + register(ForceHeightChallenge.class); + register(ForceBlockChallenge.class); + register(ForceMobChallenge.class); + register(ForceItemChallenge.class); + register(ForceBiomeChallenge.class); + + // Entities + register(HydraNormalChallenge.class); + register(HydraPlusChallenge.class); + register(DupedSpawningChallenge.class); + register(NewEntityOnJumpChallenge.class); + register(InvisibleMobsChallenge.class); + register(StoneSightChallenge.class); + register(MobSightDamageChallenge.class); + register(AllMobsToDeathPoint.class); + register(MobsRespawnInEndChallenge.class); + register(MobTransformationChallenge.class); + register(BlockMobsChallenge.class); + + // Damage + register(DamagePerBlockChallenge.class); + register(SneakDamageChallenge.class); + register(JumpDamageChallenge.class); + register(BlockBreakDamageChallenge.class); + register(BlockPlaceDamageChallenge.class); + register(AdvancementDamageChallenge.class); + register(DamagePerItemChallenge.class); + register(WaterAllergyChallenge.class); + register(DeathOnFallChallenge.class); + register(ReversedDamageChallenge.class); + register(FreezeChallenge.class); + register(DelayDamageChallenge.class); + + // Effect + register(ChunkRandomEffectChallenge.class); + register(BlockEffectChallenge.class); + register(EntityRandomEffectChallenge.class); + register(RandomPotionEffectChallenge.class); + register(PermanentEffectOnDamageChallenge.class); + register(InfectionChallenge.class); + + // World + register(SurfaceHoleChallenge.class); + register(BedrockWallChallenge.class); + register(BedrockPathChallenge.class); + register(FloorIsLavaChallenge.class); + register(ChunkDeconstructionChallenge.class); + register(AllBlocksDisappearChallenge.class); + register(AnvilRainChallenge.class); + register(TsunamiChallenge.class); + register(RepeatInChunkChallenge.class); + register(SnakeChallenge.class); + register(BlockFlyInAirChallenge.class); + register(BlocksDisappearAfterTimeChallenge.class); + register(LoopChallenge.class); + register(IceFloorChallenge.class); + register(LevelBorderChallenge.class); + register(ChunkDeletionChallenge.class); + + // Inventory + register(PermanentItemChallenge.class); + register(NoDupedItemsChallenge.class); + register(DamageInventoryClearChallenge.class); + register(UncraftItemsChallenge.class); + registerWithCommand(MissingItemsChallenge.class, "openmissingitems"); + register(PickupItemLaunchChallenge.class); + register(MovementItemRemovingChallenge.class); + + // Movement + register(TrafficLightChallenge.class); + register(HungerPerBlockChallenge.class); + register(OnlyDownChallenge.class); + register(OnlyDirtChallenge.class); + register(HigherJumpsChallenge.class); + register(AlwaysRunningChallenge.class); + register(DontStopRunningChallenge.class); + register(MoveMouseDamage.class); + register(FiveHundredBlocksChallenge.class); + + // Limited Time + register(MaxBiomeTimeChallenge.class); + register(MaxHeightTimeChallenge.class); + + // Custom World + register(WaterMLGChallenge.class); + register(JumpAndRunChallenge.class); + + // Misc + register(OneDurabilityChallenge.class); + register(NoTradingChallenge.class); + register(NoExpChallenge.class); + register(FoodOnceChallenge.class); + register(FoodLaunchChallenge.class); + register(LowDropRateChallenge.class); + register(EnderGamesChallenge.class); + register(InvertHealthChallenge.class); + register(NoSharedAdvancementsChallenge.class); + + + // Goal + + // Kill + register(KillEnderDragonGoal.class); + register(KillWitherGoal.class); + register(KillElderGuardianGoal.class); + register(KillWardenGoal.class); + register(KillAllBossesGoal.class); + register(KillAllBossesNewGoal.class); + register(KillIronGolemGoal.class); + register(KillSnowGolemGoal.class); + register(KillAllMobsGoal.class); + register(KillAllMonsterGoal.class); + + // Score Points + register(CollectMostDeathsGoal.class); + register(CollectMostItemsGoal.class); + register(MineMostBlocksGoal.class); + register(CollectMostExpGoal.class); + register(MostEmeraldsGoal.class); + register(MostOresGoal.class); + register(EatMostGoal.class); + + // Fastest Time + register(FirstOneToDieGoal.class); + register(CollectWoodGoal.class); + register(FinishRaidGoal.class); + register(AllAdvancementGoal.class); + register(MaxHeightGoal.class); + register(MinHeightGoal.class); + register(RaceGoal.class); + register(FindElytraGoal.class); + register(EatCakeGoal.class); + register(CollectHorseAmorGoal.class); + register(CollectIceBlocksGoal.class); + register(CollectSwordsGoal.class); + register(CollectWorkstationsGoal.class); + register(GetFullHealthGoal.class); + + // Force battle + register(ForceItemBattleGoal.class); + register(ForceMobBattleGoal.class); + register(ForceAdvancementBattleGoal.class); + register(ForceBlockBattleGoal.class); + register(ForceBiomeBattleGoal.class); + register(ForceDamageBattleGoal.class); + register(ForceHeightBattleGoal.class); + register(ForcePositionBattleGoal.class); + register(ExtremeForceBattleGoal.class); + + // Misc + register(LastManStandingGoal.class); + registerWithCommand(CollectAllItemsGoal.class, "skipitem"); + + + // Damage Rules + registerDamageRule("none", Material.TOTEM_OF_UNDYING, DamageCause.values()); + registerDamageRule("fire", Material.LAVA_BUCKET, DamageCause.FIRE, DamageCause.FIRE_TICK, DamageCause.LAVA, DamageCause.HOT_FLOOR); + registerDamageRule("attack", Material.DIAMOND_SWORD, DamageCause.ENTITY_ATTACK, DamageCause.ENTITY_SWEEP_ATTACK, DamageCause.ENTITY_EXPLOSION, DamageCause.THORNS); + registerDamageRule("projectile", Material.ARROW, DamageCause.PROJECTILE); + registerDamageRule("fall", Material.FEATHER, DamageCause.FALL); + registerDamageRule("explosion", Material.TNT, DamageCause.ENTITY_EXPLOSION, DamageCause.BLOCK_EXPLOSION); + registerDamageRule("drowning", PotionBuilder.createWaterBottle(), DamageCause.DROWNING); + registerDamageRule("block", Material.SAND, DamageCause.FALLING_BLOCK, DamageCause.SUFFOCATION, DamageCause.CONTACT); + registerDamageRule("magic", Material.BREWING_STAND, DamageCause.MAGIC, DamageCause.POISON, DamageCause.WITHER); + + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_17)) { + registerDamageRule("freeze", Material.POWDER_SNOW_BUCKET, DamageCause.FREEZE); + } + + // Material Rules + registerMaterialRule("§cArmor", "Armor", ArmorUtils.getArmor()); + registerMaterialRule("§6Golden Apple", "Golden Apple", Material.GOLDEN_APPLE, Material.ENCHANTED_GOLDEN_APPLE); + registerMaterialRule("§6Crafting Table", "Crafting Table", Material.CRAFTING_TABLE); + registerMaterialRule("§6Chest", "Chest", Material.CHEST); + registerMaterialRule("§cFurnace", "Furnace", Material.FURNACE, Material.FURNACE_MINECART); + registerMaterialRule("§5Enchanting Table", "Enchanting Table", Material.ENCHANTING_TABLE); + registerMaterialRule("§cAnvil", "Anvil", Material.ANVIL, Material.CHIPPED_ANVIL, Material.DAMAGED_ANVIL); + registerMaterialRule("§dBrewing Stand", "Brewing Stand", Material.BREWING_STAND); + registerMaterialRule("§cBow", "Bow", Material.BOW); + registerMaterialRule("§fSnowball", "Snowball", Material.SNOWBALL); + registerMaterialRule("§cFlint and Steel", "Flint and Steel", Material.FLINT_AND_STEEL); + registerMaterialRule("§cBucket", "Bucket", Material.BUCKET); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java index 993a08dc5..849b9d866 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java @@ -20,106 +20,106 @@ @Getter public class CustomChallengesLoader extends ModuleChallengeLoader { - private final Map customChallenges = new LinkedHashMap<>(); - - private final int maxNameLength; - - public CustomChallengesLoader() { - super(Challenges.getInstance()); - maxNameLength = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-name-length"); - } - - public CustomChallenge registerCustomChallenge(@Nonnull UUID uuid, Material material, String name, ChallengeTrigger trigger, - Map subTriggers, ChallengeAction action, Map subActions, boolean generate) { - CustomChallenge challenge = customChallenges.getOrDefault(uuid, new CustomChallenge(MenuType.CUSTOM, uuid, material, name, trigger, subTriggers, action, subActions)); - if (!customChallenges.containsKey(uuid)) { - customChallenges.put(uuid, challenge); - register(challenge); - } else { - challenge.applySettings(material, name, trigger, subTriggers, action, subActions); - } - generateCustomChallenge(challenge, false, generate); - return challenge; - } - - public void unregisterCustomChallenge(@Nonnull UUID uuid) { - CustomChallenge challenge = customChallenges.remove(uuid); - if (challenge == null) return; - Challenges.getInstance().getChallengeLoader().unregister(challenge); - generateCustomChallenge(challenge, true, true); - } - - public void loadCustomChallengesFrom(@Nonnull Document document) { - customChallenges.clear(); - Challenges.getInstance().getChallengeManager().unregisterIf(iChallenge -> iChallenge.getType() == MenuType.CUSTOM); - ((ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetChallengeCache(); - - for (String key : document.keys()) { - try { - Document doc = document.getDocument(key); - - UUID uuid = UUID.fromString(key); - String name = doc.getString("name"); - Material material = doc.getEnum("material", Material.class); - ChallengeTrigger trigger = Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(doc.getString("trigger")); - Map subTriggers = MapUtils.createSubSettingsMapFromDocument(doc.getDocument("subTrigger")); - ChallengeAction action = Challenges.getInstance().getCustomSettingsLoader().getActionByName(doc.getString("action")); - Map subActions = MapUtils.createSubSettingsMapFromDocument(doc.getDocument("subActions")); - - CustomChallenge challenge = registerCustomChallenge(uuid, material, name, trigger, subTriggers, action, subActions, false); - challenge.setEnabled(doc.getBoolean("enabled")); - - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Something went wrong while initializing custom challenge {} :: {}", key, exception.getMessage()); - Challenges.getInstance().getLogger().error("", exception); - } - - } - - MenuType.CUSTOM.getMenuGenerator().generateInventories(); - } - - public void resetChallenges() { - customChallenges.clear(); - Challenges.getInstance().getChallengeManager().unregisterIf(iChallenge -> iChallenge.getType() == MenuType.CUSTOM); - ((ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetChallengeCache(); - } - - private void generateCustomChallenge(CustomChallenge challenge, boolean deleted, boolean generate) { - MenuGenerator generator = challenge.getType().getMenuGenerator(); - if (generator instanceof ChallengeMenuGenerator) { - ChallengeMenuGenerator menuGenerator = (ChallengeMenuGenerator) generator; - if (deleted) { - menuGenerator.removeChallengeFromCache(challenge); - if (generate) generator.generateInventories(); - } else { - if (!menuGenerator.isInChallengeCache(challenge)) { - menuGenerator.addChallengeToCache(challenge); - if (generate) generator.generateInventories(); - } else { - menuGenerator.updateItem(challenge); - } - - } - } - } - - public List getCustomChallengesByTrigger(@Nonnull IChallengeTrigger trigger) { - List challenges = new LinkedList<>(); - - for (CustomChallenge challenge : customChallenges.values()) { - if (challenge.getTrigger() != null && challenge.getTrigger() == trigger) { - challenges.add(challenge); - } - } - - return challenges; - } - - public void executeTrigger(@Nonnull ChallengeExecutionData challengeExecutionData) { - getCustomChallengesByTrigger(challengeExecutionData.getTrigger()) - .forEach(customChallenge -> customChallenge - .onTriggerFulfilled(challengeExecutionData)); - } + private final Map customChallenges = new LinkedHashMap<>(); + + private final int maxNameLength; + + public CustomChallengesLoader() { + super(Challenges.getInstance()); + maxNameLength = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-name-length"); + } + + public CustomChallenge registerCustomChallenge(@Nonnull UUID uuid, Material material, String name, ChallengeTrigger trigger, + Map subTriggers, ChallengeAction action, Map subActions, boolean generate) { + CustomChallenge challenge = customChallenges.getOrDefault(uuid, new CustomChallenge(MenuType.CUSTOM, uuid, material, name, trigger, subTriggers, action, subActions)); + if (!customChallenges.containsKey(uuid)) { + customChallenges.put(uuid, challenge); + register(challenge); + } else { + challenge.applySettings(material, name, trigger, subTriggers, action, subActions); + } + generateCustomChallenge(challenge, false, generate); + return challenge; + } + + public void unregisterCustomChallenge(@Nonnull UUID uuid) { + CustomChallenge challenge = customChallenges.remove(uuid); + if (challenge == null) return; + Challenges.getInstance().getChallengeLoader().unregister(challenge); + generateCustomChallenge(challenge, true, true); + } + + public void loadCustomChallengesFrom(@Nonnull Document document) { + customChallenges.clear(); + Challenges.getInstance().getChallengeManager().unregisterIf(iChallenge -> iChallenge.getType() == MenuType.CUSTOM); + ((ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetChallengeCache(); + + for (String key : document.keys()) { + try { + Document doc = document.getDocument(key); + + UUID uuid = UUID.fromString(key); + String name = doc.getString("name"); + Material material = doc.getEnum("material", Material.class); + ChallengeTrigger trigger = Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(doc.getString("trigger")); + Map subTriggers = MapUtils.createSubSettingsMapFromDocument(doc.getDocument("subTrigger")); + ChallengeAction action = Challenges.getInstance().getCustomSettingsLoader().getActionByName(doc.getString("action")); + Map subActions = MapUtils.createSubSettingsMapFromDocument(doc.getDocument("subActions")); + + CustomChallenge challenge = registerCustomChallenge(uuid, material, name, trigger, subTriggers, action, subActions, false); + challenge.setEnabled(doc.getBoolean("enabled")); + + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Something went wrong while initializing custom challenge {} :: {}", key, exception.getMessage()); + Challenges.getInstance().getLogger().error("", exception); + } + + } + + MenuType.CUSTOM.getMenuGenerator().generateInventories(); + } + + public void resetChallenges() { + customChallenges.clear(); + Challenges.getInstance().getChallengeManager().unregisterIf(iChallenge -> iChallenge.getType() == MenuType.CUSTOM); + ((ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetChallengeCache(); + } + + private void generateCustomChallenge(CustomChallenge challenge, boolean deleted, boolean generate) { + MenuGenerator generator = challenge.getType().getMenuGenerator(); + if (generator instanceof ChallengeMenuGenerator) { + ChallengeMenuGenerator menuGenerator = (ChallengeMenuGenerator) generator; + if (deleted) { + menuGenerator.removeChallengeFromCache(challenge); + if (generate) generator.generateInventories(); + } else { + if (!menuGenerator.isInChallengeCache(challenge)) { + menuGenerator.addChallengeToCache(challenge); + if (generate) generator.generateInventories(); + } else { + menuGenerator.updateItem(challenge); + } + + } + } + } + + public List getCustomChallengesByTrigger(@Nonnull IChallengeTrigger trigger) { + List challenges = new LinkedList<>(); + + for (CustomChallenge challenge : customChallenges.values()) { + if (challenge.getTrigger() != null && challenge.getTrigger() == trigger) { + challenges.add(challenge); + } + } + + return challenges; + } + + public void executeTrigger(@Nonnull ChallengeExecutionData challengeExecutionData) { + getCustomChallengesByTrigger(challengeExecutionData.getTrigger()) + .forEach(customChallenge -> customChallenge + .onTriggerFulfilled(challengeExecutionData)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java index 67734ab3e..67c14cba2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java @@ -12,7 +12,7 @@ @Retention(RetentionPolicy.RUNTIME) public @interface RequireVersion { - @Nonnull - MinecraftVersion value(); + @Nonnull + MinecraftVersion value(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java index 89a79d854..4f24c0ff8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java @@ -6,10 +6,10 @@ public interface GamestateSaveable { - String getUniqueGamestateName(); + String getUniqueGamestateName(); - void writeGameState(@Nonnull Document document); + void writeGameState(@Nonnull Document document); - void loadGameState(@Nonnull Document document); + void loadGameState(@Nonnull Document document); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java index c77f80de4..d916ae229 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java @@ -7,18 +7,18 @@ public interface CloudSupport { - @Nonnull - String getColoredName(@Nonnull Player player); + @Nonnull + String getColoredName(@Nonnull Player player); - @Nonnull - String getColoredName(@Nonnull UUID uuid); + @Nonnull + String getColoredName(@Nonnull UUID uuid); - boolean hasNameFor(@Nonnull UUID uuid); + boolean hasNameFor(@Nonnull UUID uuid); - void setIngame(); + void setIngame(); - void setLobby(); + void setLobby(); - void startNewService(); + void startNewService(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java index e5fa7d45c..cc98c7bc8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java @@ -23,139 +23,139 @@ public final class CloudSupportManager implements Listener { - private final Map cachedColoredNames = new HashMap<>(); - private final boolean nameSupport; - private final boolean resetToLobby; - private final boolean setIngame; - @Getter + private final Map cachedColoredNames = new HashMap<>(); + private final boolean nameSupport; + private final boolean resetToLobby; + private final boolean setIngame; + @Getter private final String type; - private final boolean startNewService; - private boolean startedNewService = false; - private CloudSupport support; - - public CloudSupportManager() { - Document config = Challenges.getInstance().getConfigDocument().getDocument("cloud-support"); - - startNewService = config.getBoolean("start-new-service"); - nameSupport = config.getBoolean("name-rank-colors"); - resetToLobby = config.getBoolean("reset-to-lobby"); - setIngame = config.getBoolean("set-ingame"); - type = config.getString("type", "none"); - Logger.debug("Detected cloud support type '{}'", type); - - if (type.equals("none")) return; - - support = loadSupport(type); - ChallengeAPI.registerScheduler(this); - Challenges.getInstance().registerListener(this); - - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onCommandsUpdate(@Nonnull PlayerCommandSendEvent event) { - cachedColoredNames.remove(event.getPlayer().getUniqueId()); - } - - private CloudSupport loadSupport(@Nonnull String name) { - switch (name) { - default: - return null; - case "cloudnet": - case "cloudnet3": - return new CloudNet3Support(); - case "cloudnet2": - return new CloudNet2Support(); - } - } - - @Nonnull - public String getColoredName(@Nonnull Player player) { - if (support == null) - throw new IllegalStateException("No support loaded! Check compatibility before use"); - if (cachedColoredNames.containsKey(player.getUniqueId())) - return cachedColoredNames.get(player.getUniqueId()); - - try { - return cacheColoredName(player.getUniqueId(), support.getColoredName(player)); - } catch (NoClassDefFoundError ex) { - Logger.error("Unable to get name with cloud support '{}', missing dependencies", type); - throw new WrappedException(ex); - } - } - - @Nonnull - public String getColoredName(@Nonnull UUID uuid) { - if (support == null) - throw new IllegalStateException("No support loaded! Check compatibility before use"); - if (cachedColoredNames.containsKey(uuid)) return cachedColoredNames.get(uuid); - - try { - return cacheColoredName(uuid, support.getColoredName(uuid)); - } catch (NoClassDefFoundError ex) { - Logger.error("Unable to get name with cloud support '{}', missing dependencies", type); - throw new WrappedException(ex); - } - } - - @Nonnull - private String cacheColoredName(@Nonnull UUID uuid, @Nonnull String name) { - cachedColoredNames.put(uuid, name); - return name; - } - - public boolean hasNameFor(@Nonnull UUID uuid) { - if (support == null) return false; - - try { - return support.hasNameFor(uuid); - } catch (NoClassDefFoundError ex) { - Logger.error("Unable to check name with cloud support '{}', missing dependencies", type); - return false; - } - } - - @TimerTask(status = TimerStatus.RUNNING, async = false) - public void setIngameAndStartService() { - if (!setIngame) return; - if (support == null) return; - - try { - support.setIngame(); - - if (startNewService && !startedNewService) - support.startNewService(); - startedNewService = true; - } catch (NoClassDefFoundError ex) { - Logger.error("Unable to set to ingame with cloud support '{}', missing dependencies", type); - } - } - - @TimerTask(status = TimerStatus.PAUSED, async = false) - public void setLobby() { - if (!resetToLobby || !startNewService) return; - if (support == null) return; - - try { - support.setLobby(); - } catch (NoClassDefFoundError ex) { - Logger.error("Unable to set to lobby with cloud support '{}', missing dependencies", type); - } - } + private final boolean startNewService; + private boolean startedNewService = false; + private CloudSupport support; + + public CloudSupportManager() { + Document config = Challenges.getInstance().getConfigDocument().getDocument("cloud-support"); + + startNewService = config.getBoolean("start-new-service"); + nameSupport = config.getBoolean("name-rank-colors"); + resetToLobby = config.getBoolean("reset-to-lobby"); + setIngame = config.getBoolean("set-ingame"); + type = config.getString("type", "none"); + Logger.debug("Detected cloud support type '{}'", type); + + if (type.equals("none")) return; + + support = loadSupport(type); + ChallengeAPI.registerScheduler(this); + Challenges.getInstance().registerListener(this); + + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onCommandsUpdate(@Nonnull PlayerCommandSendEvent event) { + cachedColoredNames.remove(event.getPlayer().getUniqueId()); + } + + private CloudSupport loadSupport(@Nonnull String name) { + switch (name) { + default: + return null; + case "cloudnet": + case "cloudnet3": + return new CloudNet3Support(); + case "cloudnet2": + return new CloudNet2Support(); + } + } + + @Nonnull + public String getColoredName(@Nonnull Player player) { + if (support == null) + throw new IllegalStateException("No support loaded! Check compatibility before use"); + if (cachedColoredNames.containsKey(player.getUniqueId())) + return cachedColoredNames.get(player.getUniqueId()); + + try { + return cacheColoredName(player.getUniqueId(), support.getColoredName(player)); + } catch (NoClassDefFoundError ex) { + Logger.error("Unable to get name with cloud support '{}', missing dependencies", type); + throw new WrappedException(ex); + } + } + + @Nonnull + public String getColoredName(@Nonnull UUID uuid) { + if (support == null) + throw new IllegalStateException("No support loaded! Check compatibility before use"); + if (cachedColoredNames.containsKey(uuid)) return cachedColoredNames.get(uuid); + + try { + return cacheColoredName(uuid, support.getColoredName(uuid)); + } catch (NoClassDefFoundError ex) { + Logger.error("Unable to get name with cloud support '{}', missing dependencies", type); + throw new WrappedException(ex); + } + } + + @Nonnull + private String cacheColoredName(@Nonnull UUID uuid, @Nonnull String name) { + cachedColoredNames.put(uuid, name); + return name; + } + + public boolean hasNameFor(@Nonnull UUID uuid) { + if (support == null) return false; + + try { + return support.hasNameFor(uuid); + } catch (NoClassDefFoundError ex) { + Logger.error("Unable to check name with cloud support '{}', missing dependencies", type); + return false; + } + } + + @TimerTask(status = TimerStatus.RUNNING, async = false) + public void setIngameAndStartService() { + if (!setIngame) return; + if (support == null) return; + + try { + support.setIngame(); + + if (startNewService && !startedNewService) + support.startNewService(); + startedNewService = true; + } catch (NoClassDefFoundError ex) { + Logger.error("Unable to set to ingame with cloud support '{}', missing dependencies", type); + } + } + + @TimerTask(status = TimerStatus.PAUSED, async = false) + public void setLobby() { + if (!resetToLobby || !startNewService) return; + if (support == null) return; + + try { + support.setLobby(); + } catch (NoClassDefFoundError ex) { + Logger.error("Unable to set to lobby with cloud support '{}', missing dependencies", type); + } + } private boolean isEnabled() { - return support != null; - } + return support != null; + } - public boolean isNameSupport() { - return isEnabled() && nameSupport; - } + public boolean isNameSupport() { + return isEnabled() && nameSupport; + } - public boolean isResetToLobby() { - return isEnabled() && resetToLobby; - } + public boolean isResetToLobby() { + return isEnabled() && resetToLobby; + } - public boolean isStartNewService() { - return isEnabled() && startNewService; - } + public boolean isStartNewService() { + return isEnabled() && startNewService; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java index 2aa437518..8fcd02f28 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java @@ -13,39 +13,39 @@ public final class CloudNet2Support implements CloudSupport { - @Nonnull - @Override - public String getColoredName(@Nonnull Player player) { - return getColoredName(player.getUniqueId()); - } - - @Nonnull - @Override - public String getColoredName(@Nonnull UUID uuid) { - OfflinePlayer offlinePlayer = CloudAPI.getInstance().getOfflinePlayer(uuid); - PermissionGroup permissionGroup = offlinePlayer.getPermissionEntity().getHighestPermissionGroup(CloudAPI.getInstance().getPermissionPool()); - String color = permissionGroup.getColor(); - return color.replace('&', '§') + offlinePlayer.getName(); - } - - @Override - public boolean hasNameFor(@Nonnull UUID uuid) { - return CloudAPI.getInstance().getOfflinePlayer(uuid) != null; - } - - @Override - public void startNewService() { - CloudServer.getInstance().changeToIngame(); - } - - @Override - public void setIngame() { - CloudServer.getInstance().setServerState(ServerState.INGAME); - } - - @Override - public void setLobby() { - CloudServer.getInstance().setServerStateAndUpdate(ServerState.LOBBY); - } + @Nonnull + @Override + public String getColoredName(@Nonnull Player player) { + return getColoredName(player.getUniqueId()); + } + + @Nonnull + @Override + public String getColoredName(@Nonnull UUID uuid) { + OfflinePlayer offlinePlayer = CloudAPI.getInstance().getOfflinePlayer(uuid); + PermissionGroup permissionGroup = offlinePlayer.getPermissionEntity().getHighestPermissionGroup(CloudAPI.getInstance().getPermissionPool()); + String color = permissionGroup.getColor(); + return color.replace('&', '§') + offlinePlayer.getName(); + } + + @Override + public boolean hasNameFor(@Nonnull UUID uuid) { + return CloudAPI.getInstance().getOfflinePlayer(uuid) != null; + } + + @Override + public void startNewService() { + CloudServer.getInstance().changeToIngame(); + } + + @Override + public void setIngame() { + CloudServer.getInstance().setServerState(ServerState.INGAME); + } + + @Override + public void setLobby() { + CloudServer.getInstance().setServerStateAndUpdate(ServerState.LOBBY); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java index 356dcc2eb..36019f377 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java @@ -26,130 +26,130 @@ public final class DatabaseManager { - private final Map> registry = new HashMap<>(); - @Getter + private final Map> registry = new HashMap<>(); + @Getter private String type; - @Getter + @Getter private Database database; - { - // Database types supported by default - registerDatabase("sqlite", SQLiteDatabase.class, Challenges.getInstance()); - registerDatabase("mysql", MySQLDatabase.class, Challenges.getInstance()); - } - - public void enable() { - Document document = Challenges.getInstance().getConfigDocument().getDocument("database"); - - type = document.getString("type", "none").toLowerCase(); - if ("none".equals(type)) return; - - // Check dependencies - if ("mongodb".equals(type) && !checkDependencies("com.mongodb.client.MongoClient")) { - ConsolePrint.noMongoDependencies(); - return; - } - - try { - Tuple pair = getDatabaseForName(type); - if (pair == null) { - Logger.error("Selected illegal database type '{}'", type); - return; - } - - JavaPlugin provider = pair.getSecond(); - PluginManager manager = Bukkit.getPluginManager(); - if (!manager.isPluginEnabled(provider) && provider != Challenges.getInstance()) { - manager.enablePlugin(provider); - } - - ClassLoader loader = provider.getClass().getClassLoader(); - - String className = pair.getFirst(); - @SuppressWarnings("unchecked") - Class classOfDatabase = (Class) loader.loadClass(className); - - DatabaseConfig config = new DatabaseConfig(document.getDocument(type)); - Constructor constructor = classOfDatabase.getDeclaredConstructor(DatabaseConfig.class); - database = constructor.newInstance(config); - - connect(); - } catch (ClassNotFoundException ex) { - Logger.error("Could not find class for database '{}'", type, ex); - } catch (Throwable ex) { - Logger.error("Could not create database", ex); - } - } - - private void connect() { - Challenges.getInstance().runAsync(() -> { - database.connectSafely(); - database.createTableSafely("challenges", - new SQLColumn("uuid", "varchar", 36), - new SQLColumn("name", "varchar", 16), - new SQLColumn("textures", "varchar", 500), - new SQLColumn("stats", "varchar", 1500), - new SQLColumn("config", "varchar", 15000), - new SQLColumn("custom_challenges", "text", 30000) - ); - loadMigration(); - }); - } - - private void loadMigration() { - - if (database instanceof AbstractSQLDatabase) { - AbstractSQLDatabase sqlDatabase = (AbstractSQLDatabase) this.database; - - // Create custom_challenges column - try { - ExecutedQuery execute = sqlDatabase.query("challenges").select("custom_challenges").execute(); - } catch (DatabaseException databaseException) { - try { - sqlDatabase.prepare("ALTER TABLE `challenges` ADD COLUMN `custom_challenges` text(60000)").execute(); - Challenges.getInstance().getLogger().info("Creating not existing column 'custom_challenges' in SQL Database"); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create non existing column 'custom_challenges' in SQL Database"); - Challenges.getInstance().getLogger().error("", exception); - } - } - - } - - } - - public void disconnectIfConnected() { - if (database != null) { - database.disconnectSafely(); - } - } - - @Nullable - private Tuple getDatabaseForName(@Nonnull String type) throws ClassNotFoundException { - return registry.get(type); - } - - public void registerDatabase(@Nonnull String name, @Nonnull Class classOfDatabase, @Nonnull JavaPlugin provider) { - registry.put(name, new Tuple<>(classOfDatabase.getName(), provider)); - } - - public boolean isConnected() { - return database != null && database.isConnected(); - } - - public boolean isEnabled() { - return database != null; - } + { + // Database types supported by default + registerDatabase("sqlite", SQLiteDatabase.class, Challenges.getInstance()); + registerDatabase("mysql", MySQLDatabase.class, Challenges.getInstance()); + } + + public void enable() { + Document document = Challenges.getInstance().getConfigDocument().getDocument("database"); + + type = document.getString("type", "none").toLowerCase(); + if ("none".equals(type)) return; + + // Check dependencies + if ("mongodb".equals(type) && !checkDependencies("com.mongodb.client.MongoClient")) { + ConsolePrint.noMongoDependencies(); + return; + } + + try { + Tuple pair = getDatabaseForName(type); + if (pair == null) { + Logger.error("Selected illegal database type '{}'", type); + return; + } + + JavaPlugin provider = pair.getSecond(); + PluginManager manager = Bukkit.getPluginManager(); + if (!manager.isPluginEnabled(provider) && provider != Challenges.getInstance()) { + manager.enablePlugin(provider); + } + + ClassLoader loader = provider.getClass().getClassLoader(); + + String className = pair.getFirst(); + @SuppressWarnings("unchecked") + Class classOfDatabase = (Class) loader.loadClass(className); + + DatabaseConfig config = new DatabaseConfig(document.getDocument(type)); + Constructor constructor = classOfDatabase.getDeclaredConstructor(DatabaseConfig.class); + database = constructor.newInstance(config); + + connect(); + } catch (ClassNotFoundException ex) { + Logger.error("Could not find class for database '{}'", type, ex); + } catch (Throwable ex) { + Logger.error("Could not create database", ex); + } + } + + private void connect() { + Challenges.getInstance().runAsync(() -> { + database.connectSafely(); + database.createTableSafely("challenges", + new SQLColumn("uuid", "varchar", 36), + new SQLColumn("name", "varchar", 16), + new SQLColumn("textures", "varchar", 500), + new SQLColumn("stats", "varchar", 1500), + new SQLColumn("config", "varchar", 15000), + new SQLColumn("custom_challenges", "text", 30000) + ); + loadMigration(); + }); + } + + private void loadMigration() { + + if (database instanceof AbstractSQLDatabase) { + AbstractSQLDatabase sqlDatabase = (AbstractSQLDatabase) this.database; + + // Create custom_challenges column + try { + ExecutedQuery execute = sqlDatabase.query("challenges").select("custom_challenges").execute(); + } catch (DatabaseException databaseException) { + try { + sqlDatabase.prepare("ALTER TABLE `challenges` ADD COLUMN `custom_challenges` text(60000)").execute(); + Challenges.getInstance().getLogger().info("Creating not existing column 'custom_challenges' in SQL Database"); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Failed to create non existing column 'custom_challenges' in SQL Database"); + Challenges.getInstance().getLogger().error("", exception); + } + } + + } + + } + + public void disconnectIfConnected() { + if (database != null) { + database.disconnectSafely(); + } + } + + @Nullable + private Tuple getDatabaseForName(@Nonnull String type) throws ClassNotFoundException { + return registry.get(type); + } + + public void registerDatabase(@Nonnull String name, @Nonnull Class classOfDatabase, @Nonnull JavaPlugin provider) { + registry.put(name, new Tuple<>(classOfDatabase.getName(), provider)); + } + + public boolean isConnected() { + return database != null && database.isConnected(); + } + + public boolean isEnabled() { + return database != null; + } private boolean checkDependencies(@Nonnull String... classes) { - try { - for (String name : classes) { - Class.forName(name); - } - } catch (Throwable ex) { - return false; - } - return true; - } + try { + for (String name : classes) { + Class.forName(name); + } + } catch (Throwable ex) { + return false; + } + return true; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java index 48580b8c6..6b589a3e2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java @@ -19,91 +19,91 @@ public final class ConfigManager { - private final List missingConfigSettings; - @Getter + private final List missingConfigSettings; + @Getter private FileDocument sessionConfig, gamestateConfig, settingsConfig, customChallengesConfig; - public ConfigManager() { - missingConfigSettings = new LinkedList<>(); - GsonDocument.setCleanupEmptyObjects(true); - GsonDocument.setCleanupEmptyObjects(true); - } - - public void loadConfigs() { - sessionConfig = load("internal/session.json"); - gamestateConfig = load("internal/gamestate.json"); - settingsConfig = load("internal/settings.json"); - customChallengesConfig = load("internal/custom_challenges.json"); - - Challenges plugin = Challenges.getInstance(); - Document config = plugin.getConfigDocument(); - YamlConfiguration defaultConfig = getDefaultConfig(); - - if (defaultConfig != null) { - for (String key : defaultConfig.getKeys(true)) { - if (!config.contains(key)) { - missingConfigSettings.add(key); - } - } - } - - } - - public Document getDefaultConfigDocument() { - YamlConfiguration defaultConfig = getDefaultConfig(); - return defaultConfig == null ? null : new YamlDocument(defaultConfig); - } - - public YamlConfiguration getDefaultConfig() { - Challenges plugin = Challenges.getInstance(); - try { - // Create Temp File for loading the yaml configuration - File defaultConfigTempFile = new File("defaultConfig.yml"); - // Create an output stream from that file to write into it - FileOutputStream stream = new FileOutputStream(defaultConfigTempFile); - // Copy the default config inside the temp file - InputStream resource = plugin.getResource("config.yml"); - if (resource == null) return null; - copyLarge(resource, stream, new byte[1024 * 4]); - // Load the File as a yaml config - // Spigot Config Implementation because the Document Library does not contain deep-keys. - YamlConfiguration defaultConfig = new YamlConfiguration(); - defaultConfig.load(defaultConfigTempFile); - - return defaultConfig; - } catch (IOException | NullPointerException | InvalidConfigurationException exception) { - plugin.getLogger().severe("Error while checking missing keys in the current config"); - Challenges.getInstance().getLogger().error("", exception); - } - - return null; - } - - /** - * Copied method from or {@link org.apache.commons.io.IOUtils} because it is not implemented in older versions - */ - private void copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException { - int n; - while (-1 != (n = input.read(buffer))) { - output.write(buffer, 0, n); - } - } - - @Nullable - private FileDocument load(@Nonnull String filename) { - try { - File file = Challenges.getInstance().getDataFile(filename); - FileUtils.createFilesIfNecessary(file); - return FileDocument.readJsonFile(file); - } catch (Exception ex) { - Logger.error("Could not load config '{}': {}", filename, ex); - return null; - } - } - - @Nonnull - public List getMissingConfigSettings() { - return new LinkedList<>(missingConfigSettings); - } + public ConfigManager() { + missingConfigSettings = new LinkedList<>(); + GsonDocument.setCleanupEmptyObjects(true); + GsonDocument.setCleanupEmptyObjects(true); + } + + public void loadConfigs() { + sessionConfig = load("internal/session.json"); + gamestateConfig = load("internal/gamestate.json"); + settingsConfig = load("internal/settings.json"); + customChallengesConfig = load("internal/custom_challenges.json"); + + Challenges plugin = Challenges.getInstance(); + Document config = plugin.getConfigDocument(); + YamlConfiguration defaultConfig = getDefaultConfig(); + + if (defaultConfig != null) { + for (String key : defaultConfig.getKeys(true)) { + if (!config.contains(key)) { + missingConfigSettings.add(key); + } + } + } + + } + + public Document getDefaultConfigDocument() { + YamlConfiguration defaultConfig = getDefaultConfig(); + return defaultConfig == null ? null : new YamlDocument(defaultConfig); + } + + public YamlConfiguration getDefaultConfig() { + Challenges plugin = Challenges.getInstance(); + try { + // Create Temp File for loading the yaml configuration + File defaultConfigTempFile = new File("defaultConfig.yml"); + // Create an output stream from that file to write into it + FileOutputStream stream = new FileOutputStream(defaultConfigTempFile); + // Copy the default config inside the temp file + InputStream resource = plugin.getResource("config.yml"); + if (resource == null) return null; + copyLarge(resource, stream, new byte[1024 * 4]); + // Load the File as a yaml config + // Spigot Config Implementation because the Document Library does not contain deep-keys. + YamlConfiguration defaultConfig = new YamlConfiguration(); + defaultConfig.load(defaultConfigTempFile); + + return defaultConfig; + } catch (IOException | NullPointerException | InvalidConfigurationException exception) { + plugin.getLogger().severe("Error while checking missing keys in the current config"); + Challenges.getInstance().getLogger().error("", exception); + } + + return null; + } + + /** + * Copied method from or {@link org.apache.commons.io.IOUtils} because it is not implemented in older versions + */ + private void copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException { + int n; + while (-1 != (n = input.read(buffer))) { + output.write(buffer, 0, n); + } + } + + @Nullable + private FileDocument load(@Nonnull String filename) { + try { + File file = Challenges.getInstance().getDataFile(filename); + FileUtils.createFilesIfNecessary(file); + return FileDocument.readJsonFile(file); + } catch (Exception ex) { + Logger.error("Could not load config '{}': {}", filename, ex); + return null; + } + } + + @Nonnull + public List getMissingConfigSettings() { + return new LinkedList<>(missingConfigSettings); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java index 9ded8cf2a..331ba48f4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java @@ -31,250 +31,250 @@ public final class PlayerInventoryManager implements Listener { - private final List hotbarItems; - - public PlayerInventoryManager() { - Challenges.getInstance().registerListener(this); - ChallengeAPI.registerScheduler(this); - ChallengeAPI.subscribeLoader(LanguageLoader.class, () -> Bukkit.getOnlinePlayers().forEach(Challenges.getInstance().getPlayerInventoryManager()::updateInventoryAuto)); - - hotbarItems = new LinkedList<>(); - loadItems(); - } - - public void loadItems() { - FileDocument config = Challenges.getInstance().getConfig("hotbar-items.yml"); - loadItem(config.getDocument("timer"), "item-menu-timer", "challenges.timer", p -> p.performCommand("timer")); - loadItem(config.getDocument("challenges"), "item-menu-challenges", "challenges.gui", p -> p.performCommand("challenges")); - loadItem(config.getDocument("start"), "item-menu-start", "challenges.timer", p -> p.performCommand("start")); - loadItem(config.getDocument("leaderboard"), "item-menu-leaderboard", null, p -> p.performCommand("leaderboard")); - loadItem(config.getDocument("stats"), "item-menu-stats", null, p -> p.performCommand("stats")); - } - - public void loadItem(Document config, String message, String permission, Consumer action) { - if (!config.getBoolean("enabled", false)) return; - int slot = config.getInt("slot", 0); - Material material = config.getEnum("material", Material.BARRIER); - HotbarItem item = new HotbarItem(slot, message, material, action, permission); - hotbarItems.add(item); - } - - public void handleDisable() { - Bukkit.getOnlinePlayers().forEach(this::removeItems); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onCommandsUpdate(@Nonnull PlayerCommandSendEvent event) { - updateInventoryAuto(event.getPlayer()); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onJoin(@Nonnull PlayerJoinEvent event) { - updateInventoryJoin(event.getPlayer(), true); - } - - @EventHandler - public void onQuit(@Nonnull PlayerQuitEvent event) { - removeItems(event.getPlayer()); - } - - @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) - public void onGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { - updateInventoryGamemode(event.getPlayer(), event.getNewGameMode()); - } - - @EventHandler(priority = EventPriority.HIGH) - public void onDrop(@Nonnull PlayerDropItemEvent event) { - if (ChallengeAPI.isStarted()) return; - if (!hasItems(event.getPlayer())) return; - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onRespawn(@Nonnull PlayerRespawnEvent event) { - updateInventoryAlive(event.getPlayer(), true); - } - - @EventHandler - public void onInteract(@Nonnull PlayerInteractEvent event) { - switch (event.getAction()) { - case LEFT_CLICK_AIR: - case LEFT_CLICK_BLOCK: - case PHYSICAL: - return; - } - - if (ChallengeAPI.isStarted()) return; - if (!hasItems(event.getPlayer())) return; - Triple, String>[] pairs = createItemPairs(event.getPlayer()); - - int slot = event.getPlayer().getInventory().getHeldItemSlot(); - if (slot >= pairs.length) return; - Triple, String> pair = pairs[slot]; - if (pair == null) return; - if (pair.getThird() != null && !event.getPlayer().hasPermission(pair.getThird())) return; - - Consumer action = pair.getSecond(); - if (action == null) return; - - action.accept(event.getPlayer()); - SoundSample.PLOP.play(event.getPlayer()); - } - - @TimerTask(status = {TimerStatus.PAUSED, TimerStatus.RUNNING}) - public void updateInventories() { - Bukkit.getOnlinePlayers().forEach(this::updateInventoryAuto); - } - - public void updateInventoryAuto(@Nonnull Player player) { - updateInventory(player, player.getGameMode(), false, !player.isDead()); - } - - public void updateInventoryAlive(@Nonnull Player player, boolean alive) { - updateInventory(player, player.getGameMode(), false, alive); - } - - public void updateInventoryGamemode(@Nonnull Player player, @Nonnull GameMode gamemode) { - updateInventory(player, gamemode, false, !player.isDead()); - } - - public void updateInventoryJoin(@Nonnull Player player, boolean join) { - updateInventory(player, player.getGameMode(), join, !player.isDead()); - } - - public void updateInventory(@Nonnull Player player, @Nonnull GameMode gamemode, boolean join, boolean alive) { - if (Bukkit.isPrimaryThread()) { - Challenges.getInstance().runAsync(() -> updateInventory(player, gamemode, join, alive)); - return; - } - - try { - if (!LanguageLoader.isLoaded()) return; - if (ChallengeAPI.isPaused()) { - updateInventoryPaused(player, gamemode, join, alive); - } else { - updateInventoryStarted(player, gamemode, join, alive); - } - } catch (Exception ex) { - Logger.error("Failed to update inventory", ex); - } - } - - private void updateInventoryStarted(@Nonnull Player player, @Nonnull GameMode gamemode, boolean join, boolean alive) { - removeItems(player); - } - - private void updateInventoryPaused(@Nonnull Player player, @Nonnull GameMode gamemode, boolean join, boolean alive) { - if (gamemode == GameMode.CREATIVE || gamemode == GameMode.SPECTATOR) { - removeItems(player); - return; - } - if (canGiveItems(player)) { - if (!alive) return; - giveItems(player); - if (join) player.getInventory().setHeldItemSlot(4); - } - } - - private boolean hasItems(@Nonnull Player player) { - Triple, String>[] pairs = createItemPairs(player); - for (int i = 0; i < pairs.length; i++) { - Triple, String> pair = pairs[i]; - ItemStack expected = pair == null ? null : pair.getFirst(); - ItemStack found = player.getInventory().getItem(i); - if (pair != null && pair.getThird() != null && !player.hasPermission(pair.getThird())) - continue; - if (expected != null && found == null) return false; - if (expected == null) continue; - if (expected.getType() != found.getType()) return false; - } - return true; - } - - private boolean canGiveItems(@Nonnull Player player) { - Triple, String>[] pairs = createItemPairs(player); - for (int i = 0; i < pairs.length; i++) { - Triple, String> pair = pairs[i]; - ItemStack expected = pair == null ? null : pair.getFirst(); - ItemStack found = player.getInventory().getItem(i); - if (expected == null && found != null) return false; - if (expected == null) continue; - if (found == null) continue; - if (expected.getType() != found.getType()) return false; - } - return true; - } - - private void removeItems(@Nonnull Player player) { - Triple, String>[] pairs = createItemPairs(player); - for (Triple, String> pair : pairs) { - if (pair == null) continue; - ItemStack item = pair.getFirst(); - if (item == null) continue; - if (item.getItemMeta() == null) continue; - ItemStack[] content = player.getInventory().getContents(); - for (int i = 0; i < content.length; i++) { - ItemStack current = content[i]; - if (current == null) continue; - if (current.getType() != item.getType()) continue; - if (current.getItemMeta() == null) continue; - if (!current.getItemMeta().getDisplayName().equals(item.getItemMeta().getDisplayName())) - continue; - player.getInventory().setItem(i, null); - } - } - } - - private void giveItems(@Nonnull Player player) { - Triple, String>[] pairs = createItemPairs(player); - for (int i = 0; i < pairs.length; i++) { - Triple, String> pair = pairs[i]; - if (pair == null) continue; - if (pair.getThird() != null && !player.hasPermission(pair.getThird())) continue; - player.getInventory().setItem(i, pair.getFirst()); - } - } - - @Nonnull - private Triple, String>[] createItemPairs(@Nonnull Player player) { - Triple, String>[] pairs = new Triple[9]; - - for (HotbarItem item : hotbarItems) { - - ItemStack stack; - if (item.getMaterial() == Material.PLAYER_HEAD) { - stack = new SkullBuilder(Message.forName(item.getMessage()).asString()) - .setOwner(player.getUniqueId(), player.getName()).build(); - } else { - stack = new ItemBuilder(item.getMaterial(), Message.forName(item.getMessage()).asString()).build(); - } - - pairs[item.getSlot()] = new Triple<>( - stack, - item.getAction(), - item.getPermission() - ); - } - - return pairs; - } - - @Getter + private final List hotbarItems; + + public PlayerInventoryManager() { + Challenges.getInstance().registerListener(this); + ChallengeAPI.registerScheduler(this); + ChallengeAPI.subscribeLoader(LanguageLoader.class, () -> Bukkit.getOnlinePlayers().forEach(Challenges.getInstance().getPlayerInventoryManager()::updateInventoryAuto)); + + hotbarItems = new LinkedList<>(); + loadItems(); + } + + public void loadItems() { + FileDocument config = Challenges.getInstance().getConfig("hotbar-items.yml"); + loadItem(config.getDocument("timer"), "item-menu-timer", "challenges.timer", p -> p.performCommand("timer")); + loadItem(config.getDocument("challenges"), "item-menu-challenges", "challenges.gui", p -> p.performCommand("challenges")); + loadItem(config.getDocument("start"), "item-menu-start", "challenges.timer", p -> p.performCommand("start")); + loadItem(config.getDocument("leaderboard"), "item-menu-leaderboard", null, p -> p.performCommand("leaderboard")); + loadItem(config.getDocument("stats"), "item-menu-stats", null, p -> p.performCommand("stats")); + } + + public void loadItem(Document config, String message, String permission, Consumer action) { + if (!config.getBoolean("enabled", false)) return; + int slot = config.getInt("slot", 0); + Material material = config.getEnum("material", Material.BARRIER); + HotbarItem item = new HotbarItem(slot, message, material, action, permission); + hotbarItems.add(item); + } + + public void handleDisable() { + Bukkit.getOnlinePlayers().forEach(this::removeItems); + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onCommandsUpdate(@Nonnull PlayerCommandSendEvent event) { + updateInventoryAuto(event.getPlayer()); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJoin(@Nonnull PlayerJoinEvent event) { + updateInventoryJoin(event.getPlayer(), true); + } + + @EventHandler + public void onQuit(@Nonnull PlayerQuitEvent event) { + removeItems(event.getPlayer()); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { + updateInventoryGamemode(event.getPlayer(), event.getNewGameMode()); + } + + @EventHandler(priority = EventPriority.HIGH) + public void onDrop(@Nonnull PlayerDropItemEvent event) { + if (ChallengeAPI.isStarted()) return; + if (!hasItems(event.getPlayer())) return; + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onRespawn(@Nonnull PlayerRespawnEvent event) { + updateInventoryAlive(event.getPlayer(), true); + } + + @EventHandler + public void onInteract(@Nonnull PlayerInteractEvent event) { + switch (event.getAction()) { + case LEFT_CLICK_AIR: + case LEFT_CLICK_BLOCK: + case PHYSICAL: + return; + } + + if (ChallengeAPI.isStarted()) return; + if (!hasItems(event.getPlayer())) return; + Triple, String>[] pairs = createItemPairs(event.getPlayer()); + + int slot = event.getPlayer().getInventory().getHeldItemSlot(); + if (slot >= pairs.length) return; + Triple, String> pair = pairs[slot]; + if (pair == null) return; + if (pair.getThird() != null && !event.getPlayer().hasPermission(pair.getThird())) return; + + Consumer action = pair.getSecond(); + if (action == null) return; + + action.accept(event.getPlayer()); + SoundSample.PLOP.play(event.getPlayer()); + } + + @TimerTask(status = {TimerStatus.PAUSED, TimerStatus.RUNNING}) + public void updateInventories() { + Bukkit.getOnlinePlayers().forEach(this::updateInventoryAuto); + } + + public void updateInventoryAuto(@Nonnull Player player) { + updateInventory(player, player.getGameMode(), false, !player.isDead()); + } + + public void updateInventoryAlive(@Nonnull Player player, boolean alive) { + updateInventory(player, player.getGameMode(), false, alive); + } + + public void updateInventoryGamemode(@Nonnull Player player, @Nonnull GameMode gamemode) { + updateInventory(player, gamemode, false, !player.isDead()); + } + + public void updateInventoryJoin(@Nonnull Player player, boolean join) { + updateInventory(player, player.getGameMode(), join, !player.isDead()); + } + + public void updateInventory(@Nonnull Player player, @Nonnull GameMode gamemode, boolean join, boolean alive) { + if (Bukkit.isPrimaryThread()) { + Challenges.getInstance().runAsync(() -> updateInventory(player, gamemode, join, alive)); + return; + } + + try { + if (!LanguageLoader.isLoaded()) return; + if (ChallengeAPI.isPaused()) { + updateInventoryPaused(player, gamemode, join, alive); + } else { + updateInventoryStarted(player, gamemode, join, alive); + } + } catch (Exception ex) { + Logger.error("Failed to update inventory", ex); + } + } + + private void updateInventoryStarted(@Nonnull Player player, @Nonnull GameMode gamemode, boolean join, boolean alive) { + removeItems(player); + } + + private void updateInventoryPaused(@Nonnull Player player, @Nonnull GameMode gamemode, boolean join, boolean alive) { + if (gamemode == GameMode.CREATIVE || gamemode == GameMode.SPECTATOR) { + removeItems(player); + return; + } + if (canGiveItems(player)) { + if (!alive) return; + giveItems(player); + if (join) player.getInventory().setHeldItemSlot(4); + } + } + + private boolean hasItems(@Nonnull Player player) { + Triple, String>[] pairs = createItemPairs(player); + for (int i = 0; i < pairs.length; i++) { + Triple, String> pair = pairs[i]; + ItemStack expected = pair == null ? null : pair.getFirst(); + ItemStack found = player.getInventory().getItem(i); + if (pair != null && pair.getThird() != null && !player.hasPermission(pair.getThird())) + continue; + if (expected != null && found == null) return false; + if (expected == null) continue; + if (expected.getType() != found.getType()) return false; + } + return true; + } + + private boolean canGiveItems(@Nonnull Player player) { + Triple, String>[] pairs = createItemPairs(player); + for (int i = 0; i < pairs.length; i++) { + Triple, String> pair = pairs[i]; + ItemStack expected = pair == null ? null : pair.getFirst(); + ItemStack found = player.getInventory().getItem(i); + if (expected == null && found != null) return false; + if (expected == null) continue; + if (found == null) continue; + if (expected.getType() != found.getType()) return false; + } + return true; + } + + private void removeItems(@Nonnull Player player) { + Triple, String>[] pairs = createItemPairs(player); + for (Triple, String> pair : pairs) { + if (pair == null) continue; + ItemStack item = pair.getFirst(); + if (item == null) continue; + if (item.getItemMeta() == null) continue; + ItemStack[] content = player.getInventory().getContents(); + for (int i = 0; i < content.length; i++) { + ItemStack current = content[i]; + if (current == null) continue; + if (current.getType() != item.getType()) continue; + if (current.getItemMeta() == null) continue; + if (!current.getItemMeta().getDisplayName().equals(item.getItemMeta().getDisplayName())) + continue; + player.getInventory().setItem(i, null); + } + } + } + + private void giveItems(@Nonnull Player player) { + Triple, String>[] pairs = createItemPairs(player); + for (int i = 0; i < pairs.length; i++) { + Triple, String> pair = pairs[i]; + if (pair == null) continue; + if (pair.getThird() != null && !player.hasPermission(pair.getThird())) continue; + player.getInventory().setItem(i, pair.getFirst()); + } + } + + @Nonnull + private Triple, String>[] createItemPairs(@Nonnull Player player) { + Triple, String>[] pairs = new Triple[9]; + + for (HotbarItem item : hotbarItems) { + + ItemStack stack; + if (item.getMaterial() == Material.PLAYER_HEAD) { + stack = new SkullBuilder(Message.forName(item.getMessage()).asString()) + .setOwner(player.getUniqueId(), player.getName()).build(); + } else { + stack = new ItemBuilder(item.getMaterial(), Message.forName(item.getMessage()).asString()).build(); + } + + pairs[item.getSlot()] = new Triple<>( + stack, + item.getAction(), + item.getPermission() + ); + } + + return pairs; + } + + @Getter public static class HotbarItem { - private final int slot; - private final String message; - private final Material material; - private final Consumer action; - private final String permission; - - public HotbarItem(int slot, String message, Material material, Consumer action, String permission) { - this.slot = slot; - this.message = message; - this.material = material; - this.action = action; - this.permission = permission; - } + private final int slot; + private final String message; + private final Material material; + private final Consumer action; + private final String permission; + + public HotbarItem(int slot, String message, Material material, Consumer action, String permission) { + this.slot = slot; + this.message = message; + this.material = material; + this.action = action; + this.permission = permission; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java index 6bcebc258..10d59d1a2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java @@ -6,61 +6,61 @@ public final class InventoryTitleManager { - private InventoryTitleManager() { - } + private InventoryTitleManager() { + } - @Nonnull - public static String getTitle(@Nonnull String name) { - return "§8» " + Message.forName("inventory-color").asString() + name; - } + @Nonnull + public static String getTitle(@Nonnull String name) { + return "§8» " + Message.forName("inventory-color").asString() + name; + } - @Nonnull - public static String getMainMenuTitle() { - return getTitle(Message.forName("menu-title").asString()); - } + @Nonnull + public static String getMainMenuTitle() { + return getTitle(Message.forName("menu-title").asString()); + } - @Nonnull - public static String getTitle(@Nonnull MenuType menu, int page) { - return getTitle(menu.getName(), String.valueOf(page + 1)); - } + @Nonnull + public static String getTitle(@Nonnull MenuType menu, int page) { + return getTitle(menu.getName(), String.valueOf(page + 1)); + } - @Nonnull - public static String getTitle(@Nonnull MenuType menu, String... sub) { - return getTitle(menu.getName(), sub); - } + @Nonnull + public static String getTitle(@Nonnull MenuType menu, String... sub) { + return getTitle(menu.getName(), sub); + } - @Nonnull - public static String getTitle(@Nonnull String menu, String... sub) { - StringBuilder name = new StringBuilder(menu); - for (String s : sub) { - name.append(getTitleSplitter()).append(s); - } - return getTitle(name.toString()); - } + @Nonnull + public static String getTitle(@Nonnull String menu, String... sub) { + StringBuilder name = new StringBuilder(menu); + for (String s : sub) { + name.append(getTitleSplitter()).append(s); + } + return getTitle(name.toString()); + } - @Nonnull - public static String getTitleSplitter() { - return " §8┃ " + Message.forName("inventory-color").asString(); - } + @Nonnull + public static String getTitleSplitter() { + return " §8┃ " + Message.forName("inventory-color").asString(); + } - @Nonnull - public static String getMenuSettingTitle(@Nonnull MenuType menu, @Nonnull String name, int page, boolean showPages) { - return getTitle(menu.getName() + getTitleSplitter() + name + (false ? " §8• " + Message.forName("inventory-color") + (page + 1) : "")); - } + @Nonnull + public static String getMenuSettingTitle(@Nonnull MenuType menu, @Nonnull String name, int page, boolean showPages) { + return getTitle(menu.getName() + getTitleSplitter() + name + (false ? " §8• " + Message.forName("inventory-color") + (page + 1) : "")); + } - @Nonnull - public static String getStatsTitle(@Nonnull String playerName) { - return getTitle("§2Stats §8┃ §2" + playerName); - } + @Nonnull + public static String getStatsTitle(@Nonnull String playerName) { + return getTitle("§2Stats §8┃ §2" + playerName); + } - @Nonnull - public static String getLeaderboardTitle() { - return getTitle("§2Leaderboard"); - } + @Nonnull + public static String getLeaderboardTitle() { + return getTitle("§2Leaderboard"); + } - @Nonnull - public static String getLeaderboardTitle(@Nonnull String name, int page) { - return getTitle("§2" + name + " §8┃ §2" + page); - } + @Nonnull + public static String getLeaderboardTitle(@Nonnull String name, int page) { + return getTitle("§2" + name + " §8┃ §2" + page); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java index cacd68a2e..8dc5528c0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java @@ -17,50 +17,50 @@ public enum MenuType { - TIMER("timer", Material.CLOCK, new TimerMenuGenerator(), false), - GOAL("goal", Material.COMPASS, new SmallCategorisedMenuGenerator()), - DAMAGE("damage", Material.IRON_SWORD, new SettingsMenuGenerator()), - ITEMS("item_blocks", Material.STICK, new SettingsMenuGenerator()), - CHALLENGES("challenges", Material.BOOK, new CategorisedMenuGenerator()), - SETTINGS("settings", Material.COMPARATOR, new SettingsMenuGenerator()), - CUSTOM("custom", Material.WRITABLE_BOOK, new MainCustomMenuGenerator()); + TIMER("timer", Material.CLOCK, new TimerMenuGenerator(), false), + GOAL("goal", Material.COMPASS, new SmallCategorisedMenuGenerator()), + DAMAGE("damage", Material.IRON_SWORD, new SettingsMenuGenerator()), + ITEMS("item_blocks", Material.STICK, new SettingsMenuGenerator()), + CHALLENGES("challenges", Material.BOOK, new CategorisedMenuGenerator()), + SETTINGS("settings", Material.COMPARATOR, new SettingsMenuGenerator()), + CUSTOM("custom", Material.WRITABLE_BOOK, new MainCustomMenuGenerator()); - private final String key; - @Getter + private final String key; + @Getter private final Material displayItem; - @Getter + @Getter private final MenuGenerator menuGenerator; - @Getter + @Getter private final boolean usable; - MenuType(@Nonnull String key, @Nonnull Material displayItem, MenuGenerator menuGenerator, boolean usable) { - this.key = key; - this.displayItem = displayItem; - this.menuGenerator = menuGenerator; - this.usable = usable; + MenuType(@Nonnull String key, @Nonnull Material displayItem, MenuGenerator menuGenerator, boolean usable) { + this.key = key; + this.displayItem = displayItem; + this.menuGenerator = menuGenerator; + this.usable = usable; - menuGenerator.setMenuType(this); - } + menuGenerator.setMenuType(this); + } - MenuType(@Nonnull String key, @Nonnull Material displayItem, MenuGenerator menuGenerator) { - this(key, displayItem, menuGenerator, true); - } + MenuType(@Nonnull String key, @Nonnull Material displayItem, MenuGenerator menuGenerator) { + this(key, displayItem, menuGenerator, true); + } - @Nonnull - public String getName() { - return ChatColor.stripColor(getDisplayName()); - } + @Nonnull + public String getName() { + return ChatColor.stripColor(getDisplayName()); + } - @Nonnull - public String getDisplayName() { - return Message.forName("menu-" + key).asString(); - } + @Nonnull + public String getDisplayName() { + return Message.forName("menu-" + key).asString(); + } @SuppressWarnings("unchecked") - public void executeWithGenerator(Class clazz, Consumer action) { - if (clazz.isAssignableFrom(menuGenerator.getClass())) { - action.accept((T) menuGenerator); - } - } + public void executeWithGenerator(Class clazz, Consumer action) { + if (clazz.isAssignableFrom(menuGenerator.getClass())) { + action.accept((T) menuGenerator); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java index 3a27bfcee..d5bb0eaa4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java @@ -26,231 +26,231 @@ public abstract class ChallengeMenuGenerator extends MultiPageMenuGenerator { - protected final List challenges = new LinkedList<>(); - protected final boolean newSuffix; + protected final List challenges = new LinkedList<>(); + protected final boolean newSuffix; - private final int startPage; - protected Consumer onLeaveClick; + private final int startPage; + protected Consumer onLeaveClick; - public ChallengeMenuGenerator(int startPage, Consumer onLeaveClick) { - newSuffix = Challenges.getInstance().getConfigDocument().getBoolean("new-suffix"); - this.startPage = startPage; - this.onLeaveClick = onLeaveClick; - } + public ChallengeMenuGenerator(int startPage, Consumer onLeaveClick) { + newSuffix = Challenges.getInstance().getConfigDocument().getBoolean("new-suffix"); + this.startPage = startPage; + this.onLeaveClick = onLeaveClick; + } - public ChallengeMenuGenerator(int startPage) { - this(startPage, player -> Challenges.getInstance().getMenuManager().openGUIInstantly(player)); - } + public ChallengeMenuGenerator(int startPage) { + this(startPage, player -> Challenges.getInstance().getMenuManager().openGUIInstantly(player)); + } - public ChallengeMenuGenerator() { - this(0); - } - - public static boolean playNoPermissionsEffect(@Nonnull Player player) { - MenuManager menuManager = Challenges.getInstance().getMenuManager(); - if (!menuManager.permissionToManageGUI()) return false; - if (mayManageSettings(player)) return false; - menuManager.playNoPermissionsEffect(player); - return true; - } - - private static boolean mayManageSettings(@Nonnull Player player) { - return player.hasPermission(MenuManager.MANAGE_GUI_PERMISSION); - } - - @Override - public MenuPosition getMenuPosition(int page) { - return new ChallengeMenuPositionGenerator(this, page); - } - - @Override - public int getPagesCount() { - return (int) (Math.ceil((double) challenges.size() / getSlots().length) + startPage); - } - - @Override - public void generatePage(@Nonnull Inventory inventory, int page) { - - } - - @Override - public void generateInventories() { - super.generateInventories(); - - for (IChallenge challenge : challenges) { - updateItem(challenge); - } - - } - - public void updateItem(IChallenge challenge) { - - int index = challenges.indexOf(challenge); - if (index == -1) return; // Challenge not registered or menus not loaded - - int page = (index / getSlots().length); - if (page >= getInventories().size()) return; // This should never happen - - int slot = index - getSlots().length * page; - - Inventory inventory = getInventories().get(page + startPage); - setSettingsItems(inventory, challenge, slot); - - if (newSuffix && isNew(challenge)) { - inventory.setItem(slot + 1, new ItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); - inventory.setItem(slot + 28, new ItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); - } - } - - public int getPageOfChallenge(IChallenge challenge) { - int index = challenges.indexOf(challenge); - if (index == -1) return -1; // Challenge not registered or menus not loaded - - int page = (index / getSlots().length); - if (page >= getInventories().size()) return -1; // This should never happen - - return page; - } - - public void setSettingsItems(@Nonnull Inventory inventory, @Nonnull IChallenge challenge, int topSlot) { - inventory.setItem(getSlots()[topSlot], getDisplayItem(challenge)); - inventory.setItem(getSlots()[topSlot] + 9, getSettingsItem(challenge)); - } - - public void resetChallengeCache() { - this.challenges.clear(); - } - - public boolean isInChallengeCache(@Nonnull IChallenge challenge) { - return challenges.contains(challenge); - } - - public void addChallengeToCache(@Nonnull IChallenge challenge) { - if (isNew(challenge) && Challenges.getInstance().getMenuManager().isDisplayNewInFront()) { - challenges.add(countNewChallenges(), challenge); - } else { - challenges.add(challenge); - } - } - - public void removeChallengeFromCache(@Nonnull IChallenge challenge) { - challenges.remove(challenge); - } - - protected ItemStack getDisplayItem(@Nonnull IChallenge challenge) { - return getDisplayItemBuilder(challenge).build(); - } - - protected ItemBuilder getDisplayItemBuilder(@Nonnull IChallenge challenge) { - try { - ItemBuilder item = new ItemBuilder(challenge.getDisplayItem()).hideAttributes(); - if (newSuffix && isNew(challenge)) { - return item.appendName(" " + Message.forName("new-challenge")); - } else { - return item; - } - } catch (Exception ex) { - Logger.error("Error while generating challenge display item for challenge {}", challenge.getClass().getSimpleName(), ex); - return new ItemBuilder(); - } - } - - protected ItemStack getSettingsItem(@Nonnull IChallenge challenge) { - try { - ItemBuilder item = new ItemBuilder(challenge.getSettingsItem()).hideAttributes(); - return item.build(); - } catch (Exception ex) { - Logger.error("Error while generating challenge settings item for challenge {}", challenge.getClass().getSimpleName(), ex); - return new ItemBuilder().build(); - } - } - - protected boolean isNew(@Nonnull IChallenge challenge) { - Version version = Challenges.getInstance().getVersion(); - Version since = Version.getAnnotatedSince(challenge); - return since.isNewerOrEqualThan(version); - } - - protected int countNewChallenges() { - return (int) challenges.stream().filter(this::isNew).count(); - } - - public abstract int[] getSlots(); - - public abstract void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClickInfo info, int itemIndex); - - public void onPreChallengePageClicking(@Nonnull MenuClickInfo clickInfo, @Nonnegative int page) { - - } - - public List getChallenges() { - return ImmutableList.copyOf(challenges); - } - - private class ChallengeMenuPositionGenerator extends GeneratorMenuPosition { - - public ChallengeMenuPositionGenerator(MenuGenerator generator, int page) { - super(generator, page); - } - - @Override - public void handleClick(@Nonnull MenuClickInfo info) { - - if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onLeaveClick.accept(info.getPlayer()))) { - return; - } - - - if (page < startPage) { - onPreChallengePageClicking(info, page); - return; - } - - int itemIndex = 0; - int index = 0; - for (int i : getSlots()) { - if (i == info.getSlot()) break; - if ((i + 9) == info.getSlot()) { - itemIndex = 1; - break; - } else if ((i + 18) == info.getSlot()) { - itemIndex = 2; - break; - } - index++; - } - - if (itemIndex == 2) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - if (index == getSlots().length) { // No possible bound slot was clicked - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - int offset = (page - startPage) * getSlots().length; - index += offset; - - if (index >= challenges.size()) { // No bound slot was clicked - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - IChallenge challenge = challenges.get(index); - - if (playNoPermissionsEffect(info.getPlayer())) return; - - try { - executeClickAction(challenge, info, itemIndex); - updateItem(challenge); - } catch (Exception ex) { - Logger.error("An exception occurred while handling click on {}", challenge.getClass().getName(), ex); - } - - } - - } + public ChallengeMenuGenerator() { + this(0); + } + + public static boolean playNoPermissionsEffect(@Nonnull Player player) { + MenuManager menuManager = Challenges.getInstance().getMenuManager(); + if (!menuManager.permissionToManageGUI()) return false; + if (mayManageSettings(player)) return false; + menuManager.playNoPermissionsEffect(player); + return true; + } + + private static boolean mayManageSettings(@Nonnull Player player) { + return player.hasPermission(MenuManager.MANAGE_GUI_PERMISSION); + } + + @Override + public MenuPosition getMenuPosition(int page) { + return new ChallengeMenuPositionGenerator(this, page); + } + + @Override + public int getPagesCount() { + return (int) (Math.ceil((double) challenges.size() / getSlots().length) + startPage); + } + + @Override + public void generatePage(@Nonnull Inventory inventory, int page) { + + } + + @Override + public void generateInventories() { + super.generateInventories(); + + for (IChallenge challenge : challenges) { + updateItem(challenge); + } + + } + + public void updateItem(IChallenge challenge) { + + int index = challenges.indexOf(challenge); + if (index == -1) return; // Challenge not registered or menus not loaded + + int page = (index / getSlots().length); + if (page >= getInventories().size()) return; // This should never happen + + int slot = index - getSlots().length * page; + + Inventory inventory = getInventories().get(page + startPage); + setSettingsItems(inventory, challenge, slot); + + if (newSuffix && isNew(challenge)) { + inventory.setItem(slot + 1, new ItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); + inventory.setItem(slot + 28, new ItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); + } + } + + public int getPageOfChallenge(IChallenge challenge) { + int index = challenges.indexOf(challenge); + if (index == -1) return -1; // Challenge not registered or menus not loaded + + int page = (index / getSlots().length); + if (page >= getInventories().size()) return -1; // This should never happen + + return page; + } + + public void setSettingsItems(@Nonnull Inventory inventory, @Nonnull IChallenge challenge, int topSlot) { + inventory.setItem(getSlots()[topSlot], getDisplayItem(challenge)); + inventory.setItem(getSlots()[topSlot] + 9, getSettingsItem(challenge)); + } + + public void resetChallengeCache() { + this.challenges.clear(); + } + + public boolean isInChallengeCache(@Nonnull IChallenge challenge) { + return challenges.contains(challenge); + } + + public void addChallengeToCache(@Nonnull IChallenge challenge) { + if (isNew(challenge) && Challenges.getInstance().getMenuManager().isDisplayNewInFront()) { + challenges.add(countNewChallenges(), challenge); + } else { + challenges.add(challenge); + } + } + + public void removeChallengeFromCache(@Nonnull IChallenge challenge) { + challenges.remove(challenge); + } + + protected ItemStack getDisplayItem(@Nonnull IChallenge challenge) { + return getDisplayItemBuilder(challenge).build(); + } + + protected ItemBuilder getDisplayItemBuilder(@Nonnull IChallenge challenge) { + try { + ItemBuilder item = new ItemBuilder(challenge.getDisplayItem()).hideAttributes(); + if (newSuffix && isNew(challenge)) { + return item.appendName(" " + Message.forName("new-challenge")); + } else { + return item; + } + } catch (Exception ex) { + Logger.error("Error while generating challenge display item for challenge {}", challenge.getClass().getSimpleName(), ex); + return new ItemBuilder(); + } + } + + protected ItemStack getSettingsItem(@Nonnull IChallenge challenge) { + try { + ItemBuilder item = new ItemBuilder(challenge.getSettingsItem()).hideAttributes(); + return item.build(); + } catch (Exception ex) { + Logger.error("Error while generating challenge settings item for challenge {}", challenge.getClass().getSimpleName(), ex); + return new ItemBuilder().build(); + } + } + + protected boolean isNew(@Nonnull IChallenge challenge) { + Version version = Challenges.getInstance().getVersion(); + Version since = Version.getAnnotatedSince(challenge); + return since.isNewerOrEqualThan(version); + } + + protected int countNewChallenges() { + return (int) challenges.stream().filter(this::isNew).count(); + } + + public abstract int[] getSlots(); + + public abstract void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClickInfo info, int itemIndex); + + public void onPreChallengePageClicking(@Nonnull MenuClickInfo clickInfo, @Nonnegative int page) { + + } + + public List getChallenges() { + return ImmutableList.copyOf(challenges); + } + + private class ChallengeMenuPositionGenerator extends GeneratorMenuPosition { + + public ChallengeMenuPositionGenerator(MenuGenerator generator, int page) { + super(generator, page); + } + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + + if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onLeaveClick.accept(info.getPlayer()))) { + return; + } + + + if (page < startPage) { + onPreChallengePageClicking(info, page); + return; + } + + int itemIndex = 0; + int index = 0; + for (int i : getSlots()) { + if (i == info.getSlot()) break; + if ((i + 9) == info.getSlot()) { + itemIndex = 1; + break; + } else if ((i + 18) == info.getSlot()) { + itemIndex = 2; + break; + } + index++; + } + + if (itemIndex == 2) { + SoundSample.CLICK.play(info.getPlayer()); + return; + } + + if (index == getSlots().length) { // No possible bound slot was clicked + SoundSample.CLICK.play(info.getPlayer()); + return; + } + + int offset = (page - startPage) * getSlots().length; + index += offset; + + if (index >= challenges.size()) { // No bound slot was clicked + SoundSample.CLICK.play(info.getPlayer()); + return; + } + + IChallenge challenge = challenges.get(index); + + if (playNoPermissionsEffect(info.getPlayer())) return; + + try { + executeClickAction(challenge, info, itemIndex); + updateItem(challenge); + } catch (Exception ex) { + Logger.error("An exception occurred while handling click on {}", challenge.getClass().getName(), ex); + } + + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java index 9a114acda..d63a57f47 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java @@ -1,9 +1,5 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import java.util.List; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; - import lombok.Getter; import lombok.Setter; import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; @@ -15,49 +11,53 @@ import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import java.util.List; + @Getter @Setter public abstract class MenuGenerator { - // ONLY MODIFY IF YOU KNOW WHAT YOU ARE DOING - private MenuType menuType; - - public abstract void generateInventories(); - - public abstract List getInventories(); - - public abstract MenuPosition getMenuPosition(@Nonnegative int page); - - public boolean hasInventoryOpen(Player player) { - MenuPosition menuPosition = MenuPosition.get(player); - return menuPosition instanceof GeneratorMenuPosition - && CompatibilityUtils.getTopInventory(player).getType() != InventoryType.CRAFTING - && ((GeneratorMenuPosition) menuPosition).getGenerator() == this; - } - - public int getPage(Player player) { - MenuPosition menuPosition = MenuPosition.get(player); - if (menuPosition instanceof GeneratorMenuPosition) - return ((GeneratorMenuPosition) menuPosition).getPage(); - return 0; - } - - public void reopenInventoryForPlayers() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (hasInventoryOpen(player)) { - open(player, getPage(player)); - } - } - } - - public void open(@Nonnull Player player, @Nonnegative int page) { - List inventories = getInventories(); - if (inventories == null || inventories.isEmpty()) generateInventories(); - if (inventories == null || inventories.isEmpty()) return; - if (page >= inventories.size()) page = inventories.size() - 1; - Inventory inventory = inventories.get(page); - MenuPosition.set(player, getMenuPosition(page)); - player.openInventory(inventory); - } + // ONLY MODIFY IF YOU KNOW WHAT YOU ARE DOING + private MenuType menuType; + + public abstract void generateInventories(); + + public abstract List getInventories(); + + public abstract MenuPosition getMenuPosition(@Nonnegative int page); + + public boolean hasInventoryOpen(Player player) { + MenuPosition menuPosition = MenuPosition.get(player); + return menuPosition instanceof GeneratorMenuPosition + && CompatibilityUtils.getTopInventory(player).getType() != InventoryType.CRAFTING + && ((GeneratorMenuPosition) menuPosition).getGenerator() == this; + } + + public int getPage(Player player) { + MenuPosition menuPosition = MenuPosition.get(player); + if (menuPosition instanceof GeneratorMenuPosition) + return ((GeneratorMenuPosition) menuPosition).getPage(); + return 0; + } + + public void reopenInventoryForPlayers() { + for (Player player : Bukkit.getOnlinePlayers()) { + if (hasInventoryOpen(player)) { + open(player, getPage(player)); + } + } + } + + public void open(@Nonnull Player player, @Nonnegative int page) { + List inventories = getInventories(); + if (inventories == null || inventories.isEmpty()) generateInventories(); + if (inventories == null || inventories.isEmpty()) return; + if (page >= inventories.size()) page = inventories.size() - 1; + Inventory inventory = inventories.get(page); + MenuPosition.set(player, getMenuPosition(page)); + player.openInventory(inventory); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java index 971853af9..79798c9e8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java @@ -16,56 +16,56 @@ public abstract class MultiPageMenuGenerator extends MenuGenerator { - protected final List inventories = new ArrayList<>(); + protected final List inventories = new ArrayList<>(); - @Nonnull - protected Inventory createNewInventory(int page) { - Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, getSize(), getTitle(page)); - InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); - inventories.add(inventory); - return inventory; - } + @Nonnull + protected Inventory createNewInventory(int page) { + Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, getSize(), getTitle(page)); + InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); + inventories.add(inventory); + return inventory; + } - protected String getTitle(@Nonnegative int page) { - return InventoryTitleManager.getTitle(getMenuType(), page); - } + protected String getTitle(@Nonnegative int page) { + return InventoryTitleManager.getTitle(getMenuType(), page); + } - public abstract int getSize(); + public abstract int getSize(); - public abstract int getPagesCount(); + public abstract int getPagesCount(); - public abstract void generatePage(@Nonnull Inventory inventory, int page); + public abstract void generatePage(@Nonnull Inventory inventory, int page); - public abstract int[] getNavigationSlots(@Nonnegative int page); + public abstract int[] getNavigationSlots(@Nonnegative int page); - @Override - public void generateInventories() { - inventories.clear(); + @Override + public void generateInventories() { + inventories.clear(); - for (int page = 0; page < getPagesCount(); page++) { - Inventory inventory = createNewInventory(page); - generatePage(inventory, page); - } + for (int page = 0; page < getPagesCount(); page++) { + Inventory inventory = createNewInventory(page); + generatePage(inventory, page); + } - for (int i = 0; i < inventories.size(); i++) { - addNavigationItems(inventories.get(i), i); - } + for (int i = 0; i < inventories.size(); i++) { + addNavigationItems(inventories.get(i), i); + } - reopenInventoryForPlayers(); + reopenInventoryForPlayers(); - } + } - @Override - public List getInventories() { - return inventories; - } + @Override + public List getInventories() { + return inventories; + } - public void addNavigationItems(@Nonnull Inventory inventory, int page) { - InventoryUtils.setNavigationItems(inventory, - getNavigationSlots(page), true, - InventorySetter.INVENTORY, page, inventories.size(), - DefaultItem.navigateBack().clone().setLore("", "§7Shift §8» §7-5"), - DefaultItem.navigateNext().clone().setLore("", "§7Shift §8» §7+5")); - } + public void addNavigationItems(@Nonnull Inventory inventory, int page) { + InventoryUtils.setNavigationItems(inventory, + getNavigationSlots(page), true, + InventorySetter.INVENTORY, page, inventories.size(), + DefaultItem.navigateBack().clone().setLore("", "§7Shift §8» §7-5"), + DefaultItem.navigateNext().clone().setLore("", "§7Shift §8» §7+5")); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java index 8106fdf87..fe49411ca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java @@ -21,100 +21,100 @@ @Getter public abstract class ValueMenuGenerator extends MultiPageMenuGenerator { - public static final int FINISH_SLOT = 31; + public static final int FINISH_SLOT = 31; - private final Map settings; + private final Map settings; - public ValueMenuGenerator(Map settings) { - this.settings = settings; - } + public ValueMenuGenerator(Map settings) { + this.settings = settings; + } - @Override - public MenuPosition getMenuPosition(int page) { - return new GeneratorMenuPosition(this, page) { + @Override + public MenuPosition getMenuPosition(int page) { + return new GeneratorMenuPosition(this, page) { - @Override - public void handleClick(@Nonnull MenuClickInfo info) { + @Override + public void handleClick(@Nonnull MenuClickInfo info) { - if (info.getSlot() == FINISH_SLOT) { - onSaveItemClick(info.getPlayer()); - SoundSample.PLOP.play(info.getPlayer()); - return; - } + if (info.getSlot() == FINISH_SLOT) { + onSaveItemClick(info.getPlayer()); + SoundSample.PLOP.play(info.getPlayer()); + return; + } - if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { - return; - } + if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { + return; + } - int slot = info.getSlot(); + int slot = info.getSlot(); - int index = getItemsPerPage() * page + slot - 10; + int index = getItemsPerPage() * page + slot - 10; - if (slot > 18) index -= 9; + if (slot > 18) index -= 9; - if (index >= settings.size() || index < 0) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } + if (index >= settings.size() || index < 0) { + SoundSample.CLICK.play(info.getPlayer()); + return; + } - ValueSetting[] array = settings.keySet().toArray(new ValueSetting[0]); + ValueSetting[] array = settings.keySet().toArray(new ValueSetting[0]); - ValueSetting key = array[index]; - String oldValue = settings.get(key); + ValueSetting key = array[index]; + String oldValue = settings.get(key); - int itemIndex = slot >= 18 ? 1 : 0; - String newValue = key.onClick(info, oldValue, itemIndex); - settings.put(key, newValue); - SoundSample.CLICK.play(info.getPlayer()); - generatePage(info.getInventory(), page); - open(info.getPlayer(), page); - } - }; - } + int itemIndex = slot >= 18 ? 1 : 0; + String newValue = key.onClick(info, oldValue, itemIndex); + settings.put(key, newValue); + SoundSample.CLICK.play(info.getPlayer()); + generatePage(info.getInventory(), page); + open(info.getPlayer(), page); + } + }; + } - @Override - public int getSize() { - return 4 * 9; - } + @Override + public int getSize() { + return 4 * 9; + } - @Override - public int getPagesCount() { - return (settings.size() / getItemsPerPage()) + 1; - } + @Override + public int getPagesCount() { + return (settings.size() / getItemsPerPage()) + 1; + } - public int getItemsPerPage() { - return 4; - } + public int getItemsPerPage() { + return 4; + } - @Override - public void generatePage(@Nonnull Inventory inventory, int page) { + @Override + public void generatePage(@Nonnull Inventory inventory, int page) { - int startIndex = getItemsPerPage() * page; - for (int i = startIndex; i < startIndex + getItemsPerPage() && i < settings.size(); i++) { - int slot = i - (getItemsPerPage() * page) + 10; - ValueSetting key = settings.keySet().toArray(new ValueSetting[0])[i]; - String value = settings.get(key); - inventory.setItem(slot, key.getDisplayItem(value).build()); - inventory.setItem(slot + 9, key.getSettingsItem(value).build()); - } + int startIndex = getItemsPerPage() * page; + for (int i = startIndex; i < startIndex + getItemsPerPage() && i < settings.size(); i++) { + int slot = i - (getItemsPerPage() * page) + 10; + ValueSetting key = settings.keySet().toArray(new ValueSetting[0])[i]; + String value = settings.get(key); + inventory.setItem(slot, key.getDisplayItem(value).build()); + inventory.setItem(slot + 9, key.getSettingsItem(value).build()); + } - inventory.setItem(FINISH_SLOT, DefaultItem.create(Material.LIME_DYE, Message.forName("custom-sub-finish")).build()); - } + inventory.setItem(FINISH_SLOT, DefaultItem.create(Material.LIME_DYE, Message.forName("custom-sub-finish")).build()); + } - @Override - public int[] getNavigationSlots(int page) { - return new int[]{27, 35}; - } + @Override + public int[] getNavigationSlots(int page) { + return new int[]{27, 35}; + } - @Override - protected String getTitle(int page) { - return InventoryTitleManager.getTitle(MenuType.CUSTOM, getSubTitles(page)); - } + @Override + protected String getTitle(int page) { + return InventoryTitleManager.getTitle(MenuType.CUSTOM, getSubTitles(page)); + } - public abstract String[] getSubTitles(int page); + public abstract String[] getSubTitles(int page); - public abstract void onSaveItemClick(Player player); + public abstract void onSaveItemClick(Player player); - public abstract void onBackToMenuItemClick(Player player); + public abstract void onBackToMenuItemClick(Player player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java index 20291244b..44ff6898c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java @@ -22,172 +22,172 @@ public class CategorisedMenuGenerator extends SettingsMenuGenerator { - private final Map categories = new LinkedHashMap<>(); - - @Override - public void addChallengeToCache(@NotNull IChallenge challenge) { - SettingCategory category = challenge.getCategory() != null ? challenge.getCategory() : getMiscCategory(); - if (!categories.containsKey(challenge.getCategory())) { - categories.computeIfAbsent(category, challengeCategory -> { - CategorisedSettingsMenuGenerator generator = new CategorisedSettingsMenuGenerator(this, category); - generator.setMenuType(getMenuType()); - return generator; - }); - } - categories.get(category).addChallengeToCache(challenge); - } - - @Override - public void resetChallengeCache() { - categories.clear(); - } - - private SettingCategory getMiscCategory() { - if (getMenuType() == MenuType.GOAL) { - return SettingCategory.MISC_GOAL; - } - return SettingCategory.MISC_CHALLENGE; - } - - @Override - public void generatePage(@NotNull Inventory inventory, int page) { - - int i = 0; - for (Map.Entry entry : getCategoriesForPage(page)) { - SettingCategory category = entry.getKey(); - CategorisedSettingsMenuGenerator generator = entry.getValue(); - - ItemBuilder builder = category.getDisplayItem(); - String attachment = getLoreAttachment(generator); - if (!attachment.isEmpty()) { - builder.appendLore("", attachment); - } - - int slot = i + 10; - if (i >= 7) slot += 2; - - for (IChallenge challenge : generator.getChallenges()) { - if (newSuffix && isNew(challenge)) { - builder.appendName(" " + Message.forName("new-challenge")); - break; - } - } - - inventory.setItem(slot, builder.build()); - i++; - } - - } - - private String getLoreAttachment(CategorisedSettingsMenuGenerator generator) { - - if (getMenuType() == MenuType.GOAL) { - for (IChallenge challenge : generator.getChallenges()) { - if (challenge.isEnabled()) { - return Message.forName("lore-category-activated").asString(); - } - } - return Message.forName("lore-category-deactivated").asString(); - } - long activatedCount = generator.getChallenges().stream().filter(IChallenge::isEnabled).count(); - return Message.forName("lore-category-activated-count").asString(activatedCount, generator.getChallenges().size()); - } - - @Override - public void updateItem(IChallenge challenge) { - generateInventories(); - - for (Map.Entry entry : categories.entrySet()) { - if (entry.getValue().getChallenges().contains(challenge)) { - entry.getValue().updateGeneratorItem(challenge); - } - } - - } - - @Override - public int getPagesCount() { - return (int) (Math.ceil((double) categories.size() / getEntriesPerPage())); - } - - public int getEntriesPerPage() { - return 14; - } - - @Override - public MenuPosition getMenuPosition(int page) { - return info -> { - if (InventoryUtils.handleNavigationClicking(this, - getNavigationSlots(page), - page, - info, - () -> Challenges.getInstance().getMenuManager().openGUIInstantly(info.getPlayer()))) { - return; - } - - int i = 0; - for (Map.Entry entry : getCategoriesForPage(page)) { - int slot = i + 10; - if (i >= 7) slot += 2; - if (slot == info.getSlot()) { - SettingsMenuGenerator generator = entry.getValue(); - SoundSample.CLICK.play(info.getPlayer()); - generator.open(info.getPlayer(), 0); - return; - } - i++; - } - - SoundSample.CLICK.play(info.getPlayer()); - }; - } - - private List> getCategoriesForPage(int page) { - - List> list = categories.entrySet() - .stream() - // Priority might be removed in a future version - .sorted(Comparator.comparingInt(value -> value.getKey().getPriority())) - .collect(Collectors.toList()); - - int entriesPerPage = getEntriesPerPage(); - int startIndex = page * entriesPerPage; - int endIndex = Math.min(page * entriesPerPage + entriesPerPage, categories.size()); - - return list.subList(startIndex, endIndex); - } - - public static class CategorisedSettingsMenuGenerator extends SettingsMenuGenerator { - - private final CategorisedMenuGenerator generator; - private final SettingCategory category; - - public CategorisedSettingsMenuGenerator(CategorisedMenuGenerator generator, SettingCategory category) { - this.generator = generator; - this.category = category; - this.onLeaveClick = player -> { - SoundSample.CLICK.play(player); - generator.open(player, 0); - }; - } - - @Override - protected String getTitle(int page) { - String[] strings = category.getMessageSupplier().get().asArray(); - String display = strings.length == 0 ? "" : ChatColor.stripColor(strings[0]); - return InventoryTitleManager.getTitle(getMenuType(), display, String.valueOf(page + 1)); - } - - @Override - public void updateItem(IChallenge challenge) { - generator.updateItem(challenge); - super.updateItem(challenge); - } - - public void updateGeneratorItem(IChallenge challenge) { - super.updateItem(challenge); - } - - } + private final Map categories = new LinkedHashMap<>(); + + @Override + public void addChallengeToCache(@NotNull IChallenge challenge) { + SettingCategory category = challenge.getCategory() != null ? challenge.getCategory() : getMiscCategory(); + if (!categories.containsKey(challenge.getCategory())) { + categories.computeIfAbsent(category, challengeCategory -> { + CategorisedSettingsMenuGenerator generator = new CategorisedSettingsMenuGenerator(this, category); + generator.setMenuType(getMenuType()); + return generator; + }); + } + categories.get(category).addChallengeToCache(challenge); + } + + @Override + public void resetChallengeCache() { + categories.clear(); + } + + private SettingCategory getMiscCategory() { + if (getMenuType() == MenuType.GOAL) { + return SettingCategory.MISC_GOAL; + } + return SettingCategory.MISC_CHALLENGE; + } + + @Override + public void generatePage(@NotNull Inventory inventory, int page) { + + int i = 0; + for (Map.Entry entry : getCategoriesForPage(page)) { + SettingCategory category = entry.getKey(); + CategorisedSettingsMenuGenerator generator = entry.getValue(); + + ItemBuilder builder = category.getDisplayItem(); + String attachment = getLoreAttachment(generator); + if (!attachment.isEmpty()) { + builder.appendLore("", attachment); + } + + int slot = i + 10; + if (i >= 7) slot += 2; + + for (IChallenge challenge : generator.getChallenges()) { + if (newSuffix && isNew(challenge)) { + builder.appendName(" " + Message.forName("new-challenge")); + break; + } + } + + inventory.setItem(slot, builder.build()); + i++; + } + + } + + private String getLoreAttachment(CategorisedSettingsMenuGenerator generator) { + + if (getMenuType() == MenuType.GOAL) { + for (IChallenge challenge : generator.getChallenges()) { + if (challenge.isEnabled()) { + return Message.forName("lore-category-activated").asString(); + } + } + return Message.forName("lore-category-deactivated").asString(); + } + long activatedCount = generator.getChallenges().stream().filter(IChallenge::isEnabled).count(); + return Message.forName("lore-category-activated-count").asString(activatedCount, generator.getChallenges().size()); + } + + @Override + public void updateItem(IChallenge challenge) { + generateInventories(); + + for (Map.Entry entry : categories.entrySet()) { + if (entry.getValue().getChallenges().contains(challenge)) { + entry.getValue().updateGeneratorItem(challenge); + } + } + + } + + @Override + public int getPagesCount() { + return (int) (Math.ceil((double) categories.size() / getEntriesPerPage())); + } + + public int getEntriesPerPage() { + return 14; + } + + @Override + public MenuPosition getMenuPosition(int page) { + return info -> { + if (InventoryUtils.handleNavigationClicking(this, + getNavigationSlots(page), + page, + info, + () -> Challenges.getInstance().getMenuManager().openGUIInstantly(info.getPlayer()))) { + return; + } + + int i = 0; + for (Map.Entry entry : getCategoriesForPage(page)) { + int slot = i + 10; + if (i >= 7) slot += 2; + if (slot == info.getSlot()) { + SettingsMenuGenerator generator = entry.getValue(); + SoundSample.CLICK.play(info.getPlayer()); + generator.open(info.getPlayer(), 0); + return; + } + i++; + } + + SoundSample.CLICK.play(info.getPlayer()); + }; + } + + private List> getCategoriesForPage(int page) { + + List> list = categories.entrySet() + .stream() + // Priority might be removed in a future version + .sorted(Comparator.comparingInt(value -> value.getKey().getPriority())) + .collect(Collectors.toList()); + + int entriesPerPage = getEntriesPerPage(); + int startIndex = page * entriesPerPage; + int endIndex = Math.min(page * entriesPerPage + entriesPerPage, categories.size()); + + return list.subList(startIndex, endIndex); + } + + public static class CategorisedSettingsMenuGenerator extends SettingsMenuGenerator { + + private final CategorisedMenuGenerator generator; + private final SettingCategory category; + + public CategorisedSettingsMenuGenerator(CategorisedMenuGenerator generator, SettingCategory category) { + this.generator = generator; + this.category = category; + this.onLeaveClick = player -> { + SoundSample.CLICK.play(player); + generator.open(player, 0); + }; + } + + @Override + protected String getTitle(int page) { + String[] strings = category.getMessageSupplier().get().asArray(); + String display = strings.length == 0 ? "" : ChatColor.stripColor(strings[0]); + return InventoryTitleManager.getTitle(getMenuType(), display, String.valueOf(page + 1)); + } + + @Override + public void updateItem(IChallenge challenge) { + generator.updateItem(challenge); + super.updateItem(challenge); + } + + public void updateGeneratorItem(IChallenge challenge) { + super.updateItem(challenge); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java index 2059f5128..99a11186e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java @@ -11,39 +11,39 @@ @Getter public class SettingCategory { - //Challenges - public static final SettingCategory MISC_CHALLENGE = new SettingCategory(99, Material.MINECART, () -> Message.forName("category-misc_challenge")); - public static final SettingCategory RANDOMIZER = new SettingCategory(1, Material.COMMAND_BLOCK, () -> Message.forName("category-randomizer")); - public static final SettingCategory FORCE = new SettingCategory(2, Material.BLUE_BANNER, () -> Message.forName("category-force")); - public static final SettingCategory ENTITIES = new SettingCategory(3, Material.PIG_SPAWN_EGG, () -> Message.forName("category-entities")); - public static final SettingCategory DAMAGE = new SettingCategory(4, MinecraftNameWrapper.RED_DYE, () -> Message.forName("category-damage")); - public static final SettingCategory EFFECT = new SettingCategory(5, Material.FERMENTED_SPIDER_EYE, () -> Message.forName("category-effect")); - public static final SettingCategory WORLD = new SettingCategory(6, Material.TNT, () -> Message.forName("category-world")); - public static final SettingCategory INVENTORY = new SettingCategory(7, Material.CHEST, () -> Message.forName("category-inventory")); - public static final SettingCategory MOVEMENT = new SettingCategory(8, Material.RABBIT_FOOT, () -> Message.forName("category-movement")); - public static final SettingCategory LIMITED_TIME = new SettingCategory(9, Material.CLOCK, () -> Message.forName("category-limited_time")); - public static final SettingCategory EXTRA_WORLD = new SettingCategory(10, Material.GRASS_BLOCK, () -> Message.forName("category-extra_world")); - - //Goals - public static final SettingCategory MISC_GOAL = new SettingCategory(99, Material.MINECART, () -> Message.forName("category-misc_goal")); - public static final SettingCategory KILL_ENTITY = new SettingCategory(1, Material.BOW, () -> Message.forName("category-kill_entity")); - public static final SettingCategory SCORE_POINTS = new SettingCategory(2, Material.CHEST, () -> Message.forName("category-score_points")); - public static final SettingCategory FASTEST_TIME = new SettingCategory(3, Material.CLOCK, () -> Message.forName("category-fastest_time")); - public static final SettingCategory FORCE_BATTLE = new SettingCategory(4, Material.BLUE_BANNER, () -> Message.forName("category-force_battle")); - - // Lowest priority will be displayed first - private final int priority; - private final Material material; - private final Supplier messageSupplier; - - public SettingCategory(int priority, Material material, Supplier messageSupplier) { - this.priority = priority; - this.material = material; - this.messageSupplier = messageSupplier; - } - - public ItemBuilder getDisplayItem() { - return new ItemBuilder(material, messageSupplier.get()); - } + //Challenges + public static final SettingCategory MISC_CHALLENGE = new SettingCategory(99, Material.MINECART, () -> Message.forName("category-misc_challenge")); + public static final SettingCategory RANDOMIZER = new SettingCategory(1, Material.COMMAND_BLOCK, () -> Message.forName("category-randomizer")); + public static final SettingCategory FORCE = new SettingCategory(2, Material.BLUE_BANNER, () -> Message.forName("category-force")); + public static final SettingCategory ENTITIES = new SettingCategory(3, Material.PIG_SPAWN_EGG, () -> Message.forName("category-entities")); + public static final SettingCategory DAMAGE = new SettingCategory(4, MinecraftNameWrapper.RED_DYE, () -> Message.forName("category-damage")); + public static final SettingCategory EFFECT = new SettingCategory(5, Material.FERMENTED_SPIDER_EYE, () -> Message.forName("category-effect")); + public static final SettingCategory WORLD = new SettingCategory(6, Material.TNT, () -> Message.forName("category-world")); + public static final SettingCategory INVENTORY = new SettingCategory(7, Material.CHEST, () -> Message.forName("category-inventory")); + public static final SettingCategory MOVEMENT = new SettingCategory(8, Material.RABBIT_FOOT, () -> Message.forName("category-movement")); + public static final SettingCategory LIMITED_TIME = new SettingCategory(9, Material.CLOCK, () -> Message.forName("category-limited_time")); + public static final SettingCategory EXTRA_WORLD = new SettingCategory(10, Material.GRASS_BLOCK, () -> Message.forName("category-extra_world")); + + //Goals + public static final SettingCategory MISC_GOAL = new SettingCategory(99, Material.MINECART, () -> Message.forName("category-misc_goal")); + public static final SettingCategory KILL_ENTITY = new SettingCategory(1, Material.BOW, () -> Message.forName("category-kill_entity")); + public static final SettingCategory SCORE_POINTS = new SettingCategory(2, Material.CHEST, () -> Message.forName("category-score_points")); + public static final SettingCategory FASTEST_TIME = new SettingCategory(3, Material.CLOCK, () -> Message.forName("category-fastest_time")); + public static final SettingCategory FORCE_BATTLE = new SettingCategory(4, Material.BLUE_BANNER, () -> Message.forName("category-force_battle")); + + // Lowest priority will be displayed first + private final int priority; + private final Material material; + private final Supplier messageSupplier; + + public SettingCategory(int priority, Material material, Supplier messageSupplier) { + this.priority = priority; + this.material = material; + this.messageSupplier = messageSupplier; + } + + public ItemBuilder getDisplayItem() { + return new ItemBuilder(material, messageSupplier.get()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java index ce6d290fa..36c597f33 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java @@ -15,8 +15,8 @@ import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; -import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Material; @@ -31,197 +31,197 @@ public class TimerMenuGenerator extends MenuGenerator { - public static final int SIZE = 5 * 9; - public static final int[] NAVIGATION_SLOTS = {36, 44}; - public static final int START_SLOT = 21; - public static final int MODE_SLOT = 23; - public static final int[] HOUR_SLOTS = {11, 20, 29}; - public static final int[] MINUTE_SLOTS = {13, 22, 31}; - public static final int[] SECOND_SLOTS = {15, 24, 33}; - - private final List inventories = new ArrayList<>(); - - public TimerMenuGenerator() { - ChallengeAPI.registerScheduler(this); - Challenges.getInstance().getLoaderRegistry().subscribe(LanguageLoader.class, this::generateInventories); - } - - @TimerTask(status = {TimerStatus.PAUSED, TimerStatus.RUNNING}) - public void updateInventories() { - updateFirstPage(); - updateSecondPage(); - } - - public void updateFirstPage() { - Inventory inventory = inventories.get(0); - inventory.setItem(START_SLOT, Challenges.getInstance().getChallengeTimer().isStarted() ? - new ItemBuilder(Material.LIME_DYE).name(Message.forName("timer-is-running")).build() : - new ItemBuilder(MinecraftNameWrapper.RED_DYE).name(Message.forName("timer-is-paused")).build()); - inventory.setItem(MODE_SLOT, Challenges.getInstance().getChallengeTimer().isCountingUp() ? - new PotionBuilder(Material.TIPPED_ARROW).setColor(Color.LIME).name(Message.forName("timer-counting-up")).hideAttributes().build() : - new PotionBuilder(Material.TIPPED_ARROW).setColor(Color.RED).name(Message.forName("timer-counting-down")).hideAttributes().build()); - } - - @ScheduledTask(ticks = 20) - public void updateSecondPage() { - setTimeNavigation(HOUR_SLOTS, Message.forName("hour"), Message.forName("hours")); - setTimeNavigation(MINUTE_SLOTS, Message.forName("minute"), Message.forName("minutes")); - setTimeNavigation(SECOND_SLOTS, Message.forName("second"), Message.forName("seconds")); - - long seconds = Challenges.getInstance().getChallengeTimer().getTime(); - long minutes = seconds / 60; - long hours = minutes / 60; - seconds %= 60; - minutes %= 60; - - Inventory inventory = inventories.get(1); - inventory.setItem(HOUR_SLOTS[1], getTimeItem(hours, Message.forName("hour"), Message.forName("hours"))); - inventory.setItem(MINUTE_SLOTS[1], getTimeItem(minutes, Message.forName("minute"), Message.forName("minutes"))); - inventory.setItem(SECOND_SLOTS[1], getTimeItem(seconds, Message.forName("second"), Message.forName("seconds"))); - } - - private void setTimeNavigation(@Nonnull int[] slots, @Nonnull Message singular, @Nonnull Message plural) { - Inventory inventory = inventories.get(1); - inventory.setItem(slots[0], getNavigationItem(true, singular, plural)); - inventory.setItem(slots[2], getNavigationItem(false, singular, plural)); - } - - @Nonnull - private ItemStack getNavigationItem(boolean up, @Nonnull Message singular, @Nonnull Message plural) { - return new ItemBuilder(up ? Material.DARK_OAK_BUTTON : Material.STONE_BUTTON).name( - " ", - "§7§o[Click] §8» §" + (up ? "a+" : "c-") + "1 " + singular, - "§7§o[Shift-Click] §8» §" + (up ? "a+" : "c-") + "10 " + plural, - " " - ).hideAttributes().build(); - } - - @Nonnull - private ItemStack getTimeItem(long value, @Nonnull Message singular, @Nonnull Message plural) { - return new ItemBuilder(Material.CLOCK).name( - "§8» §7" + (value == 1 ? singular : plural) + ": §e" + value, - " ", - "§7§o[Click] §8» §cReset §7timer", - " " - ).hideAttributes().amount((int) Math.max(value, 1)).build(); - } - - @Nonnull - private Inventory createNewInventory(int page) { - Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, SIZE, InventoryTitleManager.getTitle(MenuType.TIMER, page)); - InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); - for (int i : new int[]{1, 2, 6, 7, 9, 10, 16, 17, 27, 28, 34, 35, 37, 38, 39, 41, 42, 43}) { - inventory.setItem(i, ItemBuilder.FILL_ITEM_2); - } - inventories.add(inventory); - return inventory; - } - - private void setNavigation() { - InventoryUtils.setNavigationItemsToInventory(inventories, NAVIGATION_SLOTS); - } - - @Override - public void generateInventories() { - createNewInventory(0); - createNewInventory(1); - setNavigation(); - updateInventories(); - } - - @Override - public List getInventories() { - return inventories; - } - - @Override - public MenuPosition getMenuPosition(int page) { - return new TimerMenuPosition(page); - } - - private class TimerMenuPosition implements MenuPosition { - - private final int page; - - public TimerMenuPosition(@Nonnegative int page) { - this.page = page; - } - - @Override - public void handleClick(@Nonnull MenuClickInfo info) { - - if (info.getSlot() == NAVIGATION_SLOTS[0]) { - SoundSample.CLICK.play(info.getPlayer()); - if (page == 0) { - Challenges.getInstance().getMenuManager().openGUIInstantly(info.getPlayer()); - } else { - open(info.getPlayer(), page - 1); - } - return; - } else if (info.getSlot() == NAVIGATION_SLOTS[1]) { - SoundSample.CLICK.play(info.getPlayer()); - if (page < (inventories.size() - 1)) - open(info.getPlayer(), page + 1); - return; - } - - if (page == 0) { - if (info.getSlot() == START_SLOT) { - if (playNoPermissionsEffect(info.getPlayer())) return; - if (Challenges.getInstance().getChallengeTimer().isStarted()) { - Challenges.getInstance().getChallengeTimer().pause(true); - } else { - Challenges.getInstance().getChallengeTimer().resume(); - } - return; - } else if (info.getSlot() == MODE_SLOT) { - if (playNoPermissionsEffect(info.getPlayer())) return; - Challenges.getInstance().getChallengeTimer().setCountingUp(!Challenges.getInstance().getChallengeTimer().isCountingUp()); - return; - } - } else if (page == 1) { - for (int[] slots : new int[][]{HOUR_SLOTS, MINUTE_SLOTS, SECOND_SLOTS}) { - for (int i = 0; i < 3; i++) { - - if (info.getSlot() != slots[i]) continue; - if (playNoPermissionsEffect(info.getPlayer())) return; - - if (i == 1) { - Challenges.getInstance().getChallengeTimer().reset(); - SoundSample.BASS_OFF.play(info.getPlayer()); - updateInventories(); - Challenges.getInstance().getChallengeTimer().updateActionbar(); - return; - } - - int amount = (slots == HOUR_SLOTS ? 60 * 60 : (slots == MINUTE_SLOTS ? 60 : 1)); - if (info.isShiftClick()) amount *= 10; - - boolean plus = i == 0; - - Challenges.getInstance().getChallengeTimer().addSeconds(plus ? +amount : -amount); - updateInventories(); - - SoundSample.PLOP.play(info.getPlayer()); - return; - } - } - } - - SoundSample.CLICK.play(info.getPlayer()); - - } - - private boolean playNoPermissionsEffect(@Nonnull Player player) { - if (mayManageTimer(player)) return false; - Challenges.getInstance().getMenuManager().playNoPermissionsEffect(player); - return true; - } - - private boolean mayManageTimer(@Nonnull Player player) { - return player.hasPermission("challenges.timer"); - } - - } + public static final int SIZE = 5 * 9; + public static final int[] NAVIGATION_SLOTS = {36, 44}; + public static final int START_SLOT = 21; + public static final int MODE_SLOT = 23; + public static final int[] HOUR_SLOTS = {11, 20, 29}; + public static final int[] MINUTE_SLOTS = {13, 22, 31}; + public static final int[] SECOND_SLOTS = {15, 24, 33}; + + private final List inventories = new ArrayList<>(); + + public TimerMenuGenerator() { + ChallengeAPI.registerScheduler(this); + Challenges.getInstance().getLoaderRegistry().subscribe(LanguageLoader.class, this::generateInventories); + } + + @TimerTask(status = {TimerStatus.PAUSED, TimerStatus.RUNNING}) + public void updateInventories() { + updateFirstPage(); + updateSecondPage(); + } + + public void updateFirstPage() { + Inventory inventory = inventories.get(0); + inventory.setItem(START_SLOT, Challenges.getInstance().getChallengeTimer().isStarted() ? + new ItemBuilder(Material.LIME_DYE).name(Message.forName("timer-is-running")).build() : + new ItemBuilder(MinecraftNameWrapper.RED_DYE).name(Message.forName("timer-is-paused")).build()); + inventory.setItem(MODE_SLOT, Challenges.getInstance().getChallengeTimer().isCountingUp() ? + new PotionBuilder(Material.TIPPED_ARROW).setColor(Color.LIME).name(Message.forName("timer-counting-up")).hideAttributes().build() : + new PotionBuilder(Material.TIPPED_ARROW).setColor(Color.RED).name(Message.forName("timer-counting-down")).hideAttributes().build()); + } + + @ScheduledTask(ticks = 20) + public void updateSecondPage() { + setTimeNavigation(HOUR_SLOTS, Message.forName("hour"), Message.forName("hours")); + setTimeNavigation(MINUTE_SLOTS, Message.forName("minute"), Message.forName("minutes")); + setTimeNavigation(SECOND_SLOTS, Message.forName("second"), Message.forName("seconds")); + + long seconds = Challenges.getInstance().getChallengeTimer().getTime(); + long minutes = seconds / 60; + long hours = minutes / 60; + seconds %= 60; + minutes %= 60; + + Inventory inventory = inventories.get(1); + inventory.setItem(HOUR_SLOTS[1], getTimeItem(hours, Message.forName("hour"), Message.forName("hours"))); + inventory.setItem(MINUTE_SLOTS[1], getTimeItem(minutes, Message.forName("minute"), Message.forName("minutes"))); + inventory.setItem(SECOND_SLOTS[1], getTimeItem(seconds, Message.forName("second"), Message.forName("seconds"))); + } + + private void setTimeNavigation(@Nonnull int[] slots, @Nonnull Message singular, @Nonnull Message plural) { + Inventory inventory = inventories.get(1); + inventory.setItem(slots[0], getNavigationItem(true, singular, plural)); + inventory.setItem(slots[2], getNavigationItem(false, singular, plural)); + } + + @Nonnull + private ItemStack getNavigationItem(boolean up, @Nonnull Message singular, @Nonnull Message plural) { + return new ItemBuilder(up ? Material.DARK_OAK_BUTTON : Material.STONE_BUTTON).name( + " ", + "§7§o[Click] §8» §" + (up ? "a+" : "c-") + "1 " + singular, + "§7§o[Shift-Click] §8» §" + (up ? "a+" : "c-") + "10 " + plural, + " " + ).hideAttributes().build(); + } + + @Nonnull + private ItemStack getTimeItem(long value, @Nonnull Message singular, @Nonnull Message plural) { + return new ItemBuilder(Material.CLOCK).name( + "§8» §7" + (value == 1 ? singular : plural) + ": §e" + value, + " ", + "§7§o[Click] §8» §cReset §7timer", + " " + ).hideAttributes().amount((int) Math.max(value, 1)).build(); + } + + @Nonnull + private Inventory createNewInventory(int page) { + Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, SIZE, InventoryTitleManager.getTitle(MenuType.TIMER, page)); + InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); + for (int i : new int[]{1, 2, 6, 7, 9, 10, 16, 17, 27, 28, 34, 35, 37, 38, 39, 41, 42, 43}) { + inventory.setItem(i, ItemBuilder.FILL_ITEM_2); + } + inventories.add(inventory); + return inventory; + } + + private void setNavigation() { + InventoryUtils.setNavigationItemsToInventory(inventories, NAVIGATION_SLOTS); + } + + @Override + public void generateInventories() { + createNewInventory(0); + createNewInventory(1); + setNavigation(); + updateInventories(); + } + + @Override + public List getInventories() { + return inventories; + } + + @Override + public MenuPosition getMenuPosition(int page) { + return new TimerMenuPosition(page); + } + + private class TimerMenuPosition implements MenuPosition { + + private final int page; + + public TimerMenuPosition(@Nonnegative int page) { + this.page = page; + } + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + + if (info.getSlot() == NAVIGATION_SLOTS[0]) { + SoundSample.CLICK.play(info.getPlayer()); + if (page == 0) { + Challenges.getInstance().getMenuManager().openGUIInstantly(info.getPlayer()); + } else { + open(info.getPlayer(), page - 1); + } + return; + } else if (info.getSlot() == NAVIGATION_SLOTS[1]) { + SoundSample.CLICK.play(info.getPlayer()); + if (page < (inventories.size() - 1)) + open(info.getPlayer(), page + 1); + return; + } + + if (page == 0) { + if (info.getSlot() == START_SLOT) { + if (playNoPermissionsEffect(info.getPlayer())) return; + if (Challenges.getInstance().getChallengeTimer().isStarted()) { + Challenges.getInstance().getChallengeTimer().pause(true); + } else { + Challenges.getInstance().getChallengeTimer().resume(); + } + return; + } else if (info.getSlot() == MODE_SLOT) { + if (playNoPermissionsEffect(info.getPlayer())) return; + Challenges.getInstance().getChallengeTimer().setCountingUp(!Challenges.getInstance().getChallengeTimer().isCountingUp()); + return; + } + } else if (page == 1) { + for (int[] slots : new int[][]{HOUR_SLOTS, MINUTE_SLOTS, SECOND_SLOTS}) { + for (int i = 0; i < 3; i++) { + + if (info.getSlot() != slots[i]) continue; + if (playNoPermissionsEffect(info.getPlayer())) return; + + if (i == 1) { + Challenges.getInstance().getChallengeTimer().reset(); + SoundSample.BASS_OFF.play(info.getPlayer()); + updateInventories(); + Challenges.getInstance().getChallengeTimer().updateActionbar(); + return; + } + + int amount = (slots == HOUR_SLOTS ? 60 * 60 : (slots == MINUTE_SLOTS ? 60 : 1)); + if (info.isShiftClick()) amount *= 10; + + boolean plus = i == 0; + + Challenges.getInstance().getChallengeTimer().addSeconds(plus ? +amount : -amount); + updateInventories(); + + SoundSample.PLOP.play(info.getPlayer()); + return; + } + } + } + + SoundSample.CLICK.play(info.getPlayer()); + + } + + private boolean playNoPermissionsEffect(@Nonnull Player player) { + if (mayManageTimer(player)) return false; + Challenges.getInstance().getMenuManager().playNoPermissionsEffect(player); + return true; + } + + private boolean mayManageTimer(@Nonnull Player player) { + return player.hasPermission("challenges.timer"); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java index e0d5fa869..3aad5dcf6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java @@ -16,76 +16,76 @@ public class CustomMainSettingsMenuGenerator extends ChooseItemGenerator implements IParentCustomGenerator { - @Getter + @Getter private final IParentCustomGenerator parent; - private final SettingType type; - private final String title; - private final String key; - private final Function instanceGetter; - private IChallengeSetting setting; - private SubSettingsBuilder subSettingsBuilder; - private Map subSettings; - - public CustomMainSettingsMenuGenerator(IParentCustomGenerator parent, SettingType type, String key, String title, LinkedHashMap items, Function instanceGetter) { - super(items); - this.parent = parent; - this.type = type; - this.title = title; - this.key = key; - this.instanceGetter = instanceGetter; - this.subSettings = new HashMap<>(); - } - - @Override - public String[] getSubTitles(int page) { - return new String[]{title}; - } - - @Override - public void accept(Player player, SettingType type, Map data) { - - subSettings.putAll(data); - - if (!openSubSettingsMenu(player)) { - parent.accept(player, this.type, subSettings); - } - - } - - @Override - public void onItemClick(Player player, String itemKey) { - this.setting = instanceGetter.apply(itemKey); - this.subSettingsBuilder = setting.getSubSettingsBuilder(); - - subSettings.put(key, new String[]{setting.getName()}); - - if (!openSubSettingsMenu(player)) { - parent.accept(player, type, subSettings); - } - - } - - private boolean openSubSettingsMenu(Player player) { - - if (subSettingsBuilder != null && subSettingsBuilder.hasSettings()) { - subSettingsBuilder.open(player, this, title); - subSettingsBuilder = subSettingsBuilder.getChild(); - - return true; - } - return false; - } - - @Override - public void onBackToMenuItemClick(Player player) { - parent.decline(player); - } - - @Override - public void decline(Player player) { - if (setting != null) - this.subSettings = MapUtils.createStringArrayMap(key, setting.getName()); - open(player, 0); - } + private final SettingType type; + private final String title; + private final String key; + private final Function instanceGetter; + private IChallengeSetting setting; + private SubSettingsBuilder subSettingsBuilder; + private Map subSettings; + + public CustomMainSettingsMenuGenerator(IParentCustomGenerator parent, SettingType type, String key, String title, LinkedHashMap items, Function instanceGetter) { + super(items); + this.parent = parent; + this.type = type; + this.title = title; + this.key = key; + this.instanceGetter = instanceGetter; + this.subSettings = new HashMap<>(); + } + + @Override + public String[] getSubTitles(int page) { + return new String[]{title}; + } + + @Override + public void accept(Player player, SettingType type, Map data) { + + subSettings.putAll(data); + + if (!openSubSettingsMenu(player)) { + parent.accept(player, this.type, subSettings); + } + + } + + @Override + public void onItemClick(Player player, String itemKey) { + this.setting = instanceGetter.apply(itemKey); + this.subSettingsBuilder = setting.getSubSettingsBuilder(); + + subSettings.put(key, new String[]{setting.getName()}); + + if (!openSubSettingsMenu(player)) { + parent.accept(player, type, subSettings); + } + + } + + private boolean openSubSettingsMenu(Player player) { + + if (subSettingsBuilder != null && subSettingsBuilder.hasSettings()) { + subSettingsBuilder.open(player, this, title); + subSettingsBuilder = subSettingsBuilder.getChild(); + + return true; + } + return false; + } + + @Override + public void onBackToMenuItemClick(Player player) { + parent.decline(player); + } + + @Override + public void decline(Player player) { + if (setting != null) + this.subSettings = MapUtils.createStringArrayMap(key, setting.getName()); + open(player, 0); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java index d0465a925..0e5abe92e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java @@ -37,272 +37,272 @@ @ToString public class InfoMenuGenerator extends MenuGenerator implements IParentCustomGenerator { - public static final int DELETE_SLOT = 19 + 9, SAVE_SLOT = 25 + 9, CONDITION_SLOT = 21 + 9, ACTION_SLOT = 23 + 9, MATERIAL_SLOT = 14, NAME_SLOT = 12; - - private static final Material[] defaultMaterials; - private static final boolean savePlayerChallenges; - - static { - savePlayerChallenges = Challenges.getInstance().getConfigDocument().getBoolean("save-player_challenges"); - ArrayList list = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - list.removeIf(material1 -> !material1.isItem()); - defaultMaterials = list.toArray(new Material[0]); - } - - private final UUID uuid; - private String name; - private Material material; - private ChallengeTrigger trigger; - private Map subTriggers; - private ChallengeAction action; - private Map subActions; - private Inventory inventory; - - public InfoMenuGenerator(CustomChallenge customChallenge) { - this.uuid = customChallenge.getUniqueId(); - this.material = customChallenge.getMaterial(); - this.name = customChallenge.getDisplayName(); - this.trigger = customChallenge.getTrigger(); - this.subTriggers = customChallenge.getSubTriggers(); - this.action = customChallenge.getAction(); - this.subActions = customChallenge.getSubActions(); - } - - /** - * Default Settings for new Custom Challenges - */ - public InfoMenuGenerator() { - this.trigger = null; - this.action = null; - this.subTriggers = new HashMap<>(); - this.subActions = new HashMap<>(); - this.uuid = UUID.randomUUID(); - this.material = IRandom.threadLocal().choose(defaultMaterials); - this.name = "§7Custom §e#" + - (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() + 1); - } - - public static List getSubSettingsDisplay(SubSettingsBuilder builder, Map activated) { - List display = new LinkedList<>(); - for (SubSettingsBuilder child : builder.getAllChildren()) { - display.addAll(child.getDisplay(activated)); - } - return display; - } - - @Override - public void generateInventories() { - inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(MenuType.CUSTOM, "Info")); - InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); - - updateItems(); - - InventoryUtils.setNavigationItems(inventory, new int[]{36 + 9}, true, InventorySetter.INVENTORY, 0, 1); - } - - public void updateItems() { - String currently = Message.forName("custom-info-currently").asString(); - String none = Message.forName("none").asString(); - - // Save / Delete Item - inventory.setItem(DELETE_SLOT, new ItemBuilder(Material.BARRIER, Message.forName("item-custom-info-delete")).build()); - inventory.setItem(SAVE_SLOT, new ItemBuilder(Material.LIME_DYE, Message.forName("item-custom-info-save")).build()); - - // Trigger Item - ItemBuilder triggerItem = new ItemBuilder(Material.WITHER_SKELETON_SKULL, - Message.forName("item-custom-info-trigger")) - .appendLore( - currently + (trigger != null ? Message.forName(trigger.getMessage()) : none)); - if (trigger != null) { - triggerItem.appendLore(getSubSettingsDisplay(trigger.getSubSettingsBuilder(), subTriggers)); - } - inventory.setItem(CONDITION_SLOT, triggerItem.build()); - - // Action Item - ItemBuilder actionItem = new ItemBuilder(Material.NETHER_STAR, - Message.forName("item-custom-info-action")) - .appendLore(currently + (action != null ? Message.forName(action.getMessage()) : none)); - if (action != null) { - actionItem.appendLore(getSubSettingsDisplay(action.getSubSettingsBuilder(), subActions)); - } - inventory.setItem(ACTION_SLOT, actionItem.build()); - - // Display Item - inventory.setItem(MATERIAL_SLOT, new ItemBuilder(material == null ? Material.BARRIER : material, Message.forName("item-custom-info-material")) - .appendLore(currently + (material != null ? BukkitStringUtils.getItemName(material).toPlainText() : none)).build()); - - // Name Item - inventory.setItem(NAME_SLOT, new ItemBuilder(Material.NAME_TAG, Message.forName("item-custom-info-name")) - .appendLore(currently + "§7" + name).build()); - } - - @Override - public List getInventories() { - return Collections.singletonList(inventory); - } - - @Override - public MenuPosition getMenuPosition(int page) { - return new InfoMenuPosition(page, this); - } - - @Override - public void open(@Nonnull Player player, int page) { - if (inventory == null) generateInventories(); - super.open(player, page); - } - - @Override - public void accept(Player player, SettingType type, Map data) { - open(player, 0); - - switch (type) { - case CONDITION: - trigger = Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(data.remove("trigger")[0]); - this.subTriggers = data; - break; - - case ACTION: - action = Challenges.getInstance().getCustomSettingsLoader().getActionByName(data.remove("action")[0]); - this.subActions = data; - break; - - case MATERIAL: - material = Material.valueOf(data.remove("material")[0]); - updateItems(); - break; - } - - updateItems(); - } - - public void setName(String name) { - this.name = name; - updateItems(); - } - - @Override - public void decline(Player player) { - open(player, 0); - } - - public CustomChallenge save() { - return Challenges.getInstance().getCustomChallengesLoader().registerCustomChallenge(uuid, material, name, - trigger, subTriggers, action, subActions, true); - } - - public void openChallengeMenu(Player player) { - CustomChallenge challenge = Challenges.getInstance().getCustomChallengesLoader() - .getCustomChallenges().get(uuid); - if (challenge == null) { - Challenges.getInstance().getMenuManager().openMenu(player, MenuType.CUSTOM, 0); - } else { - ChallengeMenuGenerator menuGenerator = (ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator(); - int page = menuGenerator.getPageOfChallenge(challenge) + 1; // +1 because the main and challenge menu are in the same generator - Challenges.getInstance().getMenuManager().openMenu(player, MenuType.CUSTOM, page); - } - } - - public class InfoMenuPosition implements MenuPosition { - - private final int page; - @Getter + public static final int DELETE_SLOT = 19 + 9, SAVE_SLOT = 25 + 9, CONDITION_SLOT = 21 + 9, ACTION_SLOT = 23 + 9, MATERIAL_SLOT = 14, NAME_SLOT = 12; + + private static final Material[] defaultMaterials; + private static final boolean savePlayerChallenges; + + static { + savePlayerChallenges = Challenges.getInstance().getConfigDocument().getBoolean("save-player_challenges"); + ArrayList list = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); + list.removeIf(material1 -> !material1.isItem()); + defaultMaterials = list.toArray(new Material[0]); + } + + private final UUID uuid; + private String name; + private Material material; + private ChallengeTrigger trigger; + private Map subTriggers; + private ChallengeAction action; + private Map subActions; + private Inventory inventory; + + public InfoMenuGenerator(CustomChallenge customChallenge) { + this.uuid = customChallenge.getUniqueId(); + this.material = customChallenge.getMaterial(); + this.name = customChallenge.getDisplayName(); + this.trigger = customChallenge.getTrigger(); + this.subTriggers = customChallenge.getSubTriggers(); + this.action = customChallenge.getAction(); + this.subActions = customChallenge.getSubActions(); + } + + /** + * Default Settings for new Custom Challenges + */ + public InfoMenuGenerator() { + this.trigger = null; + this.action = null; + this.subTriggers = new HashMap<>(); + this.subActions = new HashMap<>(); + this.uuid = UUID.randomUUID(); + this.material = IRandom.threadLocal().choose(defaultMaterials); + this.name = "§7Custom §e#" + + (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() + 1); + } + + public static List getSubSettingsDisplay(SubSettingsBuilder builder, Map activated) { + List display = new LinkedList<>(); + for (SubSettingsBuilder child : builder.getAllChildren()) { + display.addAll(child.getDisplay(activated)); + } + return display; + } + + @Override + public void generateInventories() { + inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(MenuType.CUSTOM, "Info")); + InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); + + updateItems(); + + InventoryUtils.setNavigationItems(inventory, new int[]{36 + 9}, true, InventorySetter.INVENTORY, 0, 1); + } + + public void updateItems() { + String currently = Message.forName("custom-info-currently").asString(); + String none = Message.forName("none").asString(); + + // Save / Delete Item + inventory.setItem(DELETE_SLOT, new ItemBuilder(Material.BARRIER, Message.forName("item-custom-info-delete")).build()); + inventory.setItem(SAVE_SLOT, new ItemBuilder(Material.LIME_DYE, Message.forName("item-custom-info-save")).build()); + + // Trigger Item + ItemBuilder triggerItem = new ItemBuilder(Material.WITHER_SKELETON_SKULL, + Message.forName("item-custom-info-trigger")) + .appendLore( + currently + (trigger != null ? Message.forName(trigger.getMessage()) : none)); + if (trigger != null) { + triggerItem.appendLore(getSubSettingsDisplay(trigger.getSubSettingsBuilder(), subTriggers)); + } + inventory.setItem(CONDITION_SLOT, triggerItem.build()); + + // Action Item + ItemBuilder actionItem = new ItemBuilder(Material.NETHER_STAR, + Message.forName("item-custom-info-action")) + .appendLore(currently + (action != null ? Message.forName(action.getMessage()) : none)); + if (action != null) { + actionItem.appendLore(getSubSettingsDisplay(action.getSubSettingsBuilder(), subActions)); + } + inventory.setItem(ACTION_SLOT, actionItem.build()); + + // Display Item + inventory.setItem(MATERIAL_SLOT, new ItemBuilder(material == null ? Material.BARRIER : material, Message.forName("item-custom-info-material")) + .appendLore(currently + (material != null ? BukkitStringUtils.getItemName(material).toPlainText() : none)).build()); + + // Name Item + inventory.setItem(NAME_SLOT, new ItemBuilder(Material.NAME_TAG, Message.forName("item-custom-info-name")) + .appendLore(currently + "§7" + name).build()); + } + + @Override + public List getInventories() { + return Collections.singletonList(inventory); + } + + @Override + public MenuPosition getMenuPosition(int page) { + return new InfoMenuPosition(page, this); + } + + @Override + public void open(@Nonnull Player player, int page) { + if (inventory == null) generateInventories(); + super.open(player, page); + } + + @Override + public void accept(Player player, SettingType type, Map data) { + open(player, 0); + + switch (type) { + case CONDITION: + trigger = Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(data.remove("trigger")[0]); + this.subTriggers = data; + break; + + case ACTION: + action = Challenges.getInstance().getCustomSettingsLoader().getActionByName(data.remove("action")[0]); + this.subActions = data; + break; + + case MATERIAL: + material = Material.valueOf(data.remove("material")[0]); + updateItems(); + break; + } + + updateItems(); + } + + public void setName(String name) { + this.name = name; + updateItems(); + } + + @Override + public void decline(Player player) { + open(player, 0); + } + + public CustomChallenge save() { + return Challenges.getInstance().getCustomChallengesLoader().registerCustomChallenge(uuid, material, name, + trigger, subTriggers, action, subActions, true); + } + + public void openChallengeMenu(Player player) { + CustomChallenge challenge = Challenges.getInstance().getCustomChallengesLoader() + .getCustomChallenges().get(uuid); + if (challenge == null) { + Challenges.getInstance().getMenuManager().openMenu(player, MenuType.CUSTOM, 0); + } else { + ChallengeMenuGenerator menuGenerator = (ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator(); + int page = menuGenerator.getPageOfChallenge(challenge) + 1; // +1 because the main and challenge menu are in the same generator + Challenges.getInstance().getMenuManager().openMenu(player, MenuType.CUSTOM, page); + } + } + + public class InfoMenuPosition implements MenuPosition { + + private final int page; + @Getter private final InfoMenuGenerator generator; - public InfoMenuPosition(int page, InfoMenuGenerator generator) { - this.page = page; - this.generator = generator; - } - - @Override - public void handleClick(@Nonnull MenuClickInfo info) { - if (InventoryUtils.handleNavigationClicking(generator, new int[]{36 + 9}, page, info, () -> Challenges.getInstance().getMenuManager().openMenu(info.getPlayer(), MenuType.CUSTOM, 0))) { - return; - } - - if (ChallengeMenuGenerator.playNoPermissionsEffect(info.getPlayer())) { - info.getPlayer().closeInventory(); - return; - } - - Player player = info.getPlayer(); - - switch (info.getSlot()) { - case DELETE_SLOT: - if (!Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().containsKey(uuid)) { - Message.forName("custom-not-deleted").send(player, Prefix.CUSTOM); - SoundSample.BASS_OFF.play(player); - break; - } - openChallengeMenu(player); - Challenges.getInstance().getCustomChallengesLoader().unregisterCustomChallenge(uuid); - new SoundSample().addSound(Sound.ENTITY_WITHER_BREAK_BLOCK, 0.4f).play(player); - break; - case SAVE_SLOT: - - String defaults = new InfoMenuGenerator().toString(); - String current = InfoMenuGenerator.this.toString(); - if (defaults.equals(current)) { - Message.forName("custom-no-changes").send(player, Prefix.CUSTOM); - SoundSample.BASS_OFF.play(player); - return; - } - - save(); - openChallengeMenu(player); - Message.forName("custom-saved").send(player, Prefix.CUSTOM); - if (savePlayerChallenges) { - Message.forName("custom-saved-db").send(player, Prefix.CUSTOM); - } - SoundSample.LEVEL_UP.play(player); - break; - case CONDITION_SLOT: - new CustomMainSettingsMenuGenerator(generator, SettingType.CONDITION, - "trigger", Message.forName("custom-title-trigger").asString(), - ChallengeTrigger.getMenuItems(), - s -> Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(s)) - .open(player, 0); - SoundSample.CLICK.play(player); - break; - case ACTION_SLOT: - new CustomMainSettingsMenuGenerator(generator, SettingType.ACTION, - "action", Message.forName("custom-title-action").asString(), - ChallengeAction.getMenuItems(), - s -> Challenges.getInstance().getCustomSettingsLoader().getActionByName(s)) - .open(player, 0); - SoundSample.CLICK.play(player); - break; - case NAME_SLOT: - - Message.forName("custom-name-info").send(player, Prefix.CUSTOM); - player.closeInventory(); - - ChatInputListener.setInputAction(player, event -> { - int maxNameLength = Challenges.getInstance().getCustomChallengesLoader() - .getMaxNameLength(); - if (event.getMessage().length() > maxNameLength) { - Message.forName("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxNameLength); - return; - } - - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - setName(ChatColor.translateAlternateColorCodes('&', event.getMessage())); - open(event.getPlayer(), 0); - }); - - }); - - break; - case MATERIAL_SLOT: - MaterialMenuGenerator materialMenuGenerator = new MaterialMenuGenerator(generator); - materialMenuGenerator.open(player, 0); - SoundSample.CLICK.play(player); - break; - default: - SoundSample.CLICK.play(player); - break; + public InfoMenuPosition(int page, InfoMenuGenerator generator) { + this.page = page; + this.generator = generator; + } + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + if (InventoryUtils.handleNavigationClicking(generator, new int[]{36 + 9}, page, info, () -> Challenges.getInstance().getMenuManager().openMenu(info.getPlayer(), MenuType.CUSTOM, 0))) { + return; + } + + if (ChallengeMenuGenerator.playNoPermissionsEffect(info.getPlayer())) { + info.getPlayer().closeInventory(); + return; + } + + Player player = info.getPlayer(); + + switch (info.getSlot()) { + case DELETE_SLOT: + if (!Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().containsKey(uuid)) { + Message.forName("custom-not-deleted").send(player, Prefix.CUSTOM); + SoundSample.BASS_OFF.play(player); + break; + } + openChallengeMenu(player); + Challenges.getInstance().getCustomChallengesLoader().unregisterCustomChallenge(uuid); + new SoundSample().addSound(Sound.ENTITY_WITHER_BREAK_BLOCK, 0.4f).play(player); + break; + case SAVE_SLOT: + + String defaults = new InfoMenuGenerator().toString(); + String current = InfoMenuGenerator.this.toString(); + if (defaults.equals(current)) { + Message.forName("custom-no-changes").send(player, Prefix.CUSTOM); + SoundSample.BASS_OFF.play(player); + return; + } + + save(); + openChallengeMenu(player); + Message.forName("custom-saved").send(player, Prefix.CUSTOM); + if (savePlayerChallenges) { + Message.forName("custom-saved-db").send(player, Prefix.CUSTOM); + } + SoundSample.LEVEL_UP.play(player); + break; + case CONDITION_SLOT: + new CustomMainSettingsMenuGenerator(generator, SettingType.CONDITION, + "trigger", Message.forName("custom-title-trigger").asString(), + ChallengeTrigger.getMenuItems(), + s -> Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(s)) + .open(player, 0); + SoundSample.CLICK.play(player); + break; + case ACTION_SLOT: + new CustomMainSettingsMenuGenerator(generator, SettingType.ACTION, + "action", Message.forName("custom-title-action").asString(), + ChallengeAction.getMenuItems(), + s -> Challenges.getInstance().getCustomSettingsLoader().getActionByName(s)) + .open(player, 0); + SoundSample.CLICK.play(player); + break; + case NAME_SLOT: + + Message.forName("custom-name-info").send(player, Prefix.CUSTOM); + player.closeInventory(); + + ChatInputListener.setInputAction(player, event -> { + int maxNameLength = Challenges.getInstance().getCustomChallengesLoader() + .getMaxNameLength(); + if (event.getMessage().length() > maxNameLength) { + Message.forName("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxNameLength); + return; } - } + + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + setName(ChatColor.translateAlternateColorCodes('&', event.getMessage())); + open(event.getPlayer(), 0); + }); + + }); + + break; + case MATERIAL_SLOT: + MaterialMenuGenerator materialMenuGenerator = new MaterialMenuGenerator(generator); + materialMenuGenerator.open(player, 0); + SoundSample.CLICK.play(player); + break; + default: + SoundSample.CLICK.play(player); + break; + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java index 4c7da170a..3286ecd78 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java @@ -19,91 +19,91 @@ public class MainCustomMenuGenerator extends ChallengeMenuGenerator { - public static final int[] SLOTS = {10, 11, 12, 13, 14, 15, 16}; - public static final int[] NAVIGATION_SLOTS = {36, 44}; - public static final int SIZE = 5 * 9; - private static final int VIEW_SLOT = 21; - private static final int CREATE_SLOT = 23; - - private static final int maxCustomChallenges; - - static { - maxCustomChallenges = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-challenges"); - } - - public MainCustomMenuGenerator() { - super(1); - } - - @Override - protected String getTitle(int page) { - return page != 0 ? InventoryTitleManager.getTitle(getMenuType(), - Message.forName("custom-title-view").asString(), String.valueOf(page)) : - InventoryTitleManager.getTitle(getMenuType(), "Menu"); - } - - @Override - public void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClickInfo info, int itemIndex) { - if (itemIndex == 0 || itemIndex == 2) { - challenge.handleClick(new ChallengeMenuClickInfo(info, itemIndex == 0)); - } else if (challenge instanceof CustomChallenge) { - InfoMenuGenerator infoMenuGenerator = new InfoMenuGenerator((CustomChallenge) challenge); - infoMenuGenerator.open(info.getPlayer(), 0); - SoundSample.CLICK.play(info.getPlayer()); - } - } - - @Override - public void generatePage(@Nonnull Inventory inventory, int page) { - if (page == 0) { - inventory.setItem(VIEW_SLOT, new ItemBuilder(Material.BOOK, Message.forName("custom-main-view-challenges")).build()); - inventory.setItem(CREATE_SLOT, new ItemBuilder(Material.WRITABLE_BOOK, Message.forName("custom-main-create-challenge")).build()); - } - } - - @Override - public void onPreChallengePageClicking(@Nonnull MenuClickInfo info, int page) { - if (info.getSlot() == VIEW_SLOT) { - if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().isEmpty()) { - Message.forName("custom-not-loaded").send(info.getPlayer(), Prefix.CUSTOM); - return; - } - open(info.getPlayer(), 1); - SoundSample.PLOP.play(info.getPlayer()); - } else if (info.getSlot() == CREATE_SLOT) { - if (ChallengeMenuGenerator.playNoPermissionsEffect(info.getPlayer())) { - return; - } - if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() > maxCustomChallenges) { - Message.forName("custom-limit").send(info.getPlayer(), Prefix.CUSTOM, maxCustomChallenges); - SoundSample.BASS_OFF.play(info.getPlayer()); - return; - } - new InfoMenuGenerator().open(info.getPlayer(), 0); - SoundSample.PLING.play(info.getPlayer()); - } - } - - @Override - public void setSettingsItems(@Nonnull Inventory inventory, @Nonnull IChallenge challenge, int topSlot) { - inventory.setItem(getSlots()[topSlot], getDisplayItemBuilder(challenge).build()); - inventory.setItem(getSlots()[topSlot] + 9, DefaultItem.customize().build()); - inventory.setItem(getSlots()[topSlot] + 18, getSettingsItem(challenge)); - } - - @Override - public int[] getSlots() { - return SLOTS; - } - - @Override - public int getSize() { - return SIZE; - } - - @Override - public int[] getNavigationSlots(int page) { - return page == 0 ? new int[]{NAVIGATION_SLOTS[0]} : NAVIGATION_SLOTS; - } + public static final int[] SLOTS = {10, 11, 12, 13, 14, 15, 16}; + public static final int[] NAVIGATION_SLOTS = {36, 44}; + public static final int SIZE = 5 * 9; + private static final int VIEW_SLOT = 21; + private static final int CREATE_SLOT = 23; + + private static final int maxCustomChallenges; + + static { + maxCustomChallenges = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-challenges"); + } + + public MainCustomMenuGenerator() { + super(1); + } + + @Override + protected String getTitle(int page) { + return page != 0 ? InventoryTitleManager.getTitle(getMenuType(), + Message.forName("custom-title-view").asString(), String.valueOf(page)) : + InventoryTitleManager.getTitle(getMenuType(), "Menu"); + } + + @Override + public void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClickInfo info, int itemIndex) { + if (itemIndex == 0 || itemIndex == 2) { + challenge.handleClick(new ChallengeMenuClickInfo(info, itemIndex == 0)); + } else if (challenge instanceof CustomChallenge) { + InfoMenuGenerator infoMenuGenerator = new InfoMenuGenerator((CustomChallenge) challenge); + infoMenuGenerator.open(info.getPlayer(), 0); + SoundSample.CLICK.play(info.getPlayer()); + } + } + + @Override + public void generatePage(@Nonnull Inventory inventory, int page) { + if (page == 0) { + inventory.setItem(VIEW_SLOT, new ItemBuilder(Material.BOOK, Message.forName("custom-main-view-challenges")).build()); + inventory.setItem(CREATE_SLOT, new ItemBuilder(Material.WRITABLE_BOOK, Message.forName("custom-main-create-challenge")).build()); + } + } + + @Override + public void onPreChallengePageClicking(@Nonnull MenuClickInfo info, int page) { + if (info.getSlot() == VIEW_SLOT) { + if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().isEmpty()) { + Message.forName("custom-not-loaded").send(info.getPlayer(), Prefix.CUSTOM); + return; + } + open(info.getPlayer(), 1); + SoundSample.PLOP.play(info.getPlayer()); + } else if (info.getSlot() == CREATE_SLOT) { + if (ChallengeMenuGenerator.playNoPermissionsEffect(info.getPlayer())) { + return; + } + if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() > maxCustomChallenges) { + Message.forName("custom-limit").send(info.getPlayer(), Prefix.CUSTOM, maxCustomChallenges); + SoundSample.BASS_OFF.play(info.getPlayer()); + return; + } + new InfoMenuGenerator().open(info.getPlayer(), 0); + SoundSample.PLING.play(info.getPlayer()); + } + } + + @Override + public void setSettingsItems(@Nonnull Inventory inventory, @Nonnull IChallenge challenge, int topSlot) { + inventory.setItem(getSlots()[topSlot], getDisplayItemBuilder(challenge).build()); + inventory.setItem(getSlots()[topSlot] + 9, DefaultItem.customize().build()); + inventory.setItem(getSlots()[topSlot] + 18, getSettingsItem(challenge)); + } + + @Override + public int[] getSlots() { + return SLOTS; + } + + @Override + public int getSize() { + return SIZE; + } + + @Override + public int[] getNavigationSlots(int page) { + return page == 0 ? new int[]{NAVIGATION_SLOTS[0]} : NAVIGATION_SLOTS; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java index ea7d84c44..1e7c300c7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java @@ -10,34 +10,34 @@ public class SubSettingValueMenuGenerator extends ValueMenuGenerator { - private final IParentCustomGenerator parent; - private final String title; - - public SubSettingValueMenuGenerator(IParentCustomGenerator parent, Map settings, String title) { - super(settings); - this.title = title; - this.parent = parent; - } - - @Override - public String[] getSubTitles(int page) { - return new String[]{title}; - } - - @Override - public void onSaveItemClick(Player player) { - - Map map = new HashMap<>(); - for (Entry entry : getSettings().entrySet()) { - map.put(entry.getKey().getKey(), new String[]{entry.getValue()}); - } - - parent.accept(player, null, map); - } - - @Override - public void onBackToMenuItemClick(Player player) { - parent.decline(player); - } + private final IParentCustomGenerator parent; + private final String title; + + public SubSettingValueMenuGenerator(IParentCustomGenerator parent, Map settings, String title) { + super(settings); + this.title = title; + this.parent = parent; + } + + @Override + public String[] getSubTitles(int page) { + return new String[]{title}; + } + + @Override + public void onSaveItemClick(Player player) { + + Map map = new HashMap<>(); + for (Entry entry : getSettings().entrySet()) { + map.put(entry.getKey().getKey(), new String[]{entry.getValue()}); + } + + parent.accept(player, null, map); + } + + @Override + public void onBackToMenuItemClick(Player player) { + parent.decline(player); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java index 5f0484895..793f86dc9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java @@ -5,10 +5,10 @@ @Getter public abstract class AbstractTaskConfig { - protected final boolean async; + protected final boolean async; - public AbstractTaskConfig(boolean async) { - this.async = async; - } + public AbstractTaskConfig(boolean async) { + this.async = async; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java index de7305d1d..cac8bf196 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java @@ -13,109 +13,109 @@ public final class ScheduleManager { - private final Map scheduledTaskExecutorsByConfig = new ConcurrentHashMap<>(); - private final Map timerTaskExecutorsByConfig = new ConcurrentHashMap<>(); - private boolean started = false; - - public void register(@Nonnull Object... schedulers) { - for (Object scheduler : schedulers) { - register(scheduler); - } - } - - public void register(@Nonnull Object scheduler) { - for (Method method : ReflectionUtils.getMethodsAnnotatedWith(scheduler.getClass(), ScheduledTask.class)) { - if (method.getParameterCount() != 0) { - Logger.warn("Could not register scheduler " + method); - continue; - } - - ScheduledTask annotation = method.getAnnotation(ScheduledTask.class); - ScheduledFunction function = new ScheduledFunction(scheduler, method, new PoliciesContainer(annotation)); - - Logger.debug("Registered scheduled task {}", function); - register(function, new ScheduledTaskConfig(annotation)); - } - for (Method method : ReflectionUtils.getMethodsAnnotatedWith(scheduler.getClass(), TimerTask.class)) { - if (method.getParameterCount() != 0) { - Logger.warn("Could not register scheduler {}", method); - continue; - } - - TimerTask annotation = method.getAnnotation(TimerTask.class); - ScheduledFunction function = new ScheduledFunction(scheduler, method, new PoliciesContainer(annotation)); - - Logger.debug("Registered timer task {}", function); - register(function, new TimerTaskConfig(annotation)); - } - } - - public void unregister(@Nonnull Object object) { - for (ScheduledTaskExecutor scheduler : scheduledTaskExecutorsByConfig.values()) { - scheduler.unregister(object); - } - } - - private void register(@Nonnull ScheduledFunction function, @Nonnull AbstractTaskConfig config) { - if (config instanceof ScheduledTaskConfig) { - ScheduledTaskConfig taskConfig = (ScheduledTaskConfig) config; - if (taskConfig.getRate() < 1) { - Logger.warn("Schedule rate cannot be less than 1; Could not register {}", function); - return; - } - - ScheduledTaskExecutor executor = getOrCreateScheduledTaskExecutor(taskConfig); - executor.register(function); - } - if (config instanceof TimerTaskConfig) { - TimerTaskConfig taskConfig = (TimerTaskConfig) config; - - TimerTaskExecutor executor = getOrCreateTimerTaskExecutor(taskConfig); - executor.register(function); - } - } - - @Nonnull - private ScheduledTaskExecutor getOrCreateScheduledTaskExecutor(@Nonnull ScheduledTaskConfig config) { - ScheduledTaskExecutor executor = scheduledTaskExecutorsByConfig.get(config); - if (executor != null) return executor; - - // Create a new task - executor = new ScheduledTaskExecutor(config); - if (started) executor.start(); - scheduledTaskExecutorsByConfig.put(config, executor); - return executor; - } - - @Nonnull - private TimerTaskExecutor getOrCreateTimerTaskExecutor(@Nonnull TimerTaskConfig config) { - TimerTaskExecutor executor = timerTaskExecutorsByConfig.get(config); - if (executor != null) return executor; - - // Create a new task - executor = new TimerTaskExecutor(config); - timerTaskExecutorsByConfig.put(config, executor); - return executor; - } - - public void fireTimerStatusChange() { - if (!started) return; - for (TimerTaskExecutor executor : timerTaskExecutorsByConfig.values()) { - if (!executor.getConfig().acceptsStatus(ChallengeAPI.getTimerStatus())) continue; - executor.execute(); - } - } - - public void stop() { - started = false; - scheduledTaskExecutorsByConfig.values().forEach(ScheduledTaskExecutor::stop); - scheduledTaskExecutorsByConfig.clear(); - timerTaskExecutorsByConfig.clear(); - } - - public void start() { - started = true; - scheduledTaskExecutorsByConfig.values().forEach(ScheduledTaskExecutor::start); - } + private final Map scheduledTaskExecutorsByConfig = new ConcurrentHashMap<>(); + private final Map timerTaskExecutorsByConfig = new ConcurrentHashMap<>(); + private boolean started = false; + + public void register(@Nonnull Object... schedulers) { + for (Object scheduler : schedulers) { + register(scheduler); + } + } + + public void register(@Nonnull Object scheduler) { + for (Method method : ReflectionUtils.getMethodsAnnotatedWith(scheduler.getClass(), ScheduledTask.class)) { + if (method.getParameterCount() != 0) { + Logger.warn("Could not register scheduler " + method); + continue; + } + + ScheduledTask annotation = method.getAnnotation(ScheduledTask.class); + ScheduledFunction function = new ScheduledFunction(scheduler, method, new PoliciesContainer(annotation)); + + Logger.debug("Registered scheduled task {}", function); + register(function, new ScheduledTaskConfig(annotation)); + } + for (Method method : ReflectionUtils.getMethodsAnnotatedWith(scheduler.getClass(), TimerTask.class)) { + if (method.getParameterCount() != 0) { + Logger.warn("Could not register scheduler {}", method); + continue; + } + + TimerTask annotation = method.getAnnotation(TimerTask.class); + ScheduledFunction function = new ScheduledFunction(scheduler, method, new PoliciesContainer(annotation)); + + Logger.debug("Registered timer task {}", function); + register(function, new TimerTaskConfig(annotation)); + } + } + + public void unregister(@Nonnull Object object) { + for (ScheduledTaskExecutor scheduler : scheduledTaskExecutorsByConfig.values()) { + scheduler.unregister(object); + } + } + + private void register(@Nonnull ScheduledFunction function, @Nonnull AbstractTaskConfig config) { + if (config instanceof ScheduledTaskConfig) { + ScheduledTaskConfig taskConfig = (ScheduledTaskConfig) config; + if (taskConfig.getRate() < 1) { + Logger.warn("Schedule rate cannot be less than 1; Could not register {}", function); + return; + } + + ScheduledTaskExecutor executor = getOrCreateScheduledTaskExecutor(taskConfig); + executor.register(function); + } + if (config instanceof TimerTaskConfig) { + TimerTaskConfig taskConfig = (TimerTaskConfig) config; + + TimerTaskExecutor executor = getOrCreateTimerTaskExecutor(taskConfig); + executor.register(function); + } + } + + @Nonnull + private ScheduledTaskExecutor getOrCreateScheduledTaskExecutor(@Nonnull ScheduledTaskConfig config) { + ScheduledTaskExecutor executor = scheduledTaskExecutorsByConfig.get(config); + if (executor != null) return executor; + + // Create a new task + executor = new ScheduledTaskExecutor(config); + if (started) executor.start(); + scheduledTaskExecutorsByConfig.put(config, executor); + return executor; + } + + @Nonnull + private TimerTaskExecutor getOrCreateTimerTaskExecutor(@Nonnull TimerTaskConfig config) { + TimerTaskExecutor executor = timerTaskExecutorsByConfig.get(config); + if (executor != null) return executor; + + // Create a new task + executor = new TimerTaskExecutor(config); + timerTaskExecutorsByConfig.put(config, executor); + return executor; + } + + public void fireTimerStatusChange() { + if (!started) return; + for (TimerTaskExecutor executor : timerTaskExecutorsByConfig.values()) { + if (!executor.getConfig().acceptsStatus(ChallengeAPI.getTimerStatus())) continue; + executor.execute(); + } + } + + public void stop() { + started = false; + scheduledTaskExecutorsByConfig.values().forEach(ScheduledTaskExecutor::stop); + scheduledTaskExecutorsByConfig.clear(); + timerTaskExecutorsByConfig.clear(); + } + + public void start() { + started = true; + scheduledTaskExecutorsByConfig.values().forEach(ScheduledTaskExecutor::start); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java index 5881e556c..ac7d2f019 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java @@ -1,45 +1,46 @@ package net.codingarea.challenges.plugin.management.scheduler; +import lombok.EqualsAndHashCode; + +import javax.annotation.Nonnull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import javax.annotation.Nonnull; -import lombok.EqualsAndHashCode; @EqualsAndHashCode public final class ScheduledFunction { - private final Method method; - private final Object holder; - private final PoliciesContainer policies; - - ScheduledFunction(@Nonnull Object holder, @Nonnull Method method, @Nonnull PoliciesContainer policies) { - this.method = method; - this.holder = holder; - this.policies = policies; - } - - public void invoke() throws InvocationTargetException, IllegalAccessException { - if (shouldInvoke()) - invokeAnyway(); - } - - public void invokeAnyway() throws InvocationTargetException, IllegalAccessException { - method.setAccessible(true); - method.invoke(holder); - } - - private boolean shouldInvoke() { - return policies.allPoliciesAreTrue(holder); - } - - @Nonnull - public Object getHolder() { - return holder; - } - - @Override - public String toString() { - return holder.getClass().getName() + "." + method.getName() + "()"; - } + private final Method method; + private final Object holder; + private final PoliciesContainer policies; + + ScheduledFunction(@Nonnull Object holder, @Nonnull Method method, @Nonnull PoliciesContainer policies) { + this.method = method; + this.holder = holder; + this.policies = policies; + } + + public void invoke() throws InvocationTargetException, IllegalAccessException { + if (shouldInvoke()) + invokeAnyway(); + } + + public void invokeAnyway() throws InvocationTargetException, IllegalAccessException { + method.setAccessible(true); + method.invoke(holder); + } + + private boolean shouldInvoke() { + return policies.allPoliciesAreTrue(holder); + } + + @Nonnull + public Object getHolder() { + return holder; + } + + @Override + public String toString() { + return holder.getClass().getName() + "." + method.getName() + "()"; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java index 97d295ddb..763b1e8b3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java @@ -9,31 +9,31 @@ final class ScheduledTaskExecutor extends AbstractTaskExecutor { - private final ScheduledTaskConfig config; - private BukkitTask task; - - ScheduledTaskExecutor(@Nonnull ScheduledTaskConfig config) { - this.config = config; - } - - public void stop() { - if (task != null && !task.isCancelled()) { - task.cancel(); - task = null; - } - } - - public void start() { - BukkitScheduler scheduler = Bukkit.getScheduler(); - Challenges plugin = Challenges.getInstance(); - task = config.isAsync() ? scheduler.runTaskTimerAsynchronously(plugin, this, 0, config.getRate()) : - scheduler.runTaskTimer(plugin, this, 0, config.getRate()); - } - - @Nonnull - @Override - public ScheduledTaskConfig getConfig() { - return config; - } + private final ScheduledTaskConfig config; + private BukkitTask task; + + ScheduledTaskExecutor(@Nonnull ScheduledTaskConfig config) { + this.config = config; + } + + public void stop() { + if (task != null && !task.isCancelled()) { + task.cancel(); + task = null; + } + } + + public void start() { + BukkitScheduler scheduler = Bukkit.getScheduler(); + Challenges plugin = Challenges.getInstance(); + task = config.isAsync() ? scheduler.runTaskTimerAsynchronously(plugin, this, 0, config.getRate()) : + scheduler.runTaskTimer(plugin, this, 0, config.getRate()); + } + + @Nonnull + @Override + public ScheduledTaskConfig getConfig() { + return config; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java index 7460bd972..dd70940d6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java @@ -8,24 +8,24 @@ public final class TimerTaskConfig extends AbstractTaskConfig { - private final TimerStatus[] status; + private final TimerStatus[] status; - TimerTaskConfig(@Nonnull TimerTask annotation) { - this(annotation.status(), annotation.async()); - } + TimerTaskConfig(@Nonnull TimerTask annotation) { + this(annotation.status(), annotation.async()); + } - TimerTaskConfig(@Nonnull TimerStatus[] status, boolean async) { - super(async); - this.status = status; - } + TimerTaskConfig(@Nonnull TimerStatus[] status, boolean async) { + super(async); + this.status = status; + } - @Nonnull - public TimerStatus[] getStatus() { - return status; - } + @Nonnull + public TimerStatus[] getStatus() { + return status; + } - public boolean acceptsStatus(@Nonnull TimerStatus status) { - return Arrays.asList(this.status).contains(status); - } + public boolean acceptsStatus(@Nonnull TimerStatus status) { + return Arrays.asList(this.status).contains(status); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java index 854d8b41d..526198307 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java @@ -7,24 +7,24 @@ final class TimerTaskExecutor extends AbstractTaskExecutor { - private final TimerTaskConfig config; - - TimerTaskExecutor(@Nonnull TimerTaskConfig config) { - this.config = config; - } - - public void execute() { - if (config.isAsync()) - Bukkit.getScheduler().runTaskAsynchronously(Challenges.getInstance(), this); - else if (!Bukkit.isPrimaryThread()) - Bukkit.getScheduler().runTask(Challenges.getInstance(), this); - else this.run(); - } - - @Nonnull - @Override - public TimerTaskConfig getConfig() { - return config; - } + private final TimerTaskConfig config; + + TimerTaskExecutor(@Nonnull TimerTaskConfig config) { + this.config = config; + } + + public void execute() { + if (config.isAsync()) + Bukkit.getScheduler().runTaskAsynchronously(Challenges.getInstance(), this); + else if (!Bukkit.isPrimaryThread()) + Bukkit.getScheduler().runTask(Challenges.getInstance(), this); + else this.run(); + } + + @Nonnull + @Override + public TimerTaskConfig getConfig() { + return config; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java index a39cf8479..6ea65ffc3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java @@ -7,24 +7,24 @@ public enum ChallengeStatusPolicy implements IPolicy { - ALWAYS(challenge -> true), - DISABLED(challenge -> !challenge.isEnabled()), - ENABLED(IChallenge::isEnabled); + ALWAYS(challenge -> true), + DISABLED(challenge -> !challenge.isEnabled()), + ENABLED(IChallenge::isEnabled); - private final Predicate check; + private final Predicate check; - ChallengeStatusPolicy(@Nonnull Predicate check) { - this.check = check; - } + ChallengeStatusPolicy(@Nonnull Predicate check) { + this.check = check; + } - @Override - public boolean check(@Nonnull Object holder) { - return check.test((IChallenge) holder); - } + @Override + public boolean check(@Nonnull Object holder) { + return check.test((IChallenge) holder); + } - @Override - public boolean isApplicable(@Nonnull Object holder) { - return holder instanceof IChallenge; - } + @Override + public boolean isApplicable(@Nonnull Object holder) { + return holder instanceof IChallenge; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java index 6b62fa74d..50de73c31 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java @@ -7,19 +7,19 @@ public enum ExtraWorldPolicy implements IPolicy { - ALWAYS(() -> true), - USED(ChallengeAPI::isWorldInUse), - NOT_USED(() -> !ChallengeAPI.isWorldInUse()); + ALWAYS(() -> true), + USED(ChallengeAPI::isWorldInUse), + NOT_USED(() -> !ChallengeAPI.isWorldInUse()); - private final BooleanSupplier check; + private final BooleanSupplier check; - ExtraWorldPolicy(@Nonnull BooleanSupplier check) { - this.check = check; - } + ExtraWorldPolicy(@Nonnull BooleanSupplier check) { + this.check = check; + } - @Override - public boolean check(@Nonnull Object holder) { - return check.getAsBoolean(); - } + @Override + public boolean check(@Nonnull Object holder) { + return check.getAsBoolean(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java index 22f223d38..af87bdbd8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java @@ -7,19 +7,19 @@ public enum FreshnessPolicy implements IPolicy { - ALWAYS(() -> true), - FRESH(ChallengeAPI::isFresh), - NOT_FRESH(() -> !ChallengeAPI.isFresh()); + ALWAYS(() -> true), + FRESH(ChallengeAPI::isFresh), + NOT_FRESH(() -> !ChallengeAPI.isFresh()); - private final BooleanSupplier check; + private final BooleanSupplier check; - FreshnessPolicy(@Nonnull BooleanSupplier check) { - this.check = check; - } + FreshnessPolicy(@Nonnull BooleanSupplier check) { + this.check = check; + } - @Override - public boolean check(@Nonnull Object holder) { - return check.getAsBoolean(); - } + @Override + public boolean check(@Nonnull Object holder) { + return check.getAsBoolean(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java index 300612cbe..a2bed96cf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java @@ -4,10 +4,10 @@ public interface IPolicy { - boolean check(@Nonnull Object holder); + boolean check(@Nonnull Object holder); - default boolean isApplicable(@Nonnull Object holder) { - return true; - } + default boolean isApplicable(@Nonnull Object holder) { + return true; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java index 36b206be3..13b516467 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java @@ -7,20 +7,20 @@ public enum PlayerCountPolicy implements IPolicy { - ALWAYS((online, max) -> true), - EMPTY((online, max) -> online == 0), - SOMEONE((online, max) -> online > 0), - FULL(Integer::equals); + ALWAYS((online, max) -> true), + EMPTY((online, max) -> online == 0), + SOMEONE((online, max) -> online > 0), + FULL(Integer::equals); - private final BiPredicate check; + private final BiPredicate check; - PlayerCountPolicy(@Nonnull BiPredicate check) { - this.check = check; - } + PlayerCountPolicy(@Nonnull BiPredicate check) { + this.check = check; + } - @Override - public boolean check(@Nonnull Object holder) { - return check.test(Bukkit.getOnlinePlayers().size(), Bukkit.getMaxPlayers()); - } + @Override + public boolean check(@Nonnull Object holder) { + return check.test(Bukkit.getOnlinePlayers().size(), Bukkit.getMaxPlayers()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java index 5b44e293c..9b0a6c3b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java @@ -13,24 +13,24 @@ @Retention(RetentionPolicy.RUNTIME) public @interface ScheduledTask { - @Nonnegative - int ticks(); + @Nonnegative + int ticks(); - boolean async() default true; + boolean async() default true; - @Nonnull - TimerPolicy timerPolicy() default TimerPolicy.STARTED; + @Nonnull + TimerPolicy timerPolicy() default TimerPolicy.STARTED; - @Nonnull - ChallengeStatusPolicy challengePolicy() default ChallengeStatusPolicy.ENABLED; + @Nonnull + ChallengeStatusPolicy challengePolicy() default ChallengeStatusPolicy.ENABLED; - @Nonnull - PlayerCountPolicy playerPolicy() default PlayerCountPolicy.SOMEONE; + @Nonnull + PlayerCountPolicy playerPolicy() default PlayerCountPolicy.SOMEONE; - @Nonnull - ExtraWorldPolicy worldPolicy() default ExtraWorldPolicy.NOT_USED; + @Nonnull + ExtraWorldPolicy worldPolicy() default ExtraWorldPolicy.NOT_USED; - @Nonnull - FreshnessPolicy freshnessPolicy() default FreshnessPolicy.ALWAYS; + @Nonnull + FreshnessPolicy freshnessPolicy() default FreshnessPolicy.ALWAYS; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java index cf8ba7870..68250f891 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java @@ -16,21 +16,21 @@ @Retention(RetentionPolicy.RUNTIME) public @interface TimerTask { - @Nonnull - TimerStatus[] status(); + @Nonnull + TimerStatus[] status(); - boolean async() default true; + boolean async() default true; - @Nonnull - ChallengeStatusPolicy challengePolicy() default ChallengeStatusPolicy.ENABLED; + @Nonnull + ChallengeStatusPolicy challengePolicy() default ChallengeStatusPolicy.ENABLED; - @Nonnull - PlayerCountPolicy playerPolicy() default PlayerCountPolicy.SOMEONE; + @Nonnull + PlayerCountPolicy playerPolicy() default PlayerCountPolicy.SOMEONE; - @Nonnull - ExtraWorldPolicy worldPolicy() default ExtraWorldPolicy.NOT_USED; + @Nonnull + ExtraWorldPolicy worldPolicy() default ExtraWorldPolicy.NOT_USED; - @Nonnull - FreshnessPolicy freshnessPolicy() default FreshnessPolicy.ALWAYS; + @Nonnull + FreshnessPolicy freshnessPolicy() default FreshnessPolicy.ALWAYS; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java index 2c1873c2d..c3cddbee6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java @@ -26,207 +26,207 @@ public final class ChallengeTimer { - @Getter - private final TimerFormat format; - private final Message stoppedMessage, upMessage, downMessage; - private final boolean specificStartSounds, defaultStartSound; - @Getter + @Getter + private final TimerFormat format; + private final Message stoppedMessage, upMessage, downMessage; + private final boolean specificStartSounds, defaultStartSound; + @Getter private long time = 0; - @Getter + @Getter private boolean countingUp = true; - @Getter + @Getter private boolean paused = true; - private boolean hidden = false; - private boolean sentEmpty; - - public ChallengeTimer() { - - Document pluginConfig = Challenges.getInstance().getConfigDocument(); - specificStartSounds = pluginConfig.getBoolean("enable-specific-start-sounds"); - defaultStartSound = pluginConfig.getBoolean("enable-default-start-sounds"); - - // Load format + messages - Document timerConfig = pluginConfig.getDocument("timer"); - stoppedMessage = Message.forName("stopped-message"); - upMessage = Message.forName("count-up-message"); - downMessage = Message.forName("count-down-message"); - - Document formatConfig = timerConfig.getDocument("format"); - format = new TimerFormat(formatConfig); - - Challenges.getInstance().getScheduler().register(this); - } - - public void enable() { - updateTimeRule(); - } - - private void updateTimeRule() { - for (World world : ChallengeAPI.getGameWorlds()) { - world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, !paused); - } - } - - @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.ALWAYS, playerPolicy = PlayerCountPolicy.ALWAYS) - public void onTimerSecond() { - - if (!paused) { - if (countingUp) time++; - else time--; - - if (time <= 0) { - time = 0; - countingUp = true; - handleHitZero(); - } - } - - updateActionbar(); - - } - - @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.PAUSED) - public void playPausedParticles() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (AbstractChallenge.ignorePlayer(player)) continue; - Location location = player.getLocation(); - if (location.getWorld() == null) continue; - location.getWorld().playEffect(location, Effect.ENDER_SIGNAL, 1); - } - } - - private void handleHitZero() { - ChallengeAPI.endChallenge(ChallengeEndCause.TIMER_HIT_ZERO); - } - - public void resume() { - if (!paused) return; - paused = false; - - updateActionbar(); - updateTimeRule(); - - Message.forName("timer-was-started").broadcast(Prefix.TIMER); - Challenges.getInstance().getScheduler().fireTimerStatusChange(); - Challenges.getInstance().getTitleManager().sendTimerStatusTitle(Message.forName("title-timer-started")); - Challenges.getInstance().getServerManager().setNotFresh(); - - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.getGameMode() != GameMode.CREATIVE) - player.setGameMode(GameMode.SURVIVAL); - } - - IGoal currentGoal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); - if (currentGoal != null && specificStartSounds) { - currentGoal.getStartSound().broadcast(); - } else if (defaultStartSound) { - SoundSample.DRAGON_BREATH.broadcast(); - } - - } - - public void pause(boolean playInGameEffects) { - if (paused) return; - paused = true; - - updateActionbar(); - updateTimeRule(); - - Challenges.getInstance().getScheduler().fireTimerStatusChange(); - if (playInGameEffects) { - Challenges.getInstance().getTitleManager().sendTimerStatusTitle(Message.forName("title-timer-paused")); - Message.forName("timer-was-paused").broadcast(Prefix.TIMER); - SoundSample.BASS_OFF.broadcast(); - } - } - - public void reset() { - if (!countingUp) pause(true); - time = 0; - countingUp = true; - updateActionbar(); - } - - public void updateActionbar() { - if (sentEmpty && hidden) return; - if (hidden) sentEmpty = true; - if (!hidden) { - for (Player player : Bukkit.getOnlinePlayers()) { - player.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(getActionbar())); - } - } - - } - - @Nonnull - private String getActionbar() { - Message message = !paused || (!countingUp && time > 0) ? (countingUp ? upMessage : downMessage) : stoppedMessage; - String time = getFormattedTime(); - return message.asString(time); - } - - private boolean isSmallCaps() { - LanguageLoader languageLoader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); - if (languageLoader == null) return false; - return languageLoader.isSmallCapsFont(); - } - - public synchronized void loadSession() { - FileDocument config = Challenges.getInstance().getConfigManager().getSessionConfig(); - time = config.getInt("timer.seconds"); - countingUp = config.getBoolean("timer.countingUp", true); - hidden = config.getBoolean("timer.hidden", false); - } - - public synchronized void saveSession(boolean async) { - FileDocument config = Challenges.getInstance().getConfigManager().getSessionConfig(); - config.set("timer.seconds", time); - config.set("timer.countingUp", countingUp); - config.set("timer.hidden", hidden); - config.save(async); - } - - public void addSeconds(int amount) { - time += amount; - if (time < 0) - time = 0; - updateActionbar(); - } - - public void setSeconds(long seconds) { - this.time = seconds; - updateActionbar(); - } - - public void setHidden(boolean hide) { - this.sentEmpty = false; - this.hidden = hide; - updateActionbar(); - } - - @Nonnull - public String getFormattedTime() { - return format.format(time); - } + private boolean hidden = false; + private boolean sentEmpty; + + public ChallengeTimer() { + + Document pluginConfig = Challenges.getInstance().getConfigDocument(); + specificStartSounds = pluginConfig.getBoolean("enable-specific-start-sounds"); + defaultStartSound = pluginConfig.getBoolean("enable-default-start-sounds"); + + // Load format + messages + Document timerConfig = pluginConfig.getDocument("timer"); + stoppedMessage = Message.forName("stopped-message"); + upMessage = Message.forName("count-up-message"); + downMessage = Message.forName("count-down-message"); + + Document formatConfig = timerConfig.getDocument("format"); + format = new TimerFormat(formatConfig); + + Challenges.getInstance().getScheduler().register(this); + } + + public void enable() { + updateTimeRule(); + } + + private void updateTimeRule() { + for (World world : ChallengeAPI.getGameWorlds()) { + world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, !paused); + } + } + + @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.ALWAYS, playerPolicy = PlayerCountPolicy.ALWAYS) + public void onTimerSecond() { + + if (!paused) { + if (countingUp) time++; + else time--; + + if (time <= 0) { + time = 0; + countingUp = true; + handleHitZero(); + } + } + + updateActionbar(); + + } + + @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.PAUSED) + public void playPausedParticles() { + for (Player player : Bukkit.getOnlinePlayers()) { + if (AbstractChallenge.ignorePlayer(player)) continue; + Location location = player.getLocation(); + if (location.getWorld() == null) continue; + location.getWorld().playEffect(location, Effect.ENDER_SIGNAL, 1); + } + } + + private void handleHitZero() { + ChallengeAPI.endChallenge(ChallengeEndCause.TIMER_HIT_ZERO); + } + + public void resume() { + if (!paused) return; + paused = false; + + updateActionbar(); + updateTimeRule(); + + Message.forName("timer-was-started").broadcast(Prefix.TIMER); + Challenges.getInstance().getScheduler().fireTimerStatusChange(); + Challenges.getInstance().getTitleManager().sendTimerStatusTitle(Message.forName("title-timer-started")); + Challenges.getInstance().getServerManager().setNotFresh(); + + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.getGameMode() != GameMode.CREATIVE) + player.setGameMode(GameMode.SURVIVAL); + } + + IGoal currentGoal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); + if (currentGoal != null && specificStartSounds) { + currentGoal.getStartSound().broadcast(); + } else if (defaultStartSound) { + SoundSample.DRAGON_BREATH.broadcast(); + } + + } + + public void pause(boolean playInGameEffects) { + if (paused) return; + paused = true; + + updateActionbar(); + updateTimeRule(); + + Challenges.getInstance().getScheduler().fireTimerStatusChange(); + if (playInGameEffects) { + Challenges.getInstance().getTitleManager().sendTimerStatusTitle(Message.forName("title-timer-paused")); + Message.forName("timer-was-paused").broadcast(Prefix.TIMER); + SoundSample.BASS_OFF.broadcast(); + } + } + + public void reset() { + if (!countingUp) pause(true); + time = 0; + countingUp = true; + updateActionbar(); + } + + public void updateActionbar() { + if (sentEmpty && hidden) return; + if (hidden) sentEmpty = true; + if (!hidden) { + for (Player player : Bukkit.getOnlinePlayers()) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(getActionbar())); + } + } + + } @Nonnull - public TimerStatus getStatus() { - return paused ? TimerStatus.PAUSED : TimerStatus.RUNNING; - } + private String getActionbar() { + Message message = !paused || (!countingUp && time > 0) ? (countingUp ? upMessage : downMessage) : stoppedMessage; + String time = getFormattedTime(); + return message.asString(time); + } + + private boolean isSmallCaps() { + LanguageLoader languageLoader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); + if (languageLoader == null) return false; + return languageLoader.isSmallCapsFont(); + } + + public synchronized void loadSession() { + FileDocument config = Challenges.getInstance().getConfigManager().getSessionConfig(); + time = config.getInt("timer.seconds"); + countingUp = config.getBoolean("timer.countingUp", true); + hidden = config.getBoolean("timer.hidden", false); + } + + public synchronized void saveSession(boolean async) { + FileDocument config = Challenges.getInstance().getConfigManager().getSessionConfig(); + config.set("timer.seconds", time); + config.set("timer.countingUp", countingUp); + config.set("timer.hidden", hidden); + config.save(async); + } + + public void addSeconds(int amount) { + time += amount; + if (time < 0) + time = 0; + updateActionbar(); + } + + public void setSeconds(long seconds) { + this.time = seconds; + updateActionbar(); + } + + public void setHidden(boolean hide) { + this.sentEmpty = false; + this.hidden = hide; + updateActionbar(); + } + + @Nonnull + public String getFormattedTime() { + return format.format(time); + } + + @Nonnull + public TimerStatus getStatus() { + return paused ? TimerStatus.PAUSED : TimerStatus.RUNNING; + } public boolean isStarted() { - return !paused; - } + return !paused; + } public void setCountingUp(boolean countingUp) { - if (this.countingUp == countingUp) return; - - this.countingUp = countingUp; - updateActionbar(); - TimerMenuGenerator menuGenerator = (TimerMenuGenerator) MenuType.TIMER.getMenuGenerator(); - menuGenerator.updateFirstPage(); - Message.forName("timer-mode-set-" + (countingUp ? "up" : "down")).broadcast(Prefix.TIMER); - SoundSample.BASS_ON.broadcast(); - } + if (this.countingUp == countingUp) return; + + this.countingUp = countingUp; + updateActionbar(); + TimerMenuGenerator menuGenerator = (TimerMenuGenerator) MenuType.TIMER.getMenuGenerator(); + menuGenerator.updateFirstPage(); + Message.forName("timer-mode-set-" + (countingUp ? "up" : "down")).broadcast(Prefix.TIMER); + SoundSample.BASS_ON.broadcast(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java index 3bc78d9e0..d06b1fcf4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java @@ -7,65 +7,65 @@ public final class TimerFormat { - private final String seconds, minutes, hours, day, days; + private final String seconds, minutes, hours, day, days; - public TimerFormat(@Nonnull Document document) { - seconds = document.getString("seconds", ""); - minutes = document.getString("minutes", ""); - hours = document.getString("hours", ""); - day = document.getString("day", ""); - days = document.getString("days", ""); - } + public TimerFormat(@Nonnull Document document) { + seconds = document.getString("seconds", ""); + minutes = document.getString("minutes", ""); + hours = document.getString("hours", ""); + day = document.getString("day", ""); + days = document.getString("days", ""); + } - public TimerFormat() { - seconds = "{mm}:{ss}"; - minutes = "{mm}:{ss}"; - hours = "{hh}:{mm}:{ss}"; - day = "{d}:{hh}:{mm}:{ss}"; - days = "{d}:{hh}:{mm}:{ss}"; - } + public TimerFormat() { + seconds = "{mm}:{ss}"; + minutes = "{mm}:{ss}"; + hours = "{hh}:{mm}:{ss}"; + day = "{d}:{hh}:{mm}:{ss}"; + days = "{d}:{hh}:{mm}:{ss}"; + } - @Nonnull - public String format(@Nonnegative long time) { + @Nonnull + public String format(@Nonnegative long time) { - long seconds = time; - long minutes = seconds / 60; - long hours = minutes / 60; - long days = hours / 24; + long seconds = time; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; - seconds %= 60; - minutes %= 60; - hours %= 24; + seconds %= 60; + minutes %= 60; + hours %= 24; - return getFormat(minutes, hours, days) - .replace("{d}", String.valueOf(days)) - .replace("{dd}", digit2(days)) - .replace("{h}", String.valueOf(hours)) - .replace("{hh}", digit2(hours)) - .replace("{m}", String.valueOf(minutes)) - .replace("{mm}", digit2(minutes)) - .replace("{s}", String.valueOf(seconds)) - .replace("{ss}", digit2(seconds)); - } + return getFormat(minutes, hours, days) + .replace("{d}", String.valueOf(days)) + .replace("{dd}", digit2(days)) + .replace("{h}", String.valueOf(hours)) + .replace("{hh}", digit2(hours)) + .replace("{m}", String.valueOf(minutes)) + .replace("{mm}", digit2(minutes)) + .replace("{s}", String.valueOf(seconds)) + .replace("{ss}", digit2(seconds)); + } - private String getFormat(long minutes, long hours, long days) { - String format; - if (days > 1) { - format = this.days; - } else if (days == 1) { - format = this.day; - } else if (hours >= 1) { - format = this.hours; - } else if (minutes >= 1) { - format = this.minutes; - } else { - format = this.seconds; - } - return format; - } + private String getFormat(long minutes, long hours, long days) { + String format; + if (days > 1) { + format = this.days; + } else if (days == 1) { + format = this.day; + } else if (hours >= 1) { + format = this.hours; + } else if (minutes >= 1) { + format = this.minutes; + } else { + format = this.seconds; + } + return format; + } - private String digit2(@Nonnegative long number) { - return number > 9 ? String.valueOf(number) : "0" + number; - } + private String digit2(@Nonnegative long number) { + return number > 9 ? String.valueOf(number) : "0" + number; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerStatus.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerStatus.java index 1e2406fb9..242900031 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerStatus.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerStatus.java @@ -2,7 +2,7 @@ public enum TimerStatus { - RUNNING, - PAUSED + RUNNING, + PAUSED } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java index 4fa74dacf..114d0bff3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java @@ -1,31 +1,32 @@ package net.codingarea.challenges.plugin.management.server; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import lombok.Getter; import net.codingarea.challenges.plugin.content.Message; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + @Getter public enum ChallengeEndCause { - TIMER_HIT_ZERO(Message.forName("challenge-end-timer-hit-zero"), Message.forName("challenge-end-timer-hit-zero-winner")), - GOAL_REACHED(Message.forName("challenge-end-goal-reached"), Message.forName("challenge-end-goal-reached-winner")), - GOAL_FAILED(Message.forName("challenge-end-goal-failed"), null); + TIMER_HIT_ZERO(Message.forName("challenge-end-timer-hit-zero"), Message.forName("challenge-end-timer-hit-zero-winner")), + GOAL_REACHED(Message.forName("challenge-end-goal-reached"), Message.forName("challenge-end-goal-reached-winner")), + GOAL_FAILED(Message.forName("challenge-end-goal-failed"), null); - private final Message noWinnerMessage, winnerMessage; + private final Message noWinnerMessage, winnerMessage; - ChallengeEndCause(@Nonnull Message noWinnerMessage, @Nullable Message winnerMessage) { - this.noWinnerMessage = noWinnerMessage; - this.winnerMessage = winnerMessage; - } + ChallengeEndCause(@Nonnull Message noWinnerMessage, @Nullable Message winnerMessage) { + this.noWinnerMessage = noWinnerMessage; + this.winnerMessage = winnerMessage; + } - @Nonnull - public Message getMessage(boolean withWinner) { - return withWinner && winnerMessage != null ? winnerMessage : noWinnerMessage; - } + @Nonnull + public Message getMessage(boolean withWinner) { + return withWinner && winnerMessage != null ? winnerMessage : noWinnerMessage; + } - public boolean isWinnable() { - return winnerMessage != null; - } + public boolean isWinnable() { + return winnerMessage != null; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java index 80e0bf35d..3c459357b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java @@ -19,97 +19,97 @@ public class GameWorldStorage implements GamestateSaveable { - private final List worlds = new LinkedList<>(); - private World overworld; - private World nether; - private World end; - private World voidWorld; - - public void enable() { - Challenges.getInstance().getChallengeManager().registerGameStateSaver(this); - - for (int i = 0; i < 3 && i < Bukkit.getWorlds().size(); i++) { - World world = Bukkit.getWorlds().get(i); - switch (i) { - case 0: { - overworld = world; - worlds.add(world); - } - break; - case 1: { - if (world.getEnvironment() == Environment.NETHER) { - nether = world; - worlds.add(world); - } else if (world.getEnvironment() == Environment.THE_END) { - end = world; - worlds.add(world); - } - } - break; - case 2: { - if (world.getEnvironment() == Environment.THE_END) { - end = world; - worlds.add(world); - } - } - break; - } - } - - } - - @Override - public String getUniqueGamestateName() { - return getClass().getSimpleName().toLowerCase(); - } - - @Override - public void writeGameState(@NotNull Document document) { - document.set("void-generated", voidWorld != null); - } - - @Override - public void loadGameState(@NotNull Document document) { - if (document.getBoolean("void-generated")) { - getOrCreateVoidWorld(); - } - } - - @Nonnull - public World getOrCreateVoidWorld() { - if (voidWorld != null) { - return voidWorld; - } - - VoidMapGenerator generator = new VoidMapGenerator(); - voidWorld = new WorldCreator("void").type(WorldType.FLAT).generator( - generator).createWorld(); - worlds.add(voidWorld); - - return voidWorld; - } - - public World getWorld(@Nullable Environment environment) { - if (environment == null) return null; - switch (environment) { - case NORMAL: - return overworld; - case NETHER: - return nether; - case THE_END: - return end; - case CUSTOM: - return Challenges.getInstance().getWorldManager().getExtraWorld(); - } - return null; - } - - public List getCustomGeneratedGameWorlds() { - return Collections.singletonList("void"); - } - - public List getGameWorlds() { - return Collections.unmodifiableList(worlds); - } + private final List worlds = new LinkedList<>(); + private World overworld; + private World nether; + private World end; + private World voidWorld; + + public void enable() { + Challenges.getInstance().getChallengeManager().registerGameStateSaver(this); + + for (int i = 0; i < 3 && i < Bukkit.getWorlds().size(); i++) { + World world = Bukkit.getWorlds().get(i); + switch (i) { + case 0: { + overworld = world; + worlds.add(world); + } + break; + case 1: { + if (world.getEnvironment() == Environment.NETHER) { + nether = world; + worlds.add(world); + } else if (world.getEnvironment() == Environment.THE_END) { + end = world; + worlds.add(world); + } + } + break; + case 2: { + if (world.getEnvironment() == Environment.THE_END) { + end = world; + worlds.add(world); + } + } + break; + } + } + + } + + @Override + public String getUniqueGamestateName() { + return getClass().getSimpleName().toLowerCase(); + } + + @Override + public void writeGameState(@NotNull Document document) { + document.set("void-generated", voidWorld != null); + } + + @Override + public void loadGameState(@NotNull Document document) { + if (document.getBoolean("void-generated")) { + getOrCreateVoidWorld(); + } + } + + @Nonnull + public World getOrCreateVoidWorld() { + if (voidWorld != null) { + return voidWorld; + } + + VoidMapGenerator generator = new VoidMapGenerator(); + voidWorld = new WorldCreator("void").type(WorldType.FLAT).generator( + generator).createWorld(); + worlds.add(voidWorld); + + return voidWorld; + } + + public World getWorld(@Nullable Environment environment) { + if (environment == null) return null; + switch (environment) { + case NORMAL: + return overworld; + case NETHER: + return nether; + case THE_END: + return end; + case CUSTOM: + return Challenges.getInstance().getWorldManager().getExtraWorld(); + } + return null; + } + + public List getCustomGeneratedGameWorlds() { + return Collections.singletonList("void"); + } + + public List getGameWorlds() { + return Collections.unmodifiableList(worlds); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java index e274b348d..167230187 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java @@ -19,52 +19,52 @@ */ public class GeneratorWorldPortalManager implements GamestateSaveable { - public Map lastWorldLocations; + public Map lastWorldLocations; - public GeneratorWorldPortalManager() { - lastWorldLocations = new HashMap<>(); - Challenges.getInstance().getChallengeManager().registerGameStateSaver(this); - } + public GeneratorWorldPortalManager() { + lastWorldLocations = new HashMap<>(); + Challenges.getInstance().getChallengeManager().registerGameStateSaver(this); + } - @Nullable - public Location getAndRemoveLastWorld(@Nonnull Player player) { - return lastWorldLocations.remove(player.getUniqueId()); - } + @Nullable + public Location getAndRemoveLastWorld(@Nonnull Player player) { + return lastWorldLocations.remove(player.getUniqueId()); + } - public void setLastLocation(@Nonnull Player player, @Nonnull Location location) { - lastWorldLocations.put(player.getUniqueId(), location); - } + public void setLastLocation(@Nonnull Player player, @Nonnull Location location) { + lastWorldLocations.put(player.getUniqueId(), location); + } - public boolean isCustomWorld(@Nonnull String name) { - return Challenges.getInstance().getGameWorldStorage().getCustomGeneratedGameWorlds().contains(name); - } + public boolean isCustomWorld(@Nonnull String name) { + return Challenges.getInstance().getGameWorldStorage().getCustomGeneratedGameWorlds().contains(name); + } - @Override - public String getUniqueGamestateName() { - return getClass().getSimpleName().toLowerCase(); - } + @Override + public String getUniqueGamestateName() { + return getClass().getSimpleName().toLowerCase(); + } - @Override - public void writeGameState(@NotNull Document document) { - for (Entry entry : lastWorldLocations.entrySet()) { - UUID uuid = entry.getKey(); - Location location = entry.getValue(); - document.set(uuid.toString(), location); - } - } + @Override + public void writeGameState(@NotNull Document document) { + for (Entry entry : lastWorldLocations.entrySet()) { + UUID uuid = entry.getKey(); + Location location = entry.getValue(); + document.set(uuid.toString(), location); + } + } - @Override - public void loadGameState(@NotNull Document document) { - for (String key : document.keys()) { - try { - Location location = document.getInstance(key, Location.class); - UUID uuid = UUID.fromString(key); - lastWorldLocations.put(uuid, location); - } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Couldn't load last location of: " + key); - Challenges.getInstance().getLogger().error("", exception); - } - } - } + @Override + public void loadGameState(@NotNull Document document) { + for (String key : document.keys()) { + try { + Location location = document.getInstance(key, Location.class); + UUID uuid = UUID.fromString(key); + lastWorldLocations.put(uuid, location); + } catch (Exception exception) { + Challenges.getInstance().getLogger().error("Couldn't load last location of: " + key); + Challenges.getInstance().getLogger().error("", exception); + } + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java index e2eb84f9e..f054d28aa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java @@ -17,82 +17,82 @@ public final class ScoreboardManager { - private final List bossbars = new ArrayList<>(); - private ChallengeScoreboard currentScoreboard; - - public ScoreboardManager() { - ChallengeAPI.subscribeLoader(LanguageLoader.class, this::updateAll); - ChallengeAPI.registerScheduler(this); - } - - public void handleQuit(@Nonnull Player player) { - for (ChallengeBossBar bossbar : bossbars) { - bossbar.applyHide(player); - } - if (currentScoreboard != null) { - currentScoreboard.applyHide(player); - Bukkit.getScheduler().runTaskLaterAsynchronously(Challenges.getInstance(), () -> currentScoreboard.update(), 1); - } - } - - public void handleJoin(@Nonnull Player player) { - updateAll(); - } - - @TimerTask(status = {TimerStatus.RUNNING, TimerStatus.PAUSED}) - public void updateAll() { - for (ChallengeBossBar bossbar : bossbars) { - bossbar.update(); - } - if (currentScoreboard != null) { - currentScoreboard.update(); - } - } - - public void showBossBar(@Nonnull ChallengeBossBar bossbar) { - if (bossbars.contains(bossbar)) return; - bossbars.add(bossbar); - bossbar.update(); - } - - public void hideBossBar(@Nonnull ChallengeBossBar bossbar) { - if (!bossbars.remove(bossbar)) return; - Bukkit.getOnlinePlayers().forEach(bossbar::applyHide); - } - - @Nullable - public ChallengeScoreboard getCurrentScoreboard() { - return currentScoreboard; - } - - public void setCurrentScoreboard(@Nullable ChallengeScoreboard scoreboard) { - if (currentScoreboard == scoreboard) return; - - // Remove old scoreboard - if (currentScoreboard != null) { - Bukkit.getOnlinePlayers().forEach(currentScoreboard::applyHide); - } - - currentScoreboard = scoreboard; - - // Add new scoreboard if available - if (scoreboard == null) return; - scoreboard.update(); - } - - public void disable() { - for (ChallengeBossBar bossbar : bossbars.toArray(new ChallengeBossBar[0])) { - hideBossBar(bossbar); - } - setCurrentScoreboard(null); - } - - public boolean isShown(@Nonnull ChallengeBossBar bossbar) { - return bossbars.contains(bossbar); - } - - public boolean isShown(@Nonnull ChallengeScoreboard scoreboard) { - return currentScoreboard == scoreboard; - } + private final List bossbars = new ArrayList<>(); + private ChallengeScoreboard currentScoreboard; + + public ScoreboardManager() { + ChallengeAPI.subscribeLoader(LanguageLoader.class, this::updateAll); + ChallengeAPI.registerScheduler(this); + } + + public void handleQuit(@Nonnull Player player) { + for (ChallengeBossBar bossbar : bossbars) { + bossbar.applyHide(player); + } + if (currentScoreboard != null) { + currentScoreboard.applyHide(player); + Bukkit.getScheduler().runTaskLaterAsynchronously(Challenges.getInstance(), () -> currentScoreboard.update(), 1); + } + } + + public void handleJoin(@Nonnull Player player) { + updateAll(); + } + + @TimerTask(status = {TimerStatus.RUNNING, TimerStatus.PAUSED}) + public void updateAll() { + for (ChallengeBossBar bossbar : bossbars) { + bossbar.update(); + } + if (currentScoreboard != null) { + currentScoreboard.update(); + } + } + + public void showBossBar(@Nonnull ChallengeBossBar bossbar) { + if (bossbars.contains(bossbar)) return; + bossbars.add(bossbar); + bossbar.update(); + } + + public void hideBossBar(@Nonnull ChallengeBossBar bossbar) { + if (!bossbars.remove(bossbar)) return; + Bukkit.getOnlinePlayers().forEach(bossbar::applyHide); + } + + @Nullable + public ChallengeScoreboard getCurrentScoreboard() { + return currentScoreboard; + } + + public void setCurrentScoreboard(@Nullable ChallengeScoreboard scoreboard) { + if (currentScoreboard == scoreboard) return; + + // Remove old scoreboard + if (currentScoreboard != null) { + Bukkit.getOnlinePlayers().forEach(currentScoreboard::applyHide); + } + + currentScoreboard = scoreboard; + + // Add new scoreboard if available + if (scoreboard == null) return; + scoreboard.update(); + } + + public void disable() { + for (ChallengeBossBar bossbar : bossbars.toArray(new ChallengeBossBar[0])) { + hideBossBar(bossbar); + } + setCurrentScoreboard(null); + } + + public boolean isShown(@Nonnull ChallengeBossBar bossbar) { + return bossbars.contains(bossbar); + } + + public boolean isShown(@Nonnull ChallengeScoreboard scoreboard) { + return currentScoreboard == scoreboard; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java index 07bc2790a..635ca5ad2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java @@ -25,104 +25,104 @@ public final class ServerManager { - private final boolean setSpectatorOnWin; - private final boolean dropItemsOnEnd; - private final boolean winSounds; - - private boolean isFresh; // This indicated if the timer was never started before - private boolean hasCheated; - - public ServerManager() { - Document sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); - hasCheated = sessionConfig.getBoolean("cheated"); - isFresh = sessionConfig.getBoolean("fresh", true); - - Document pluginConfig = Challenges.getInstance().getConfigDocument(); - setSpectatorOnWin = pluginConfig.getBoolean("set-spectator-on-win"); - dropItemsOnEnd = pluginConfig.getBoolean("drop-items-on-end"); - winSounds = pluginConfig.getBoolean("enabled-win-sounds"); - } - - public void setNotFresh() { - isFresh = false; - Challenges.getInstance().getConfigManager().getSessionConfig().set("fresh", false); - } - - public void setHasCheated() { - hasCheated = true; - Challenges.getInstance().getConfigManager().getSessionConfig().set("cheated", true); - } - - public boolean isFresh() { - return isFresh; - } - - public boolean hasCheated() { - return hasCheated; - } - - public void endChallenge(@Nonnull ChallengeEndCause endCause, Supplier> winnerGetter) { - if (ChallengeAPI.isPaused()) { - Logger.warn("Tried to end challenge while timer was paused"); - return; - } - - IGoal currentGoal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); - List winners = new LinkedList<>(); - if (winnerGetter != null) { - winners = winnerGetter.get(); - } else if (currentGoal != null && endCause.isWinnable()) { - currentGoal.getWinnersOnEnd(winners); - } - - if (endCause != ChallengeEndCause.GOAL_REACHED || setSpectatorOnWin) { - setSpectator(); - } - if (endCause == ChallengeEndCause.GOAL_REACHED && winSounds && currentGoal != null && currentGoal.getWinSound() != null) { - currentGoal.getWinSound().broadcast(); - } - if (dropItemsOnEnd) { - for (Player player : Bukkit.getOnlinePlayers()) { - if (winners.isEmpty() || winners.contains(player)) continue; - dropItems(player); - } - } - - Challenges.getInstance().getChallengeTimer().pause(false); - - String winnerString = StringUtils.getIterableAsString(winners, "§7, ", player -> "§e§l" + NameHelper.getName(player)); - String time = Challenges.getInstance().getChallengeTimer().getFormattedTime(); - String seed = Bukkit.getWorlds().isEmpty() ? "?" : - String.valueOf(ChallengeAPI.getGameWorld(Environment.NORMAL).getSeed()); - endCause.getMessage(!winners.isEmpty()).broadcast(Prefix.CHALLENGES, time, winnerString, seed); - - } - - private void setSpectator() { - for (Player player : Bukkit.getOnlinePlayers()) { - player.setGameMode(GameMode.SPECTATOR); - SoundSample.BLAST.play(player); - - try { - player.getWorld().spawnEntity(player.getLocation(), MinecraftNameWrapper.FIREWORK); - } catch (IllegalArgumentException ex) { - // We cant spawn fireworks like that in some versions of spigot - } - } - } - - private void dropItems(@Nonnull Player player) { - dropItems(player.getLocation(), player.getInventory().getContents()); - player.getInventory().clear(); - } - - private void dropItems(@Nonnull Location location, @Nonnull ItemStack[] items) { - for (ItemStack item : items) { - if (item == null) continue; - if (BukkitReflectionUtils.isAir(item.getType())) continue; - if (location.getWorld() == null) return; - location.getWorld().dropItem(location, item); - } - } + private final boolean setSpectatorOnWin; + private final boolean dropItemsOnEnd; + private final boolean winSounds; + + private boolean isFresh; // This indicated if the timer was never started before + private boolean hasCheated; + + public ServerManager() { + Document sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); + hasCheated = sessionConfig.getBoolean("cheated"); + isFresh = sessionConfig.getBoolean("fresh", true); + + Document pluginConfig = Challenges.getInstance().getConfigDocument(); + setSpectatorOnWin = pluginConfig.getBoolean("set-spectator-on-win"); + dropItemsOnEnd = pluginConfig.getBoolean("drop-items-on-end"); + winSounds = pluginConfig.getBoolean("enabled-win-sounds"); + } + + public void setNotFresh() { + isFresh = false; + Challenges.getInstance().getConfigManager().getSessionConfig().set("fresh", false); + } + + public void setHasCheated() { + hasCheated = true; + Challenges.getInstance().getConfigManager().getSessionConfig().set("cheated", true); + } + + public boolean isFresh() { + return isFresh; + } + + public boolean hasCheated() { + return hasCheated; + } + + public void endChallenge(@Nonnull ChallengeEndCause endCause, Supplier> winnerGetter) { + if (ChallengeAPI.isPaused()) { + Logger.warn("Tried to end challenge while timer was paused"); + return; + } + + IGoal currentGoal = Challenges.getInstance().getChallengeManager().getCurrentGoal(); + List winners = new LinkedList<>(); + if (winnerGetter != null) { + winners = winnerGetter.get(); + } else if (currentGoal != null && endCause.isWinnable()) { + currentGoal.getWinnersOnEnd(winners); + } + + if (endCause != ChallengeEndCause.GOAL_REACHED || setSpectatorOnWin) { + setSpectator(); + } + if (endCause == ChallengeEndCause.GOAL_REACHED && winSounds && currentGoal != null && currentGoal.getWinSound() != null) { + currentGoal.getWinSound().broadcast(); + } + if (dropItemsOnEnd) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (winners.isEmpty() || winners.contains(player)) continue; + dropItems(player); + } + } + + Challenges.getInstance().getChallengeTimer().pause(false); + + String winnerString = StringUtils.getIterableAsString(winners, "§7, ", player -> "§e§l" + NameHelper.getName(player)); + String time = Challenges.getInstance().getChallengeTimer().getFormattedTime(); + String seed = Bukkit.getWorlds().isEmpty() ? "?" : + String.valueOf(ChallengeAPI.getGameWorld(Environment.NORMAL).getSeed()); + endCause.getMessage(!winners.isEmpty()).broadcast(Prefix.CHALLENGES, time, winnerString, seed); + + } + + private void setSpectator() { + for (Player player : Bukkit.getOnlinePlayers()) { + player.setGameMode(GameMode.SPECTATOR); + SoundSample.BLAST.play(player); + + try { + player.getWorld().spawnEntity(player.getLocation(), MinecraftNameWrapper.FIREWORK); + } catch (IllegalArgumentException ex) { + // We cant spawn fireworks like that in some versions of spigot + } + } + } + + private void dropItems(@Nonnull Player player) { + dropItems(player.getLocation(), player.getInventory().getContents()); + player.getInventory().clear(); + } + + private void dropItems(@Nonnull Location location, @Nonnull ItemStack[] items) { + for (ItemStack item : items) { + if (item == null) continue; + if (BukkitReflectionUtils.isAir(item.getType())) continue; + if (location.getWorld() == null) return; + location.getWorld().dropItem(location, item); + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java index 6f6d3552a..2a995251f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.management.server; -import java.nio.file.Files; import lombok.Getter; import lombok.Setter; import net.anweisen.utilities.bukkit.utils.logging.Logger; @@ -19,327 +18,332 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.io.*; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; import java.util.HashMap; import java.util.Map; import java.util.UUID; public final class WorldManager { - private static final String customSeedWorldPrefix = "pregenerated_"; - private final boolean restartOnReset; - @Getter - private final boolean enableFreshReset; - private final long customSeed; - private final String levelName; - private final String[] worlds; - private final Map playerData = new HashMap<>(); - @Getter + private static final String customSeedWorldPrefix = "pregenerated_"; + private final boolean restartOnReset; + @Getter + private final boolean enableFreshReset; + private final long customSeed; + private final String levelName; + private final String[] worlds; + private final Map playerData = new HashMap<>(); + @Getter private boolean shutdownBecauseOfReset = false; - private boolean useCustomSeed; - private WorldSettings settings = new WorldSettings(); - private World flatWorld; - @Getter - private boolean worldInUse; - public WorldManager() { - Document pluginConfig = Challenges.getInstance().getConfigDocument(); - restartOnReset = pluginConfig.getBoolean("restart-on-reset"); - enableFreshReset = pluginConfig.getBoolean("enable-fresh-reset"); + private boolean useCustomSeed; + private WorldSettings settings = new WorldSettings(); + private World flatWorld; + @Getter + private boolean worldInUse; + + public WorldManager() { + Document pluginConfig = Challenges.getInstance().getConfigDocument(); + restartOnReset = pluginConfig.getBoolean("restart-on-reset"); + enableFreshReset = pluginConfig.getBoolean("enable-fresh-reset"); + + Document seedConfig = pluginConfig.getDocument("custom-seed"); + useCustomSeed = seedConfig.getBoolean("config"); + customSeed = seedConfig.getLong("seed"); + + Document sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); + levelName = sessionConfig.getString("level-name", "world"); + worlds = new String[]{ + levelName, + levelName + "_nether", + levelName + "_the_end" + }; + } + + public void load() { + executeWorldResetIfNecessary(); + } + + public void enable() { + loadExtraWorld(); + } + + public void prepareWorldReset(@Nullable CommandSender requestedBy) { + prepareWorldReset(requestedBy, customSeed); + } + + public void prepareWorldReset(@Nullable CommandSender requestedBy, @Nullable Long seed) { + if (seed == null && useCustomSeed) seed = customSeed; + if (seed != null) useCustomSeed = true; + + shutdownBecauseOfReset = true; + ChallengeAPI.pauseTimer(false); + + // Stop all tasks to prevent them from overwriting configs + Challenges.getInstance().getScheduler().stop(); + + resetConfigs(); + + String requester = requestedBy instanceof Player ? NameHelper.getName((Player) requestedBy) : "§4§lConsole"; + String kickMessage = Message.forName("server-reset").asString(requester); + Bukkit.getOnlinePlayers().forEach(player -> player.kickPlayer(kickMessage)); + + if (seed != null) { + generateCustomSeedWorlds(seed); + } + + Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), this::stopServerNow, 3); + + } + + private void generateCustomSeedWorlds(long seed) { + + Logger.debug("Generating custom seed worlds with seed " + seed); + for (String name : worlds) { + + World world = Bukkit.getWorld(name); + if (world == null) { + Logger.error("Could not find world {}", name); + continue; + } + + String newWorldName = customSeedWorldPrefix + name; + File folder = new File(Bukkit.getWorldContainer(), newWorldName); + if (folder.exists()) FileUtils.deleteWorldFolder(folder); + + WorldCreator creator = new WorldCreator(newWorldName).seed(seed).environment(world.getEnvironment()); + creator.createWorld(); + + Logger.debug("Created custom seed world {}", newWorldName); + + } + + } + + private void resetConfigs() { + + FileDocument sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); + sessionConfig.clear(); + sessionConfig.set("reset", true); + sessionConfig.set("seed-reset", useCustomSeed); + if (!Bukkit.getWorlds().isEmpty()) { + sessionConfig.set("level-name", ChallengeAPI.getGameWorld(Environment.NORMAL).getName()); + } + sessionConfig.save(); + + FileDocument gamestateConfig = Challenges.getInstance().getConfigManager().getGamestateConfig(); + gamestateConfig.clear(); + gamestateConfig.save(); + + } + + private void loadExtraWorld() { + if (!Challenges.getInstance().isReloaded()) + deleteWorld("challenges-extra"); + + try { + flatWorld = new WorldCreator("challenges-extra").type(WorldType.FLAT).generateStructures(false).createWorld(); + if (flatWorld == null) return; + flatWorld.setSpawnFlags(false, false); + disableGameRuleInFlatWorld("doMobSpawning"); + disableGameRuleInFlatWorld("doTraderSpawning"); + disableGameRuleInFlatWorld("doWeatherCycle"); + disableGameRuleInFlatWorld("doDaylightCycle"); + disableGameRuleInFlatWorld("disableRaids"); + disableGameRuleInFlatWorld("mobGriefing"); + + } catch (Exception ex) { + Logger.error("Could not load extra world!", ex); + Logger.error("Probably the server version or server system was changed and the old world is not compatible with it"); + Logger.error("Please delete all worlds and try again!"); + return; + } + + teleportPlayersOutOfExtraWorld(); + } + + private void teleportPlayersOutOfExtraWorld() { + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.getWorld() != flatWorld) continue; + + Location location = player.getRespawnLocation(); + if (location == null) { + World world = Bukkit.getWorld(levelName); + if (world == null) { + world = ChallengeAPI.getGameWorld(Environment.NORMAL); + } + location = world.getSpawnLocation(); + } + + player.teleport(location); + } + } + + @SuppressWarnings("unchecked") + private void disableGameRuleInFlatWorld(@Nonnull String name) { + GameRule gamerule = (GameRule) GameRule.getByName(name); + if (gamerule == null) return; + flatWorld.setGameRule(gamerule, false); + } + + private void executeWorldResetIfNecessary() { + if (Challenges.getInstance().getConfigManager().getSessionConfig().getBoolean("reset")) + executeWorldReset(); + } + + public void executeWorldReset() { + FileDocument sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); + boolean seedReset = sessionConfig.getBoolean("seed-reset"); + + Logger.info("Deleting worlds.."); + + for (String world : worlds) { + deleteWorld(world); + if (seedReset) { + copyPreGeneratedWorld(world); + } else { + deletePreGeneratedWorld(world); + } + } + + for (String world : Challenges.getInstance().getGameWorldStorage().getCustomGeneratedGameWorlds()) { + deleteWorld(world); + } + + sessionConfig.set("reset", false); + sessionConfig.set("seed-reset", false); + sessionConfig.save(); + + } + + private void deleteWorld(@Nonnull String name) { + File folder = new File(Bukkit.getWorldContainer(), name); + FileUtils.deleteWorldFolder(folder); + Logger.info("Deleted world {}", name); + } + + private void copyPreGeneratedWorld(@Nonnull String name) { + File source = new File(Bukkit.getWorldContainer(), customSeedWorldPrefix + name); + if (!source.exists() || !source.isDirectory()) { + Logger.warn("Custom seed world '{}' does not exist!", name); + return; + } + + File target = new File(Bukkit.getWorldContainer(), name); + try { + copy(source, target); + Logger.debug("Copied pre generated custom seed world {}", name); + } catch (IOException ex) { + Logger.error("Unable to copy pre generated custom seed world {}", name, ex); + } + } + + private void deletePreGeneratedWorld(@Nonnull String name) { + File source = new File(Bukkit.getWorldContainer(), customSeedWorldPrefix + name); + if (!source.exists() || !source.isDirectory()) return; + + FileUtils.deleteWorldFolder(source); + Logger.debug("Deleted pre generated custom seed world {}", name); + } + + public void copy(@Nonnull File source, @Nonnull File target) throws IOException { + if (source.isDirectory()) { + copyDirectory(source, target); + } else { + copyFile(source, target); + } + } + + private void copyDirectory(@Nonnull File source, @Nonnull File target) throws IOException { + if (!target.exists()) { + if (!target.mkdir()) { + return; + } + } + + String[] list = source.list(); + if (list == null) return; + for (String child : list) { + if ("session.lock".equals(child)) continue; + copy(new File(source, child), new File(target, child)); + } + } + + private void copyFile(@Nonnull File source, @Nonnull File target) throws IOException { + try (InputStream in = Files.newInputStream(source.toPath()); OutputStream out = Files.newOutputStream(target.toPath())) { + byte[] buf = new byte[1024]; + int length; + while ((length = in.read(buf)) > 0) + out.write(buf, 0, length); + } + } + + private void stopServerNow() { + if (!restartOnReset) { + Bukkit.shutdown(); + return; + } + + try { + Bukkit.spigot().restart(); + } catch (NoSuchMethodError ex) { + Bukkit.shutdown(); + } + } + + public void setWorldInUse(boolean worldInUse) { + this.worldInUse = worldInUse; + if (worldInUse) { + cachePlayerData(); + } else { + settings = new WorldSettings(); + restorePlayerData(); + } + } + + private void cachePlayerData() { + Bukkit.getOnlinePlayers().forEach(this::cachePlayerData); + } + + public void cachePlayerData(@Nonnull Player player) { + playerData.put(player.getUniqueId(), new PlayerData(player)); + } + + public void restorePlayerData() { + Bukkit.getOnlinePlayers().forEach(this::restorePlayerData); + } + + public void restorePlayerData(@Nonnull Player player) { + PlayerData data = playerData.remove(player.getUniqueId()); + if (data == null) return; + data.apply(player); + } + + public boolean hasPlayerData(@Nonnull Player player) { + return playerData.containsKey(player.getUniqueId()); + } + + @Nonnull + public World getExtraWorld() { + return flatWorld; + } + + @Nonnull + public WorldSettings getSettings() { + return settings; + } - Document seedConfig = pluginConfig.getDocument("custom-seed"); - useCustomSeed = seedConfig.getBoolean("config"); - customSeed = seedConfig.getLong("seed"); - - Document sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); - levelName = sessionConfig.getString("level-name", "world"); - worlds = new String[]{ - levelName, - levelName + "_nether", - levelName + "_the_end" - }; - } - - public void load() { - executeWorldResetIfNecessary(); - } - - public void enable() { - loadExtraWorld(); - } - - public void prepareWorldReset(@Nullable CommandSender requestedBy) { - prepareWorldReset(requestedBy, customSeed); - } - - public void prepareWorldReset(@Nullable CommandSender requestedBy, @Nullable Long seed) { - if (seed == null && useCustomSeed) seed = customSeed; - if (seed != null) useCustomSeed = true; - - shutdownBecauseOfReset = true; - ChallengeAPI.pauseTimer(false); - - // Stop all tasks to prevent them from overwriting configs - Challenges.getInstance().getScheduler().stop(); - - resetConfigs(); - - String requester = requestedBy instanceof Player ? NameHelper.getName((Player) requestedBy) : "§4§lConsole"; - String kickMessage = Message.forName("server-reset").asString(requester); - Bukkit.getOnlinePlayers().forEach(player -> player.kickPlayer(kickMessage)); - - if (seed != null) { - generateCustomSeedWorlds(seed); - } - - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), this::stopServerNow, 3); - - } - - private void generateCustomSeedWorlds(long seed) { - - Logger.debug("Generating custom seed worlds with seed " + seed); - for (String name : worlds) { - - World world = Bukkit.getWorld(name); - if (world == null) { - Logger.error("Could not find world {}", name); - continue; - } - - String newWorldName = customSeedWorldPrefix + name; - File folder = new File(Bukkit.getWorldContainer(), newWorldName); - if (folder.exists()) FileUtils.deleteWorldFolder(folder); - - WorldCreator creator = new WorldCreator(newWorldName).seed(seed).environment(world.getEnvironment()); - creator.createWorld(); - - Logger.debug("Created custom seed world {}", newWorldName); - - } - - } - - private void resetConfigs() { - - FileDocument sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); - sessionConfig.clear(); - sessionConfig.set("reset", true); - sessionConfig.set("seed-reset", useCustomSeed); - if (!Bukkit.getWorlds().isEmpty()) { - sessionConfig.set("level-name", ChallengeAPI.getGameWorld(Environment.NORMAL).getName()); - } - sessionConfig.save(); - - FileDocument gamestateConfig = Challenges.getInstance().getConfigManager().getGamestateConfig(); - gamestateConfig.clear(); - gamestateConfig.save(); - - } - - private void loadExtraWorld() { - if (!Challenges.getInstance().isReloaded()) - deleteWorld("challenges-extra"); - - try { - flatWorld = new WorldCreator("challenges-extra").type(WorldType.FLAT).generateStructures(false).createWorld(); - if (flatWorld == null) return; - flatWorld.setSpawnFlags(false, false); - disableGameRuleInFlatWorld("doMobSpawning"); - disableGameRuleInFlatWorld("doTraderSpawning"); - disableGameRuleInFlatWorld("doWeatherCycle"); - disableGameRuleInFlatWorld("doDaylightCycle"); - disableGameRuleInFlatWorld("disableRaids"); - disableGameRuleInFlatWorld("mobGriefing"); - - } catch (Exception ex) { - Logger.error("Could not load extra world!", ex); - Logger.error("Probably the server version or server system was changed and the old world is not compatible with it"); - Logger.error("Please delete all worlds and try again!"); - return; - } - - teleportPlayersOutOfExtraWorld(); - } - - private void teleportPlayersOutOfExtraWorld() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.getWorld() != flatWorld) continue; - - Location location = player.getRespawnLocation(); - if (location == null) { - World world = Bukkit.getWorld(levelName); - if (world == null) { - world = ChallengeAPI.getGameWorld(Environment.NORMAL); - } - location = world.getSpawnLocation(); - } - - player.teleport(location); - } - } - - @SuppressWarnings("unchecked") - private void disableGameRuleInFlatWorld(@Nonnull String name) { - GameRule gamerule = (GameRule) GameRule.getByName(name); - if (gamerule == null) return; - flatWorld.setGameRule(gamerule, false); - } - - private void executeWorldResetIfNecessary() { - if (Challenges.getInstance().getConfigManager().getSessionConfig().getBoolean("reset")) - executeWorldReset(); - } - - public void executeWorldReset() { - FileDocument sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); - boolean seedReset = sessionConfig.getBoolean("seed-reset"); - - Logger.info("Deleting worlds.."); - - for (String world : worlds) { - deleteWorld(world); - if (seedReset) { - copyPreGeneratedWorld(world); - } else { - deletePreGeneratedWorld(world); - } - } - - for (String world : Challenges.getInstance().getGameWorldStorage().getCustomGeneratedGameWorlds()) { - deleteWorld(world); - } - - sessionConfig.set("reset", false); - sessionConfig.set("seed-reset", false); - sessionConfig.save(); - - } - - private void deleteWorld(@Nonnull String name) { - File folder = new File(Bukkit.getWorldContainer(), name); - FileUtils.deleteWorldFolder(folder); - Logger.info("Deleted world {}", name); - } - - private void copyPreGeneratedWorld(@Nonnull String name) { - File source = new File(Bukkit.getWorldContainer(), customSeedWorldPrefix + name); - if (!source.exists() || !source.isDirectory()) { - Logger.warn("Custom seed world '{}' does not exist!", name); - return; - } - - File target = new File(Bukkit.getWorldContainer(), name); - try { - copy(source, target); - Logger.debug("Copied pre generated custom seed world {}", name); - } catch (IOException ex) { - Logger.error("Unable to copy pre generated custom seed world {}", name, ex); - } - } - - private void deletePreGeneratedWorld(@Nonnull String name) { - File source = new File(Bukkit.getWorldContainer(), customSeedWorldPrefix + name); - if (!source.exists() || !source.isDirectory()) return; - - FileUtils.deleteWorldFolder(source); - Logger.debug("Deleted pre generated custom seed world {}", name); - } - - public void copy(@Nonnull File source, @Nonnull File target) throws IOException { - if (source.isDirectory()) { - copyDirectory(source, target); - } else { - copyFile(source, target); - } - } - - private void copyDirectory(@Nonnull File source, @Nonnull File target) throws IOException { - if (!target.exists()) { - if (!target.mkdir()) { - return; - } - } - - String[] list = source.list(); - if (list == null) return; - for (String child : list) { - if ("session.lock".equals(child)) continue; - copy(new File(source, child), new File(target, child)); - } - } - - private void copyFile(@Nonnull File source, @Nonnull File target) throws IOException { - try (InputStream in = Files.newInputStream(source.toPath()); OutputStream out = Files.newOutputStream(target.toPath())) { - byte[] buf = new byte[1024]; - int length; - while ((length = in.read(buf)) > 0) - out.write(buf, 0, length); - } - } - - private void stopServerNow() { - if (!restartOnReset) { - Bukkit.shutdown(); - return; - } - - try { - Bukkit.spigot().restart(); - } catch (NoSuchMethodError ex) { - Bukkit.shutdown(); - } - } - - public void setWorldInUse(boolean worldInUse) { - this.worldInUse = worldInUse; - if (worldInUse) { - cachePlayerData(); - } else { - settings = new WorldSettings(); - restorePlayerData(); - } - } - - private void cachePlayerData() { - Bukkit.getOnlinePlayers().forEach(this::cachePlayerData); - } - - public void cachePlayerData(@Nonnull Player player) { - playerData.put(player.getUniqueId(), new PlayerData(player)); - } - - public void restorePlayerData() { - Bukkit.getOnlinePlayers().forEach(this::restorePlayerData); - } - - public void restorePlayerData(@Nonnull Player player) { - PlayerData data = playerData.remove(player.getUniqueId()); - if (data == null) return; - data.apply(player); - } - - public boolean hasPlayerData(@Nonnull Player player) { - return playerData.containsKey(player.getUniqueId()); - } - - @Nonnull - public World getExtraWorld() { - return flatWorld; - } - - @Nonnull - public WorldSettings getSettings() { - return settings; - } - - @Setter + @Setter @Getter public static class WorldSettings { - private boolean placeBlocks = false; - private boolean destroyBlocks = false; - private boolean dropItems = false; - private boolean pickupItems = false; + private boolean placeBlocks = false; + private boolean destroyBlocks = false; + private boolean dropItems = false; + private boolean pickupItems = false; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java index 90158fe5f..5cd463aa5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java @@ -21,132 +21,132 @@ public final class ChallengeBossBar { - private final Map bossbars = new ConcurrentHashMap<>(); - private BiConsumer content = (bossbar, player) -> { - }; - - private BossBar createBossbar(@Nonnull BossBarInstance instance) { - BossBar bossbar = Bukkit.createBossBar(instance.title.toPlainText(), instance.color, instance.style); - bossbar.setProgress(instance.progress); - return bossbar; - } - - private void apply(@Nonnull BossBar bossbar, @Nonnull BossBarInstance instance) { - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_20_5)) { - bossbar.setTitle(instance.title.toPlainText()); - } else { - NMSUtils.setBossBarTitle(bossbar, instance.title); - } - bossbar.setColor(instance.color); - bossbar.setStyle(instance.style); - bossbar.setProgress(instance.progress); - bossbar.setVisible(instance.visible); - } - - public void setContent(@Nonnull BiConsumer content) { - this.content = content; - } - - public void applyHide(@Nonnull Player player) { - BossBar bossbar = bossbars.get(player); - if (bossbar == null) return; - bossbar.removePlayer(player); - } - - public void update() { - Bukkit.getOnlinePlayers().forEach(this::update); - } - - public void update(@Nonnull Player player) { - if (!isShown()) { - Logger.warn("Tried to update bossbar which is not shown"); - return; - } - - try { - - BossBarInstance instance = new BossBarInstance(); - - if (ChallengeAPI.isPaused()) { - instance.setTitle(Message.forName("bossbar-timer-paused").asString()); - instance.setColor(BarColor.RED); - } else { - content.accept(instance, player); - } - - - BossBar bossbar = bossbars.computeIfAbsent(player, key -> createBossbar(instance)); - apply(bossbar, instance); - - if (!bossbar.getPlayers().contains(player)) - bossbar.addPlayer(player); - - } catch (Exception ex) { - Logger.error("Unable to update bossbar for player '{}'", player.getName(), ex); - } - } - - public void show() { - Challenges.getInstance().getScoreboardManager().showBossBar(this); - } - - public void hide() { - Challenges.getInstance().getScoreboardManager().hideBossBar(this); - } - - public boolean isShown() { - return Challenges.getInstance().getScoreboardManager().isShown(this); - } - - public static final class BossBarInstance { - - private BaseComponent title = new TextComponent(); - private double progress = 1; - private BarColor color = BarColor.WHITE; - private BarStyle style = BarStyle.SOLID; - private boolean visible = true; - - private BossBarInstance() { - } - - @Nonnull - public BossBarInstance setTitle(@Nonnull String title) { - this.title = new TextComponent(title); - return this; - } - - @Nonnull - public BossBarInstance setTitle(@Nonnull BaseComponent title) { - this.title = title; - return this; - } - - @Nonnull - public BossBarInstance setProgress(double progress) { - if (progress < 0 || progress > 1) - throw new IllegalArgumentException("Progress must be between 0 and 1; Got " + progress); - this.progress = progress; - return this; - } - - @Nonnull - public BossBarInstance setColor(@Nonnull BarColor color) { - this.color = color; - return this; - } - - @Nonnull - public BossBarInstance setStyle(@Nonnull BarStyle style) { - this.style = style; - return this; - } - - @Nonnull - public BossBarInstance setVisible(boolean visible) { - this.visible = visible; - return this; - } - - } + private final Map bossbars = new ConcurrentHashMap<>(); + private BiConsumer content = (bossbar, player) -> { + }; + + private BossBar createBossbar(@Nonnull BossBarInstance instance) { + BossBar bossbar = Bukkit.createBossBar(instance.title.toPlainText(), instance.color, instance.style); + bossbar.setProgress(instance.progress); + return bossbar; + } + + private void apply(@Nonnull BossBar bossbar, @Nonnull BossBarInstance instance) { + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_20_5)) { + bossbar.setTitle(instance.title.toPlainText()); + } else { + NMSUtils.setBossBarTitle(bossbar, instance.title); + } + bossbar.setColor(instance.color); + bossbar.setStyle(instance.style); + bossbar.setProgress(instance.progress); + bossbar.setVisible(instance.visible); + } + + public void setContent(@Nonnull BiConsumer content) { + this.content = content; + } + + public void applyHide(@Nonnull Player player) { + BossBar bossbar = bossbars.get(player); + if (bossbar == null) return; + bossbar.removePlayer(player); + } + + public void update() { + Bukkit.getOnlinePlayers().forEach(this::update); + } + + public void update(@Nonnull Player player) { + if (!isShown()) { + Logger.warn("Tried to update bossbar which is not shown"); + return; + } + + try { + + BossBarInstance instance = new BossBarInstance(); + + if (ChallengeAPI.isPaused()) { + instance.setTitle(Message.forName("bossbar-timer-paused").asString()); + instance.setColor(BarColor.RED); + } else { + content.accept(instance, player); + } + + + BossBar bossbar = bossbars.computeIfAbsent(player, key -> createBossbar(instance)); + apply(bossbar, instance); + + if (!bossbar.getPlayers().contains(player)) + bossbar.addPlayer(player); + + } catch (Exception ex) { + Logger.error("Unable to update bossbar for player '{}'", player.getName(), ex); + } + } + + public void show() { + Challenges.getInstance().getScoreboardManager().showBossBar(this); + } + + public void hide() { + Challenges.getInstance().getScoreboardManager().hideBossBar(this); + } + + public boolean isShown() { + return Challenges.getInstance().getScoreboardManager().isShown(this); + } + + public static final class BossBarInstance { + + private BaseComponent title = new TextComponent(); + private double progress = 1; + private BarColor color = BarColor.WHITE; + private BarStyle style = BarStyle.SOLID; + private boolean visible = true; + + private BossBarInstance() { + } + + @Nonnull + public BossBarInstance setTitle(@Nonnull String title) { + this.title = new TextComponent(title); + return this; + } + + @Nonnull + public BossBarInstance setTitle(@Nonnull BaseComponent title) { + this.title = title; + return this; + } + + @Nonnull + public BossBarInstance setProgress(double progress) { + if (progress < 0 || progress > 1) + throw new IllegalArgumentException("Progress must be between 0 and 1; Got " + progress); + this.progress = progress; + return this; + } + + @Nonnull + public BossBarInstance setColor(@Nonnull BarColor color) { + this.color = color; + return this; + } + + @Nonnull + public BossBarInstance setStyle(@Nonnull BarStyle style) { + this.style = style; + return this; + } + + @Nonnull + public BossBarInstance setVisible(boolean visible) { + this.visible = visible; + return this; + } + + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java index 78f5e5b2b..2df8a1d38 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java @@ -20,130 +20,130 @@ public final class ChallengeScoreboard { - private final Map objectives = new ConcurrentHashMap<>(); - private BiConsumer content = (scoreboard, player) -> { - }; - - public void setContent(@Nonnull BiConsumer content) { - this.content = content; - } - - public void applyHide(@Nonnull Player player) { - unregister(objectives.remove(player)); - } - - public void update() { - for (Player player : new LinkedList<>(Bukkit.getOnlinePlayers())) { - update(player); - } - } - - public void update(@Nonnull Player player) { - if (!isShown()) { - Logger.warn("Tried to update scoreboard which is not shown"); - return; - } - - try { - if (objectives.containsKey(player)) { - unregister(objectives.remove(player)); - } - - ScoreboardInstance instance = new ScoreboardInstance(); - content.accept(instance, player); - - Collection lines = instance.getLines(); - if (lines.isEmpty()) { - return; - } - - Scoreboard scoreboard = player.getScoreboard(); - if (Bukkit.getScoreboardManager() == null) { - return; - } - if (scoreboard == Bukkit.getScoreboardManager().getMainScoreboard()) { - player.setScoreboard(scoreboard = Bukkit.getScoreboardManager().getNewScoreboard()); - } - - String name = String.valueOf(player.getUniqueId().hashCode()); - // Unregister any old objective existing - Objective objective1 = scoreboard.getObjective(name); - if (objective1 != null) { - unregister(objective1); - } - - Objective objective = scoreboard.registerNewObjective(name, "dummy", String.valueOf(instance.getTitle())); - int score = lines.size(); - for (String line : lines) { - if (line.isEmpty()) line = StringUtils.repeat(' ', score + 1); - score--; - objective.getScore(line).setScore(score); - } - - objective.setDisplaySlot(DisplaySlot.SIDEBAR); - objectives.put(player, objective); - - } catch (Exception ex) { - Logger.error("Unable to update scoreboard for player '{}'", player.getName(), ex); - } - } - - public void show() { - Challenges.getInstance().getScoreboardManager().setCurrentScoreboard(this); - } - - public void hide() { - if (Challenges.getInstance().getScoreboardManager().getCurrentScoreboard() != this) return; - Challenges.getInstance().getScoreboardManager().setCurrentScoreboard(null); - } - - public boolean isShown() { - return Challenges.getInstance().getScoreboardManager().isShown(this); - } - - private void unregister(@Nullable Objective objective) { - try { - if (objective == null) return; - objective.unregister(); - } catch (Exception ex) { - Logger.error("Unable to unregister objective " + objective.getName()); - } - } - - @ToString - public static final class ScoreboardInstance { - - private final String[] lines = new String[15]; - @Getter - private String title = Message.forName("scoreboard-title").asString(); - private int linesIndex = 0; - - private ScoreboardInstance() { - } - - @Nonnull - public ScoreboardInstance addLine(@Nonnull String text) { - if (linesIndex >= lines.length) - throw new IllegalStateException("All lines are already used! (" + lines.length + ")"); - lines[linesIndex++] = text; - return this; - } - - @Nonnull - public Collection getLines() { - List list = new ArrayList<>(); - for (String line : lines) { - if (line == null) continue; - list.add(line); - } - return list; - } - - @Nonnull - public ScoreboardInstance setTitle(@Nonnull String title) { - this.title = title; - return this; - } - } + private final Map objectives = new ConcurrentHashMap<>(); + private BiConsumer content = (scoreboard, player) -> { + }; + + public void setContent(@Nonnull BiConsumer content) { + this.content = content; + } + + public void applyHide(@Nonnull Player player) { + unregister(objectives.remove(player)); + } + + public void update() { + for (Player player : new LinkedList<>(Bukkit.getOnlinePlayers())) { + update(player); + } + } + + public void update(@Nonnull Player player) { + if (!isShown()) { + Logger.warn("Tried to update scoreboard which is not shown"); + return; + } + + try { + if (objectives.containsKey(player)) { + unregister(objectives.remove(player)); + } + + ScoreboardInstance instance = new ScoreboardInstance(); + content.accept(instance, player); + + Collection lines = instance.getLines(); + if (lines.isEmpty()) { + return; + } + + Scoreboard scoreboard = player.getScoreboard(); + if (Bukkit.getScoreboardManager() == null) { + return; + } + if (scoreboard == Bukkit.getScoreboardManager().getMainScoreboard()) { + player.setScoreboard(scoreboard = Bukkit.getScoreboardManager().getNewScoreboard()); + } + + String name = String.valueOf(player.getUniqueId().hashCode()); + // Unregister any old objective existing + Objective objective1 = scoreboard.getObjective(name); + if (objective1 != null) { + unregister(objective1); + } + + Objective objective = scoreboard.registerNewObjective(name, "dummy", String.valueOf(instance.getTitle())); + int score = lines.size(); + for (String line : lines) { + if (line.isEmpty()) line = StringUtils.repeat(' ', score + 1); + score--; + objective.getScore(line).setScore(score); + } + + objective.setDisplaySlot(DisplaySlot.SIDEBAR); + objectives.put(player, objective); + + } catch (Exception ex) { + Logger.error("Unable to update scoreboard for player '{}'", player.getName(), ex); + } + } + + public void show() { + Challenges.getInstance().getScoreboardManager().setCurrentScoreboard(this); + } + + public void hide() { + if (Challenges.getInstance().getScoreboardManager().getCurrentScoreboard() != this) return; + Challenges.getInstance().getScoreboardManager().setCurrentScoreboard(null); + } + + public boolean isShown() { + return Challenges.getInstance().getScoreboardManager().isShown(this); + } + + private void unregister(@Nullable Objective objective) { + try { + if (objective == null) return; + objective.unregister(); + } catch (Exception ex) { + Logger.error("Unable to unregister objective " + objective.getName()); + } + } + + @ToString + public static final class ScoreboardInstance { + + private final String[] lines = new String[15]; + @Getter + private String title = Message.forName("scoreboard-title").asString(); + private int linesIndex = 0; + + private ScoreboardInstance() { + } + + @Nonnull + public ScoreboardInstance addLine(@Nonnull String text) { + if (linesIndex >= lines.length) + throw new IllegalStateException("All lines are already used! (" + lines.length + ")"); + lines[linesIndex++] = text; + return this; + } + + @Nonnull + public Collection getLines() { + List list = new ArrayList<>(); + for (String line : lines) { + if (line == null) continue; + list.add(line); + } + return list; + } + + @Nonnull + public ScoreboardInstance setTitle(@Nonnull String title) { + this.title = title; + return this; + } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java index 1fec51752..1768554da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java @@ -7,44 +7,44 @@ public enum Statistic { - DRAGON_KILLED(Display.INTEGER), - DEATHS(Display.INTEGER), - DAMAGE_TAKEN(Display.HEARTS), - ENTITY_KILLS(Display.INTEGER), - DAMAGE_DEALT(Display.HEARTS), - BLOCKS_MINED(Display.INTEGER), - BLOCKS_PLACED(Display.INTEGER), - BLOCKS_TRAVELED(Display.INTEGER), - CHALLENGES_PLAYED(Display.INTEGER), - JUMPS(Display.INTEGER); + DRAGON_KILLED(Display.INTEGER), + DEATHS(Display.INTEGER), + DAMAGE_TAKEN(Display.HEARTS), + ENTITY_KILLS(Display.INTEGER), + DAMAGE_DEALT(Display.HEARTS), + BLOCKS_MINED(Display.INTEGER), + BLOCKS_PLACED(Display.INTEGER), + BLOCKS_TRAVELED(Display.INTEGER), + CHALLENGES_PLAYED(Display.INTEGER), + JUMPS(Display.INTEGER); - private final Display display; + private final Display display; - Statistic(@Nonnull Display display) { - this.display = display; - } + Statistic(@Nonnull Display display) { + this.display = display; + } - @Nonnull - public String formatChat(double value) { - return display.formatChat(value); - } + @Nonnull + public String formatChat(double value) { + return display.formatChat(value); + } - public enum Display { + public enum Display { - HEARTS(value -> NumberFormatter.BIG_NUMBER.format(value / 2) + " §c❤"), - INTEGER(NumberFormatter.BIG_NUMBER::format); + HEARTS(value -> NumberFormatter.BIG_NUMBER.format(value / 2) + " §c❤"), + INTEGER(NumberFormatter.BIG_NUMBER::format); - private final Function chatFormat; + private final Function chatFormat; - Display(@Nonnull Function chatFormat) { - this.chatFormat = chatFormat; - } + Display(@Nonnull Function chatFormat) { + this.chatFormat = chatFormat; + } - @Nonnull - public String formatChat(double value) { - return chatFormat.apply(value); - } + @Nonnull + public String formatChat(double value) { + return chatFormat.apply(value); + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java index b4f4d9c6b..a38572dc3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java @@ -25,161 +25,161 @@ public final class StatsManager implements Listener { - @Getter + @Getter private final boolean enabled, noStatsAfterCheating; - private final Map cache = new ConcurrentHashMap<>(); - - private List cachedLeaderboard; - private long leaderboardCacheTimestamp; - - public StatsManager() { - enabled = Challenges.getInstance().getConfigDocument().getBoolean("save-player-stats"); - noStatsAfterCheating = enabled && Challenges.getInstance().getConfigDocument().getBoolean("no-stats-after-cheating"); - } - - @Nonnull - public static Comparator getStatsComparator(@Nonnull Statistic statistic) { - return Comparator.comparingDouble(value -> value.getStatisticValue(statistic)).reversed(); - } - - public void register() { - if (enabled) { - StatsListener listener = new StatsListener(); - ChallengeAPI.registerScheduler(this, listener); - Challenges.getInstance().registerListener(this, listener); - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onLeave(@Nonnull PlayerQuitEvent event) { - PlayerStats cached = cache.remove(event.getPlayer().getUniqueId()); - if (cached == null) return; - store(event.getPlayer().getUniqueId(), cached); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onJoin(@Nonnull PlayerJoinEvent event) { - getStats(event.getPlayer()); // Cache stats - } - - @ScheduledTask(ticks = 30 * 20, challengePolicy = ChallengeStatusPolicy.ALWAYS) - public void storeCached() { - for (Entry entry : cache.entrySet()) { - store(entry.getKey(), entry.getValue()); - } - } - - private void store(@Nonnull UUID uuid, @Nonnull PlayerStats stats) { - try { - Challenges.getInstance().getDatabaseManager().getDatabase() - .insertOrUpdate("challenges") - .where("uuid", uuid) - .set("stats", stats.asDocument()) - .execute(); - Logger.debug("Saved stats for {}: {}", uuid, stats); - } catch (DatabaseException ex) { - Logger.error("Could not save player stats for {}", uuid, ex); - } - } - - @Nonnull - public PlayerStats getStats(@Nonnull Player player) { - return getStats(player.getUniqueId(), player.getName()); - } - - @Nonnull - public PlayerStats getStats(@Nonnull UUID uuid, @Nonnull String name) { - PlayerStats cached = cache.get(uuid); - if (cached != null) return cached; - - try { - PlayerStats stats = getStatsFromDatabase(uuid, name); - if (Bukkit.getPlayer(uuid) != null) { - cache.put(uuid, stats); - Logger.debug("Loaded stats for uuid {}: {}", uuid, stats); - } - return stats; - } catch (DatabaseException ex) { - Logger.error("Could not get player stats for {}", uuid, ex); - return new PlayerStats(uuid, name); - } - } - - @Nonnull - private PlayerStats getStatsFromDatabase(@Nonnull UUID uuid, @Nonnull String name) throws DatabaseException { - return Challenges.getInstance().getDatabaseManager().getDatabase() - .query("challenges") - .select("stats", "name") - .where("uuid", uuid) - .execute().first() - .map(result -> new PlayerStats(uuid, Objects.requireNonNull(result.getString("name")), result.getDocument("stats"))) - .orElse(new PlayerStats(uuid, name)); - } - - @Nonnull - private List getAllStats() throws DatabaseException { - if (cachedLeaderboard != null && System.currentTimeMillis() - leaderboardCacheTimestamp < 3 * 60 * 1000) { - return cachedLeaderboard; - } - - leaderboardCacheTimestamp = System.currentTimeMillis(); - return cachedLeaderboard = getAllStats0(); - } - - @Nonnull - private List getAllStats0() throws DatabaseException { - return Challenges.getInstance().getDatabaseManager().getDatabase() - .query("challenges") - .select("uuid", "stats", "name") - .execute().all() - .filter(result -> result.getUUID("uuid") != null) - .map(result -> new PlayerStats(Objects.requireNonNull(result.getUUID("uuid")), Objects.requireNonNull(result.getString("name")), result.getDocument("stats"))) - .collect(Collectors.toList()); - } - - @Nonnull - public LeaderboardInfo getLeaderboardInfo(@Nonnull UUID uuid) { - try { - List stats = getAllStats(); - LeaderboardInfo info = new LeaderboardInfo(); - for (Statistic statistic : Statistic.values()) { - int place = determineIndex(new ArrayList<>(stats), PlayerStats::getPlayerUUID, uuid, getStatsComparator(statistic)) + 1; - info.setPlace(statistic, place); - } - - return info; - } catch (DatabaseException ex) { - Logger.error("Could not get player leaderboard information for {}", uuid, ex); - return new LeaderboardInfo(); - } - } - - @Nonnull - public List getLeaderboard(@Nonnull Statistic statistic) { - try { - List stats = getAllStats(); - stats.sort(getStatsComparator(statistic)); - return stats; - } catch (Exception ex) { - Logger.error("Could not get leaderboard in {}", statistic, ex); - return new ArrayList<>(); - } - } - - private int determineIndex(@Nonnull List list, @Nonnull Function extractor, @Nonnull U target, @Nonnull Comparator sort) { - list.sort(sort); - int index = 0; - for (T t : list) { - U u = extractor.apply(t); - if (target.equals(u)) return index; - index++; - } - return index; - } + private final Map cache = new ConcurrentHashMap<>(); + + private List cachedLeaderboard; + private long leaderboardCacheTimestamp; + + public StatsManager() { + enabled = Challenges.getInstance().getConfigDocument().getBoolean("save-player-stats"); + noStatsAfterCheating = enabled && Challenges.getInstance().getConfigDocument().getBoolean("no-stats-after-cheating"); + } + + @Nonnull + public static Comparator getStatsComparator(@Nonnull Statistic statistic) { + return Comparator.comparingDouble(value -> value.getStatisticValue(statistic)).reversed(); + } + + public void register() { + if (enabled) { + StatsListener listener = new StatsListener(); + ChallengeAPI.registerScheduler(this, listener); + Challenges.getInstance().registerListener(this, listener); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onLeave(@Nonnull PlayerQuitEvent event) { + PlayerStats cached = cache.remove(event.getPlayer().getUniqueId()); + if (cached == null) return; + store(event.getPlayer().getUniqueId(), cached); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onJoin(@Nonnull PlayerJoinEvent event) { + getStats(event.getPlayer()); // Cache stats + } + + @ScheduledTask(ticks = 30 * 20, challengePolicy = ChallengeStatusPolicy.ALWAYS) + public void storeCached() { + for (Entry entry : cache.entrySet()) { + store(entry.getKey(), entry.getValue()); + } + } + + private void store(@Nonnull UUID uuid, @Nonnull PlayerStats stats) { + try { + Challenges.getInstance().getDatabaseManager().getDatabase() + .insertOrUpdate("challenges") + .where("uuid", uuid) + .set("stats", stats.asDocument()) + .execute(); + Logger.debug("Saved stats for {}: {}", uuid, stats); + } catch (DatabaseException ex) { + Logger.error("Could not save player stats for {}", uuid, ex); + } + } + + @Nonnull + public PlayerStats getStats(@Nonnull Player player) { + return getStats(player.getUniqueId(), player.getName()); + } + + @Nonnull + public PlayerStats getStats(@Nonnull UUID uuid, @Nonnull String name) { + PlayerStats cached = cache.get(uuid); + if (cached != null) return cached; + + try { + PlayerStats stats = getStatsFromDatabase(uuid, name); + if (Bukkit.getPlayer(uuid) != null) { + cache.put(uuid, stats); + Logger.debug("Loaded stats for uuid {}: {}", uuid, stats); + } + return stats; + } catch (DatabaseException ex) { + Logger.error("Could not get player stats for {}", uuid, ex); + return new PlayerStats(uuid, name); + } + } + + @Nonnull + private PlayerStats getStatsFromDatabase(@Nonnull UUID uuid, @Nonnull String name) throws DatabaseException { + return Challenges.getInstance().getDatabaseManager().getDatabase() + .query("challenges") + .select("stats", "name") + .where("uuid", uuid) + .execute().first() + .map(result -> new PlayerStats(uuid, Objects.requireNonNull(result.getString("name")), result.getDocument("stats"))) + .orElse(new PlayerStats(uuid, name)); + } + + @Nonnull + private List getAllStats() throws DatabaseException { + if (cachedLeaderboard != null && System.currentTimeMillis() - leaderboardCacheTimestamp < 3 * 60 * 1000) { + return cachedLeaderboard; + } + + leaderboardCacheTimestamp = System.currentTimeMillis(); + return cachedLeaderboard = getAllStats0(); + } + + @Nonnull + private List getAllStats0() throws DatabaseException { + return Challenges.getInstance().getDatabaseManager().getDatabase() + .query("challenges") + .select("uuid", "stats", "name") + .execute().all() + .filter(result -> result.getUUID("uuid") != null) + .map(result -> new PlayerStats(Objects.requireNonNull(result.getUUID("uuid")), Objects.requireNonNull(result.getString("name")), result.getDocument("stats"))) + .collect(Collectors.toList()); + } + + @Nonnull + public LeaderboardInfo getLeaderboardInfo(@Nonnull UUID uuid) { + try { + List stats = getAllStats(); + LeaderboardInfo info = new LeaderboardInfo(); + for (Statistic statistic : Statistic.values()) { + int place = determineIndex(new ArrayList<>(stats), PlayerStats::getPlayerUUID, uuid, getStatsComparator(statistic)) + 1; + info.setPlace(statistic, place); + } + + return info; + } catch (DatabaseException ex) { + Logger.error("Could not get player leaderboard information for {}", uuid, ex); + return new LeaderboardInfo(); + } + } + + @Nonnull + public List getLeaderboard(@Nonnull Statistic statistic) { + try { + List stats = getAllStats(); + stats.sort(getStatsComparator(statistic)); + return stats; + } catch (Exception ex) { + Logger.error("Could not get leaderboard in {}", statistic, ex); + return new ArrayList<>(); + } + } + + private int determineIndex(@Nonnull List list, @Nonnull Function extractor, @Nonnull U target, @Nonnull Comparator sort) { + list.sort(sort); + int index = 0; + for (T t : list) { + U u = extractor.apply(t); + if (target.equals(u)) return index; + index++; + } + return index; + } public boolean hasDatabaseConnection() { - return Challenges.getInstance().getDatabaseManager().getDatabase() != null && Challenges.getInstance().getDatabaseManager().isConnected(); - } + return Challenges.getInstance().getDatabaseManager().getDatabase() != null && Challenges.getInstance().getDatabaseManager().isConnected(); + } } From bf60b8abc325dc18d87d63c8d6ccdda2e1ec4572 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 18 Apr 2025 12:47:16 +0200 Subject: [PATCH 052/119] fix: package --- .../plugin/utils/bukkit/misc/Version/MinecraftVersion.java | 2 +- .../challenges/plugin/utils/bukkit/misc/Version/Version.java | 2 +- .../plugin/utils/bukkit/misc/Version/VersionComparator.java | 2 +- .../plugin/utils/bukkit/misc/Version/VersionInfo.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java index 65c5b4e43..2077593a8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; +package net.codingarea.challenges.plugin.utils.bukkit.misc.version; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java index 17f4ddeae..e21567f10 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; +package net.codingarea.challenges.plugin.utils.bukkit.misc.version; import net.anweisen.utilities.common.annotations.Since; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java index 93cc33322..3f937009f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; +package net.codingarea.challenges.plugin.utils.bukkit.misc.version; import javax.annotation.Nonnull; import java.util.Comparator; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java index 3bd2f5b33..af9f78e34 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.Version; +package net.codingarea.challenges.plugin.utils.bukkit.misc.version; import lombok.Getter; import net.anweisen.utilities.common.logging.ILogger; From 629b43ead4bff0e7827b89196054b62ce8f7fd48 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 18 Apr 2025 12:49:55 +0200 Subject: [PATCH 053/119] fix: useParameter --- .../plugin/management/menu/InventoryTitleManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java index 10d59d1a2..3a82767da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java @@ -45,7 +45,7 @@ public static String getTitleSplitter() { @Nonnull public static String getMenuSettingTitle(@Nonnull MenuType menu, @Nonnull String name, int page, boolean showPages) { - return getTitle(menu.getName() + getTitleSplitter() + name + (false ? " §8• " + Message.forName("inventory-color") + (page + 1) : "")); + return getTitle(menu.getName() + getTitleSplitter() + name + (showPages ? " §8• " + Message.forName("inventory-color") + (page + 1) : "")); } @Nonnull From e1961ffa5e0d089d9eca5321aac9d3a807701239 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 18 Apr 2025 13:01:56 +0200 Subject: [PATCH 054/119] feat: team provider --- .../challenges/plugin/Challenges.java | 2 + .../plugin/management/team/CustomTeam.java | 19 +++++++ .../plugin/management/team/PlayerTeam.java | 22 ++++++++ .../plugin/management/team/Team.java | 14 +++++ .../plugin/management/team/TeamProvider.java | 55 +++++++++++++++++++ .../plugin/management/team/TemporaryTeam.java | 4 ++ 6 files changed, 116 insertions(+) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/team/CustomTeam.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/team/PlayerTeam.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/team/Team.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TemporaryTeam.java diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java index 3b8a554d1..c711fe5b1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java @@ -22,6 +22,7 @@ import net.codingarea.challenges.plugin.management.scheduler.timer.ChallengeTimer; import net.codingarea.challenges.plugin.management.server.*; import net.codingarea.challenges.plugin.management.stats.StatsManager; +import net.codingarea.challenges.plugin.management.team.TeamProvider; import net.codingarea.challenges.plugin.spigot.command.*; import net.codingarea.challenges.plugin.spigot.listener.*; import net.codingarea.challenges.plugin.utils.bukkit.command.ForwardingCommand; @@ -53,6 +54,7 @@ public final class Challenges extends BukkitModule { private MetricsLoader metricsLoader; private GameWorldStorage gameWorldStorage; private GeneratorWorldPortalManager generatorWorldPortalManager; + private TeamProvider teamProvider; @Nonnull public static Challenges getInstance() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/CustomTeam.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/CustomTeam.java new file mode 100644 index 000000000..74bfcacda --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/CustomTeam.java @@ -0,0 +1,19 @@ +package net.codingarea.challenges.plugin.management.team; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +import java.util.UUID; + +@Getter +@RequiredArgsConstructor +public class CustomTeam implements Team { + + private final UUID uniqueId; + private final String displayName; + + public CustomTeam(String displayName) { + this(UUID.randomUUID(), displayName); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/PlayerTeam.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/PlayerTeam.java new file mode 100644 index 000000000..a5d819f1e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/PlayerTeam.java @@ -0,0 +1,22 @@ +package net.codingarea.challenges.plugin.management.team; + +import lombok.RequiredArgsConstructor; +import org.bukkit.entity.Player; + +import java.util.UUID; + +@RequiredArgsConstructor +public class PlayerTeam implements Team, TemporaryTeam { + + private final Player player; + + @Override + public UUID getUniqueId() { + return player.getUniqueId(); + } + + @Override + public String getDisplayName() { + return player.getDisplayName(); + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/Team.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/Team.java new file mode 100644 index 000000000..c9d4d14bb --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/Team.java @@ -0,0 +1,14 @@ +package net.codingarea.challenges.plugin.management.team; + +import java.util.UUID; + +public interface Team { + + UUID getUniqueId(); + + /** + * Todo: replace with components + */ + String getDisplayName(); + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java new file mode 100644 index 000000000..778228d9e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java @@ -0,0 +1,55 @@ +package net.codingarea.challenges.plugin.management.team; + +import net.anweisen.utilities.bukkit.utils.logging.Logger; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +public class TeamProvider { + + private final ConcurrentHashMap customTeams = new ConcurrentHashMap<>(); + private final ConcurrentHashMap userTeams = new ConcurrentHashMap<>(); + + public TeamProvider() { + + } + + @NotNull + public Team getTeam(Player player) { + UUID uuid = userTeams.get(player.getUniqueId()); + if (uuid != null) { + Team team = customTeams.get(uuid); + if (team != null) { + return team; + } + } + return new PlayerTeam(player); + } + + public void setTeam(Player player, UUID teamId) { + Team team = customTeams.get(teamId); + if (team instanceof TemporaryTeam) { + userTeams.remove(player.getUniqueId()); + return; + } + userTeams.put(player.getUniqueId(), teamId); + } + + public void registerTeam(Team team) { + if (team instanceof TemporaryTeam) { + Logger.error("Attempted to register a temporary team as a team!"); + return; + } + customTeams.put(team.getUniqueId(), team); + } + + public void unregisterTeam(Team team) { + if (team instanceof TemporaryTeam) { + Logger.error("Attempted to unregister a temporary team!"); + return; + } + customTeams.remove(team.getUniqueId()); + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TemporaryTeam.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TemporaryTeam.java new file mode 100644 index 000000000..368b5aa72 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TemporaryTeam.java @@ -0,0 +1,4 @@ +package net.codingarea.challenges.plugin.management.team; + +public interface TemporaryTeam { +} From 63e2476bc87b91c8a00993b1a78992092aae2cf9 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 18 Apr 2025 13:03:19 +0200 Subject: [PATCH 055/119] fix: instantiate team provider --- .../main/java/net/codingarea/challenges/plugin/Challenges.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java index c711fe5b1..08ba1633e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java @@ -105,6 +105,7 @@ private void createManagers() { titleManager = new TitleManager(); challengeTimer = new ChallengeTimer(); blockDropManager = new BlockDropManager(); + teamProvider = new TeamProvider(); challengeManager = new ChallengeManager(); challengeLoader = new ChallengeLoader(); customChallengesLoader = new CustomChallengesLoader(); @@ -115,7 +116,6 @@ private void createManagers() { metricsLoader = new MetricsLoader(); gameWorldStorage = new GameWorldStorage(); generatorWorldPortalManager = new GeneratorWorldPortalManager(); - } private void loadManagers() { From 806040dc13d87f5042fa2963633e491a5880cd1f Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 18 Apr 2025 13:05:59 +0200 Subject: [PATCH 056/119] feat: team getter by id --- .../challenges/plugin/management/team/TeamProvider.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java index 778228d9e..a9671fba3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java @@ -4,6 +4,7 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -28,6 +29,10 @@ public Team getTeam(Player player) { return new PlayerTeam(player); } + Optional getTeam(UUID uuid) { + return Optional.ofNullable(customTeams.get(uuid)); + } + public void setTeam(Player player, UUID teamId) { Team team = customTeams.get(teamId); if (team instanceof TemporaryTeam) { From 881031d01cee3d1639b477b6fad8911686b40116 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 18 Apr 2025 13:13:59 +0200 Subject: [PATCH 057/119] feat: team members getters --- plugin/pom.xml | 4 +- .../plugin/management/team/CustomTeam.java | 21 ++++++++- .../plugin/management/team/PlayerTeam.java | 16 ++++++- .../management/team/RegisteredTeam.java | 7 +++ .../plugin/management/team/Team.java | 7 +++ .../plugin/management/team/TeamProvider.java | 46 ++++++++++++++----- .../plugin/management/team/TemporaryTeam.java | 4 -- 7 files changed, 85 insertions(+), 20 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/team/RegisteredTeam.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TemporaryTeam.java diff --git a/plugin/pom.xml b/plugin/pom.xml index 76c5becdd..1e1785238 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -129,8 +129,8 @@ maven-compiler-plugin 3.14.0 - 1.8 - 1.8 + 16 + 16 utf-8 diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/CustomTeam.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/CustomTeam.java index 74bfcacda..09eff1885 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/CustomTeam.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/CustomTeam.java @@ -2,18 +2,37 @@ import lombok.Getter; import lombok.RequiredArgsConstructor; +import org.bukkit.entity.Player; +import java.util.LinkedList; +import java.util.List; import java.util.UUID; @Getter @RequiredArgsConstructor -public class CustomTeam implements Team { +public class CustomTeam implements Team, RegisteredTeam { private final UUID uniqueId; private final String displayName; + private TeamProvider provider; + public CustomTeam(String displayName) { this(UUID.randomUUID(), displayName); } + @Override + public void supplyTeamProvider(TeamProvider teamProvider) { + this.provider = teamProvider; + } + + @Override + public List getMembers() { + return provider.getTeamMembers(getUniqueId()); + } + + @Override + public List getOnlineMembers() { + return provider.getOnlineTeamMembers(getUniqueId()); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/PlayerTeam.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/PlayerTeam.java index a5d819f1e..362319ea5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/PlayerTeam.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/PlayerTeam.java @@ -1,12 +1,16 @@ package net.codingarea.challenges.plugin.management.team; +import lombok.Getter; import lombok.RequiredArgsConstructor; import org.bukkit.entity.Player; +import java.util.LinkedList; +import java.util.List; import java.util.UUID; +@Getter @RequiredArgsConstructor -public class PlayerTeam implements Team, TemporaryTeam { +public class PlayerTeam implements Team { private final Player player; @@ -19,4 +23,14 @@ public UUID getUniqueId() { public String getDisplayName() { return player.getDisplayName(); } + + @Override + public List getMembers() { + return new LinkedList<>(List.of(player.getUniqueId())); + } + + @Override + public List getOnlineMembers() { + return new LinkedList<>(List.of(player)); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/RegisteredTeam.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/RegisteredTeam.java new file mode 100644 index 000000000..4379756dc --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/RegisteredTeam.java @@ -0,0 +1,7 @@ +package net.codingarea.challenges.plugin.management.team; + +public interface RegisteredTeam { + + void supplyTeamProvider(TeamProvider teamProvider); + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/Team.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/Team.java index c9d4d14bb..01f0698c4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/Team.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/Team.java @@ -1,5 +1,8 @@ package net.codingarea.challenges.plugin.management.team; +import org.bukkit.entity.Player; + +import java.util.List; import java.util.UUID; public interface Team { @@ -11,4 +14,8 @@ public interface Team { */ String getDisplayName(); + List getMembers(); + + List getOnlineMembers(); + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java index a9671fba3..a79e00ec1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java @@ -4,24 +4,25 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import java.util.LinkedList; +import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; public class TeamProvider { - private final ConcurrentHashMap customTeams = new ConcurrentHashMap<>(); + private final ConcurrentHashMap registeredTeams = new ConcurrentHashMap<>(); private final ConcurrentHashMap userTeams = new ConcurrentHashMap<>(); public TeamProvider() { } - @NotNull - public Team getTeam(Player player) { + public Team getPlayerTeam(Player player) { UUID uuid = userTeams.get(player.getUniqueId()); if (uuid != null) { - Team team = customTeams.get(uuid); + Team team = registeredTeams.get(uuid); if (team != null) { return team; } @@ -29,13 +30,33 @@ public Team getTeam(Player player) { return new PlayerTeam(player); } - Optional getTeam(UUID uuid) { - return Optional.ofNullable(customTeams.get(uuid)); + public List getAllTeams() { + return new LinkedList<>(List.copyOf(registeredTeams.values())); + } + + public List getTeamMembers(UUID teamId) { + Team team = registeredTeams.get(teamId); + if (team == null) { + return new LinkedList<>(); + } + return team.getMembers(); + } + + public List getOnlineTeamMembers(UUID teamId) { + Team team = registeredTeams.get(teamId); + if (team == null) { + return new LinkedList<>(); + } + return team.getOnlineMembers(); + } + + Optional getRegisteredTeam(UUID uuid) { + return Optional.ofNullable(registeredTeams.get(uuid)); } public void setTeam(Player player, UUID teamId) { - Team team = customTeams.get(teamId); - if (team instanceof TemporaryTeam) { + Team team = registeredTeams.get(teamId); + if (!(team instanceof RegisteredTeam)) { userTeams.remove(player.getUniqueId()); return; } @@ -43,18 +64,19 @@ public void setTeam(Player player, UUID teamId) { } public void registerTeam(Team team) { - if (team instanceof TemporaryTeam) { + if (!(team instanceof RegisteredTeam registeredTeam)) { Logger.error("Attempted to register a temporary team as a team!"); return; } - customTeams.put(team.getUniqueId(), team); + registeredTeam.supplyTeamProvider(this); + registeredTeams.put(team.getUniqueId(), team); } public void unregisterTeam(Team team) { - if (team instanceof TemporaryTeam) { + if (!(team instanceof RegisteredTeam)) { Logger.error("Attempted to unregister a temporary team!"); return; } - customTeams.remove(team.getUniqueId()); + registeredTeams.remove(team.getUniqueId()); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TemporaryTeam.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TemporaryTeam.java deleted file mode 100644 index 368b5aa72..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TemporaryTeam.java +++ /dev/null @@ -1,4 +0,0 @@ -package net.codingarea.challenges.plugin.management.team; - -public interface TemporaryTeam { -} From cb52fd967039f4092d4bd1546617ef02635db2c3 Mon Sep 17 00:00:00 2001 From: Dominik Date: Fri, 18 Apr 2025 13:15:10 +0200 Subject: [PATCH 058/119] Update CustomTeam.java --- .../codingarea/challenges/plugin/management/team/CustomTeam.java | 1 - 1 file changed, 1 deletion(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/CustomTeam.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/CustomTeam.java index 09eff1885..d7964e938 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/CustomTeam.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/CustomTeam.java @@ -4,7 +4,6 @@ import lombok.RequiredArgsConstructor; import org.bukkit.entity.Player; -import java.util.LinkedList; import java.util.List; import java.util.UUID; From ee5e2539e14470c50867152b2bc0bc583acf9a3d Mon Sep 17 00:00:00 2001 From: Rollocraft Date: Fri, 18 Apr 2025 17:03:21 +0200 Subject: [PATCH 059/119] Change to lowercase --- .../utils/bukkit/misc/{Version => version}/MinecraftVersion.java | 0 .../plugin/utils/bukkit/misc/{Version => version}/Version.java | 0 .../utils/bukkit/misc/{Version => version}/VersionComparator.java | 0 .../utils/bukkit/misc/{Version => version}/VersionInfo.java | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/{Version => version}/MinecraftVersion.java (100%) rename plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/{Version => version}/Version.java (100%) rename plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/{Version => version}/VersionComparator.java (100%) rename plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/{Version => version}/VersionInfo.java (100%) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/MinecraftVersion.java similarity index 100% rename from plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/MinecraftVersion.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/MinecraftVersion.java diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/Version.java similarity index 100% rename from plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/Version.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/Version.java diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionComparator.java similarity index 100% rename from plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionComparator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionComparator.java diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionInfo.java similarity index 100% rename from plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/Version/VersionInfo.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionInfo.java From 2b6b1f2fa74e4b751057c293d87e87f5f3a92993 Mon Sep 17 00:00:00 2001 From: Dominik Date: Sat, 19 Apr 2025 12:29:39 +0200 Subject: [PATCH 060/119] refactor: implement anweisen/utilities --- mongo-connector/pom.xml | 13 +- .../mongoconnector/MongoConnector.java | 2 +- .../common/config/document/BsonDocument.java | 304 ++++++++ .../commons/common/misc/BsonUtils.java | 135 ++++ .../commons/common/misc/MongoUtils.java | 66 ++ .../database/mongodb/MongoDBDatabase.java | 148 ++++ .../mongodb/count/MongoDBCountEntries.java | 42 ++ .../mongodb/deletion/MongoDBDeletion.java | 108 +++ .../mongodb/insertion/MongoDBInsertion.java | 61 ++ .../MongoDBInsertionOrUpdate.java | 85 +++ .../mongodb/list/MongoDBListTables.java | 29 + .../database/mongodb/query/MongoDBQuery.java | 128 ++++ .../database/mongodb/query/MongoDBResult.java | 18 + .../mongodb/update/MongoDBUpdate.java | 139 ++++ .../database/mongodb/where/MongoDBWhere.java | 17 + .../database/mongodb/where/ObjectWhere.java | 49 ++ .../mongodb/where/StringIgnoreCaseWhere.java | 47 ++ plugin/pom.xml | 36 +- .../challenges/plugin/Challenges.java | 4 +- .../challenges/custom/CustomChallenge.java | 2 +- .../custom/settings/CustomSettingsLoader.java | 4 +- .../settings/action/ChallengeAction.java | 2 +- .../settings/action/IChallengeAction.java | 2 +- .../action/impl/BoostEntityInAirAction.java | 2 +- .../action/impl/ChangeWorldBorderAction.java | 2 +- .../action/impl/HealEntityAction.java | 2 +- .../action/impl/PlaceStructureAction.java | 4 +- .../action/impl/PotionEffectAction.java | 4 +- .../action/impl/SpawnEntityAction.java | 2 +- .../action/impl/SwapRandomMobAction.java | 2 +- .../settings/sub/SubSettingsBuilder.java | 2 +- .../custom/settings/sub/ValueSetting.java | 2 +- .../sub/builder/ValueSubSettingsBuilder.java | 2 +- .../settings/sub/impl/BooleanSetting.java | 2 +- .../settings/sub/impl/ModifierSetting.java | 6 +- .../trigger/impl/EntityDamageTrigger.java | 4 +- .../challenge/DamageTeleportChallenge.java | 2 +- .../challenge/ZeroHeartsChallenge.java | 4 +- .../damage/BlockPlaceDamageChallenge.java | 2 +- .../damage/DeathOnFallChallenge.java | 2 +- .../damage/DelayDamageChallenge.java | 2 +- .../challenge/damage/FreezeChallenge.java | 2 +- .../challenge/damage/JumpDamageChallenge.java | 2 +- .../damage/WaterAllergyChallenge.java | 2 +- .../effect/BlockEffectChallenge.java | 6 +- .../effect/ChunkRandomEffectChallenge.java | 6 +- .../effect/EntityRandomEffectChallenge.java | 2 +- .../PermanentEffectOnDamageChallenge.java | 8 +- .../effect/RandomPotionEffectChallenge.java | 4 +- .../entities/AllMobsToDeathPoint.java | 2 +- .../entities/BlockMobsChallenge.java | 2 +- .../entities/HydraPlusChallenge.java | 2 +- .../entities/InvisibleMobsChallenge.java | 2 +- .../entities/MobSightDamageChallenge.java | 2 +- .../entities/MobTransformationChallenge.java | 2 +- .../entities/MobsRespawnInEndChallenge.java | 6 +- .../entities/NewEntityOnJumpChallenge.java | 2 +- .../entities/StoneSightChallenge.java | 4 +- .../extraworld/JumpAndRunChallenge.java | 4 +- .../challenge/force/ForceBiomeChallenge.java | 4 +- .../challenge/force/ForceBlockChallenge.java | 4 +- .../challenge/force/ForceHeightChallenge.java | 4 +- .../challenge/force/ForceItemChallenge.java | 6 +- .../challenge/force/ForceMobChallenge.java | 2 +- .../inventory/MissingItemsChallenge.java | 14 +- .../MovementItemRemovingChallenge.java | 2 +- .../inventory/NoDupedItemsChallenge.java | 4 +- .../inventory/PermanentItemChallenge.java | 4 +- .../inventory/PickupItemLaunchChallenge.java | 2 +- .../inventory/UncraftItemsChallenge.java | 4 +- .../miscellaneous/EnderGamesChallenge.java | 4 +- .../miscellaneous/FoodLaunchChallenge.java | 2 +- .../miscellaneous/InvertHealthChallenge.java | 4 +- .../miscellaneous/LowDropRateChallenge.java | 2 +- .../NoSharedAdvancementsChallenge.java | 6 +- .../movement/AlwaysRunningChallenge.java | 4 +- .../movement/DontStopRunningChallenge.java | 2 +- .../movement/FiveHundredBlocksChallenge.java | 8 +- .../movement/HungerPerBlockChallenge.java | 2 +- .../challenge/movement/MoveMouseDamage.java | 2 +- .../challenge/movement/OnlyDirtChallenge.java | 2 +- .../challenge/movement/OnlyDownChallenge.java | 2 +- .../movement/TrafficLightChallenge.java | 4 +- .../challenge/quiz/QuizChallenge.java | 12 +- .../randomizer/BlockRandomizerChallenge.java | 4 +- .../CraftingRandomizerChallenge.java | 2 +- .../EntityLootRandomizerChallenge.java | 2 +- .../randomizer/HotBarRandomizerChallenge.java | 4 +- .../randomizer/MobRandomizerChallenge.java | 6 +- .../randomizer/RandomChallengeChallenge.java | 2 +- .../randomizer/RandomEventChallenge.java | 6 +- .../randomizer/RandomItemChallenge.java | 2 +- .../RandomItemDroppingChallenge.java | 2 +- .../RandomItemRemovingChallenge.java | 2 +- .../RandomItemSwappingChallenge.java | 2 +- .../RandomTeleportOnHitChallenge.java | 2 +- .../randomizer/RandomizedHPChallenge.java | 2 +- .../challenge/time/MaxBiomeTimeChallenge.java | 2 +- .../time/MaxHeightTimeChallenge.java | 2 +- .../world/AllBlocksDisappearChallenge.java | 6 +- .../challenge/world/AnvilRainChallenge.java | 2 +- .../challenge/world/BedrockWallChallenge.java | 2 +- .../world/BlockFlyInAirChallenge.java | 2 +- .../BlocksDisappearAfterTimeChallenge.java | 2 +- .../world/ChunkDeconstructionChallenge.java | 2 +- .../world/ChunkDeletionChallenge.java | 2 +- .../challenge/world/IceFloorChallenge.java | 4 +- .../challenge/world/LevelBorderChallenge.java | 8 +- .../challenge/world/LoopChallenge.java | 8 +- .../world/RepeatInChunkChallenge.java | 10 +- .../challenge/world/SnakeChallenge.java | 2 +- .../challenge/world/SurfaceHoleChallenge.java | 2 +- .../challenge/world/TsunamiChallenge.java | 6 +- .../goal/AllAdvancementGoal.java | 2 +- .../goal/CollectAllItemsGoal.java | 10 +- .../goal/CollectHorseAmorGoal.java | 4 +- .../goal/CollectIceBlocksGoal.java | 2 +- .../goal/CollectMostDeathsGoal.java | 4 +- .../goal/CollectMostExpGoal.java | 2 +- .../goal/CollectMostItemsGoal.java | 4 +- .../goal/CollectSwordsGoal.java | 4 +- .../implementation/goal/CollectWoodGoal.java | 4 +- .../goal/CollectWorkstationsGoal.java | 4 +- .../implementation/goal/EatCakeGoal.java | 2 +- .../implementation/goal/EatMostGoal.java | 2 +- .../implementation/goal/FindElytraGoal.java | 2 +- .../implementation/goal/FinishRaidGoal.java | 4 +- .../goal/FirstOneToDieGoal.java | 2 +- .../goal/GetFullHealthGoal.java | 4 +- .../goal/KillAllBossesGoal.java | 2 +- .../goal/KillAllBossesNewGoal.java | 4 +- .../implementation/goal/KillAllMobsGoal.java | 2 +- .../goal/KillAllMonsterGoal.java | 4 +- .../goal/KillElderGuardianGoal.java | 4 +- .../goal/KillEnderDragonGoal.java | 2 +- .../goal/KillIronGolemGoal.java | 4 +- .../goal/KillSnowGolemGoal.java | 4 +- .../implementation/goal/KillWardenGoal.java | 6 +- .../implementation/goal/KillWitherGoal.java | 2 +- .../goal/LastManStandingGoal.java | 2 +- .../implementation/goal/MaxHeightGoal.java | 2 +- .../implementation/goal/MinHeightGoal.java | 4 +- .../implementation/goal/MostEmeraldsGoal.java | 2 +- .../implementation/goal/MostOresGoal.java | 4 +- .../implementation/goal/RaceGoal.java | 6 +- .../forcebattle/ExtremeForceBattleGoal.java | 6 +- .../ForceAdvancementBattleGoal.java | 6 +- .../forcebattle/ForceBiomeBattleGoal.java | 2 +- .../forcebattle/ForceBlockBattleGoal.java | 4 +- .../forcebattle/ForceDamageBattleGoal.java | 2 +- .../forcebattle/ForceHeightBattleGoal.java | 4 +- .../goal/forcebattle/ForceItemBattleGoal.java | 4 +- .../goal/forcebattle/ForceMobBattleGoal.java | 4 +- .../forcebattle/ForcePositionBattleGoal.java | 2 +- .../goal/forcebattle/targets/BlockTarget.java | 2 +- .../goal/forcebattle/targets/ItemTarget.java | 2 +- .../forcebattle/targets/PositionTarget.java | 6 +- .../setting/BackpackSetting.java | 6 +- .../setting/BastionSpawnSetting.java | 4 +- .../setting/CutCleanSetting.java | 6 +- .../setting/DamageDisplaySetting.java | 2 +- .../setting/DeathPositionSetting.java | 2 +- .../setting/DifficultySetting.java | 2 +- .../setting/EnderChestCommandSetting.java | 2 +- .../setting/FortressSpawnSetting.java | 2 +- .../setting/HealthDisplaySetting.java | 6 +- .../setting/ImmediateRespawnSetting.java | 2 +- .../setting/MaxHealthSetting.java | 10 +- .../setting/NoOffhandSetting.java | 2 +- .../implementation/setting/OldPvPSetting.java | 4 +- .../setting/PositionSetting.java | 4 +- .../setting/RespawnSetting.java | 2 +- .../setting/SlotLimitSetting.java | 2 +- .../implementation/setting/SoupSetting.java | 2 +- .../setting/SplitHealthSetting.java | 2 +- .../implementation/setting/TimberSetting.java | 4 +- .../setting/TopCommandSetting.java | 2 +- .../setting/TotemSaveDeathSetting.java | 2 +- .../challenges/type/EmptyChallenge.java | 4 +- .../plugin/challenges/type/IChallenge.java | 2 +- .../plugin/challenges/type/IGoal.java | 2 +- .../type/abstraction/AbstractChallenge.java | 6 +- .../abstraction/AbstractForceChallenge.java | 4 +- .../type/abstraction/CollectionGoal.java | 4 +- .../CompletableForceChallenge.java | 2 +- .../abstraction/EndingForceChallenge.java | 2 +- .../abstraction/ForceBattleDisplayGoal.java | 2 +- .../type/abstraction/ForceBattleGoal.java | 6 +- .../type/abstraction/ItemCollectionGoal.java | 2 +- .../type/abstraction/KillMobsGoal.java | 2 +- .../challenges/type/abstraction/MenuGoal.java | 2 +- .../type/abstraction/MenuSetting.java | 10 +- .../challenges/type/abstraction/Modifier.java | 4 +- .../abstraction/ModifierCollectionGoal.java | 2 +- .../abstraction/NetherPortalSpawnSetting.java | 2 +- .../type/abstraction/PointsGoal.java | 4 +- .../type/abstraction/RandomizerSetting.java | 6 +- .../challenges/type/abstraction/Setting.java | 6 +- .../type/abstraction/SettingGoal.java | 2 +- .../type/abstraction/SettingModifier.java | 4 +- .../SettingModifierCollectionGoal.java | 4 +- .../type/abstraction/SettingModifierGoal.java | 2 +- .../type/abstraction/TimedChallenge.java | 4 +- .../abstraction/WorldDependentChallenge.java | 2 +- .../type/helper/ChallengeConfigHelper.java | 2 +- .../type/helper/ChallengeHelper.java | 4 +- .../challenges/type/helper/GoalHelper.java | 2 +- .../type/helper/SubSettingsHelper.java | 6 +- .../plugin/content/ItemDescription.java | 2 +- .../challenges/plugin/content/Message.java | 4 +- .../plugin/content/impl/MessageImpl.java | 4 +- .../plugin/content/loader/LanguageLoader.java | 14 +- .../plugin/content/loader/LoaderRegistry.java | 2 +- .../plugin/content/loader/PrefixLoader.java | 6 +- .../plugin/content/loader/UpdateLoader.java | 6 +- .../management/blocks/BlockDropManager.java | 2 +- .../management/bstats/MetricsLoader.java | 10 +- .../challenges/ChallengeLoader.java | 2 +- .../challenges/ChallengeManager.java | 12 +- .../challenges/CustomChallengesLoader.java | 6 +- .../challenges/ModuleChallengeLoader.java | 6 +- .../annotations/RequireVersion.java | 2 +- .../entities/GamestateSaveable.java | 2 +- .../management/cloud/CloudSupportManager.java | 6 +- .../management/database/DatabaseManager.java | 28 +- .../management/files/ConfigManager.java | 14 +- .../inventory/PlayerInventoryManager.java | 10 +- .../plugin/management/menu/MenuManager.java | 10 +- .../generator/ChallengeMenuGenerator.java | 10 +- .../menu/generator/ChooseItemGenerator.java | 6 +- .../ChooseMultipleItemGenerator.java | 6 +- .../menu/generator/MenuGenerator.java | 4 +- .../generator/MultiPageMenuGenerator.java | 2 +- .../menu/generator/ValueMenuGenerator.java | 6 +- .../categorised/CategorisedMenuGenerator.java | 4 +- .../implementation/SettingsMenuGenerator.java | 2 +- .../implementation/TimerMenuGenerator.java | 6 +- .../custom/InfoMenuGenerator.java | 8 +- .../custom/MainCustomMenuGenerator.java | 4 +- .../custom/MaterialMenuGenerator.java | 2 +- .../menu/info/ChallengeMenuClickInfo.java | 2 +- .../menu/position/GeneratorMenuPosition.java | 2 +- .../scheduler/AbstractTaskExecutor.java | 2 +- .../management/scheduler/ScheduleManager.java | 4 +- .../scheduler/timer/ChallengeTimer.java | 6 +- .../scheduler/timer/TimerFormat.java | 2 +- .../management/server/GameWorldStorage.java | 2 +- .../server/GeneratorWorldPortalManager.java | 6 +- .../management/server/ServerManager.java | 10 +- .../management/server/TitleManager.java | 2 +- .../management/server/WorldManager.java | 8 +- .../server/scoreboard/ChallengeBossBar.java | 4 +- .../scoreboard/ChallengeScoreboard.java | 4 +- .../plugin/management/stats/PlayerStats.java | 4 +- .../plugin/management/stats/Statistic.java | 2 +- .../plugin/management/stats/StatsManager.java | 4 +- .../plugin/management/team/TeamProvider.java | 2 +- .../spigot/command/DatabaseCommand.java | 4 +- .../spigot/command/GamestateCommand.java | 2 +- .../plugin/spigot/command/HealCommand.java | 2 +- .../plugin/spigot/command/InvseeCommand.java | 4 +- .../spigot/command/LeaderboardCommand.java | 8 +- .../plugin/spigot/command/ResetCommand.java | 6 +- .../plugin/spigot/command/ResultCommand.java | 2 +- .../plugin/spigot/command/SearchCommand.java | 4 +- .../plugin/spigot/command/StatsCommand.java | 6 +- .../plugin/spigot/command/TimeCommand.java | 2 +- .../plugin/spigot/command/TimerCommand.java | 4 +- .../plugin/spigot/command/VillageCommand.java | 2 +- .../spigot/generator/VoidMapGenerator.java | 4 +- .../spigot/listener/BlockDropListener.java | 4 +- .../plugin/spigot/listener/CheatListener.java | 2 +- .../spigot/listener/CustomEventListener.java | 2 +- .../listener/PlayerConnectionListener.java | 4 +- .../utils/bukkit/command/PlayerCommand.java | 2 +- .../utils/bukkit/command/SenderCommand.java | 2 +- .../bukkit/jumpgeneration/IJumpGenerator.java | 2 +- .../jumpgeneration/RandomJumpGenerator.java | 2 +- .../utils/bukkit/misc/BukkitStringUtils.java | 6 +- .../bukkit/misc/version/MinecraftVersion.java | 114 --- .../utils/bukkit/misc/version/Version.java | 105 --- .../misc/version/VersionComparator.java | 13 - .../bukkit/misc/version/VersionInfo.java | 70 -- .../plugin/utils/bukkit/nms/NMSProvider.java | 8 +- .../plugin/utils/bukkit/nms/NMSUtils.java | 8 +- .../utils/bukkit/nms/ReflectionUtil.java | 2 +- .../v1_13/BorderPacketFactory_1_13.java | 2 +- .../v1_13/CraftPlayer_1_13.java | 4 +- .../v1_13/PacketBorder_1_13.java | 16 +- .../v1_13/PlayerConnection_1_13.java | 2 +- .../v1_13/WorldServer_1_13.java | 2 +- .../v1_17/BorderPacketFactory_1_17.java | 2 +- .../v1_17/CraftPlayer_1_17.java | 4 +- .../v1_18/PacketBorder_1_18.java | 10 +- .../v1_18/PlayerConnection_1_18.java | 2 +- .../plugin/utils/item/ItemBuilder.java | 4 +- .../plugin/utils/item/ItemUtils.java | 117 --- .../plugin/utils/logging/ConsolePrint.java | 2 +- .../plugin/utils/misc/DatabaseHelper.java | 4 +- .../plugin/utils/misc/InventoryUtils.java | 8 +- .../plugin/utils/misc/MapUtils.java | 4 +- .../utils/misc/MinecraftNameWrapper.java | 2 +- .../plugin/utils/misc/ParticleUtils.java | 4 +- .../plugin/utils/misc/StatsHelper.java | 2 +- .../challenges/plugin/utils/misc/Utils.java | 6 +- .../commons/bukkit/core/BukkitModule.java | 375 ++++++++++ .../bukkit/core/RequirementsChecker.java | 94 +++ .../bukkit/core/SimpleConfigManager.java | 44 ++ .../utils/animation/AnimatedInventory.java | 168 +++++ .../utils/animation/AnimationFrame.java | 84 +++ .../bukkit/utils/animation/SoundSample.java | 113 +++ .../utils/bstats/JsonObjectBuilder.java | 210 ++++++ .../commons/bukkit/utils/bstats/Metrics.java | 333 +++++++++ .../utils/bstats/chart/AdvancedBarChart.java | 47 ++ .../utils/bstats/chart/AdvancedPie.java | 47 ++ .../utils/bstats/chart/CustomChart.java | 40 ++ .../utils/bstats/chart/DrilldownPie.java | 51 ++ .../utils/bstats/chart/MultiLineChart.java | 47 ++ .../utils/bstats/chart/SimpleBarChart.java | 37 + .../bukkit/utils/bstats/chart/SimplePie.java | 32 + .../utils/bstats/chart/SingleLineChart.java | 32 + .../bukkit/utils/item/BannerPattern.java | 64 ++ .../bukkit/utils/item/ItemBuilder.java | 424 +++++++++++ .../commons/bukkit/utils/item/ItemUtils.java | 117 +++ .../commons/bukkit/utils/logging/Logger.java | 39 + .../bukkit/utils/menu/MenuClickInfo.java | 75 ++ .../bukkit/utils/menu/MenuPosition.java | 44 ++ .../bukkit/utils/menu/MenuPositionHolder.java | 16 + .../utils/menu/MenuPositionListener.java | 47 ++ .../menu/positions/EmptyMenuPosition.java | 16 + .../menu/positions/SlottedMenuPosition.java | 50 ++ .../utils/misc/BukkitReflectionUtils.java | 170 +++++ .../bukkit/utils/misc/CompatibilityUtils.java | 50 ++ .../bukkit/utils/misc/GameProfileUtils.java | 91 +++ .../bukkit/utils/misc/MinecraftVersion.java | 115 +++ .../bukkit/utils/wrapper/ActionListener.java | 57 ++ .../utils}/wrapper/AttributeWrapper.java | 4 +- .../bukkit/utils/wrapper/MaterialWrapper.java | 27 + .../utils/wrapper/SimpleEventExecutor.java | 31 + .../common/annotations/AlsoKnownAs.java | 17 + .../common/annotations/DeprecatedSince.java | 17 + .../common/annotations/ReplaceWith.java | 17 + .../commons/common/annotations/Since.java | 14 + .../common/collection/ArrayWalker.java | 56 ++ .../common/collection/ClassWalker.java | 65 ++ .../commons/common/collection/Colors.java | 38 + .../common/collection/FontBuilder.java | 93 +++ .../commons/common/collection/IOUtils.java | 43 ++ .../commons/common/collection/IRandom.java | 152 ++++ .../common/collection/NamedThreadFactory.java | 37 + .../common/collection/NumberFormatter.java | 357 ++++++++++ .../collection/PublicSecurityManager.java | 12 + .../common/collection/RandomWrapper.java | 149 ++++ .../common/collection/RomanNumerals.java | 47 ++ .../common/collection/RunnableTimerTask.java | 19 + .../collection/SeededRandomWrapper.java | 35 + .../common/collection/SingletonRandom.java | 13 + .../collection/StringBuilderPrintWriter.java | 28 + .../collection/StringBuilderWriter.java | 68 ++ .../commons/common/collection/Triple.java | 20 + .../commons/common/collection/Tuple.java | 19 + .../common/collection/WrappedException.java | 61 ++ .../commons/common/collection/pair/Pair.java | 32 + .../common/collection/pair/Quadro.java | 139 ++++ .../common/collection/pair/Triple.java | 123 ++++ .../commons/common/collection/pair/Tuple.java | 106 +++ .../cache/CleanAndWriteDatabaseCache.java | 118 ++++ .../concurrent/cache/CleanWriteableCache.java | 83 +++ .../concurrent/cache/CoolDownCache.java | 83 +++ .../concurrent/cache/DatabaseCache.java | 19 + .../common/concurrent/cache/ICache.java | 40 ++ .../concurrent/cache/WriteableCache.java | 17 + .../concurrent/task/CompletableTask.java | 169 +++++ .../common/concurrent/task/CompletedTask.java | 108 +++ .../commons/common/concurrent/task/Task.java | 228 ++++++ .../common/concurrent/task/TaskListener.java | 16 + .../commons/common/config/Config.java | 97 +++ .../commons/common/config/Document.java | 345 +++++++++ .../commons/common/config/FileDocument.java | 172 +++++ .../commons/common/config/Json.java | 48 ++ .../commons/common/config/PropertyHelper.java | 49 ++ .../commons/common/config/Propertyable.java | 199 ++++++ .../config/document/AbstractConfig.java | 278 ++++++++ .../config/document/AbstractDocument.java | 162 +++++ .../common/config/document/EmptyDocument.java | 518 ++++++++++++++ .../common/config/document/GsonDocument.java | 508 +++++++++++++ .../common/config/document/MapDocument.java | 292 ++++++++ .../config/document/PropertiesDocument.java | 285 ++++++++ .../common/config/document/YamlDocument.java | 355 ++++++++++ ...kkitReflectionSerializableTypeAdapter.java | 60 ++ .../document/gson/ClassTypeAdapter.java | 32 + .../document/gson/ColorTypeAdapter.java | 27 + .../document/gson/DocumentTypeAdapter.java | 46 ++ .../config/document/gson/GsonTypeAdapter.java | 62 ++ .../config/document/gson/PairTypeAdapter.java | 37 + .../readonly/ReadOnlyDocumentWrapper.java | 26 + .../document/wrapper/FileDocumentWrapper.java | 62 ++ .../document/wrapper/WrappedDocument.java | 510 ++++++++++++++ .../exceptions/ConfigReadOnlyException.java | 11 + .../commons/common/debug/TimingsHelper.java | 50 ++ .../common/discord/DiscordWebhook.java | 498 +++++++++++++ .../function/ExceptionallyBiConsumer.java | 21 + .../function/ExceptionallyBiFunction.java | 21 + .../function/ExceptionallyConsumer.java | 21 + .../function/ExceptionallyDoubleFunction.java | 21 + .../function/ExceptionallyFunction.java | 29 + .../function/ExceptionallyIntFunction.java | 21 + .../function/ExceptionallyLongFunction.java | 21 + .../function/ExceptionallyRunnable.java | 27 + .../function/ExceptionallySupplier.java | 27 + .../ExceptionallyToDoubleFunction.java | 21 + .../function/ExceptionallyToIntFunction.java | 21 + .../function/ExceptionallyToLongFunction.java | 21 + .../commons/common/logging/ILogger.java | 282 ++++++++ .../common/logging/ILoggerFactory.java | 15 + .../commons/common/logging/LogLevel.java | 82 +++ .../common/logging/LogOutputStream.java | 28 + .../common/logging/LoggingApiUser.java | 47 ++ .../common/logging/WrappedILogger.java | 159 +++++ .../logging/handler/HandledAsyncLogger.java | 23 + .../common/logging/handler/HandledLogger.java | 69 ++ .../logging/handler/HandledSyncLogger.java | 17 + .../common/logging/handler/LogEntry.java | 49 ++ .../common/logging/handler/LogHandler.java | 13 + .../logging/internal/BukkitLoggerWrapper.java | 25 + .../logging/internal/FallbackLogger.java | 62 ++ .../logging/internal/JavaLoggerWrapper.java | 666 ++++++++++++++++++ .../common/logging/internal/SimpleLogger.java | 365 ++++++++++ .../logging/internal/Slf4jILoggerWrapper.java | 173 +++++ .../logging/internal/Slf4jLoggerWrapper.java | 369 ++++++++++ .../factory/ConstantLoggerFactory.java | 29 + .../factory/DefaultLoggerFactory.java | 36 + .../internal/factory/Slf4jLoggerFactory.java | 25 + .../common/logging/lib/JavaILogger.java | 19 + .../common/logging/lib/Slf4jILogger.java | 41 ++ .../BukkitReflectionSerializationUtils.java | 101 +++ .../commons/common/misc/FileUtils.java | 565 +++++++++++++++ .../commons/common/misc/GsonUtils.java | 127 ++++ .../commons/common/misc/ImageUtils.java | 109 +++ .../commons/common/misc/MathHelper.java | 12 + .../commons/common/misc/PropertiesUtils.java | 18 + .../commons/common/misc/ReflectionUtils.java | 258 +++++++ .../common/misc/SimpleCollectionUtils.java | 143 ++++ .../commons/common/misc/StringUtils.java | 181 +++++ .../commons/common/version/Version.java | 105 +++ .../common/version/VersionComparator.java | 13 + .../commons/common/version/VersionInfo.java | 80 +++ .../codingarea/commons/database/Database.java | 110 +++ .../commons/database/DatabaseConfig.java | 105 +++ .../commons/database/EmptyDatabase.java | 288 ++++++++ .../codingarea/commons/database/Order.java | 13 + .../commons/database/SQLColumn.java | 134 ++++ .../database/SimpleDatabaseTypeResolver.java | 39 + .../commons/database/SpecificDatabase.java | 66 ++ .../abstraction/AbstractDatabase.java | 100 +++ .../abstraction/DefaultExecutedQuery.java | 124 ++++ .../abstraction/DefaultSpecificDatabase.java | 90 +++ .../database/access/CachedDatabaseAccess.java | 85 +++ .../database/access/DatabaseAccess.java | 33 + .../database/access/DatabaseAccessConfig.java | 32 + .../database/access/DirectDatabaseAccess.java | 69 ++ .../database/action/DatabaseAction.java | 82 +++ .../database/action/DatabaseCountEntries.java | 21 + .../database/action/DatabaseDeletion.java | 42 ++ .../database/action/DatabaseInsertion.java | 26 + .../action/DatabaseInsertionOrUpdate.java | 45 ++ .../database/action/DatabaseListTables.java | 18 + .../database/action/DatabaseQuery.java | 53 ++ .../database/action/DatabaseUpdate.java | 47 ++ .../database/action/ExecutedQuery.java | 86 +++ .../action/hierarchy/OrderedAction.java | 13 + .../database/action/hierarchy/SetAction.java | 11 + .../action/hierarchy/WhereAction.java | 29 + .../DatabaseAlreadyConnectedException.java | 12 + .../DatabaseConnectionClosedException.java | 12 + .../exceptions/DatabaseException.java | 31 + .../DatabaseUnsupportedFeatureException.java | 14 + .../exceptions/UnsignedDatabaseException.java | 24 + .../sql/abstraction/AbstractSQLDatabase.java | 134 ++++ .../database/sql/abstraction/SQLHelper.java | 37 + .../abstraction/count/SQLCountEntries.java | 54 ++ .../sql/abstraction/deletion/SQLDeletion.java | 110 +++ .../abstraction/insertion/SQLInsertion.java | 95 +++ .../insertorupdate/SQLInsertionOrUpdate.java | 85 +++ .../sql/abstraction/query/SQLQuery.java | 176 +++++ .../sql/abstraction/query/SQLResult.java | 33 + .../sql/abstraction/update/SQLUpdate.java | 140 ++++ .../sql/abstraction/where/ObjectWhere.java | 44 ++ .../sql/abstraction/where/SQLWhere.java | 13 + .../where/StringIgnoreCaseWhere.java | 41 ++ .../database/sql/mysql/MySQLDatabase.java | 36 + .../sql/mysql/list/MySQLListTables.java | 38 + .../database/sql/sqlite/SQLiteDatabase.java | 53 ++ .../sql/sqlite/list/SQLiteListTables.java | 38 + pom.xml | 1 - 495 files changed, 20080 insertions(+), 1010 deletions(-) create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/MongoDBDatabase.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/count/MongoDBCountEntries.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/deletion/MongoDBDeletion.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertion/MongoDBInsertion.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertorupdate/MongoDBInsertionOrUpdate.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/list/MongoDBListTables.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBQuery.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBResult.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/update/MongoDBUpdate.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/MongoDBWhere.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/ObjectWhere.java create mode 100644 mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/StringIgnoreCaseWhere.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/MinecraftVersion.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/Version.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionComparator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionInfo.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/Metrics.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedBarChart.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedPie.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/CustomChart.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/DrilldownPie.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/MultiLineChart.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimpleBarChart.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimplePie.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SingleLineChart.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java rename plugin/src/main/java/net/codingarea/{challenges/plugin/utils/bukkit/misc => commons/bukkit/utils}/wrapper/AttributeWrapper.java (80%) create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/PublicSecurityManager.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/SingletonRandom.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/Config.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/Document.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/Json.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiConsumer.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyConsumer.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyDoubleFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyIntFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyLongFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyRunnable.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallySupplier.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToDoubleFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToIntFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToLongFunction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/MathHelper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/version/Version.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java create mode 100644 plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/Database.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/Order.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseAlreadyConnectedException.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseConnectionClosedException.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java create mode 100644 plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java diff --git a/mongo-connector/pom.xml b/mongo-connector/pom.xml index 7dfe556eb..0fcaef25e 100644 --- a/mongo-connector/pom.xml +++ b/mongo-connector/pom.xml @@ -20,6 +20,13 @@ + + + org.slf4j + slf4j-api + 1.7.32 + + org.spigotmc spigot-api @@ -45,12 +52,6 @@ ${project.version} - - com.github.anweisen.Utility - database-mongodb - ${utilities.version} - - diff --git a/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java b/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java index 745bf6468..ee9999e4d 100644 --- a/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java +++ b/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.mongoconnector; -import net.anweisen.utilities.database.internal.mongodb.MongoDBDatabase; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.plugin.java.JavaPlugin; diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java new file mode 100644 index 000000000..f801ab556 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java @@ -0,0 +1,304 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.FileUtils; +import org.bson.BsonArray; +import org.bson.BsonValue; +import org.bson.json.JsonWriterSettings; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.*; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.*; +import java.util.List; +import java.util.function.BiConsumer; + +public class BsonDocument extends AbstractDocument { + + protected org.bson.Document bsonDocument; + + public BsonDocument(@Nonnull File file) throws IOException { + this(FileUtils.newBufferedReader(file)); + } + + public BsonDocument(@Nonnull Reader reader) { + BufferedReader buffered = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); + StringBuilder content = new StringBuilder(); + buffered.lines().forEach(content::append); + bsonDocument = org.bson.Document.parse(content.toString()); + } + + public BsonDocument(@Nonnull org.bson.Document bsonDocument) { + this.bsonDocument = bsonDocument; + } + + public BsonDocument(@Nonnull org.bson.Document bsonDocument, @Nonnull Document root, @Nullable Document parent) { + super(root, parent); + this.bsonDocument = bsonDocument; + } + + public BsonDocument() { + this(new org.bson.Document()); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + org.bson.Document document = bsonDocument.get(path, org.bson.Document.class); + if (document == null) { + bsonDocument.put(path, document = new org.bson.Document()); + } + + return new BsonDocument(document, root, parent); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + BsonArray array = bsonDocument.get(path, BsonArray.class); + if (array == null) return new ArrayList<>(); + List documents = new ArrayList<>(array.size()); + for (BsonValue value : array) { + if (!value.isDocument()) continue; + String json = value.asDocument().toJson(); + org.bson.Document document = org.bson.Document.parse(json); + documents.add(new BsonDocument(document, root, this)); + } + return documents; + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + Object value = getObject(path); + return value == null ? null : value.toString(); + } + + @Override + public long getLong(@Nonnull String path, long def) { + try { + return Long.parseLong(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public int getInt(@Nonnull String path, int def) { + try { + return Integer.parseInt(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public short getShort(@Nonnull String path, short def) { + try { + return Short.parseShort(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + try { + return Byte.parseByte(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path, double def) { + try { + return Double.parseDouble(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public float getFloat(@Nonnull String path, float def) { + try { + return Float.parseFloat(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + try { + Object value = bsonDocument.get(path); + if (value instanceof Boolean) return (Boolean) value; + if (value instanceof String) return Boolean.parseBoolean((String) value); + } catch (Exception ex) { + } + return def; + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return bsonDocument.get(path); + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + return bsonDocument.getList(path, String.class); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + try { + Object value = bsonDocument.get(path); + if (value instanceof UUID) return (UUID) value; + if (value instanceof String) return UUID.fromString((String) value); + } catch (Exception ex) { + } + return null; + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + return bsonDocument.getDate(path); + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + Object value = getObject(path); + + if (value == null) + return null; + if (value instanceof OffsetDateTime) + return (OffsetDateTime) value; + if (value instanceof Date) + return ((Date)value).toInstant().atOffset(ZoneOffset.UTC); + if (value instanceof String) + return OffsetDateTime.parse((CharSequence) value); + + throw new IllegalStateException(value.getClass().getName() + " cannot be converted to java.time.OffsetDateTime"); + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + Object value = getObject(path); + + if (value == null) + return null; + if (value instanceof Color) + return (Color) value; + if (value instanceof String) + return Color.decode((String) value); + + throw new IllegalStateException(value.getClass().getName() + " cannot be converted to java.awt.Color"); + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return copyJson().getInstance(path, classOfT); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Override + public boolean contains(@Nonnull String path) { + return bsonDocument.containsKey(path); + } + + @Override + public boolean isList(@Nonnull String path) { + Object value = bsonDocument.get(path); + return value instanceof Iterable || (value != null && value.getClass().isArray()); + } + + @Override + public boolean isDocument(@Nonnull String path) { + Object value = bsonDocument.get(path); + return value instanceof org.bson.Document; + } + + @Override + public boolean isObject(@Nonnull String path) { + return !isList(path) && !isDocument(path); + } + + @Override + public int size() { + return bsonDocument.size(); + } + + @Override + public void clear0() { + bsonDocument.clear(); + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + bsonDocument.put(path, value); + } + + @Override + public void remove0(@Nonnull String path) { + bsonDocument.remove(path); + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + String json = bsonDocument.toString(); + writer.write(json); + } + + @Nonnull + @Override + public Map values() { + return Collections.unmodifiableMap(bsonDocument); + } + + @Nonnull + @Override + public Collection keys() { + return bsonDocument.keySet(); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + bsonDocument.forEach(action); + } + + @Nonnull + @Override + public String toJson() { + return bsonDocument.toJson(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return bsonDocument.toJson(JsonWriterSettings.builder().indent(true).build()); + } + + @Override + public String toString() { + return toJson(); + } + + @Override + public boolean isReadonly() { + return false; + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java new file mode 100644 index 000000000..05611a0b0 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java @@ -0,0 +1,135 @@ +package net.codingarea.commons.common.misc; + +import com.mongodb.MongoClient; +import net.codingarea.commons.common.logging.ILogger; +import org.bson.*; +import org.bson.conversions.Bson; +import org.bson.types.ObjectId; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +public final class BsonUtils { + + protected static final ILogger logger = ILogger.forThisClass(); + + private BsonUtils() { + } + + @Nonnull + public static BsonDocument convertBsonToBsonDocument(@Nonnull Bson bson) { + return bson.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry()); + } + + @Nullable + public static Object unpackBsonElement(@Nullable Object value) { + if (value == null || value instanceof BsonNull) { + return null; + } else if (value instanceof BsonString) { + return ((BsonString) value).getValue(); + } else if (value instanceof BsonDouble) { + return ((BsonDouble) value).getValue(); + } else if (value instanceof BsonInt32) { + return ((BsonInt32) value).getValue(); + } else if (value instanceof BsonInt64) { + return ((BsonInt64) value).getValue(); + } else if (value instanceof BsonBinary) { + return ((BsonBinary) value).getData(); + } else if (value instanceof BsonObjectId) { + return ((BsonObjectId) value).getValue(); + } else if (value instanceof BsonArray) { + return convertBsonArrayToList((BsonArray) value); + } else if (value instanceof BsonDocument) { + return convertBsonDocumentToMap((BsonDocument) value); + } else if (value instanceof Document) { + return value; + } else { + return value; + } + } + + @Nonnull + public static List convertBsonArrayToList(@Nonnull BsonArray array) { + List list = new ArrayList<>(array.size()); + for (BsonValue value : array) { + list.add(unpackBsonElement(value)); + } + return list; + } + + @Nonnull + public static Map convertBsonDocumentToMap(@Nonnull BsonDocument document) { + Map map = new HashMap<>(); + for (Entry entry : document.entrySet()) { + map.put(entry.getKey(), unpackBsonElement(entry.getValue())); + } + return map; + } + + @Nonnull + public static BsonValue convertObjectToBsonElement(@Nullable Object value) { + if (value == null) { + return BsonNull.VALUE; + } else if (value instanceof BsonValue) { + return (BsonValue) value; + } else if (value instanceof Bson) { + return convertBsonToBsonDocument((Bson) value); + } else if (value instanceof String) { + return new BsonString((String) value); + } else if (value instanceof Boolean) { + return new BsonBoolean((Boolean) value); + } else if (value instanceof ObjectId) { + return new BsonObjectId((ObjectId) value); + } else if (value instanceof Double) { + return new BsonDouble((Double) value); + } else if (value instanceof Float) { + return new BsonDouble((Float) value); + } else if (value instanceof Long) { + return new BsonInt64((Long) value); + } else if (value instanceof Integer) { + return new BsonInt32((Integer) value); + } else if (value instanceof Number) { + return new BsonInt32(((Number) value).intValue()); + } else if (value instanceof byte[]) { + return new BsonBinary((byte[]) value); + } else if (value instanceof Iterable) { + return convertIterableToBsonArray((Iterable) value); + } else if (value.getClass().isArray()) { + return convertArrayToBsonArray(value); + } else if (value instanceof Map) { + BsonDocument document = new BsonDocument(); + setDocumentProperties(document, (Map) value); + return document; + } else { + logger.error("Could not serialize " + value.getClass().getName() + " to BsonValue"); + return BsonNull.VALUE; + } + } + + public static void setDocumentProperties(@Nonnull BsonDocument document, @Nonnull Map values) { + for (Entry entry : values.entrySet()) { + Object value = entry.getValue(); + document.put(entry.getKey(), convertObjectToBsonElement(value)); + } + } + + @Nonnull + public static BsonArray convertIterableToBsonArray(@Nonnull Iterable iterable) { + BsonArray bsonArray = new BsonArray(); + iterable.forEach(object -> bsonArray.add(convertObjectToBsonElement(object))); + return bsonArray; + } + + @Nonnull + public static BsonArray convertArrayToBsonArray(@Nonnull Object array) { + BsonArray bsonArray = new BsonArray(); + ReflectionUtils.forEachInArray(array, object -> bsonArray.add(convertObjectToBsonElement(object))); + return bsonArray; + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java new file mode 100644 index 000000000..d0c2c4a37 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java @@ -0,0 +1,66 @@ +package net.codingarea.commons.common.misc; + +import com.mongodb.client.FindIterable; +import com.mongodb.client.model.Collation; +import com.mongodb.client.model.Sorts; +import net.codingarea.commons.common.config.Json; +import net.codingarea.commons.database.Order; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import org.bson.BsonDocument; +import org.bson.Document; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; + +public final class MongoUtils { + + private MongoUtils() { + } + + public static void applyWhere(@Nonnull FindIterable iterable, @Nonnull Map where) { + for (Entry entry : where.entrySet()) { + MongoDBWhere value = entry.getValue(); + iterable.filter(value.toBson()); + + Collation collation = value.getCollation(); + if (collation != null) + iterable.collation(collation); + } + } + + public static void applyOrder(@Nonnull FindIterable iterable, @Nullable String orderBy, @Nullable Order order) { + if (order == null || orderBy == null) return; + switch (order) { + case HIGHEST: + iterable.sort(Sorts.descending(orderBy)); + break; + case LOWEST: + iterable.sort(Sorts.ascending(orderBy)); + break; + } + } + + @Nullable + public static Object packObject(@Nullable Object value) { + if (value == null) { + return null; + } else if (value instanceof Json) { + String json = ((Json) value).toJson(); + return Document.parse(json); + } else if (BukkitReflectionSerializationUtils.isSerializable(value.getClass())) { + Map values = BukkitReflectionSerializationUtils.serializeObject(value); + if (values == null) return null; + BsonDocument bson = new BsonDocument(); + BsonUtils.setDocumentProperties(bson, values); + return bson; + } else if (value instanceof UUID) { + return ((UUID) value).toString(); + } else { + return value; + } + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/MongoDBDatabase.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/MongoDBDatabase.java new file mode 100644 index 000000000..e6789feda --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/MongoDBDatabase.java @@ -0,0 +1,148 @@ +package net.codingarea.commons.database.mongodb; + +import com.mongodb.MongoClientSettings; +import com.mongodb.MongoCredential; +import com.mongodb.ServerAddress; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.SQLColumn; +import net.codingarea.commons.database.action.*; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.abstraction.AbstractDatabase; +import net.codingarea.commons.database.mongodb.count.MongoDBCountEntries; +import net.codingarea.commons.database.mongodb.deletion.MongoDBDeletion; +import net.codingarea.commons.database.mongodb.insertion.MongoDBInsertion; +import net.codingarea.commons.database.mongodb.insertorupdate.MongoDBInsertionOrUpdate; +import net.codingarea.commons.database.mongodb.list.MongoDBListTables; +import net.codingarea.commons.database.mongodb.query.MongoDBQuery; +import net.codingarea.commons.database.mongodb.update.MongoDBUpdate; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import org.bson.Document; + +import javax.annotation.Nonnull; +import java.util.Collections; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class MongoDBDatabase extends AbstractDatabase { + + static { + Logger.getLogger("org.mongodb").setLevel(Level.SEVERE); + } + + protected MongoClient client; + protected MongoDatabase database; + + public MongoDBDatabase(@Nonnull DatabaseConfig config) { + super(config); + } + + @Override + public void connect0() throws Exception { + MongoCredential credential = MongoCredential.createCredential(config.getUser(), config.getAuthDatabase(), config.getPassword().toCharArray()); + MongoClientSettings settings = MongoClientSettings.builder() + .retryReads(false).retryReads(false) + .credential(credential) + .applyToClusterSettings(builder -> builder.hosts(Collections.singletonList(new ServerAddress(config.getHost(), config.isPortSet() ? config.getPort() : ServerAddress.defaultPort())))) + .build(); + client = MongoClients.create(settings); + database = client.getDatabase(config.getDatabase()); + } + + @Override + public void disconnect0() throws Exception { + client.close(); + client = null; + } + + @Override + public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { + checkConnection(); + + boolean collectionExists = listTables().execute().contains(name); + if (collectionExists) return; + + try { + database.createCollection(name); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Nonnull + @Override + public DatabaseListTables listTables() { + return new MongoDBListTables(this); + } + + @Nonnull + @Override + public DatabaseCountEntries countEntries(@Nonnull String table) { + return new MongoDBCountEntries(this, table); + } + + @Nonnull + @Override + public DatabaseQuery query(@Nonnull String table) { + return new MongoDBQuery(this, table); + } + + @Nonnull + public DatabaseQuery query(@Nonnull String table, @Nonnull Map where) { + return new MongoDBQuery(this, table, where); + } + + @Nonnull + @Override + public DatabaseUpdate update(@Nonnull String table) { + return new MongoDBUpdate(this, table); + } + + @Nonnull + @Override + public DatabaseInsertion insert(@Nonnull String table) { + return new MongoDBInsertion(this, table); + } + + @Nonnull + public DatabaseInsertion insert(@Nonnull String table, @Nonnull Map values) { + return new MongoDBInsertion(this, table, new Document(values)); + } + + @Nonnull + public DatabaseInsertion insert(@Nonnull String table, @Nonnull Document document) { + return new MongoDBInsertion(this, table, document); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { + return new MongoDBInsertionOrUpdate(this, table); + } + + @Nonnull + @Override + public DatabaseDeletion delete(@Nonnull String table) { + return new MongoDBDeletion(this, table); + } + + @Nonnull + public MongoCollection getCollection(@Nonnull String collection) { + return database.getCollection(collection); + } + + @Nonnull + public MongoDatabase getDatabase() { + return database; + } + + @Override + public boolean isConnected() { + return client != null && database != null; + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/count/MongoDBCountEntries.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/count/MongoDBCountEntries.java new file mode 100644 index 000000000..e1b185de5 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/count/MongoDBCountEntries.java @@ -0,0 +1,42 @@ +package net.codingarea.commons.database.mongodb.count; + +import net.codingarea.commons.database.action.DatabaseCountEntries; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; + +import javax.annotation.Nonnull; +import java.util.Objects; + +public class MongoDBCountEntries implements DatabaseCountEntries { + + protected final MongoDBDatabase database; + protected final String table; + + public MongoDBCountEntries(@Nonnull MongoDBDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + } + + @Nonnull + @Override + public Long execute() throws DatabaseException { + try { + return database.getCollection(table).countDocuments(); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBCountEntries that = (MongoDBCountEntries) o; + return Objects.equals(database, that.database) && Objects.equals(table, that.table); + } + + @Override + public int hashCode() { + return Objects.hash(database, table); + } +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/deletion/MongoDBDeletion.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/deletion/MongoDBDeletion.java new file mode 100644 index 000000000..3073dbb40 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/deletion/MongoDBDeletion.java @@ -0,0 +1,108 @@ +package net.codingarea.commons.database.mongodb.deletion; + +import com.mongodb.client.MongoCollection; +import com.mongodb.client.model.Collation; +import com.mongodb.client.model.DeleteOptions; +import com.mongodb.client.model.Filters; +import net.codingarea.commons.common.misc.BsonUtils; +import net.codingarea.commons.database.action.DatabaseDeletion; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import net.codingarea.commons.database.mongodb.where.ObjectWhere; +import net.codingarea.commons.database.mongodb.where.StringIgnoreCaseWhere; +import org.bson.BsonDocument; +import org.bson.Document; +import org.bson.conversions.Bson; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +public class MongoDBDeletion implements DatabaseDeletion { + + protected final MongoDBDatabase database; + protected final String collection; + protected final Map where = new HashMap<>(); + + public MongoDBDeletion(@Nonnull MongoDBDatabase database, @Nonnull String collection) { + this.database = database; + this.collection = collection; + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, Filters::eq)); + return this; + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @Nonnull + @Override + public DatabaseDeletion whereNot(@Nonnull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, Filters::ne)); + return this; + } + + @Override + public Void execute() throws DatabaseException { + try { + MongoCollection collection = database.getCollection(this.collection); + + Document filter = new Document(); + DeleteOptions options = new DeleteOptions(); + + for (MongoDBWhere where : where.values()) { + Bson whereBson = where.toBson(); + BsonDocument asBsonDocument = BsonUtils.convertBsonToBsonDocument(whereBson); + filter.putAll(asBsonDocument); + + Collation collation = where.getCollation(); + if (collation != null) + options.collation(collation); + } + + collection.deleteMany(filter, options); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBDeletion that = (MongoDBDeletion) o; + return database.equals(that.database) && collection.equals(that.collection) && where.equals(that.where); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, where); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertion/MongoDBInsertion.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertion/MongoDBInsertion.java new file mode 100644 index 000000000..10e38cfc6 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertion/MongoDBInsertion.java @@ -0,0 +1,61 @@ +package net.codingarea.commons.database.mongodb.insertion; + +import net.codingarea.commons.common.misc.MongoUtils; +import net.codingarea.commons.database.action.DatabaseInsertion; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import org.bson.Document; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; + +public class MongoDBInsertion implements DatabaseInsertion { + + protected final MongoDBDatabase database; + protected final String collection; + protected final Document values; + + public MongoDBInsertion(@Nonnull MongoDBDatabase database, @Nonnull String collection) { + this.database = database; + this.collection = collection; + this.values = new Document(); + } + + public MongoDBInsertion(@Nonnull MongoDBDatabase database, @Nonnull String collection, @Nonnull Document values) { + this.database = database; + this.collection = collection; + this.values = values; + } + + @Nonnull + @Override + public DatabaseInsertion set(@Nonnull String field, @Nullable Object value) { + values.put(field, MongoUtils.packObject(value)); + return this; + } + + @Override + public Void execute() throws DatabaseException { + try { + database.getCollection(collection).insertOne(values); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBInsertion that = (MongoDBInsertion) o; + return database.equals(that.database) && collection.equals(that.collection) && values.equals(that.values); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, values); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertorupdate/MongoDBInsertionOrUpdate.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertorupdate/MongoDBInsertionOrUpdate.java new file mode 100644 index 000000000..295751f3d --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertorupdate/MongoDBInsertionOrUpdate.java @@ -0,0 +1,85 @@ +package net.codingarea.commons.database.mongodb.insertorupdate; + +import net.codingarea.commons.common.misc.BsonUtils; +import net.codingarea.commons.database.action.DatabaseInsertionOrUpdate; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import net.codingarea.commons.database.mongodb.update.MongoDBUpdate; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import org.bson.BsonDocument; +import org.bson.Document; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map.Entry; + +public class MongoDBInsertionOrUpdate extends MongoDBUpdate implements DatabaseInsertionOrUpdate { + + public MongoDBInsertionOrUpdate(@Nonnull MongoDBDatabase database, @Nonnull String collection) { + super(database, collection); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + super.where(field, value, ignoreCase); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Object value) { + super.where(field, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value) { + super.where(field, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Number value) { + super.where(field, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate whereNot(@Nonnull String field, @Nullable Object value) { + super.whereNot(field, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate set(@Nonnull String field, @Nullable Object value) { + super.set(field, value); + return this; + } + + @Override + public Void execute() throws DatabaseException { + if (database.query(collection, where).execute().isSet()) { + return super.execute(); + } else { + Document document = new Document(values); + for (Entry entry : where.entrySet()) { + BsonDocument bson = BsonUtils.convertBsonToBsonDocument(entry.getValue().toBson()); + document.putAll(bson); + } + + database.insert(collection, document).execute(); + return null; + } + } + + @Override + public boolean equals(Object o) { + return super.equals(o); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/list/MongoDBListTables.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/list/MongoDBListTables.java new file mode 100644 index 000000000..987eba440 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/list/MongoDBListTables.java @@ -0,0 +1,29 @@ +package net.codingarea.commons.database.mongodb.list; + +import net.codingarea.commons.database.action.DatabaseListTables; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; + +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.List; + +public class MongoDBListTables implements DatabaseListTables { + + protected final MongoDBDatabase database; + + public MongoDBListTables(@Nonnull MongoDBDatabase database) { + this.database = database; + } + + @Nonnull + @Override + public List execute() throws DatabaseException { + try { + return database.getDatabase().listCollectionNames().into(new ArrayList<>()); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBQuery.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBQuery.java new file mode 100644 index 000000000..e1e11832b --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBQuery.java @@ -0,0 +1,128 @@ +package net.codingarea.commons.database.mongodb.query; + +import com.mongodb.client.FindIterable; +import com.mongodb.client.model.Filters; +import net.codingarea.commons.common.misc.MongoUtils; +import net.codingarea.commons.database.Order; +import net.codingarea.commons.database.action.DatabaseQuery; +import net.codingarea.commons.database.action.ExecutedQuery; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.abstraction.DefaultExecutedQuery; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import net.codingarea.commons.database.mongodb.where.ObjectWhere; +import net.codingarea.commons.database.mongodb.where.StringIgnoreCaseWhere; +import org.bson.Document; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; + +public class MongoDBQuery implements DatabaseQuery { + + protected final MongoDBDatabase database; + protected final String collection; + protected final Map where; + protected Order order; + protected String orderBy; + + public MongoDBQuery(@Nonnull MongoDBDatabase database, @Nonnull String collection) { + this.database = database; + this.collection = collection; + this.where = new HashMap<>(); + } + + public MongoDBQuery(@Nonnull MongoDBDatabase database, @Nonnull String collection, @Nonnull Map where) { + this.database = database; + this.collection = collection; + this.where = where; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::eq)); + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable Number value) { + return where(field, (Object) value); + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable String value) { + return where(field, (Object) value); + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(field, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(field, new StringIgnoreCaseWhere(field, value)); + return this; + } + + @Nonnull + @Override + public DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::ne)); + return this; + } + + @Nonnull + @Override + public DatabaseQuery orderBy(@Nonnull String column, @Nonnull Order order) { + this.orderBy = column; + this.order = order; + return this; + } + + @Nonnull + @Override + public DatabaseQuery select(@Nonnull String... selection) { + return this; + } + + @Nonnull + @Override + public ExecutedQuery execute() throws DatabaseException { + try { + FindIterable iterable = database.getCollection(collection).find(); + MongoUtils.applyWhere(iterable, where); + MongoUtils.applyOrder(iterable, orderBy, order); + + List documents = iterable.into(new ArrayList<>()); + return createExecutedQuery(documents); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Nonnull + private ExecutedQuery createExecutedQuery(@Nonnull List documents) { + List results = new ArrayList<>(documents.size()); + for (Document document : documents) { + results.add(new MongoDBResult(document)); + } + + return new DefaultExecutedQuery(results); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBQuery that = (MongoDBQuery) o; + return database.equals(that.database) && collection.equals(that.collection) && where.equals(that.where) && order == that.order && Objects.equals(orderBy, that.orderBy); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, where, order, orderBy); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBResult.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBResult.java new file mode 100644 index 000000000..c65457f05 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBResult.java @@ -0,0 +1,18 @@ +package net.codingarea.commons.database.mongodb.query; + +import net.codingarea.commons.common.config.document.BsonDocument; + +import javax.annotation.Nonnull; + +public final class MongoDBResult extends BsonDocument { + + public MongoDBResult(@Nonnull org.bson.Document bsonDocument) { + super(bsonDocument); + } + + @Override + public boolean isReadonly() { + return true; + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/update/MongoDBUpdate.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/update/MongoDBUpdate.java new file mode 100644 index 000000000..6e30f14f4 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/update/MongoDBUpdate.java @@ -0,0 +1,139 @@ +package net.codingarea.commons.database.mongodb.update; + +import com.mongodb.BasicDBObject; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.model.Collation; +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.UpdateOptions; +import net.codingarea.commons.common.misc.BsonUtils; +import net.codingarea.commons.common.misc.MongoUtils; +import net.codingarea.commons.database.action.DatabaseUpdate; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import net.codingarea.commons.database.mongodb.where.MongoDBWhere; +import net.codingarea.commons.database.mongodb.where.ObjectWhere; +import net.codingarea.commons.database.mongodb.where.StringIgnoreCaseWhere; +import org.bson.BsonDocument; +import org.bson.Document; +import org.bson.conversions.Bson; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; + +public class MongoDBUpdate implements DatabaseUpdate { + + protected final MongoDBDatabase database; + protected final String collection; + protected final Map where; + protected final Map values; + + public MongoDBUpdate(@Nonnull MongoDBDatabase database, @Nonnull String collection) { + this.database = database; + this.collection = collection; + this.where = new HashMap<>(); + this.values = new HashMap<>(); + } + + public MongoDBUpdate(@Nonnull MongoDBDatabase database, @Nonnull String collection, @Nonnull Map where, @Nonnull Map values) { + this.database = database; + this.collection = collection; + this.where = where; + this.values = values; + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::eq)); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String field, @Nullable Number value) { + return where(field, (Object) value); + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String field, @Nullable String value) { + return where(field, (Object) value); + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(field, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(field, new StringIgnoreCaseWhere(field, value)); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate whereNot(@Nonnull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::ne)); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate set(@Nonnull String field, @Nullable Object value) { + values.put(field, MongoUtils.packObject(value)); + return this; + } + + @Override + public Void execute() throws DatabaseException { + try { + MongoCollection collection = database.getCollection(this.collection); + + Document filter = new Document(); + UpdateOptions options = new UpdateOptions(); + + for (MongoDBWhere where : where.values()) { + Bson whereBson = where.toBson(); + BsonDocument asBsonDocument = BsonUtils.convertBsonToBsonDocument(whereBson); + filter.putAll(asBsonDocument); + + Collation collation = where.getCollation(); + if (collation != null) + options.collation(collation); + } + + Document newDocument = new Document(); + for (Entry entry : values.entrySet()) { + newDocument.put(entry.getKey(), MongoUtils.packObject(entry.getValue())); + } + + BasicDBObject update = new BasicDBObject(); + update.put("$set", newDocument); + + collection.updateMany(filter, update, options); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBUpdate that = (MongoDBUpdate) o; + return database.equals(that.database) + && collection.equals(that.collection) + && where.equals(that.where) + && values.equals(that.values); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, where, values); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/MongoDBWhere.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/MongoDBWhere.java new file mode 100644 index 000000000..64a41b89e --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/MongoDBWhere.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.database.mongodb.where; + +import com.mongodb.client.model.Collation; +import org.bson.conversions.Bson; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface MongoDBWhere { + + @Nonnull + Bson toBson(); + + @Nullable + Collation getCollation(); + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/ObjectWhere.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/ObjectWhere.java new file mode 100644 index 000000000..84852ffb2 --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/ObjectWhere.java @@ -0,0 +1,49 @@ +package net.codingarea.commons.database.mongodb.where; + +import com.mongodb.client.model.Collation; +import net.codingarea.commons.common.misc.MongoUtils; +import org.bson.conversions.Bson; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; +import java.util.function.BiFunction; + +public class ObjectWhere implements MongoDBWhere { + + protected final String field; + protected final Object value; + protected final BiFunction creator; + + public ObjectWhere(@Nonnull String field, @Nullable Object value, @Nonnull BiFunction creator) { + this.field = field; + this.value = MongoUtils.packObject(value); + this.creator = creator; + } + + @Nonnull + @Override + public Bson toBson() { + return creator.apply(field, value); + } + + @Nullable + @Override + public Collation getCollation() { + return null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ObjectWhere that = (ObjectWhere) o; + return field.equals(that.field) && Objects.equals(value, that.value); + } + + @Override + public int hashCode() { + return Objects.hash(field, value); + } + +} diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/StringIgnoreCaseWhere.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/StringIgnoreCaseWhere.java new file mode 100644 index 000000000..d7e875f8e --- /dev/null +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/StringIgnoreCaseWhere.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.database.mongodb.where; + +import com.mongodb.client.model.Collation; +import com.mongodb.client.model.CollationStrength; +import com.mongodb.client.model.Filters; +import org.bson.conversions.Bson; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; + +public class StringIgnoreCaseWhere implements MongoDBWhere { + + protected final String field; + protected final String value; + + public StringIgnoreCaseWhere(@Nonnull String field, @Nonnull String value) { + this.field = field; + this.value = value; + } + + @Nonnull + @Override + public Bson toBson() { + return Filters.eq(field, value); + } + + @Nullable + @Override + public Collation getCollation() { + return Collation.builder().collationStrength(CollationStrength.SECONDARY).locale("en").build(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + StringIgnoreCaseWhere that = (StringIgnoreCaseWhere) o; + return field.equals(that.field) && value.equals(that.value); + } + + @Override + public int hashCode() { + return Objects.hash(field, value); + } + +} diff --git a/plugin/pom.xml b/plugin/pom.xml index 1e1785238..edfeaadca 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -20,6 +20,13 @@ + + + org.slf4j + slf4j-api + 1.7.32 + + org.spigotmc @@ -27,11 +34,6 @@ ${spigot.version} provided - - com.github.anweisen.Utility - bukkit-utils - ${utilities.version} - com.mojang authlib @@ -59,18 +61,6 @@ provided - - - com.github.anweisen.Utility - database-api - ${utilities.version} - - - com.github.anweisen.Utility - database-sql - ${utilities.version} - - org.projectlombok @@ -88,12 +78,6 @@ - - - jitpack.io - https://jitpack.io - - spigot-repo @@ -171,11 +155,7 @@ - com.github.anweisen.Utility:commons - com.github.anweisen.Utility:common-utils - com.github.anweisen.Utility:bukkit-utils - com.github.anweisen.Utility:database-api - com.github.anweisen.Utility:database-sql + net.kyori:adventure-api diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java index 08ba1633e..1cec3de1a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin; import lombok.Getter; -import net.anweisen.utilities.bukkit.core.BukkitModule; -import net.anweisen.utilities.common.version.Version; +import net.codingarea.commons.bukkit.core.BukkitModule; +import net.codingarea.commons.common.version.Version; import net.codingarea.challenges.plugin.challenges.custom.settings.CustomSettingsLoader; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.content.loader.LoaderRegistry; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index e0f17ae5a..e8a2e9237 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -2,7 +2,7 @@ import lombok.Getter; import lombok.ToString; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java index 117bead96..1cc84980d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.custom.settings; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.*; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java index 586ff2b89..d808902a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java index a452f268a..22194c0dd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import java.util.Map; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java index fc56b49a4..20915daf0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java index 2180fcc5e..bb6e2ecf7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java index 8044df01f..76de8e406 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java index 71165a4c1..f370a9651 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.challenges.custom.settings.FallbackNames; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java index 6e835fdcc..bd618a663 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java @@ -31,8 +31,8 @@ public void executeFor(Entity entity, Map subActions) { livingEntity.addPotionEffect(effect); } catch (Exception exception) { - Challenges.getInstance().getLogger().severe("Error while adding potion effect to player"); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().severe("Error while adding potion effect to player"); + Challenges.getInstance().getILogger().error("", exception); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java index 036b63421..f51cddf9d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java index f84400c0a..1c967aab1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java index 9e549f65d..76dbdf823 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub; import lombok.Getter; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.*; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.impl.MessageManager; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java index 99db78f06..2ba7ab835 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; public abstract class ValueSetting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java index 6e28dfb55..5ed694708 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java @@ -2,7 +2,7 @@ import com.google.common.collect.Lists; import lombok.Getter; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl.BooleanSetting; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java index f8702057c..48623e544 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java index 8b68286e1..93269312d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.challenges.type.IModifier; @@ -86,9 +86,9 @@ public int getIntValue(String value) { try { return Integer.parseInt(value); } catch (Exception exception) { - Challenges.getInstance().getLogger().severe("Something went wrong while parsing the " + Challenges.getInstance().getILogger().severe("Something went wrong while parsing the " + "value of subsetting " + getKey() + " with value " + value); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } return 0; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java index fb20cdc25..a0ca61a73 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.trigger.impl; -import net.anweisen.utilities.bukkit.utils.item.ItemBuilder.PotionBuilder; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java index 1ed8be435..01256bb88 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index cdffe4629..3a394f7c5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.implementation.setting.MaxHealthSetting; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; @@ -8,7 +8,7 @@ import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java index 53f3059fa..b1688facf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java index 7b1642b87..1fe1e8ac6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java index 320d562d6..24614d601 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java index 5c9ce881f..5c5e8222f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java index 677f1af99..67f64d91f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java index 47e5c80fa..39056f367 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java index 91e7dc361..9857ad5a2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.collection.SeededRandomWrapper; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.collection.SeededRandomWrapper; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java index fc4ca4027..30b0a6d39 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.collection.SeededRandomWrapper; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.collection.SeededRandomWrapper; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java index 637ce9f8b..b140744a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java index 14eec8b49..5b7ebeaa8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.pair.Tuple; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index a75beacdb..5b15d051e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java index f9f6943a8..f7ed9e957 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java index a60f5a536..01cb2af32 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomMobAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java index 862aab974..e82b06d22 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.HydraChallenge; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java index b5c05902a..0d9df9a5a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java index de20c8bae..064c9b2c5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java index 86dbb758e..e87867380 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java index 2bce869e2..b11f85864 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java index 630d0ce7d..08491be15 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomMobAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java index 60229a8b0..f91b95b93 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java index dd68e68e9..bfa6fc65d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.extraworld; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.WorldDependentChallenge; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java index cf65586a8..26a31ea9b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java index 8d60cccb2..85ae08737 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -11,7 +12,6 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java index 838947644..fd61eda4b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java index 7bcd5ab9f..261f26e45 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java @@ -1,7 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -14,7 +15,6 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java index a726d2019..47074dea0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java index 56fb97ae6..8e7ad6ab9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java @@ -1,10 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.pair.Tuple; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -15,7 +16,6 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.md_5.bungee.api.chat.BaseComponent; @@ -197,7 +197,7 @@ private Tuple generateMissingItemsInventory(@Nonnull ItemSta inventory.setItem(slot, getRandomItem(itemStack)); } catch (Exception exception) { inventory.setItem(slot, new ItemStack(Material.BARRIER)); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java index e086bd6ed..3a9dbd54e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java index 762143d4a..fe6b3f63c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.pair.Triple; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Triple; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java index 52747ff62..6b86b70af 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.bukkit.utils.misc.CompatibilityUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java index dca729ffa..486f05d40 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java index 47e33eabd..7c3ddab89 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index cfd3921b5..899c446cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java index 8f1df0fb9..d43893978 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java index 772f3e71f..5c22246d4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java index 2bafe978f..5cf2c4414 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java index d62b3dfcc..188c7dbb5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java index 5b7f33b5e..5f2beb3a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java index e69bb3116..c56645114 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java index 68310cd3d..25ec885dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -57,7 +57,7 @@ public void onLootGenerate(LootGenerateEvent event) { Challenges.getInstance().registerListener(listener); } catch (NoClassDefFoundError noClassDefFoundError) { - Challenges.getInstance().getLogger().warning("Loot Generation couldn't be blocked in FiveHundredBlocks Challenge: Please Use 1.15 or higher"); + Challenges.getInstance().getILogger().warning("Loot Generation couldn't be blocked in FiveHundredBlocks Challenge: Please Use 1.15 or higher"); } @@ -176,7 +176,7 @@ public void loadGameState(@NotNull Document document) { } catch (IllegalArgumentException exception) { plugin.getLogger().severe("Error while loading 500 Blocks Challenge, " + "key '" + key + "' is not a valid uuid"); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java index 3e7c18af7..8b1b57f9b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java index a85e9bcc3..bc8eb2b81 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java index 40caffe17..779262f1c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java index 9d63f1bd2..fb7817f69 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java index cbbf640d3..7b3a20314 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index e540ea849..90b44a7e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.quiz; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.implementation.challenge.quiz.QuizChallenge.IQuestion.Question; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; @@ -15,7 +15,7 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java index 7dabca933..ae3433268 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; import net.codingarea.challenges.plugin.content.Message; @@ -8,7 +9,6 @@ import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.DropPriority; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java index a4ea3360c..72628c416 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java @@ -4,8 +4,8 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java index a0b258204..659d6be31 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 004217c96..32c31c8f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.bukkit.utils.misc.CompatibilityUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java index d454c4c65..aff8383d1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; @@ -207,7 +207,7 @@ private int getSpawnLimit(@Nonnull World world) { try { return useSpawnCategories ? world.getSpawnLimit(SpawnCategory.WATER_AMBIENT) : world.getWaterAmbientSpawnLimit(); } catch (Throwable throwable) { - Challenges.getInstance().getLogger().error("", throwable); + Challenges.getInstance().getILogger().error("", throwable); } } case WATER_ANIMAL: diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java index c5c5e477e..16f8537a3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java index e876a7287..f378b2c0c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java index 7e897854d..55820aaee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomItemAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java index bb87ca313..b7e3a964e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java index 94d4b7ec5..cf96f92f3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java index f20c39856..33ded8246 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java index 007749f92..cdc626c77 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java index 8dd334665..b1686d8a2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java @@ -6,7 +6,7 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; import org.bukkit.Color; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java index b76cfe7c1..fcd1ae478 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.time; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java index f8f582a8b..515636263 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.time; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java index a2a6021aa..116e3760e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeConfigHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java index b6ee091f0..9ea5570da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java index 79eb21ac8..00369062f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java index fa448c186..61a77a830 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java index f61e93990..f86204b47 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java index c2e0120a4..2e1c5c8a3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java index b730729d6..b17959b79 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.common.collection.pair.Tuple; +import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java index 93c033f50..b3c46958b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java index 5a66768cb..e615d4b96 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.document.GsonDocument; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index 72ab023d9..000dea1ee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -13,7 +13,7 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import org.bukkit.Location; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java index 6588aa766..a0b2dc226 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import com.google.common.collect.Lists; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.pair.Triple; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.document.GsonDocument; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Triple; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index 4af53408c..28ae22550 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java index 50fcc15d6..92e6e160c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java index 5e8518a16..127b856eb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java index d7e86c3ec..ee0c8ee49 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index 5c86340c9..303b56631 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -1,10 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.SeededRandomWrapper; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.SeededRandomWrapper; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; @@ -14,7 +15,6 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java index 4e80c2757..ff3a3e747 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java index 42cbc8f41..1631103ae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java index 449d3d2e5..e2e7cbffe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.CollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java index a1acc29bf..2e710b704 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java index d9145b4c8..1e28b334f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.CollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java index 5fa0758ad..c371f63f5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java index 2a5a98552..d0c36d32b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java index 6fbb0a0ca..8027dc78b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java index e90d6996e..2fa73fcf7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java index 3c6ce547b..e84756f69 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java index 035471b55..00a768f51 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.FindItemGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java index 94644d28d..394272035 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java index b5dede66f..bd79ebbed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index 0474468bf..aa3ed1570 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -8,7 +8,7 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java index 149be26d3..170fb80ac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java index 06c17811c..376d625c3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java index 86c667581..0b97d4274 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java index d8ae5cfcd..eed2c9d87 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java index 02650f3b6..4a1cb5ac5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java index 1b1290707..3aa197d2f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java index d2d062dda..f84395c18 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java index d45086267..6fd97c7be 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java index 1059a1d3a..e98c71fbf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java index 6bf8f41fc..551b46b8f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java index 3aa89c5a3..0834bea22 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java index a834abae8..16a7bb90f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.FirstPlayerAtHeightGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java index abe805f0d..e27fb4c3a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.FirstPlayerAtHeightGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java index 98f0b326b..b4405e994 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java index 8f1e96643..d63c7a93f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java index 27a6b402e..ed4f63bf3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierGoal; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java index 711414e17..7e8908424 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.*; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java index 9290b0d2b..bd9a823b7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.AdvancementTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java index 3010f5a48..783e07722 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.BiomeTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java index 1ecf964ab..b2764d8ae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.BlockTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java index 64896b11d..9f5519808 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.DamageTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java index e454d07e0..399dbb267 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.HeightTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java index bec126bed..826021f01 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ItemTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java index be2caa7ec..3325a2396 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.annotations.Since; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.MobTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java index 885f1ceda..5e9a2c85e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.PositionTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java index 51ed23a66..088da9146 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java @@ -3,9 +3,9 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java index 5b2b1d526..d775f5a09 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java @@ -3,8 +3,8 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java index 7d5012c5a..524057bd7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.collection.pair.Tuple; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import org.bukkit.Location; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java index 34bed85b8..3b02b1a14 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; @@ -118,7 +118,7 @@ protected void loadChecked(@Nonnull Document document, @Nonnull String key, @Non if (value == null) return; BukkitSerialization.fromBase64(inventory, value); } catch (IOException exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java index bc31d6d29..3c062bb33 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.NetherPortalSpawnSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java index dc5e9aea1..c30223490 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java @@ -1,7 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -10,7 +11,6 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.Utils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java index 8e029ac56..303ddf53a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java index 6f5c14d5f..f0e163278 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java index 55c7a7a51..f6368a423 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java index 659aaeec7..551859310 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java index 748011a2d..f4abafbc2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.NetherPortalSpawnSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java index 55176e6ed..e1134eb6c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -67,7 +67,7 @@ private void show(@Nonnull Player player) { try { objective.setRenderType(RenderType.HEARTS); } catch (Exception ex) { - Challenges.getInstance().getLogger().severe("Tablist Health could not be updated. You are using an outdated version of spigot."); + Challenges.getInstance().getILogger().severe("Tablist Health could not be updated. You are using an outdated version of spigot."); // In some versions of spigot RenderType does not exist } @@ -82,7 +82,7 @@ private void hide(@Nonnull Player player) { try { objective.unregister(); } catch (Exception ex) { - Challenges.getInstance().getLogger().severe("Error while unregistering tablist hearts objective"); + Challenges.getInstance().getILogger().severe("Error while unregistering tablist hearts objective"); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java index fa6eb8e24..088db39dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index f460ecd9d..68ca3bde3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -1,14 +1,14 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.item.MaterialWrapper; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.document.GsonDocument; +import net.codingarea.commons.bukkit.utils.wrapper.MaterialWrapper; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.attribute.AttributeInstance; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java index 0e0b09421..23be5b36a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java index 3fa5c2747..054dd292d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java index 98529fca2..c1b1ce733 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java index 635874ed7..4be83995e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java index 3627347ee..6b3f76e71 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java index 60e150200..3881c0cc2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index 4333b5525..da91a8eef 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java index 36e89c03c..c4bc864bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -8,7 +9,6 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import org.bukkit.Bukkit; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java index 0d5e1a187..627bd099e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java index 2199b8451..74bd86114 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.anweisen.utilities.common.annotations.Since; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java index b96458fd0..4ef7440cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java index 708f9e99e..506d29f1c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.challenges.ChallengeManager; import net.codingarea.challenges.plugin.management.challenges.entities.GamestateSaveable; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java index c3943a7a4..6f597140d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.challenges.ChallengeManager; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java index 929fd8e19..35838577d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java @@ -2,9 +2,9 @@ import lombok.Getter; import lombok.Setter; -import net.anweisen.utilities.common.annotations.DeprecatedSince; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.annotations.DeprecatedSince; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java index 65ab3cde8..102977b53 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import lombok.Setter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java index 3e155e5a3..2ad3bacf4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java index 24c3742b1..0c2ef8b48 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java index 721c5a343..4c29f8444 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java index 694afe425..b92624eed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ForceTarget; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java index 8aa1b47ed..0ff8f60b3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.document.GsonDocument; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ForceTarget; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java index 301d87772..aeec44b76 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java index 6b772881a..5b10af2c1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java index 34a101526..11da3d1d0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java index cee709060..b2d8270ff 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.bukkit.utils.menu.positions.EmptyMenuPosition; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.positions.EmptyMenuPosition; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java index 1c7edca94..e6676859a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -68,7 +68,7 @@ public void setValue(int value) { try { if (isEnabled()) onValueChange(); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Error while modifying value of Setting {}", getClass().getSimpleName(), exception); + Challenges.getInstance().getILogger().error("Error while modifying value of Setting {}", getClass().getSimpleName(), exception); } updateItems(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java index 4a71765d2..c656d0ff7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java index 33b52d8a5..5fc09751b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java index d37d3abc7..58a57c890 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java index f625256b8..29a6f6e87 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.collection.SeededRandomWrapper; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.collection.SeededRandomWrapper; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java index 33804057c..3539e476a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -76,7 +76,7 @@ public void setEnabled(boolean enabled) { if (enabled) onEnable(); else onDisable(); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Error while {} Setting {}", enabled ? "enabling" : "disabling", getClass().getSimpleName(), exception); + Challenges.getInstance().getILogger().error("Error while {} Setting {}", enabled ? "enabling" : "disabling", getClass().getSimpleName(), exception); } updateItems(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java index d969538ca..92721607a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java index 59c5c6f4b..7d407578f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java index a29db2230..75f07e057 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java index 841c6e433..aab2ddca6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java index 2c527f4a4..a4255303a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import lombok.Setter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java index 3b7a6253e..6e57cc5c5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java index a99261bce..cc59d1b49 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.helper; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import javax.annotation.CheckReturnValue; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index 79a3b346d..7cfd70ce4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.helper; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java index e567f1e48..1051d797c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.helper; -import net.anweisen.utilities.common.collection.NumberFormatter; +import net.codingarea.commons.common.collection.NumberFormatter; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java index 1f10fa067..f4dfa9226 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.helper; -import net.anweisen.utilities.bukkit.utils.item.ItemBuilder.PotionBuilder; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.ChooseItemSubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.ChooseMultipleItemSubSettingBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java index 11e321c84..9ea299e7f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.content; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.misc.ColorConversions; import org.bukkit.ChatColor; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java index 2d5082f33..a7266d1a8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.content; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.content.impl.MessageManager; import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.command.CommandSender; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java index 5c888eec8..bbef01e1d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.content.impl; -import net.anweisen.utilities.common.collection.IRandom; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.ItemDescription; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index 556bab187..fc34aca48 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -5,12 +5,12 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.IOUtils; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; -import net.anweisen.utilities.common.misc.FileUtils; -import net.anweisen.utilities.common.misc.GsonUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.IOUtils; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.misc.FileUtils; +import net.codingarea.commons.common.misc.GsonUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; @@ -147,7 +147,7 @@ private void download() { Logger.debug("Writing language {} to {}", name, file); verifyLanguage(language, file, name); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); Logger.error("Could not download language for {}. {}: {}", element, exception.getClass().getSimpleName(), exception.getMessage()); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java index 9b9a8952d..05a44760a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.content.loader; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java index 4cd3d8f02..0cf9321b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.content.loader; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.FileDocument; -import net.anweisen.utilities.common.misc.FileUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.challenges.plugin.content.Prefix; import java.io.File; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java index bec84bcee..129814eb0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.content.loader; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.IOUtils; -import net.anweisen.utilities.common.version.Version; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.IOUtils; +import net.codingarea.commons.common.version.Version; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.configuration.file.YamlConfiguration; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java index 8f639b03f..6d9734968 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.blocks; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.challenges.implementation.setting.CutCleanSetting; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting.SubSetting; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java index 733f50598..92bd18d14 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.management.bstats; -import net.anweisen.utilities.bukkit.utils.bstats.Metrics; -import net.anweisen.utilities.bukkit.utils.bstats.chart.AdvancedPie; -import net.anweisen.utilities.bukkit.utils.bstats.chart.SimplePie; -import net.anweisen.utilities.bukkit.utils.bstats.chart.SingleLineChart; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.bstats.Metrics; +import net.codingarea.commons.bukkit.utils.bstats.chart.AdvancedPie; +import net.codingarea.commons.bukkit.utils.bstats.chart.SimplePie; +import net.codingarea.commons.bukkit.utils.bstats.chart.SingleLineChart; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.utils.misc.MemoryConverter; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java index adafa7d83..cf5b7a59a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.challenges; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.*; import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.*; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java index 7938c1f73..da5245eac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.management.challenges; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; -import net.anweisen.utilities.common.config.document.GsonDocument; -import net.anweisen.utilities.common.config.document.wrapper.FileDocumentWrapper; -import net.anweisen.utilities.database.exceptions.DatabaseException; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.wrapper.FileDocumentWrapper; +import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.type.IChallenge; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java index 849b9d866..4696a756d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.challenges; import lombok.Getter; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; @@ -70,8 +70,8 @@ public void loadCustomChallengesFrom(@Nonnull Document document) { challenge.setEnabled(doc.getBoolean("enabled")); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Something went wrong while initializing custom challenge {} :: {}", key, exception.getMessage()); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("Something went wrong while initializing custom challenge {} :: {}", key, exception.getMessage()); + Challenges.getInstance().getILogger().error("", exception); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java index c04f78eb5..28950d530 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.challenges; -import net.anweisen.utilities.bukkit.core.BukkitModule; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.core.BukkitModule; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.implementation.damage.DamageRuleSetting; import net.codingarea.challenges.plugin.challenges.implementation.material.BlockMaterialSetting; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java index 67c14cba2..3f76cf0df 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.challenges.annotations; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import javax.annotation.Nonnull; import java.lang.annotation.ElementType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java index 4f24c0ff8..58f269cee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.challenges.entities; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java index cc98c7bc8..ff36638d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.management.cloud; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.WrappedException; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.cloud.support.CloudNet2Support; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java index 36019f377..1ff4612f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java @@ -1,19 +1,19 @@ package net.codingarea.challenges.plugin.management.database; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.pair.Tuple; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.database.Database; -import net.anweisen.utilities.database.DatabaseConfig; -import net.anweisen.utilities.database.SQLColumn; -import net.anweisen.utilities.database.action.ExecutedQuery; -import net.anweisen.utilities.database.exceptions.DatabaseException; -import net.anweisen.utilities.database.internal.sql.abstraction.AbstractSQLDatabase; -import net.anweisen.utilities.database.internal.sql.mysql.MySQLDatabase; -import net.anweisen.utilities.database.internal.sql.sqlite.SQLiteDatabase; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.SQLColumn; +import net.codingarea.commons.database.action.ExecutedQuery; +import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.mysql.MySQLDatabase; +import net.codingarea.commons.database.sql.sqlite.SQLiteDatabase; import org.bukkit.Bukkit; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; @@ -107,10 +107,10 @@ private void loadMigration() { } catch (DatabaseException databaseException) { try { sqlDatabase.prepare("ALTER TABLE `challenges` ADD COLUMN `custom_challenges` text(60000)").execute(); - Challenges.getInstance().getLogger().info("Creating not existing column 'custom_challenges' in SQL Database"); + Challenges.getInstance().getILogger().info("Creating not existing column 'custom_challenges' in SQL Database"); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create non existing column 'custom_challenges' in SQL Database"); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("Failed to create non existing column 'custom_challenges' in SQL Database"); + Challenges.getInstance().getILogger().error("", exception); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java index 6b589a3e2..73ad01456 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.management.files; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; -import net.anweisen.utilities.common.config.document.GsonDocument; -import net.anweisen.utilities.common.config.document.YamlDocument; -import net.anweisen.utilities.common.misc.FileUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.YamlDocument; +import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; @@ -73,7 +73,7 @@ public YamlConfiguration getDefaultConfig() { return defaultConfig; } catch (IOException | NullPointerException | InvalidConfigurationException exception) { plugin.getLogger().severe("Error while checking missing keys in the current config"); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } return null; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java index 331ba48f4..e2c86f35f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.management.inventory; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.collection.pair.Triple; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.pair.Triple; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java index ad1b72506..f4f63b65e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.management.menu; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.AnimatedInventory; -import net.anweisen.utilities.bukkit.utils.animation.AnimationFrame; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.AnimationFrame; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java index d5bb0eaa4..6996e9588 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.management.menu.generator; import com.google.common.collect.ImmutableList; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.common.version.Version; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.common.version.Version; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java index 4a651f33e..b268c8558 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.MainCustomMenuGenerator; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java index 1cffe6938..8efcc07f5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java index d63a57f47..5fadbe3f4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java @@ -2,8 +2,8 @@ import lombok.Getter; import lombok.Setter; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.bukkit.utils.misc.CompatibilityUtils; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.position.GeneratorMenuPosition; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java index 79798c9e8..e0a398b3a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java index fe49411ca..42bcb88e1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.management.menu.generator; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java index 44ff6898c..865652da3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.menu.generator.categorised; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java index 7b3334c6b..02585fecf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.management.menu.generator.ChallengeMenuGenerator; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java index 36c597f33..194f6e778 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java index 0e5abe92e..0700ff5bc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java @@ -2,10 +2,10 @@ import lombok.Getter; import lombok.ToString; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java index 3286ecd78..2f5417ac5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.type.IChallenge; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java index 46ef222e5..ff40c7b97 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; import net.codingarea.challenges.plugin.management.menu.generator.ChooseItemGenerator; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java index ceff6e5cd..53b285c9d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.menu.info; import lombok.ToString; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java index 3fcbcb702..694b9463f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.menu.position; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; @Getter diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java index 1e77f5ddf..eecf8b281 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.scheduler; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import javax.annotation.Nonnull; import java.lang.reflect.InvocationTargetException; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java index cac8bf196..9c3c5e88b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.scheduler; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.misc.ReflectionUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.misc.ReflectionUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java index c3cddbee6..44d2789c0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.management.scheduler.timer; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java index d06b1fcf4..f96662dbc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.scheduler.timer; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java index 3c459357b..fa4c045dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.server; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.challenges.entities.GamestateSaveable; import net.codingarea.challenges.plugin.spigot.generator.VoidMapGenerator; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java index 167230187..6d192f443 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.server; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.challenges.entities.GamestateSaveable; import org.bukkit.Location; @@ -61,8 +61,8 @@ public void loadGameState(@NotNull Document document) { UUID uuid = UUID.fromString(key); lastWorldLocations.put(uuid, location); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Couldn't load last location of: " + key); - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("Couldn't load last location of: " + key); + Challenges.getInstance().getILogger().error("", exception); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java index 635ca5ad2..a94da3f0d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.management.server; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java index 5f9049f44..e27a364d9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.server; import lombok.Getter; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java index 2a995251f..2d7435838 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java @@ -2,10 +2,10 @@ import lombok.Getter; import lombok.Setter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.config.FileDocument; -import net.anweisen.utilities.common.misc.FileUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java index 5cd463aa5..a1f7d0ba8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.server.scoreboard; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java index 2df8a1d38..d61318aee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java @@ -2,8 +2,8 @@ import lombok.Getter; import lombok.ToString; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java index 323ab33ec..32f93b00f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.stats; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnull; import java.util.EnumMap; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java index 1768554da..c577f2b18 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.stats; -import net.anweisen.utilities.common.collection.NumberFormatter; +import net.codingarea.commons.common.collection.NumberFormatter; import javax.annotation.Nonnull; import java.util.function.Function; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java index a38572dc3..6a83e2f97 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.stats; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.database.exceptions.DatabaseException; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.scheduler.policy.ChallengeStatusPolicy; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java index a79e00ec1..a633ec0d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.team; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java index 69d1d4da7..987cc8bd7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import com.google.common.collect.Lists; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java index 9fbeb77f5..ae464b130 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.common.config.FileDocument; +import net.codingarea.commons.common.config.FileDocument; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java index 664b388d3..314ba6555 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; -import net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; import org.bukkit.attribute.AttributeInstance; import org.bukkit.command.CommandSender; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java index 85cfe3f5f..e32682f0e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.bukkit.utils.menu.positions.SlottedMenuPosition; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.positions.SlottedMenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java index 8f9752051..605a0a634 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.animation.AnimatedInventory; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; -import net.anweisen.utilities.bukkit.utils.menu.positions.SlottedMenuPosition; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.positions.SlottedMenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java index 88cb3bc79..e463a4d51 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import com.google.common.collect.Lists; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -69,7 +69,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { try { seed = Long.parseLong(seedInput); } catch (NumberFormatException exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java index 0c9313f58..c5f7ef062 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java index 1248a6519..1997de2b3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.RegisteredDrops; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; -import net.codingarea.challenges.plugin.utils.item.ItemUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.Utils; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java index 5e222ab6d..d14ea9e61 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.animation.AnimatedInventory; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java index a202e72c5..de37a99cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.common.collection.NumberFormatter; +import net.codingarea.commons.common.collection.NumberFormatter; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java index 2a451558d..c1a6a2e8f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.common.misc.StringUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java index f4a514e70..41b8f4d89 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java index ce34a1044..387af43cb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.generator; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.World; @@ -36,7 +36,7 @@ public ChunkData generateChunkData(@Nonnull World world, @Nonnull Random random, } // if (portalChunk.chunkX == x && portalChunk.chunkZ == z) { -// Challenges.getInstance().getLogger().info("Generating End Portal"); +// Challenges.getInstance().getILogger().info("Generating End Portal"); // generateEndPortal(chunkData); // break; // } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java index 1a82f62ba..8457776c8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.listener; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.GameMode; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java index 00b11602f..00de88ed9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.listener; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java index 05e6668f2..82dfe55ef 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.listener; -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.spigot.events.*; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index f8a2f62f1..22ef71374 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.listener; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -127,7 +127,7 @@ public void onQuit(@Nonnull PlayerQuitEvent event) { Message.forName("quit-message").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); } } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Error while handling disconnect", exception); + Challenges.getInstance().getILogger().error("Error while handling disconnect", exception); } if (Bukkit.getOnlinePlayers().size() <= 1) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java index a2f83c357..650a3e5f7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.bukkit.command; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import org.bukkit.command.Command; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java index 924e681a0..776df6c8c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.bukkit.command; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.content.Prefix; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java index 10294e07c..f403eeceb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.bukkit.jumpgeneration; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.collection.IRandom; import org.bukkit.block.Block; import javax.annotation.CheckReturnValue; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java index c0d460d35..fe582fe7c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.bukkit.jumpgeneration; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.common.collection.IRandom; import org.bukkit.block.Block; import javax.annotation.CheckReturnValue; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java index a41712252..c5f73691e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.utils.bukkit.misc; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.collection.WrappedException; -import net.anweisen.utilities.common.logging.ILogger; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.logging.ILogger; import net.codingarea.challenges.plugin.content.Prefix; import net.md_5.bungee.api.chat.*; import org.bukkit.*; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/MinecraftVersion.java deleted file mode 100644 index 2077593a8..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/MinecraftVersion.java +++ /dev/null @@ -1,114 +0,0 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.version; - -import org.bukkit.Bukkit; - -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; - -public enum MinecraftVersion implements Version { - - V1_0, // 1.0 - V1_1, // 1.1 - V1_2_1, // 1.2.1 - V1_3_1, // 1.3.1 - V1_4_2, // 1.4.2 - V1_5, // 1.5 - V1_6, // 1.6 - V1_7, // 1.7 - V1_7_2, // 1.7.2 - V1_8, // 1.8 - V1_9, // 1.9 - V1_10, // 1.10 - V1_11, // 1.11 - V1_12, // 1.12 - V1_13, // 1.13 - V1_14, // 1.14 - V1_15, // 1.15 - V1_16, // 1.16 - V1_16_5, // 1.16.5 - V1_17, // 1.17 - V1_18, // 1.18 - V1_19, // 1.19 - V1_20, // 1.20 - V1_20_1, // 1.20.1 - V1_20_2, // 1.20.2 - V1_20_3, // 1.20.3 - V1_20_4, // 1.20.4 - V1_20_5, // 1.20.5 - V1_21, // 1.21 - V1_21_1, // 1.21.1 - V1_21_2, // 1.21.2 - V1_21_3, // 1.21.3 - V1_21_4, // 1.21.4 - V1_21_5 // 1.21.5 - ; - - private final int major, minor, revision; - - MinecraftVersion() { - - String name = this.name().substring(1); - String[] version = name.split("_"); - - if (version.length != 2 && version.length != 3) - throw new IllegalArgumentException("Name '" + name() + "' does not match pattern: V{major}_{minor}_[revision]"); - - major = Integer.parseInt(version[0]); - minor = Integer.parseInt(version[1]); - revision = version.length > 2 ? Integer.parseInt(version[2]) : 0; - - } - - @Override - public int getMajor() { - return major; - } - - @Override - public int getMinor() { - return minor; - } - - @Override - public int getRevision() { - return revision; - } - - @Override - public String toString() { - return this.format(); - } - - @Nonnull - @CheckReturnValue - public static Version parseExact(@Nonnull String bukkitVersion) { - bukkitVersion = bukkitVersion.substring(0, bukkitVersion.indexOf("-")); - return Version.parse(bukkitVersion); - } - - @Nonnull - @CheckReturnValue - public static Version findNearest(@Nonnull Version realVersion) { - return Version.findNearest(realVersion, values()); - } - - private static Version currentExact; - private static Version current; - - @Nonnull - @CheckReturnValue - public static Version currentExact() { - if (currentExact == null) - currentExact = parseExact(Bukkit.getBukkitVersion()); - return currentExact; - } - - @Nonnull - @CheckReturnValue - public static Version current() { - if (current == null) - current = findNearest(currentExact()); - return current; - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/Version.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/Version.java deleted file mode 100644 index e21567f10..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/Version.java +++ /dev/null @@ -1,105 +0,0 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.version; - -import net.anweisen.utilities.common.annotations.Since; - -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.*; - -public interface Version { - @Nonnegative - int getMajor(); - - @Nonnegative - int getMinor(); - - @Nonnegative - int getRevision(); - - default boolean isNewerThan(@Nonnull Version other) { - return this.intValue() > other.intValue(); - } - - default boolean isNewerOrEqualThan(@Nonnull Version other) { - return this.intValue() >= other.intValue(); - } - - default boolean isOlderThan(@Nonnull Version other) { - return this.intValue() < other.intValue(); - } - - default boolean isOlderOrEqualThan(@Nonnull Version other) { - return this.intValue() <= other.intValue(); - } - - default boolean equals(@Nonnull Version other) { - return this.intValue() == other.intValue(); - } - - @Nonnull - default String format() { - int revision = this.getRevision(); - return revision > 0 ? String.format("%s.%s.%s", this.getMajor(), this.getMinor(), revision) : String.format("%s.%s", this.getMajor(), this.getMinor()); - } - - default int intValue() { - int major = this.getMajor(); - int minor = this.getMinor(); - int revision = this.getRevision(); - if (major > 99) { - throw new IllegalStateException("Malformed version: major is greater than 99"); - } else if (minor > 99) { - throw new IllegalStateException("Malformed version: minor is greater than 99"); - } else if (revision > 99) { - throw new IllegalStateException("Malformed version: revision is greater than 99"); - } else { - return revision + minor * 100 + major * 10000; - } - } - - @Nonnull - @CheckReturnValue - static Version parse(@Nullable String input) { - return parse(input, new VersionInfo(1, 0, 0)); - } - - @CheckReturnValue - static Version parse(@Nullable String input, Version def) { - return VersionInfo.parse(input, def); - } - - @Nonnull - @CheckReturnValue - static Version parseExceptionally(@Nullable String input) { - return VersionInfo.parseExceptionally(input); - } - - @Nonnull - @CheckReturnValue - static Version getAnnotatedSince(@Nonnull Object object) { - return (Version) (!object.getClass().isAnnotationPresent(Since.class) ? new VersionInfo(1, 0, 0) : parse(object.getClass().getAnnotation(Since.class).value())); - } - - @Nonnull - @CheckReturnValue - static V findNearest(@Nonnull Version target, @Nonnull V[] sortedVersionsArray) { - List versions = new ArrayList(Arrays.asList(sortedVersionsArray)); - Collections.reverse(versions); - - for (V version : versions) { - if (!version.isNewerThan(target)) { - return version; - } - } - - throw new IllegalArgumentException("No version found for '" + target + "'"); - } - - @Nonnull - @CheckReturnValue - static Comparator comparator() { - return new VersionComparator(); - } -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionComparator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionComparator.java deleted file mode 100644 index 3f937009f..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionComparator.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.version; - -import javax.annotation.Nonnull; -import java.util.Comparator; - -public class VersionComparator implements Comparator { - public VersionComparator() { - } - - public int compare(@Nonnull Version v1, @Nonnull Version v2) { - return v1.equals(v2) ? 0 : (v1.isNewerThan(v2) ? 1 : -1); - } -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionInfo.java deleted file mode 100644 index af9f78e34..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/version/VersionInfo.java +++ /dev/null @@ -1,70 +0,0 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.version; - -import lombok.Getter; -import net.anweisen.utilities.common.logging.ILogger; - -import javax.annotation.Nullable; -import java.util.Objects; - -@Getter -public class VersionInfo implements Version { - protected static final ILogger logger = ILogger.forThisClass(); - private final int major; - private final int minor; - private final int revision; - - public VersionInfo() { - this(1, 0, 0); - } - - public VersionInfo(int major, int minor, int revision) { - this.major = major; - this.minor = minor; - this.revision = revision; - } - - public boolean equals(Object other) { - if (this == other) { - return true; - } else { - return other instanceof Version && this.equals(other); - } - } - - public int hashCode() { - return Objects.hash(this.major, this.minor, this.revision); - } - - public String toString() { - return this.format(); - } - - public static Version parseExceptionally(@Nullable String input) { - if (input == null) { - throw new IllegalArgumentException("Version cannot be null"); - } else { - String[] array = input.split("\\."); - if (array.length == 0) { - throw new IllegalArgumentException("Version cannot be empty"); - } else { - try { - int major = Integer.parseInt(array[0]); - int minor = array.length >= 2 ? Integer.parseInt(array[1]) : 0; - int revision = array.length >= 3 ? Integer.parseInt(array[2]) : 0; - return new VersionInfo(major, minor, revision); - } catch (Exception ex) { - throw new IllegalArgumentException("Cannot parse Version: " + input + " (" + ex.getMessage() + ")"); - } - } - } - } - - public static Version parse(@Nullable String input, Version def) { - try { - return parseExceptionally(input); - } catch (Exception ex) { - logger.error("Could not parse version for input {}", ex.getMessage()); - return def; - } - } -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java index 66995d593..4b941e688 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms; import lombok.Getter; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_13.*; import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_17.BorderPacketFactory_1_17; @@ -48,7 +48,7 @@ public static WorldServer createWorldServer(World world) { return new WorldServer_1_13(world); } } catch (ClassNotFoundException exception) { - Challenges.getInstance().getLogger().error("Failed to create WorldServer instance for version {}:", majorVersion, exception); + Challenges.getInstance().getILogger().error("Failed to create WorldServer instance for version {}:", majorVersion, exception); } throw new IllegalStateException("Could not find a WorldServer implementation for version " + getFormattedVersion()); } @@ -68,7 +68,7 @@ public static CraftPlayer createCraftPlayer(Player player) { return new CraftPlayer_1_13(player); } } catch (ClassNotFoundException exception) { - Challenges.getInstance().getLogger().error("Failed to create CraftPlayer instance for version {}:", majorVersion, exception); + Challenges.getInstance().getILogger().error("Failed to create CraftPlayer instance for version {}:", majorVersion, exception); } throw new IllegalStateException("Could not find a CraftServer implementation for version " + getFormattedVersion()); } @@ -88,7 +88,7 @@ public static PlayerConnection createPlayerConnection(CraftPlayer player) { return new PlayerConnection_1_13(player.getPlayerConnectionObject()); } } catch (ClassNotFoundException exception) { - Challenges.getInstance().getLogger().error("Failed to create PlayerConnection instance for version {}:", majorVersion, exception); + Challenges.getInstance().getILogger().error("Failed to create PlayerConnection instance for version {}:", majorVersion, exception); } throw new IllegalStateException("Could not find a PlayerConnection implementation for version " + getFormattedVersion()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java index ec89489cc..65ac625ad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSUtils.java @@ -20,7 +20,7 @@ public static void setEntityName(Entity entity, BaseComponent baseComponent) { Object entityObject = ReflectionUtil.invokeMethod(craftEntityClass, entity, "getHandle"); ReflectionUtil.invokeMethod(entityClass, entityObject, "a", new Class[]{componentClass}, new Object[]{componentObject}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } } @@ -33,7 +33,7 @@ public static void setBossBarTitle(BossBar bossBar, BaseComponent baseComponent) Object bossBattleObject = ReflectionUtil.invokeMethod(craftBossBarClass, bossBar, "getHandle"); ReflectionUtil.invokeMethod(bossBattleClass, bossBattleObject, "a", new Class[]{getComponentClass()}, new Object[]{component}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } } @@ -44,7 +44,7 @@ public static Object toIChatBaseComponent(BaseComponent baseComponent) { Class componentSerializerClass = getClass("network.chat.IChatBaseComponent$ChatSerializer"); return ReflectionUtil.invokeMethod(componentSerializerClass, null, "a", new Class[]{String.class}, new Object[]{json}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } return null; } @@ -63,7 +63,7 @@ public static Class getClass(String path) { return ReflectionUtil.getNmsClass(className); } } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } return null; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java index e3aa8212c..b989752b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/ReflectionUtil.java @@ -76,7 +76,7 @@ public class ReflectionUtil { } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) { - Challenges.getInstance().getLogger().error("Failed to initialize the ReflectionUtil:", e); + Challenges.getInstance().getILogger().error("Failed to initialize the ReflectionUtil:", e); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java index ab832b11c..325144b6e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/BorderPacketFactory_1_13.java @@ -39,7 +39,7 @@ private Object createPacket(PacketBorder packetBorder, String worldBorderAction) } } } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create packet for action {}:", worldBorderAction, exception); + Challenges.getInstance().getILogger().error("Failed to create packet for action {}:", worldBorderAction, exception); } return null; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java index 056bdf485..efaefb83c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/CraftPlayer_1_13.java @@ -25,7 +25,7 @@ public Object get(Player player) { try { craftPlayer = ReflectionUtil.invokeMethod(nmsClass, player, "getHandle"); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create CraftPlayer:", exception); + Challenges.getInstance().getILogger().error("Failed to create CraftPlayer:", exception); craftPlayer = null; } return craftPlayer; @@ -39,7 +39,7 @@ public Object getPlayerConnectionObject() { try { return ReflectionUtil.getObject(this.nmsObject, "playerConnection"); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get the playerConnection object:", exception); + Challenges.getInstance().getILogger().error("Failed to get the playerConnection object:", exception); return null; } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java index de25d60f0..1cb6959a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PacketBorder_1_13.java @@ -41,7 +41,7 @@ protected Object createWorldBorder() { try { return ReflectionUtil.invokeConstructor(nmsClass); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create world border:", exception); + Challenges.getInstance().getILogger().error("Failed to create world border:", exception); return null; } } @@ -56,7 +56,7 @@ protected void setWorld(World world) { try { ReflectionUtil.setFieldValue(worldBorder, "world", getWorldServer(world)); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set world:", exception); + Challenges.getInstance().getILogger().error("Failed to set world:", exception); } } @@ -65,7 +65,7 @@ protected void setSizeField(double size) { try { ReflectionUtil.invokeMethod(worldBorder, "setSize", new Class[]{double.class}, new Object[]{size}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border size:", exception); + Challenges.getInstance().getILogger().error("Failed to set border size:", exception); } } @@ -74,7 +74,7 @@ protected void transitionSizeBetween(double oldSize, double newSize, long animat try { ReflectionUtil.invokeMethod(worldBorder, "transitionSizeBetween", new Class[]{double.class, double.class, long.class}, new Object[]{oldSize, newSize, animationTime}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border size:", exception); + Challenges.getInstance().getILogger().error("Failed to set border size:", exception); } } @@ -83,7 +83,7 @@ protected void setCenterField(double x, double z) { try { ReflectionUtil.invokeMethod(worldBorder, "setCenter", new Class[]{double.class, double.class}, new Object[]{x, z}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border center:", exception); + Challenges.getInstance().getILogger().error("Failed to set border center:", exception); } } @@ -92,7 +92,7 @@ protected void setWarningTimeField(int warningTime) { try { ReflectionUtil.invokeMethod(worldBorder, "setWarningTime", new Class[]{int.class}, new Object[]{warningTime}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border warning time:", exception); + Challenges.getInstance().getILogger().error("Failed to set border warning time:", exception); } } @@ -101,7 +101,7 @@ protected void setWarningDistanceField(int warningDistance) { try { ReflectionUtil.invokeMethod(worldBorder, "setWarningDistance", new Class[]{int.class}, new Object[]{warningDistance}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set border warning distance:", exception); + Challenges.getInstance().getILogger().error("Failed to set border warning distance:", exception); } } @@ -112,7 +112,7 @@ public void send(Player player, UpdateType updateType) { CraftPlayer craftPlayer = NMSProvider.createCraftPlayer(player); craftPlayer.getConnection().sendPacket(packet); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to send update {} to player {}:", updateType.name(), player.getName(), exception); + Challenges.getInstance().getILogger().error("Failed to send update {} to player {}:", updateType.name(), player.getName(), exception); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java index c336ab8c4..6166e17ae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/PlayerConnection_1_13.java @@ -15,7 +15,7 @@ public void sendPacket(Object packet) { try { ReflectionUtil.invokeMethod(this.connection, "sendPacket", new Class[]{nmsClass}, new Object[]{packet}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); + Challenges.getInstance().getILogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java index 1b85a2ee4..353622778 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_13/WorldServer_1_13.java @@ -26,7 +26,7 @@ public Object get(World world) { try { worldServer = ReflectionUtil.invokeMethod(nmsClass, world, "getHandle"); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get WorldServer:", exception); + Challenges.getInstance().getILogger().error("Failed to get WorldServer:", exception); worldServer = null; } return worldServer; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java index 3159aa309..07fc1f75c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/BorderPacketFactory_1_17.java @@ -33,7 +33,7 @@ private Object createPacket(PacketBorder packetBorder, String className) { try { return ReflectionUtil.invokeConstructor(clazz, new Class[]{packetBorder.getNMSClass()}, new Object[]{packetBorder.getWorldBorderObject()}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to create packet {}:", className, exception); + Challenges.getInstance().getILogger().error("Failed to create packet {}:", className, exception); return null; } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java index 1fe13159b..0b816a0c4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_17/CraftPlayer_1_17.java @@ -22,7 +22,7 @@ public Object get(Player player) { try { craftPlayer = ReflectionUtil.invokeMethod(nmsClass, player, "getHandle"); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get CraftPlayer:", exception); + Challenges.getInstance().getILogger().error("Failed to get CraftPlayer:", exception); craftPlayer = null; } return craftPlayer; @@ -33,7 +33,7 @@ public Object getPlayerConnectionObject() { try { return ReflectionUtil.getObject(this.nmsObject, "b"); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to get player connection object:", exception); + Challenges.getInstance().getILogger().error("Failed to get player connection object:", exception); return null; } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java index 0e39fdbc8..f812aad10 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PacketBorder_1_18.java @@ -16,7 +16,7 @@ protected void setCenterField(double x, double z) { try { ReflectionUtil.invokeMethod(worldBorder, "c", new Class[]{double.class, double.class}, new Object[]{x, z}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set center:", exception); + Challenges.getInstance().getILogger().error("Failed to set center:", exception); } } @@ -25,7 +25,7 @@ protected void setSizeField(double size) { try { ReflectionUtil.invokeMethod(worldBorder, "a", new Class[]{double.class}, new Object[]{size}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set size:", exception); + Challenges.getInstance().getILogger().error("Failed to set size:", exception); } } @@ -34,7 +34,7 @@ protected void setWarningDistanceField(int warningDistance) { try { ReflectionUtil.invokeMethod(worldBorder, "c", new Class[]{int.class}, new Object[]{warningDistance}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set warning distance:", exception); + Challenges.getInstance().getILogger().error("Failed to set warning distance:", exception); } } @@ -43,7 +43,7 @@ protected void setWarningTimeField(int warningTime) { try { ReflectionUtil.invokeMethod(worldBorder, "b", new Class[]{int.class}, new Object[]{warningTime}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set warning time:", exception); + Challenges.getInstance().getILogger().error("Failed to set warning time:", exception); } } @@ -52,7 +52,7 @@ protected void transitionSizeBetween(double oldSize, double newSize, long animat try { ReflectionUtil.invokeMethod(worldBorder, "a", new Class[]{double.class, double.class, long.class}, new Object[]{oldSize, newSize, animationTime}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to set size:", exception); + Challenges.getInstance().getILogger().error("Failed to set size:", exception); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java index d96c4c3ec..c254cc8d3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/implementations/v1_18/PlayerConnection_1_18.java @@ -15,7 +15,7 @@ public void sendPacket(Object packet) { try { ReflectionUtil.invokeMethod(this.connection, "a", new Class[]{nmsClass}, new Object[]{packet}); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); + Challenges.getInstance().getILogger().error("Failed to send packet {}:", packet.getClass().getSimpleName(), exception); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index 683ef1c80..b457a897e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -2,7 +2,7 @@ import com.google.gson.JsonParser; import lombok.NonNull; -import net.anweisen.utilities.bukkit.utils.item.BannerPattern; +import net.codingarea.commons.bukkit.utils.item.BannerPattern; import net.codingarea.challenges.plugin.content.ItemDescription; import net.codingarea.challenges.plugin.content.Message; import org.bukkit.*; @@ -27,7 +27,7 @@ import java.util.List; import java.util.UUID; -public class ItemBuilder extends net.anweisen.utilities.bukkit.utils.item.ItemBuilder { +public class ItemBuilder extends net.codingarea.commons.bukkit.utils.item.ItemBuilder { public static final ItemStack BLOCKED_ITEM = new ItemBuilder(Material.BARRIER, "§cBlocked").build(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java deleted file mode 100644 index ce75b81eb..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemUtils.java +++ /dev/null @@ -1,117 +0,0 @@ -package net.codingarea.challenges.plugin.utils.item; - -import net.anweisen.utilities.bukkit.utils.misc.BukkitReflectionUtils; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; -import org.bukkit.inventory.meta.ItemMeta; - -import javax.annotation.Nonnull; - -public class ItemUtils { - - @Nonnull - public static Material convertFoodToCookedFood(@Nonnull Material material) { - try { - return Material.valueOf("COOKED_" + material.name()); - } catch (Exception ex) { - return material; // No cooked material is available - } - } - - public static boolean isObtainableInSurvival(@Nonnull Material material) { - String name = material.name(); - if (BukkitReflectionUtils.isAir(material)) return false; - if (name.endsWith("_SPAWN_EGG")) return false; - if (name.startsWith("INFESTED_")) return false; - if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable - switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist - case "CHAIN_COMMAND_BLOCK": - case "REPEATING_COMMAND_BLOCK": - case "COMMAND_BLOCK": - case "COMMAND_BLOCK_MINECART": - case "JIGSAW": - case "STRUCTURE_BLOCK": - case "STRUCTURE_VOID": - case "BARRIER": - case "BEDROCK": - case "KNOWLEDGE_BOOK": - case "DEBUG_STICK": - case "END_PORTAL_FRAME": - case "END_PORTAL": - case "NETHER_PORTAL": - case "END_GATEWAY": - case "LAVA": - case "WATER": - case "LARGE_FERN": - case "TALL_GRASS": - case "TALL_SEAGRASS": - case "PATH_BLOCK": - case "CHORUS_PLANT": - case "PETRIFIED_OAK_SLAB": - case "FARMLAND": - case "PLAYER_HEAD": - case "GLOBE_BANNER_PATTERN": - case "SPAWNER": - case "AMETHYST_CLUSTER": - case "BUDDING_AMETHYST": - case "POWDER_SNOW": - case "LIGHT": - case "BUNDLE": - case "REINFORCED_DEEPSLATE": - case "FROGSPAWN": - return false; - } - - if (MinecraftVersion.current().isOlderThan(MinecraftVersion.V1_19)) { - return !name.equals("SCULK_SENSOR"); - } - - return true; - } - - public static boolean blockIsAvailableInSurvival(@Nonnull Material material) { - if (!material.isBlock()) return false; - String name = material.name(); - if (BukkitReflectionUtils.isAir(material)) return false; - if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable - switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist - case "CHAIN_COMMAND_BLOCK": - case "REPEATING_COMMAND_BLOCK": - case "COMMAND_BLOCK": - case "COMMAND_BLOCK_MINECART": - case "JIGSAW": - case "STRUCTURE_BLOCK": - case "STRUCTURE_VOID": - case "BARRIER": - case "KNOWLEDGE_BOOK": - case "DEBUG_STICK": - case "END_PORTAL": - case "NETHER_PORTAL": - case "END_GATEWAY": - case "PETRIFIED_OAK_SLAB": - case "PLAYER_HEAD": - case "GLOBE_BANNER_PATTERN": - case "LIGHT": - case "BUNDLE": - return false; - } - - return true; - } - - public static void damageItem(@Nonnull ItemStack item) { - damageItem(item, 1); - } - - public static void damageItem(@Nonnull ItemStack item, int amount) { - ItemMeta meta = item.getItemMeta(); - if (meta == null) return; - if (!(meta instanceof Damageable)) return; - Damageable damageable = (Damageable) meta; - damageable.setDamage(damageable.getDamage() + amount); - item.setItemMeta(meta); - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java index 6f4382d40..771eb1737 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.logging; -import net.anweisen.utilities.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Bukkit; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java index 6bba078ef..348a43631 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java @@ -3,8 +3,8 @@ import com.mojang.authlib.GameProfile; import com.mojang.authlib.properties.Property; import com.mojang.authlib.properties.PropertyMap; -import net.anweisen.utilities.bukkit.utils.logging.Logger; -import net.anweisen.utilities.bukkit.utils.misc.GameProfileUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.GameProfileUtils; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.Bukkit; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java index adbdcc26c..56c365fd0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.bukkit.utils.animation.AnimationFrame; -import net.anweisen.utilities.bukkit.utils.animation.SoundSample; -import net.anweisen.utilities.bukkit.utils.menu.MenuClickInfo; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.bukkit.utils.animation.AnimationFrame; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; import net.codingarea.challenges.plugin.utils.item.DefaultItem; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java index 5e8ff0de1..cf6e7c1f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.common.config.Document; +import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import java.util.*; @@ -37,7 +37,7 @@ public static Map createSubSettingsMapFromDocument(Document do try { map.put(entry.getKey(), document.getStringArray(entry.getKey())); } catch (Exception exception) { - Challenges.getInstance().getLogger().error("", exception); + Challenges.getInstance().getILogger().error("", exception); } } return map; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java index 4952998f1..023f90fa7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.common.misc.ReflectionUtils; +import net.codingarea.commons.common.misc.ReflectionUtils; import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; import org.bukkit.Material; import org.bukkit.Particle; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java index 8d8d9d524..985a65410 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.bukkit.utils.misc.MinecraftVersion; -import net.anweisen.utilities.common.collection.IRandom; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.collection.IRandom; import org.bukkit.*; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java index 96fad9239..18fe9135a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.stats.Statistic; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java index c98b80ee8..c4df7e13a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.anweisen.utilities.common.collection.IOUtils; -import net.anweisen.utilities.common.config.Document; -import net.anweisen.utilities.common.misc.ReflectionUtils; +import net.codingarea.commons.common.collection.IOUtils; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.ReflectionUtils; import org.bukkit.Material; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java new file mode 100644 index 000000000..c90eea42b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java @@ -0,0 +1,375 @@ +package net.codingarea.commons.bukkit.core; + +import com.google.common.base.Charsets; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.MenuPositionListener; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.wrapper.ActionListener; +import net.codingarea.commons.bukkit.utils.wrapper.SimpleEventExecutor; +import net.codingarea.commons.common.annotations.DeprecatedSince; +import net.codingarea.commons.common.annotations.ReplaceWith; +import net.codingarea.commons.common.collection.NamedThreadFactory; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.config.document.YamlDocument; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.internal.BukkitLoggerWrapper; +import net.codingarea.commons.common.logging.lib.JavaILogger; +import net.codingarea.commons.common.version.Version; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.PluginCommand; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; +import org.bukkit.plugin.java.JavaPlugin; + +import javax.annotation.Nonnull; +import java.io.File; +import java.io.InputStreamReader; +import java.lang.reflect.Field; +import java.util.*; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Consumer; +import java.util.logging.Level; + +public abstract class BukkitModule extends JavaPlugin { + + private static volatile BukkitModule firstInstance; + private static boolean setFirstInstance = true; + private static boolean wasShutdown; + + private final Map commands = new HashMap<>(); + private final List listeners = new ArrayList<>(); + private final SimpleConfigManager configManager = new SimpleConfigManager(this); + + private JavaILogger logger; + private ExecutorService executorService; + private Document config, pluginConfig; + private Version version; + private boolean devMode; + private boolean firstInstall; + private boolean isReloaded; + private boolean isLoaded; + + private boolean requirementsMet = true; + + @Override + public final void onLoad() { + isLoaded = true; + + if (!requirementsMet || !(requirementsMet = new RequirementsChecker(this).checkBoolean(getPluginDocument().getDocument("require")))) + return; + + if (setFirstInstance || firstInstance == null) { + setFirstInstance(this); + } + + ILogger.setConstantFactory(this.getILogger()); + trySaveDefaultConfig(); + if (wasShutdown) isReloaded = true; + if (firstInstall = !getDataFolder().exists()) { + getILogger().info("Detected first install!"); + } + if (devMode = getConfigDocument().getBoolean("dev-mode") || getConfigDocument().getBoolean("dev-mode.enabled")) { + getILogger().setLevel(Level.ALL); + getILogger().debug("Devmode is enabled: Showing debug messages. This can be disabled in the plugin.yml ('dev-mode')"); + } else { + getILogger().setLevel(Level.INFO); + } + + injectInstance(); + + try { + handleLoad(); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Override + public final void onEnable() { + if (!requirementsMet) return; + + commands.forEach((name, executor) -> registerCommand0(executor, name)); + listeners.forEach(this::registerListener); + + + try { + handleEnable(); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Override + public final void onDisable() { + Throwable error = null; + try { + handleDisable(); + } catch (Throwable ex) { + error = ex; + } + + setFirstInstance = true; + wasShutdown = true; + isLoaded = false; + commands.clear(); + listeners.clear(); + + if (executorService != null) + executorService.shutdown(); + + for (Player player : Bukkit.getOnlinePlayers()) { + InventoryView view = player.getOpenInventory(); + Inventory inventory = view.getTopInventory(); + if (inventory.getHolder() == MenuPosition.HOLDER) + view.close(); + } + + if (error != null) + throw new WrappedException(error); + } + + protected void handleLoad() throws Exception {} + protected void handleEnable() throws Exception {} + protected void handleDisable() throws Exception {} + + public boolean isDevMode() { + return devMode; + } + + public final boolean isFirstInstall() { + return firstInstall; + } + + public final boolean isReloaded() { + return isReloaded; + } + + public final boolean isLoaded() { + return isLoaded; + } + + public final boolean isFirstInstance() { + return firstInstance == this; + } + + @Nonnull + public JavaILogger getILogger() { + return logger != null ? logger : (logger = new BukkitLoggerWrapper(super.getLogger())); + } + + @Nonnull + public Document getConfigDocument() { + checkLoaded(); + return config != null ? config : (config = new YamlDocument(super.getConfig())); + } + + @Override + public void reloadConfig() { + config = null; + super.reloadConfig(); + } + + /** + * @return the plugin configuration (plugin.yml) as document + */ + @Nonnull + public Document getPluginDocument() { + return pluginConfig != null ? pluginConfig : + (pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(getResource("plugin.yml"), Charsets.UTF_8)))); + } + + @Nonnull + public FileDocument getConfig(@Nonnull String filename) { + return configManager.getDocument(filename); + } + + @Nonnull + public Version getVersion() { + return version != null ? version : (version = Version.parse(getDescription().getVersion())); + } + + @Nonnull + @Deprecated + @DeprecatedSince("1.3.0") + @ReplaceWith("MinecraftVersion.current()") + public MinecraftVersion getServerVersion() { + return MinecraftVersion.current(); + } + + @Nonnull + @Deprecated + @DeprecatedSince("1.3.0") + @ReplaceWith("MinecraftVersion.currentExact()") + public Version getServerVersionExact() { + return MinecraftVersion.currentExact(); + } + + @Nonnull + @Override + @Deprecated + @ReplaceWith("getConfigDocument()") + public FileConfiguration getConfig() { + return super.getConfig(); + } + + @Override + @Deprecated + public void saveConfig() { + super.saveConfig(); + } + + public void setRequirementsFailed() { + this.requirementsMet = false; + } + + public final void registerListenerCommand(@Nonnull T listenerAndExecutor, @Nonnull String... names) { + registerCommand(listenerAndExecutor, names); + registerListener(listenerAndExecutor); + } + + public final void registerCommand(@Nonnull CommandExecutor executor, @Nonnull String... names) { + for (String name : names) { + if (isEnabled()) { + registerCommand0(executor, name); + } else { + commands.put(name, executor); + } + } + } + + private void registerCommand0(@Nonnull CommandExecutor executor, @Nonnull String name) { + PluginCommand command = getCommand(name); + if (command == null) { + getILogger().warn("Tried to register invalid command '{}'", name); + } else { + command.setExecutor(executor); + } + } + + public final void registerListener(@Nonnull Listener... listeners) { + if (isEnabled()) { + for (Listener listener : listeners) { + registerListener0(listener); + } + } else { + this.listeners.addAll(Arrays.asList(listeners)); + } + } + + private void registerListener0(@Nonnull Listener listener) { + if (listener instanceof ActionListener) { + ActionListener actionListener = (ActionListener) listener; + getServer().getPluginManager().registerEvent( + actionListener.getClassOfEvent(), actionListener, actionListener.getPriority(), + new SimpleEventExecutor(actionListener.getClassOfEvent(), actionListener.getListener()), this, actionListener.isIgnoreCancelled() + ); + } else { + getServer().getPluginManager().registerEvents(listener, this); + } + } + + public final void on(@Nonnull Class classOfEvent, @Nonnull Consumer action) { + on(classOfEvent, EventPriority.NORMAL, action); + } + + public final void on(@Nonnull Class classOfEvent, @Nonnull EventPriority priority, @Nonnull Consumer action) { + on(classOfEvent, priority, false, action); + } + + public final void on(@Nonnull Class classOfEvent, @Nonnull EventPriority priority, boolean ignoreCancelled, @Nonnull Consumer action) { + registerListener(new ActionListener<>(classOfEvent, action, priority, ignoreCancelled)); + } + + public final void disablePlugin() { + getServer().getPluginManager().disablePlugin(this); + } + + @Nonnull + public final File getDataFile(@Nonnull String filename) { + return new File(getDataFolder(), filename); + } + + @Nonnull + public final File getDataFile(@Nonnull String subfolder, @Nonnull String filename) { + return new File(getDataFile(subfolder), filename); + } + + @Nonnull + public ExecutorService getExecutor() { + return executorService != null ? executorService : (executorService = Executors.newCachedThreadPool(new NamedThreadFactory(threadId -> String.format("%s-Task-%s", this.getName(), threadId)))); + } + + public void runAsync(@Nonnull Runnable task) { + getExecutor().submit(task); + } + + public final void checkLoaded() { + if (!isLoaded()) + throw new IllegalStateException("Plugin (" + getName() + ") is not loaded yet"); + } + + public final void checkEnabled() { + if (!isEnabled()) + throw new IllegalStateException("Plugin (" + getName() + ") is not enabled yet"); + } + + private void registerAsFirstInstance() { + getILogger().info(getName() + " was loaded as the first BukkitModule"); + registerListener( + new MenuPositionListener() + ); + getILogger().info("Detected server version {} -> {}", getServerVersionExact(), getServerVersion()); + } + + private void trySaveDefaultConfig() { + try { + saveDefaultConfig(); + } catch (IllegalArgumentException ex) { + // No default config exists + } + } + + private void injectInstance() { + try { + Field instanceField = this.getClass().getDeclaredField("instance"); + instanceField.setAccessible(true); + instanceField.set(null, this); + } catch (Throwable ex) { + } + } + + @Nonnull + public static BukkitModule getFirstInstance() { + if (firstInstance == null) { + JavaPlugin provider = JavaPlugin.getProvidingPlugin(BukkitModule.class); + if (!(provider instanceof BukkitModule)) throw new IllegalStateException("No BukkitModule was initialized yet & BukkitModule class was not loaded by a BukkitModule"); + firstInstance = (BukkitModule) provider; + } + + return firstInstance; + } + + private static synchronized void setFirstInstance(@Nonnull BukkitModule module) { + setFirstInstance = false; + firstInstance = module; + module.registerAsFirstInstance(); + } + + @Nonnull + public static BukkitModule getProvidingModule(@Nonnull Class clazz) { + JavaPlugin provider = JavaPlugin.getProvidingPlugin(clazz); + if (!(provider instanceof BukkitModule)) throw new IllegalStateException(clazz.getName() + " is not provided by a BukkitModule"); + return (BukkitModule) provider; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java new file mode 100644 index 000000000..87cae1721 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java @@ -0,0 +1,94 @@ +package net.codingarea.commons.bukkit.core; + +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.version.Version; +import org.bukkit.Bukkit; + +import javax.annotation.Nonnull; + +public final class RequirementsChecker { + + private final BukkitModule module; + + public RequirementsChecker(@Nonnull BukkitModule module) { + this.module = module; + } + + public void checkExceptionally(@Nonnull Document requirements) throws IllegalStateException { + if (requirements.getBoolean("spigot")) requireSpigot(); + if (requirements.getBoolean("paper")) requirePaper(); + if (requirements.contains("version")) requireVersion(requirements.getVersion("version")); + } + + public boolean checkBoolean(@Nonnull Document requirements) { + try { + checkExceptionally(requirements); + return true; + } catch (IllegalStateException ex) { + return false; + } + } + + private void requireSpigot() { + try { + Bukkit.spigot(); + } catch (Throwable ex) { + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + log("Your server does not run an instance of Spigot (Your server: {}", Bukkit.getVersion()); + log("Please use an instance of Spigot or Paper to be able to use this plugin!"); + log(""); + log("Paper Download: https://papermc.io/downloads"); + log("Spigot Download: https://getbukkit.org/download/spigot"); + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + + throw new IllegalStateException(); + } + } + + private void requirePaper() { + try { + Class.forName("com.destroystokyo.paper.VersionHistoryManager"); + } catch (Throwable ex) { + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + log("Your server does not run an instance of PaperMC (Your server: {}", Bukkit.getVersion()); + log("Please use an instance of Paper to be able to use this plugin!"); + log(""); + log("Paper Download: https://papermc.io/downloads"); + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + + throw new IllegalStateException(); + } + } + + private void requireVersion(@Nonnull Version required) { + if (MinecraftVersion.currentExact().isOlderThan(required)) { + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + log("This plugin requires the server version {} (You have: {})", required.format(), MinecraftVersion.currentExact().format()); + log("Please use this version (or an newer version) to be able to use this plugin!"); + log(""); + log("Paper Download: https://papermc.io/downloads"); + log("Spigot Download: https://getbukkit.org/download/spigot"); + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + + throw new IllegalStateException(); + } + } + + private void log(@Nonnull String line, @Nonnull Object... args) { + module.getILogger().error(line, args); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java new file mode 100644 index 000000000..a4570ad3f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java @@ -0,0 +1,44 @@ +package net.codingarea.commons.bukkit.core; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.YamlDocument; +import net.codingarea.commons.common.misc.FileUtils; + +import javax.annotation.Nonnull; +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +public class SimpleConfigManager { + + protected final Map configs = new HashMap<>(); + protected final BukkitModule module; + + public SimpleConfigManager(@Nonnull BukkitModule module) { + this.module = module; + } + + @Nonnull + public FileDocument getDocument(@Nonnull String filename) { + if (!filename.contains(".")) filename += ".json"; + return getDocument(module.getDataFile(filename)); + } + + public synchronized FileDocument getDocument(@Nonnull File file) { + String extension = FileUtils.getFileExtension(file); + return configs.computeIfAbsent(file.getName(), key -> FileDocument.readFile(resolveType(extension), file)); + } + + @Nonnull + public static Class resolveType(@Nonnull String extension) { + switch (extension.toLowerCase()) { + case "json": return GsonDocument.class; + case "yml": + case "yaml": return YamlDocument.class; + default: throw new IllegalArgumentException("Unknown document file extension '" + extension + "'"); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java new file mode 100644 index 000000000..3bd67d790 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java @@ -0,0 +1,168 @@ +package net.codingarea.commons.bukkit.utils.animation; + +import net.codingarea.commons.bukkit.core.BukkitModule; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.plugin.java.JavaPlugin; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +public class AnimatedInventory { + + private final List frames = new ArrayList<>(); + private final InventoryHolder holder; + private final int size; + private final String title; + private SoundSample frameSound = SoundSample.CLICK, endSound = SoundSample.OPEN; + private int frameDelay = 1; + + public AnimatedInventory(@Nonnull String title, int size) { + this(title, size, null); + } + + public AnimatedInventory(@Nonnull String title, int size, @Nullable InventoryHolder holder) { + this.title = title; + this.size = size; + this.holder = holder; + } + + public void open(@Nonnull Player player) { + open(player, BukkitModule.getFirstInstance()); + } + + public void open(@Nonnull Player player, @Nonnull JavaPlugin plugin) { + if (!Bukkit.isPrimaryThread()) { + Bukkit.getScheduler().runTask(plugin, () -> open(player, plugin)); + return; + } + + Inventory inventory = createInventory(); + applyFrame(inventory, 0, player); + player.openInventory(inventory); + + AtomicInteger index = new AtomicInteger(1); + Bukkit.getScheduler().runTaskTimer(plugin, task -> { + + boolean opened = inventory.getViewers().contains(player); + if (index.get() >= frames.size() || !opened) { + task.cancel(); + return; + } + + applyFrame(inventory, index.get(), player); + + index.incrementAndGet(); + + }, frameDelay, frameDelay); + + } + + public void openNotAnimated(@Nonnull Player player, boolean playSound) { + openNotAnimated(player, playSound, BukkitModule.getFirstInstance()); + } + + public void openNotAnimated(@Nonnull Player player, boolean playSound, @Nonnull JavaPlugin plugin) { + if (!Bukkit.isPrimaryThread()) { + Bukkit.getScheduler().runTask(plugin, () -> openNotAnimated(player, playSound, plugin)); + return; + } + + Inventory inventory = createInventory(); + + if (!frames.isEmpty()) { + AnimationFrame frame = getLastFrame(); + inventory.setContents(frame.getContent()); + } + + player.openInventory(inventory); + + if (playSound && endSound != null) endSound.play(player); + + } + + private void applyFrame(@Nonnull Inventory inventory, int index, @Nonnull Player viewer) { + AnimationFrame frame = frames.get(index); + inventory.setContents(frame.getContent()); + + if (index == frames.size() - 1 && endSound != null) endSound.play(viewer); + else if (frameSound != null && frame.shouldPlaySound()) frameSound.play(viewer); + } + + @Nonnull + public AnimatedInventory addFrame(@Nonnull AnimationFrame frame) { + if (size != frame.getSize()) throw new IllegalArgumentException("AnimationFrame must have the same size (Expected " + size + "; Got " + frame.getSize() + ")"); + frames.add(frame); + return this; + } + + @Nonnull + public AnimationFrame createAndAdd() { + AnimationFrame frame = new AnimationFrame(size); + addFrame(frame); + return frame; + } + + @Nonnull + public AnimationFrame getFrame(int index) { + return frames.get(index); + } + + @Nonnull + public AnimationFrame getOrCreateFrame(int index) { + while (frames.size() <= index) { + cloneLastAndAdd(); + } + return getFrame(index); + } + + @Nonnull + public AnimationFrame cloneAndAdd(int index) { + AnimationFrame frame = getFrame(index).clone(); + addFrame(frame); + return frame; + } + + @Nonnull + public AnimationFrame getLastFrame() { + if (frames.isEmpty()) throw new IllegalStateException("Frames are empty"); + return getFrame(frames.size() - 1); + } + + @Nonnull + public AnimationFrame cloneLastAndAdd() { + AnimationFrame frame = getLastFrame().clone(); + addFrame(frame); + return frame; + } + + @Nonnull + public AnimatedInventory setEndSound(@Nullable SoundSample endSound) { + this.endSound = endSound; + return this; + } + + @Nonnull + public AnimatedInventory setFrameSound(@Nullable SoundSample frameSound) { + this.frameSound = frameSound; + return this; + } + + @Nonnull + public AnimatedInventory setFrameDelay(int delay) { + if (delay < 1) throw new IllegalArgumentException("Delay cannot be smaller than 1"); + this.frameDelay = delay; + return this; + } + + @Nonnull + private Inventory createInventory() { + return Bukkit.createInventory(holder, size, title); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java new file mode 100644 index 000000000..130785522 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java @@ -0,0 +1,84 @@ +package net.codingarea.commons.bukkit.utils.animation; + +import net.codingarea.commons.bukkit.utils.item.ItemBuilder; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Arrays; + +public class AnimationFrame implements Cloneable { + + private final ItemStack[] content; + private boolean sound = true; + + public AnimationFrame(@Nonnull ItemStack[] content) { + this.content = Arrays.copyOf(content, content.length); + } + + public AnimationFrame(int size) { + this.content = new ItemStack[size]; + } + + @Nonnull + public AnimationFrame fill(@Nonnull ItemStack item) { + Arrays.fill(content, item); + return this; + } + + @Nonnull + public AnimationFrame setAccent(int... slots) { + for (int slot : slots) { + content[slot] = ItemBuilder.FILL_ITEM_2; + } + return this; + } + + @Nonnull + public AnimationFrame setItem(int slot, @Nonnull ItemBuilder item) { + return setItem(slot, item.build()); + } + + @Nonnull + public AnimationFrame setItem(int slot, @Nonnull ItemStack item) { + content[slot] = item; + return this; + } + + @Nonnull + public AnimationFrame setSound(boolean play) { + this.sound = play; + return this; + } + + @Nullable + public ItemStack getItem(int slot) { + return content[slot]; + } + + @Nullable + public Material getItemType(int slot) { + return getItem(slot) == null ? Material.AIR : getItem(slot).getType(); + } + + @Nonnull + public ItemStack[] getContent() { + return content; + } + + public boolean shouldPlaySound() { + return sound; + } + + public int getSize() { + return content.length; + } + + @Nonnull + @Override + public AnimationFrame clone() { + return new AnimationFrame(content); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java new file mode 100644 index 000000000..8991960e0 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java @@ -0,0 +1,113 @@ +package net.codingarea.commons.bukkit.utils.animation; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Sound; +import org.bukkit.entity.Player; + +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.List; + +public final class SoundSample { + + public static final SoundSample + CLICK = new SoundSample().addSound(Sound.BLOCK_WOODEN_BUTTON_CLICK_ON, 0.5f), + BASS_OFF = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BASS, 0.5F), + BASS_ON = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_PLING, 0.5F), + PLING = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BELL, 1), + KLING = new SoundSample().addSound(Sound.ENTITY_PLAYER_LEVELUP, 0.6F, 2), + LEVEL_UP = new SoundSample().addSound(Sound.ENTITY_PLAYER_LEVELUP, 0.6F, 1.1f), + PLOP = new SoundSample().addSound(Sound.ENTITY_CHICKEN_EGG, 1, 2), + LOW_PLOP = new SoundSample().addSound(Sound.ENTITY_CHICKEN_EGG, 1, 1.3f), + DEATH = new SoundSample().addSound(Sound.ENTITY_BAT_DEATH, 0.7F), + TELEPORT = new SoundSample().addSound(Sound.ITEM_CHORUS_FRUIT_TELEPORT, 0.9F), + OPEN = new SoundSample().addSound(KLING).addSound(PLOP), + EAT = new SoundSample().addSound(Sound.ENTITY_PLAYER_BURP, 1), + BLAST = new SoundSample().addSound(Sound.ENTITY_FIREWORK_ROCKET_LARGE_BLAST, 1), + BREAK = new SoundSample().addSound(Sound.ENTITY_WITHER_BREAK_BLOCK, 0.7f), + WIN = new SoundSample().addSound(Sound.UI_TOAST_CHALLENGE_COMPLETE, 1), + DRAGON_BREATH = new SoundSample().addSound(Sound.ENTITY_ENDER_DRAGON_GROWL, 0.5F); + + public static void playStatusSound(@Nonnull Player player, boolean enabled) { + (enabled ? BASS_ON : BASS_OFF).play(player); + } + + private static final class SoundFrame { + + private final float pitch, volume; + private final Sound sound; + + public SoundFrame(@Nonnull Sound sound, float volume, float pitch) { + this.volume = volume; + this.pitch = pitch; + this.sound = sound; + } + + public SoundFrame(@Nonnull Sound sound, float volume) { + this(sound, volume, 1); + } + + public void play(@Nonnull Player player, @Nonnull Location location) { + player.playSound(location, sound, volume, pitch); + } + + public float getPitch() { + return pitch; + } + + public float getVolume() { + return volume; + } + + @Nonnull + public Sound getSound() { + return sound; + } + + } + + private final List frames = new ArrayList<>(); + + @Nonnull + public SoundSample addSound(@Nonnull Sound sound, float volume, float pitch) { + frames.add(new SoundFrame(sound, volume, pitch)); + return this; + } + + @Nonnull + public SoundSample addSound(@Nonnull Sound sound, float volume) { + frames.add(new SoundFrame(sound, volume)); + return this; + } + + @Nonnull + public SoundSample addSound(@Nonnull SoundSample sound) { + frames.addAll(sound.frames); + return this; + } + + public void play(@Nonnull Player player) { + play(player, player.getLocation()); + } + + public void play(@Nonnull Player player, @Nonnull Location location) { + for (SoundFrame frame : frames) { + frame.play(player, location); + } + } + + public void playIfPlayer(@Nonnull Object target) { + if (target instanceof Player) + play((Player) target); + } + + public void broadcast() { + Bukkit.getOnlinePlayers().forEach(this::play); + } + + public void broadcast(@Nonnull Location location) { + Bukkit.getOnlinePlayers().forEach(player -> play(player, location)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java new file mode 100644 index 000000000..172e2e4ff --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java @@ -0,0 +1,210 @@ +package net.codingarea.commons.bukkit.utils.bstats; + +import java.util.Arrays; +import java.util.stream.Collectors; + +/** + * An extremely simple JSON builder. + * + *

While this class is neither feature-rich nor the most performant one, it's sufficient enough + * for its use-case. + */ +public class JsonObjectBuilder { + + private StringBuilder builder = new StringBuilder(); + + private boolean hasAtLeastOneField = false; + + public JsonObjectBuilder() { + builder.append("{"); + } + + /** + * Appends a null field to the JSON. + * + * @param key The key of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendNull(String key) { + appendFieldUnescaped(key, "null"); + return this; + } + + /** + * Appends a string field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String value) { + if (value == null) { + throw new IllegalArgumentException("JSON value must not be null"); + } + appendFieldUnescaped(key, "\"" + escape(value) + "\""); + return this; + } + + /** + * Appends an integer field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int value) { + appendFieldUnescaped(key, String.valueOf(value)); + return this; + } + + /** + * Appends an object to the JSON. + * + * @param key The key of the field. + * @param object The object. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject object) { + if (object == null) { + throw new IllegalArgumentException("JSON object must not be null"); + } + appendFieldUnescaped(key, object.toString()); + return this; + } + + /** + * Appends a string array to the JSON. + * + * @param key The key of the field. + * @param values The string array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values) + .map(value -> "\"" + escape(value) + "\"") + .collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an integer array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an object array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends a field to the object. + * + * @param key The key of the field. + * @param escapedValue The escaped value of the field. + */ + private void appendFieldUnescaped(String key, String escapedValue) { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + if (key == null) { + throw new IllegalArgumentException("JSON key must not be null"); + } + if (hasAtLeastOneField) { + builder.append(","); + } + builder.append("\"").append(escape(key)).append("\":").append(escapedValue); + hasAtLeastOneField = true; + } + + /** + * Builds the JSON string and invalidates this builder. + * + * @return The built JSON string. + */ + public JsonObject build() { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + JsonObject object = new JsonObject(builder.append("}").toString()); + builder = null; + return object; + } + + /** + * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. + * + *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. + * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). + * + * @param value The value to escape. + * @return The escaped value. + */ + private static String escape(String value) { + final StringBuilder builder = new StringBuilder(); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c == '"') { + builder.append("\\\""); + } else if (c == '\\') { + builder.append("\\\\"); + } else if (c <= '\u000F') { + builder.append("\\u000").append(Integer.toHexString(c)); + } else if (c <= '\u001F') { + builder.append("\\u00").append(Integer.toHexString(c)); + } else { + builder.append(c); + } + } + return builder.toString(); + } + + /** + * A super simple representation of a JSON object. + * + *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not + * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, + * JsonObject)}. + */ + public static class JsonObject { + + private final String value; + + private JsonObject(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/Metrics.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/Metrics.java new file mode 100644 index 000000000..60574d3fc --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/Metrics.java @@ -0,0 +1,333 @@ +package net.codingarea.commons.bukkit.utils.bstats; + +import net.codingarea.commons.bukkit.utils.bstats.chart.CustomChart; +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + +public class Metrics { + + private final Plugin plugin; + private final MetricsBase metricsBase; + + /** + * Creates a new Metrics instance. + * + * @param plugin Your plugin instance. + * @param serviceId The id of the service. It can be found at What is my plugin id? + */ + public Metrics(JavaPlugin plugin, int serviceId) { + this.plugin = plugin; + + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + if (!config.isSet("serverUuid")) { + config.addDefault("enabled", true); + config.addDefault("serverUuid", UUID.randomUUID().toString()); + config.addDefault("logFailedRequests", false); + config.addDefault("logSentData", false); + config.addDefault("logResponseStatusText", false); + // Inform the server owners about bStats + config + .options() + .header( + "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" + + "many people use their plugin and their total player count. It's recommended to keep bStats\n" + + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" + + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" + + "anonymous.") + .copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } + + String serverUUID = config.getString("serverUuid"); + boolean logErrors = config.getBoolean("logFailedRequests", false); + boolean logSentData = config.getBoolean("logSentData", false); + boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); + metricsBase = + new MetricsBase( + "bukkit", + serverUUID, + serviceId, + true, + this::appendPlatformData, + this::appendServiceData, + submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), + plugin::isEnabled, + (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), + (message) -> this.plugin.getLogger().log(Level.INFO, message), + logErrors, + logSentData, + logResponseStatusText); + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + metricsBase.addCustomChart(chart); + } + + private void appendPlatformData(JsonObjectBuilder builder) { + builder.appendField("playerAmount", getPlayerAmount()); + builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0); + builder.appendField("bukkitVersion", Bukkit.getVersion()); + builder.appendField("bukkitName", Bukkit.getName()); + builder.appendField("javaVersion", System.getProperty("java.version")); + builder.appendField("osName", System.getProperty("os.name")); + builder.appendField("osArch", System.getProperty("os.arch")); + builder.appendField("osVersion", System.getProperty("os.version")); + builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()); + } + + private void appendServiceData(JsonObjectBuilder builder) { + builder.appendField("pluginVersion", plugin.getDescription().getVersion()); + } + + private int getPlayerAmount() { + try { + // Around MC 1.8 the return type was changed from an array to a collection, + // This fixes java.lang.NoSuchMethodError: + // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + return onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + // Just use the new method if the reflection failed + return Bukkit.getOnlinePlayers().size(); + } + } + + public static class MetricsBase { + + /** The version of the Metrics class. */ + public static final String METRICS_VERSION = "2.2.1"; + + private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, task -> new Thread(task, "bStats-Metrics")); + private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; + + private final String platform; + private final String serverUuid; + private final int serviceId; + private final Consumer appendPlatformDataConsumer; + private final Consumer appendServiceDataConsumer; + private final Consumer submitTaskConsumer; + private final Supplier checkServiceEnabledSupplier; + private final BiConsumer errorLogger; + private final Consumer infoLogger; + private final boolean logErrors; + private final boolean logSentData; + private final boolean logResponseStatusText; + private final Set customCharts = new HashSet<>(); + private final boolean enabled; + + /** + * Creates a new MetricsBase class instance. + * + * @param platform The platform of the service. + * @param serviceId The id of the service. + * @param serverUuid The server uuid. + * @param enabled Whether or not data sending is enabled. + * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all platform-specific data. + * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all service-specific data. + * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be + * used to delegate the data collection to a another thread to prevent errors caused by + * concurrency. Can be {@code null}. + * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled. + * @param errorLogger A consumer that accepts log message and an error. + * @param infoLogger A consumer that accepts info log messages. + * @param logErrors Whether or not errors should be logged. + * @param logSentData Whether or not the sent data should be logged. + * @param logResponseStatusText Whether or not the response status text should be logged. + */ + public MetricsBase( + String platform, + String serverUuid, + int serviceId, + boolean enabled, + Consumer appendPlatformDataConsumer, + Consumer appendServiceDataConsumer, + Consumer submitTaskConsumer, + Supplier checkServiceEnabledSupplier, + BiConsumer errorLogger, + Consumer infoLogger, + boolean logErrors, + boolean logSentData, + boolean logResponseStatusText) { + this.platform = platform; + this.serverUuid = serverUuid; + this.serviceId = serviceId; + this.enabled = enabled; + this.appendPlatformDataConsumer = appendPlatformDataConsumer; + this.appendServiceDataConsumer = appendServiceDataConsumer; + this.submitTaskConsumer = submitTaskConsumer; + this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; + this.errorLogger = errorLogger; + this.infoLogger = infoLogger; + this.logErrors = logErrors; + this.logSentData = logSentData; + this.logResponseStatusText = logResponseStatusText; + checkRelocation(); + if (enabled) { + startSubmitting(); + } + } + + public void addCustomChart(CustomChart chart) { + this.customCharts.add(chart); + } + + private void startSubmitting() { + final Runnable submitTask = + () -> { + if (!enabled || !checkServiceEnabledSupplier.get()) { + // Submitting data or service is disabled + scheduler.shutdown(); + return; + } + if (submitTaskConsumer != null) { + submitTaskConsumer.accept(this::submitData); + } else { + this.submitData(); + } + }; + // Many servers tend to restart at a fixed time at xx:00 which causes an uneven distribution + // of requests on the + // bStats backend. To circumvent this problem, we introduce some randomness into the initial + // and second delay. + // WARNING: You must not modify and part of this Metrics class, including the submit delay or + // frequency! + // WARNING: Modifying this code will get your plugin banned on bStats. Just don't do it! + long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); + long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); + scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); + scheduler.scheduleAtFixedRate( + submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); + } + + private void submitData() { + final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); + appendPlatformDataConsumer.accept(baseJsonBuilder); + final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); + appendServiceDataConsumer.accept(serviceJsonBuilder); + JsonObjectBuilder.JsonObject[] chartData = + customCharts.stream() + .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) + .filter(Objects::nonNull) + .toArray(JsonObjectBuilder.JsonObject[]::new); + serviceJsonBuilder.appendField("id", serviceId); + serviceJsonBuilder.appendField("customCharts", chartData); + baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); + baseJsonBuilder.appendField("serverUUID", serverUuid); + baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); + JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); + scheduler.execute( + () -> { + try { + sendData(data); + } catch (Exception e) { + if (logErrors) { + errorLogger.accept("Could not submit bStats metrics data", e); + } + } + }); + } + + private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { + if (logSentData) { + infoLogger.accept("Sent bStats metrics data: " + data.toString()); + } + String url = String.format(REPORT_URL, platform); + HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("User-Agent", "Metrics-Service/1"); + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + StringBuilder builder = new StringBuilder(); + try (BufferedReader bufferedReader = + new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + if (logResponseStatusText) { + infoLogger.accept("Sent data to bStats and received response: " + builder); + } + } + + /** Checks that the class was properly relocated. */ + private void checkRelocation() { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null + || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little + // "trick" ... :D + final String defaultPackage = + new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'}); + final String examplePackage = + new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure no one just copy & pastes the example and uses the wrong package + // names + if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) + || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + /** + * Gzips the given string. + * + * @param str The string to gzip. + * @return The gzipped string. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedBarChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedBarChart.java new file mode 100644 index 000000000..48063d475 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedBarChart.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedPie.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedPie.java new file mode 100644 index 000000000..afdba71ee --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedPie.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/CustomChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/CustomChart.java new file mode 100644 index 000000000..3897be5c7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/CustomChart.java @@ -0,0 +1,40 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.function.BiConsumer; + +public abstract class CustomChart { + + private final String chartId; + + protected CustomChart(String chartId) { + if (chartId == null) { + throw new IllegalArgumentException("chartId must not be null"); + } + this.chartId = chartId; + } + + public JsonObject getRequestJsonObject( + BiConsumer errorLogger, boolean logErrors) { + JsonObjectBuilder builder = new JsonObjectBuilder(); + builder.appendField("chartId", chartId); + try { + JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + builder.appendField("data", data); + } catch (Throwable t) { + if (logErrors) { + errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return builder.build(); + } + + protected abstract JsonObject getChartData() throws Exception; +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/DrilldownPie.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/DrilldownPie.java new file mode 100644 index 000000000..d0cb2ff19 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/DrilldownPie.java @@ -0,0 +1,51 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/MultiLineChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/MultiLineChart.java new file mode 100644 index 000000000..0d62864af --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/MultiLineChart.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimpleBarChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimpleBarChart.java new file mode 100644 index 000000000..aa7d49220 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimpleBarChart.java @@ -0,0 +1,37 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.Map; +import java.util.concurrent.Callable; + +public class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + valuesBuilder.appendField(entry.getKey(), new int[]{entry.getValue()}); + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimplePie.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimplePie.java new file mode 100644 index 000000000..e42f4a5c7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimplePie.java @@ -0,0 +1,32 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.concurrent.Callable; + +public class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SingleLineChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SingleLineChart.java new file mode 100644 index 000000000..8e4d91259 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SingleLineChart.java @@ -0,0 +1,32 @@ +package net.codingarea.commons.bukkit.utils.bstats.chart; + +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder; +import net.codingarea.commons.bukkit.utils.bstats.JsonObjectBuilder.JsonObject; + +import java.util.concurrent.Callable; + +public class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JsonObject getChartData() throws Exception { + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java new file mode 100644 index 000000000..4901ae38d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java @@ -0,0 +1,64 @@ +package net.codingarea.commons.bukkit.utils.item; + +import org.bukkit.block.banner.PatternType; + +import javax.annotation.Nonnull; + +public enum BannerPattern { + + BASE_DEXTER_CANTON(PatternType.SQUARE_BOTTOM_LEFT), + BASE_SINISTER_CANTON(PatternType.SQUARE_BOTTOM_RIGHT), + CHIEF_DEXTER_CANTON(PatternType.SQUARE_TOP_LEFT), + CHIEF_SINISTER_CANTON(PatternType.SQUARE_TOP_RIGHT), + BASE(PatternType.STRIPE_BOTTOM), + CHIEF(PatternType.STRIPE_TOP), + PALE_DEXTER(PatternType.STRIPE_LEFT), + PALE_SINISTER(PatternType.STRIPE_RIGHT), + PALE(PatternType.STRIPE_CENTER), + FESS(PatternType.STRIPE_MIDDLE), + BEND(PatternType.STRIPE_DOWNRIGHT), + BEND_SINISTER(PatternType.STRIPE_DOWNLEFT), + PALY(PatternType.SMALL_STRIPES), + SALTIRE(PatternType.CROSS), + CROSS(PatternType.STRAIGHT_CROSS), + CHEVRON(PatternType.TRIANGLE_BOTTOM), + INVERTED_CHEVRON(PatternType.TRIANGLE_TOP), + BASE_INDENTED(PatternType.TRIANGLES_BOTTOM), + CHIEF_INDENTED(PatternType.TRIANGLES_TOP), + PER_BEND_SINISTER(PatternType.DIAGONAL_LEFT), + PER_BEND_SINISTER_INVERTED(PatternType.DIAGONAL_RIGHT), + PER_BEND_INVERTED(PatternType.DIAGONAL_UP_LEFT), + PER_BEND(PatternType.DIAGONAL_UP_RIGHT), + ROUNDEL(PatternType.CIRCLE), + LOZENGE(PatternType.STRIPE_MIDDLE), + PER_PALE(PatternType.HALF_VERTICAL), + PER_FESS(PatternType.HALF_HORIZONTAL), + PER_PALE_INVERTED(PatternType.HALF_VERTICAL_RIGHT), + PER_FESS_INVERTED(PatternType.HALF_HORIZONTAL_BOTTOM), + BORDURE(PatternType.BORDER), + BORDURE_INDENTED(PatternType.CURLY_BORDER), + GRADIENT(PatternType.GRADIENT), + BASE_GRADIENT(PatternType.GRADIENT_UP), + FIELD_MASONED(PatternType.BRICKS), + CREEPER_CHARGE(PatternType.CREEPER), + SKULL_CHARGE(PatternType.SKULL), + FLOWER_CHARGE(PatternType.FLOWER), + MOJANG(PatternType.MOJANG); + + private final PatternType patternType; + + BannerPattern(@Nonnull PatternType patternType) { + this.patternType = patternType; + } + + @Nonnull + public PatternType getPatternType() { + return patternType; + } + + @Nonnull + public String getIdentifier() { + return patternType.getKeyOrThrow().getKey(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java new file mode 100644 index 000000000..339bbaba2 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java @@ -0,0 +1,424 @@ +package net.codingarea.commons.bukkit.utils.item; + +import org.bukkit.Color; +import org.bukkit.DyeColor; +import org.bukkit.Material; +import org.bukkit.block.banner.Pattern; +import org.bukkit.block.banner.PatternType; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.*; +import org.bukkit.potion.PotionEffect; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +public class ItemBuilder { + + public static final ItemStack FILL_ITEM = new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE).setName("§0").build(), + FILL_ITEM_2 = new ItemBuilder(Material.BLACK_STAINED_GLASS_PANE).setName("§0").build(), + BLOCKED_ITEM = new ItemBuilder(Material.BARRIER, "§cBlocked").build(), + AIR = new ItemStack(Material.AIR); + + protected ItemStack item; + protected ItemMeta meta; + + public ItemBuilder(@Nonnull ItemStack item) { + this(item, item.getItemMeta()); + } + + public ItemBuilder(@Nonnull ItemStack item, @Nullable ItemMeta meta) { + this.item = item; + this.meta = meta; + } + + public ItemBuilder(@Nonnull Material material) { + this(new ItemStack(material)); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name) { + this(material); + setName(name); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + this(material); + setName(name); + setLore(lore); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + this(material); + setName(name); + setAmount(amount); + } + + @Nonnull + public ItemMeta getMeta() { + return getCastedMeta(); + } + + @Nonnull + @SuppressWarnings("unchecked") + public final M getCastedMeta() { + return (M) (meta == null ? meta = item.getItemMeta() : meta); + } + + @Nonnull + public ItemBuilder setLore(@Nonnull List lore) { + getMeta().setLore(lore); + return this; + } + + @Nonnull + public ItemBuilder setLore(@Nonnull String... lore) { + return setLore(Arrays.asList(lore)); + } + + @Nonnull + public ItemBuilder appendLore(@Nonnull String... lore) { + return appendLore(Arrays.asList(lore)); + } + + @Nonnull + public ItemBuilder appendLore(@Nonnull Collection lore) { + List newLore = getMeta().getLore(); + if (newLore == null) newLore = new ArrayList<>(); + newLore.addAll(lore); + setLore(newLore); + return this; + } + + @Nonnull + public ItemBuilder lore(@Nonnull String... lore) { + return setLore(lore); + } + + @Nonnull + public ItemBuilder setName(@Nullable String name) { + getMeta().setDisplayName(name); + return this; + } + + @Nonnull + public ItemBuilder setName(@Nullable Object name) { + return setName(name == null ? null : name.toString()); + } + + @Nonnull + public ItemBuilder setName(@Nonnull String... content) { + if (content.length > 0) setName(content[0]); + if (content.length > 1) setLore(Arrays.copyOfRange(content, 1, content.length)); + return this; + } + + @Nonnull + public ItemBuilder appendName(@Nullable Object sequence) { + String name = getMeta().getDisplayName(); + return setName(name + sequence); + } + + @Nonnull + public ItemBuilder name(@Nullable Object name) { + return setName(name); + } + + @Nonnull + public ItemBuilder name(@Nonnull String... content) { + return setName(content); + } + + @Nonnull + public ItemBuilder addEnchantment(@Nonnull Enchantment enchantment, int level) { + getMeta().addEnchant(enchantment, level, true); + return this; + } + + @Nonnull + public ItemBuilder enchant(@Nonnull Enchantment enchantment, int level) { + return addEnchantment(enchantment, level); + } + + @Nonnull + public ItemBuilder addFlag(@Nonnull ItemFlag... flags) { + getMeta().addItemFlags(flags); + return this; + } + + @Nonnull + public ItemBuilder flag(@Nonnull ItemFlag... flags) { + return addFlag(flags); + } + + @Nonnull + public ItemBuilder removeFlag(@Nonnull ItemFlag... flags) { + getMeta().removeItemFlags(flags); + return this; + } + + @Nonnull + public ItemBuilder hideAttributes() { + return addFlag(ItemFlag.values()); + } + + @Nonnull + public ItemBuilder showAttributes() { + return removeFlag(ItemFlag.values()); + } + + @Nonnull + public ItemBuilder setUnbreakable(boolean unbreakable) { + getMeta().setUnbreakable(unbreakable); + return this; + } + + @Nonnull + public ItemBuilder unbreakable() { + return setUnbreakable(true); + } + + @Nonnull + public ItemBuilder breakable() { + return setUnbreakable(false); + } + + @Nonnull + public ItemBuilder setAmount(int amount) { + item.setAmount(Math.min(Math.max(amount, 0), 64)); + return this; + } + + @Nonnull + public ItemBuilder amount(int amount) { + return setAmount(amount); + } + + @Nonnull + public ItemBuilder setDamage(int damage) { + this.getCastedMeta().setDamage(damage); + return this; + } + + @Nonnull + public ItemBuilder damage(int damage) { + return setDamage(damage); + } + + @Nonnull + public ItemBuilder setType(@Nonnull Material material) { + item.setType(material); + meta = item.getItemMeta(); + return this; + } + + @Nonnull + public String getName() { + return getMeta().getDisplayName(); + } + + @Nonnull + public List getLore() { + List lore = getMeta().getLore(); + return lore == null ? new ArrayList<>() : lore; + } + + @Nonnull + public Material getType() { + return item.getType(); + } + + public int getAmount() { + return item.getAmount(); + } + + public int getDamage() { + return this.getCastedMeta().getDamage(); + } + + @Nonnull + public ItemStack build() { + item.setItemMeta(getMeta()); // Call to getter to prevent null value + return item; + } + + @Nonnull + public ItemStack toItem() { + return build(); + } + + @Override + public ItemBuilder clone() { + return new ItemBuilder(item.clone(), getMeta().clone()); + } + + public static class BannerBuilder extends ItemBuilder { + + public BannerBuilder(@Nonnull Material material) { + super(material); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public BannerBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public BannerBuilder addPattern(@Nonnull BannerPattern pattern, @Nonnull DyeColor color) { + return addPattern(pattern.getPatternType(), color); + } + + @Nonnull + public BannerBuilder addPattern(@Nonnull PatternType pattern, @Nonnull DyeColor color) { + getMeta().addPattern(new Pattern(color, pattern)); + return this; + } + + @Nonnull + @Override + public BannerMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class SkullBuilder extends ItemBuilder { + + public SkullBuilder() { + super(Material.PLAYER_HEAD); + } + + public SkullBuilder(@Nonnull String owner) { + super(Material.PLAYER_HEAD); + setOwner(owner); + } + + public SkullBuilder(@Nonnull String owner, @Nonnull String name, @Nonnull String... lore) { + super(Material.PLAYER_HEAD, name, lore); + setOwner(owner); + } + + public SkullBuilder setOwner(@Nonnull String owner) { + getMeta().setOwner(owner); + return this; + } + + @Nonnull + @Override + public SkullMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class PotionBuilder extends ItemBuilder { + + @Nonnull + @CheckReturnValue + public static ItemBuilder createWaterBottle() { + return new PotionBuilder(Material.POTION).setColor(Color.BLUE).hideAttributes(); + } + + public PotionBuilder(@Nonnull Material material) { + super(material); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public PotionBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public PotionBuilder addEffect(@Nonnull PotionEffect effect) { + getMeta().addCustomEffect(effect, true); + return this; + } + + @Nonnull + public PotionBuilder setColor(@Nonnull Color color) { + getMeta().setColor(color); + return this; + } + + @Nonnull + public PotionBuilder color(@Nonnull Color color) { + return setColor(color); + } + + @Nonnull + @Override + public PotionMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class LeatherArmorBuilder extends ItemBuilder { + + public LeatherArmorBuilder(@Nonnull Material material) { + super(material); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public LeatherArmorBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public LeatherArmorBuilder setColor(@Nonnull Color color) { + getMeta().setColor(color); + return this; + } + + @Nonnull + public LeatherArmorBuilder color(@Nonnull Color color) { + return setColor(color); + } + + @Nonnull + @Override + public LeatherArmorMeta getMeta() { + return getCastedMeta(); + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java new file mode 100644 index 000000000..e967429a8 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java @@ -0,0 +1,117 @@ +package net.codingarea.commons.bukkit.utils.item; + +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.ItemMeta; + +import javax.annotation.Nonnull; + +public class ItemUtils { + + @Nonnull + public static Material convertFoodToCookedFood(@Nonnull Material material) { + try { + return Material.valueOf("COOKED_" + material.name()); + } catch (Exception ex) { + return material; // No cooked material is available + } + } + + public static boolean isObtainableInSurvival(@Nonnull Material material) { + String name = material.name(); + if (BukkitReflectionUtils.isAir(material)) return false; + if (name.endsWith("_SPAWN_EGG")) return false; + if (name.startsWith("INFESTED_")) return false; + if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable + switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist + case "CHAIN_COMMAND_BLOCK": + case "REPEATING_COMMAND_BLOCK": + case "COMMAND_BLOCK": + case "COMMAND_BLOCK_MINECART": + case "JIGSAW": + case "STRUCTURE_BLOCK": + case "STRUCTURE_VOID": + case "BARRIER": + case "BEDROCK": + case "KNOWLEDGE_BOOK": + case "DEBUG_STICK": + case "END_PORTAL_FRAME": + case "END_PORTAL": + case "NETHER_PORTAL": + case "END_GATEWAY": + case "LAVA": + case "WATER": + case "LARGE_FERN": + case "TALL_GRASS": + case "TALL_SEAGRASS": + case "PATH_BLOCK": + case "CHORUS_PLANT": + case "PETRIFIED_OAK_SLAB": + case "FARMLAND": + case "PLAYER_HEAD": + case "GLOBE_BANNER_PATTERN": + case "SPAWNER": + case "AMETHYST_CLUSTER": + case "BUDDING_AMETHYST": + case "POWDER_SNOW": + case "LIGHT": + case "BUNDLE": + case "REINFORCED_DEEPSLATE": + case "FROGSPAWN": + return false; + } + + if (MinecraftVersion.current().isOlderThan(MinecraftVersion.V1_19)) { + return !name.equals("SCULK_SENSOR"); + } + + return true; + } + + public static boolean blockIsAvailableInSurvival(@Nonnull Material material) { + if (!material.isBlock()) return false; + String name = material.name(); + if (BukkitReflectionUtils.isAir(material)) return false; + if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable + switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist + case "CHAIN_COMMAND_BLOCK": + case "REPEATING_COMMAND_BLOCK": + case "COMMAND_BLOCK": + case "COMMAND_BLOCK_MINECART": + case "JIGSAW": + case "STRUCTURE_BLOCK": + case "STRUCTURE_VOID": + case "BARRIER": + case "KNOWLEDGE_BOOK": + case "DEBUG_STICK": + case "END_PORTAL": + case "NETHER_PORTAL": + case "END_GATEWAY": + case "PETRIFIED_OAK_SLAB": + case "PLAYER_HEAD": + case "GLOBE_BANNER_PATTERN": + case "LIGHT": + case "BUNDLE": + return false; + } + + return true; + } + + public static void damageItem(@Nonnull ItemStack item) { + damageItem(item, 1); + } + + public static void damageItem(@Nonnull ItemStack item, int amount) { + ItemMeta meta = item.getItemMeta(); + if (meta == null) return; + if (!(meta instanceof Damageable)) return; + Damageable damageable = (Damageable) meta; + damageable.setDamage(damageable.getDamage() + amount); + item.setItemMeta(meta); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java new file mode 100644 index 000000000..ac6f766f5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java @@ -0,0 +1,39 @@ +package net.codingarea.commons.bukkit.utils.logging; + +import net.codingarea.commons.bukkit.core.BukkitModule; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.misc.ReflectionUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public final class Logger { + + private Logger() {} + + @Nonnull + public static ILogger getInstance() { + return BukkitModule.getProvidingModule(ReflectionUtils.getCaller()).getILogger(); + } + + public static void error(@Nullable Object message, @Nonnull Object... args) { + getInstance().error(message, args); + } + + public static void warn(@Nullable Object message, @Nonnull Object... args) { + getInstance().warn(message, args); + } + + public static void info(@Nullable Object message, @Nonnull Object... args) { + getInstance().info(message, args); + } + + public static void debug(@Nullable Object message, @Nonnull Object... args) { + getInstance().debug(message, args); + } + + public static void trace(@Nullable Object message, @Nonnull Object... args) { + getInstance().trace(message, args); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java new file mode 100644 index 000000000..5753ad174 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java @@ -0,0 +1,75 @@ +package net.codingarea.commons.bukkit.utils.menu; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class MenuClickInfo { + + protected final Player player; + protected final Inventory inventory; + protected final boolean shiftClick; + protected final boolean rightClick; + protected final int slot; + + public MenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boolean shiftClick, boolean rightClick, @Nonnegative int slot) { + this.player = player; + this.inventory = inventory; + this.shiftClick = shiftClick; + this.rightClick = rightClick; + this.slot = slot; + } + + @Nonnull + public Player getPlayer() { + return player; + } + + @Nonnull + public Inventory getInventory() { + return inventory; + } + + public boolean isRightClick() { + return rightClick; + } + + public boolean isLeftClick() { + return !rightClick; + } + + public boolean isShiftClick() { + return shiftClick; + } + + public int getSlot() { + return slot; + } + + @Nullable + public ItemStack getClickedItem() { + return inventory.getItem(slot); + } + + @Nonnull + public Material getClickedMaterial() { + return getClickedItem() == null ? Material.AIR : getClickedItem().getType(); + } + + @Override + public String toString() { + return "MenuClickInfo{" + + "player=" + player + + ", inventory=" + inventory + + ", shiftClick=" + shiftClick + + ", rightClick=" + rightClick + + ", slot=" + slot + + '}'; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java new file mode 100644 index 000000000..527cc844f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java @@ -0,0 +1,44 @@ +package net.codingarea.commons.bukkit.utils.menu; + +import net.codingarea.commons.bukkit.utils.menu.positions.EmptyMenuPosition; +import org.bukkit.entity.Player; +import org.bukkit.inventory.InventoryHolder; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@FunctionalInterface +public interface MenuPosition { + + final class Holder { + + private Holder() {} + + private static final Map positions = new ConcurrentHashMap<>(); + + } + + InventoryHolder HOLDER = new MenuPositionHolder(); + + static void set(@Nonnull Player player, @Nullable MenuPosition position) { + Holder.positions.put(player, position); + } + + static void remove(@Nonnull Player player) { + Holder.positions.remove(player); + } + + @Nullable + static MenuPosition get(@Nonnull Player player) { + return Holder.positions.get(player); + } + + static void setEmpty(@Nonnull Player player) { + set(player, new EmptyMenuPosition()); + } + + void handleClick(@Nonnull MenuClickInfo info); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java new file mode 100644 index 000000000..669b1367f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java @@ -0,0 +1,16 @@ +package net.codingarea.commons.bukkit.utils.menu; + +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; + +import javax.annotation.Nonnull; + +class MenuPositionHolder implements InventoryHolder { + + @Nonnull + @Override + public Inventory getInventory() { + return null; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java new file mode 100644 index 000000000..8addddaca --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.bukkit.utils.menu; + +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; + +import javax.annotation.Nonnull; + +public final class MenuPositionListener implements Listener { + + @EventHandler(priority = EventPriority.LOW) + public void onClick(@Nonnull InventoryClickEvent event) { + + HumanEntity human = event.getWhoClicked(); + if (!(human instanceof Player)) return; + Player player = (Player) human; + + Inventory inventory = event.getClickedInventory(); + if (inventory == null) return; + + if (inventory == CompatibilityUtils.getTopInventory(event)) { + + if (inventory.getHolder() != MenuPosition.HOLDER) return; // No menu inventory + + MenuPosition position = MenuPosition.get(player); + if (position == null) return; // Currently in no menu + + event.setCancelled(true); + position.handleClick(new MenuClickInfo(player, inventory, event.isShiftClick(), event.isRightClick(), event.getSlot())); + + } else if (event.isShiftClick()) { // Player inventory was clicked + + Inventory topInventory = event.getInventory(); + if (topInventory.getHolder() != MenuPosition.HOLDER) return; // No menu inventory + + event.setCancelled(true); + + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java new file mode 100644 index 000000000..dfe653abf --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java @@ -0,0 +1,16 @@ +package net.codingarea.commons.bukkit.utils.menu.positions; + +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; + +import javax.annotation.Nonnull; + +public class EmptyMenuPosition implements MenuPosition { + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + SoundSample.CLICK.play(info.getPlayer()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java new file mode 100644 index 000000000..8ea854148 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java @@ -0,0 +1,50 @@ +package net.codingarea.commons.bukkit.utils.menu.positions; + +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import org.bukkit.entity.Player; + +import javax.annotation.Nonnull; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; + +public class SlottedMenuPosition implements MenuPosition { + + protected final Map> actions = new HashMap<>(); + protected boolean emptySound = true; + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + Consumer action = actions.get(info.getSlot()); + if (action == null) { + if (emptySound) SoundSample.CLICK.play(info.getPlayer()); + return; + } + + action.accept(info); + } + + @Nonnull + public SlottedMenuPosition setAction(int slot, @Nonnull Consumer action) { + actions.put(slot, action); + return this; + } + + @Nonnull + public SlottedMenuPosition setPlayerAction(int slot, @Nonnull Consumer action) { + return setAction(slot, info -> action.accept(info.getPlayer())); + } + + @Nonnull + public SlottedMenuPosition setAction(int slot, @Nonnull Runnable action) { + return setAction(slot, info -> action.run()); + } + + public SlottedMenuPosition setEmptySound(boolean playSound) { + this.emptySound = playSound; + return this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java new file mode 100644 index 000000000..36284f5e3 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java @@ -0,0 +1,170 @@ +package net.codingarea.commons.bukkit.utils.misc; + +import com.google.common.base.Preconditions; +import net.codingarea.commons.common.logging.ILogger; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.lang.reflect.Method; +import java.util.regex.Pattern; + +/** + * This class gives access to + * - api functions which are not directly implemented in some versions of bukkit or spigot + * - some basic nms functionality. + */ +public final class BukkitReflectionUtils { + + private static final ILogger logger = ILogger.forThisClass(); + + private BukkitReflectionUtils() { + } + + public static double getAbsorptionAmount(@Nonnull Player player) { + Class classOfPlayer = player.getClass(); + + try { + return player.getAbsorptionAmount(); + } catch (Throwable ignored) { + } + + try { + Method getHandleMethod = classOfPlayer.getMethod("getHandle"); + getHandleMethod.setAccessible(true); + + Object handle = getHandleMethod.invoke(player); + Class classOfHandle = handle.getClass(); + + Method getAbsorptionMethod = classOfHandle.getMethod("getAbsorptionHearts"); + getAbsorptionMethod.setAccessible(true); + return (double) (float) getAbsorptionMethod.invoke(handle); + } catch (Throwable ignored) { + } + + logger.warn("Could not get absorption amount for player of class {}", classOfPlayer.getName()); + return 0; + } + + public static boolean isAir(@Nonnull Material material) { + try { + return material.isAir(); + } catch (Throwable ignored) { + } + + switch (material.name()) { + case "AIR": + case "VOID_AIR": + case "CAVE_AIR": + case "LEGACY_AIR": + return true; + default: + return false; + } + } + + public static int getMinHeight(@Nonnull World world) { + try { + return world.getMinHeight(); + } catch (Throwable ignored) { + } + + return 0; + } + + /** + * @return if the entity is in water, {@code false} otherwise or if not implemented + * @deprecated not implemented in all forks of bukkit + */ + @Deprecated + public static boolean isInWater(@Nonnull Entity entity) { + try { + return entity.isInWater(); + } catch (Throwable ignored) { + } + + return false; + } + + private static final Pattern VALID_KEY = Pattern.compile("[a-z0-9/._-]+"); + + /** + * Get a NamespacedKey from the supplied string. + * + * The default namespace will be Minecraft's (i.e. + * {@link NamespacedKey#minecraft(String)}). + * + * @param key the key to convert to a NamespacedKey + * @return the created NamespacedKey. null if invalid + * @see #fromString(String, Plugin) + */ + @Nullable + public static NamespacedKey fromString(@Nonnull String key) { + return fromString(key, null); + } + + /** + * Does not exists in versions prior to 1.14 + * + * Get a NamespacedKey from the supplied string with a default namespace if + * a namespace is not defined. This is a utility method meant to fetch a + * NamespacedKey from user input. Please note that casing does matter and + * any instance of uppercase characters will be considered invalid. The + * input contract is as follows: + *

+	 * fromString("foo", plugin) -{@literal >} "plugin:foo"
+	 * fromString("foo:bar", plugin) -{@literal >} "foo:bar"
+	 * fromString(":foo", null) -{@literal >} "minecraft:foo"
+	 * fromString("foo", null) -{@literal >} "minecraft:foo"
+	 * fromString("Foo", plugin) -{@literal >} null
+	 * fromString(":Foo", plugin) -{@literal >} null
+	 * fromString("foo:bar:bazz", plugin) -{@literal >} null
+	 * fromString("", plugin) -{@literal >} null
+	 * 
+ * + * @param string the string to convert to a NamespacedKey + * @param defaultNamespace the default namespace to use if none was + * supplied. If null, the {@code minecraft} namespace + * ({@link NamespacedKey#minecraft(String)}) will be used + * @return the created NamespacedKey. null if invalid key + * @see #fromString(String) + */ + @Nullable + public static NamespacedKey fromString(@Nonnull String string, @Nullable Plugin defaultNamespace) { + Preconditions.checkArgument(string != null && !string.isEmpty(), "Input string must not be empty or null"); + + String[] components = string.split(":", 3); + if (components.length > 2) { + return null; + } + + String key = (components.length == 2) ? components[1] : ""; + if (components.length == 1) { + String value = components[0]; + if (value.isEmpty() || !VALID_KEY.matcher(value).matches()) { + return null; + } + + return (defaultNamespace != null) ? new NamespacedKey(defaultNamespace, value) : NamespacedKey.minecraft(value); + } else if (components.length == 2 && !VALID_KEY.matcher(key).matches()) { + return null; + } + + String namespace = components[0]; + if (namespace.isEmpty()) { + return (defaultNamespace != null) ? new NamespacedKey(defaultNamespace, key) : NamespacedKey.minecraft(key); + } + + if (!VALID_KEY.matcher(namespace).matches()) { + return null; + } + + return new NamespacedKey(namespace, key); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java new file mode 100644 index 000000000..47cd94c9d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java @@ -0,0 +1,50 @@ +package net.codingarea.commons.bukkit.utils.misc; + +import net.codingarea.commons.common.logging.ILogger; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryView; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nonnull; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/* + * In API version 1.20.6 and earlier, InventoryView is an abstract class + * In API version 1.21, InventoryView is an interface + */ +public class CompatibilityUtils { + + protected static final ILogger logger = ILogger.forThisClass(); + private static final Logger log = LoggerFactory.getLogger(CompatibilityUtils.class); + + private CompatibilityUtils() { + } + + public static Inventory getTopInventory(@Nonnull Player player) { + InventoryView view = player.getOpenInventory(); + + try { + Method getTopInventory = InventoryView.class.getMethod("getTopInventory"); + return (Inventory) getTopInventory.invoke(view); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { + logger.error("Failed to get top inventory", ex); + return null; + } + } + + public static Inventory getTopInventory(@Nonnull InventoryClickEvent event) { + InventoryView view = event.getView(); + + try { + Method getTopInventory = InventoryView.class.getMethod("getTopInventory"); + return (Inventory) getTopInventory.invoke(view); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { + logger.error("Failed to get top inventory", ex); + return null; + } + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java new file mode 100644 index 000000000..44d8d380f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java @@ -0,0 +1,91 @@ +package net.codingarea.commons.bukkit.utils.misc; + +import com.mojang.authlib.GameProfile; +import com.mojang.authlib.properties.Property; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.logging.ILogger; +import org.bukkit.entity.Player; +import org.bukkit.inventory.meta.SkullMeta; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.UUID; + +public final class GameProfileUtils { + + private static final ILogger logger = ILogger.forThisClass(); + + private GameProfileUtils() {} + + @Nonnull + public static GameProfile getGameProfile(@Nonnull Player player) { + try { + + Class classOfPlayer = player.getClass(); + + Method getProfileMethod = classOfPlayer.getMethod("getProfile"); + getProfileMethod.setAccessible(true); + return (GameProfile) getProfileMethod.invoke(player); + + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + public static void applyTextures(@Nonnull SkullMeta meta, @Nullable UUID uuid, @Nullable String name, @Nullable String texture) { + applyTextures(meta, uuid, name, texture, null); + } + + public static void applyTextures(@Nonnull SkullMeta meta, @Nullable UUID uuid, @Nullable String name, @Nullable String texture, @Nullable String signature) { + if (texture == null || texture.isEmpty()) return; + + GameProfile profile = new GameProfile(uuid == null ? UUID.randomUUID() : uuid, name); + profile.getProperties().put("textures", new Property("textures", texture, signature)); + + Class classOfMeta = meta.getClass(); + try { + Method setProfileMethod = classOfMeta.getDeclaredMethod("setProfile", GameProfile.class); + setProfileMethod.setAccessible(true); + setProfileMethod.invoke(meta, profile); + return; + } catch (Exception ignored) { + } + + try { + Field field = classOfMeta.getDeclaredField("profile"); + field.setAccessible(true); + field.set(meta, profile); + + // This field is not implemented in every version + try { + field = classOfMeta.getDeclaredField("serializedProfile"); + field.setAccessible(true); + field.set(meta, profile); + } catch (Exception ignored) { + } + + return; + } catch (Exception ignored) { + } + + logger.warn("Unable to apply textures to item"); + + } + + @Nonnull + public static GameProfile getTextures(@Nonnull SkullMeta meta) { + + Class classOfMeta = meta.getClass(); + try { + Field field = classOfMeta.getDeclaredField("profile"); + field.setAccessible(true); + return (GameProfile) field.get(meta); + } catch (Exception ex) { + throw new WrappedException(ex); + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java new file mode 100644 index 000000000..16e369a67 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java @@ -0,0 +1,115 @@ +package net.codingarea.commons.bukkit.utils.misc; + +import net.codingarea.commons.common.version.Version; +import org.bukkit.Bukkit; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; + +public enum MinecraftVersion implements Version { + + V1_0, // 1.0 + V1_1, // 1.1 + V1_2_1, // 1.2.1 + V1_3_1, // 1.3.1 + V1_4_2, // 1.4.2 + V1_5, // 1.5 + V1_6, // 1.6 + V1_7, // 1.7 + V1_7_2, // 1.7.2 + V1_8, // 1.8 + V1_9, // 1.9 + V1_10, // 1.10 + V1_11, // 1.11 + V1_12, // 1.12 + V1_13, // 1.13 + V1_14, // 1.14 + V1_15, // 1.15 + V1_16, // 1.16 + V1_16_5, // 1.16.5 + V1_17, // 1.17 + V1_18, // 1.18 + V1_19, // 1.19 + V1_20, // 1.20 + V1_20_1, // 1.20.1 + V1_20_2, // 1.20.2 + V1_20_3, // 1.20.3 + V1_20_4, // 1.20.4 + V1_20_5, // 1.20.5 + V1_21, // 1.21 + V1_21_1, // 1.21.1 + V1_21_2, // 1.21.2 + V1_21_3, // 1.21.3 + V1_21_4, // 1.21.4 + V1_21_5 // 1.21.5 + ; + + private final int major, minor, revision; + + MinecraftVersion() { + + String name = this.name().substring(1); + String[] version = name.split("_"); + + if (version.length != 2 && version.length != 3) + throw new IllegalArgumentException("Name '" + name() + "' does not match pattern: V{major}_{minor}_[revision]"); + + major = Integer.parseInt(version[0]); + minor = Integer.parseInt(version[1]); + revision = version.length > 2 ? Integer.parseInt(version[2]) : 0; + + } + + @Override + public int getMajor() { + return major; + } + + @Override + public int getMinor() { + return minor; + } + + @Override + public int getRevision() { + return revision; + } + + @Override + public String toString() { + return this.format(); + } + + @Nonnull + @CheckReturnValue + public static Version parseExact(@Nonnull String bukkitVersion) { + bukkitVersion = bukkitVersion.substring(0, bukkitVersion.indexOf("-")); + return Version.parse(bukkitVersion); + } + + @Nonnull + @CheckReturnValue + public static MinecraftVersion findNearest(@Nonnull Version realVersion) { + return Version.findNearest(realVersion, values()); + } + + private static Version currentExact; + private static MinecraftVersion current; + + @Nonnull + @CheckReturnValue + public static Version currentExact() { + if (currentExact == null) + currentExact = parseExact(Bukkit.getBukkitVersion()); + return currentExact; + } + + @Nonnull + @CheckReturnValue + public static MinecraftVersion current() { + if (current == null) + current = findNearest(currentExact()); + return current; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java new file mode 100644 index 000000000..8faa0993b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java @@ -0,0 +1,57 @@ +package net.codingarea.commons.bukkit.utils.wrapper; + +import org.bukkit.event.Event; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +import javax.annotation.Nonnull; +import java.util.Objects; +import java.util.function.Consumer; + +public final class ActionListener implements Listener { + + private final Class classOfEvent; + private final Consumer listener; + private final EventPriority priority; + private final boolean ignoreCancelled; + + public ActionListener(@Nonnull Class classOfEvent, @Nonnull Consumer listener, @Nonnull EventPriority priority, boolean ignoreCancelled) { + this.classOfEvent = classOfEvent; + this.listener = listener; + this.priority = priority; + this.ignoreCancelled = ignoreCancelled; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ActionListener that = (ActionListener) o; + return listener.equals(that.listener); + } + + @Override + public int hashCode() { + return Objects.hash(listener); + } + + @Nonnull + public Consumer getListener() { + return listener; + } + + @Nonnull + public EventPriority getPriority() { + return priority; + } + + @Nonnull + public Class getClassOfEvent() { + return classOfEvent; + } + + public boolean isIgnoreCancelled() { + return ignoreCancelled; + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/wrapper/AttributeWrapper.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java similarity index 80% rename from plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/wrapper/AttributeWrapper.java rename to plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java index 5b5abbdb8..ea2a13e3f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/wrapper/AttributeWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java @@ -1,6 +1,6 @@ -package net.codingarea.challenges.plugin.utils.bukkit.misc.wrapper; +package net.codingarea.commons.bukkit.utils.wrapper; -import net.codingarea.challenges.plugin.utils.bukkit.misc.version.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.attribute.Attribute; public class AttributeWrapper { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java new file mode 100644 index 000000000..d073dd81f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java @@ -0,0 +1,27 @@ +package net.codingarea.commons.bukkit.utils.wrapper; + +import net.codingarea.commons.common.misc.ReflectionUtils; +import org.bukkit.Material; + +import javax.annotation.Nonnull; + +/** + * This class allows you to use materials, whose names are changed at some point, in most versions. + * For example the red dye was first named {@code ROSE_RED} but then renamed to {@code RED_DYE}. + * To prevent unwanted {@link NoSuchFieldError NoSuchFieldErrors}, you should use this wrapper instead of a direct call to the material enum {@link Material}. + */ +public final class MaterialWrapper { + + private MaterialWrapper() {} + + public static final Material GREEN_DYE = getMaterialByNames("CACTUS_GREEN", "GREEN_DYE"); + public static final Material RED_DYE = getMaterialByNames("ROSE_RED", "RED_DYE"); + public static final Material YELLOW_DYE = getMaterialByNames("DANDELION_YELLOW", "YELLOW_DYE"); + public static final Material SIGN = getMaterialByNames("SIGN", "OAK_SIGN"); + + @Nonnull + private static Material getMaterialByNames(@Nonnull String... names) { + return ReflectionUtils.getFirstEnumByNames(Material.class, names); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java new file mode 100644 index 000000000..2b3055417 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java @@ -0,0 +1,31 @@ +package net.codingarea.commons.bukkit.utils.wrapper; + +import org.bukkit.event.Event; +import org.bukkit.event.EventException; +import org.bukkit.event.Listener; +import org.bukkit.plugin.EventExecutor; + +import javax.annotation.Nonnull; +import java.util.function.Consumer; + +public class SimpleEventExecutor implements EventExecutor { + + private final Class classOfEvent; + private final Consumer action; + + public SimpleEventExecutor(@Nonnull Class classOfEvent, @Nonnull Consumer action) { + this.classOfEvent = classOfEvent; + this.action = action; + } + + @Override + public void execute(@Nonnull Listener listener, @Nonnull Event event) throws EventException { + if (!classOfEvent.isAssignableFrom(event.getClass())) return; + try { + action.accept(event); + } catch (Throwable ex) { + throw new EventException(ex); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java new file mode 100644 index 000000000..685852b83 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.common.annotations; + +import javax.annotation.Nonnull; +import java.lang.annotation.*; + +/** + * Used to declare alternate names which are used in used or similar libraries. + */ +@Documented +@Retention(RetentionPolicy.CLASS) +@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) +public @interface AlsoKnownAs { + + @Nonnull + String[] value(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java new file mode 100644 index 000000000..72fb1e113 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.common.annotations; + +import javax.annotation.Nonnull; +import java.lang.annotation.*; + +/** + * @see Deprecated + */ +@Documented +@Retention(RetentionPolicy.CLASS) +@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE}) +public @interface DeprecatedSince { + + @Nonnull + String value(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java new file mode 100644 index 000000000..469355d3b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.common.annotations; + +import javax.annotation.Nonnull; +import java.lang.annotation.*; + +/** + * @see Deprecated + */ +@Documented +@Retention(RetentionPolicy.CLASS) +@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE}) +public @interface ReplaceWith { + + @Nonnull + String value(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java new file mode 100644 index 000000000..0f27a0c69 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java @@ -0,0 +1,14 @@ +package net.codingarea.commons.common.annotations; + +import javax.annotation.Nonnull; +import java.lang.annotation.*; + +@Documented +@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PACKAGE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Since { + + @Nonnull + String value(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java b/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java new file mode 100644 index 000000000..23ba208f9 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java @@ -0,0 +1,56 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.lang.reflect.Array; +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.function.Consumer; + +public class ArrayWalker implements Iterable { + + protected final Object array; + protected final int length; + + protected ArrayWalker(@Nonnull Object array) { + if (!array.getClass().isArray()) throw new IllegalArgumentException(array.getClass().getName() + " is not an array"); + this.array = array; + this.length = Array.getLength(array); + } + + public static ArrayWalker walk(@Nonnull Object array) { + return new ArrayWalker<>(array); + } + + public static ArrayWalker walk(@Nonnull T... array) { + return new ArrayWalker<>(array); + } + + @Override + public Iterator iterator() { + return new Iterator() { + + private int cursor = 0; + + @Override + public boolean hasNext() { + return cursor < length; + } + + @Override + @SuppressWarnings("unchecked") + public T next() { + if (!hasNext()) throw new NoSuchElementException(); + return (T) Array.get(array, cursor++); + } + + }; + } + + @Override + @SuppressWarnings("unchecked") + public void forEach(Consumer action) { + for (int i = 0; i < length; i++) { + action.accept((T) Array.get(array, i)); + } + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java new file mode 100644 index 000000000..d71f0df71 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java @@ -0,0 +1,65 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.util.*; + +/** + * @author JDA | https://github.com/DV8FromTheWorld/JDA/blob/development/src/main/java/net/dv8tion/jda/internal/utils/ClassWalker.java + */ +public class ClassWalker implements Iterable> { + + protected final Class clazz; + protected final Class end; + + protected ClassWalker(@Nonnull Class clazz) { + this(clazz, Object.class); + } + + protected ClassWalker(@Nonnull Class clazz, @Nonnull Class end) { + this.clazz = clazz; + this.end = end; + } + + public static ClassWalker range(@Nonnull Class start, @Nonnull Class end) { + return new ClassWalker(start, end); + } + + public static ClassWalker walk(@Nonnull Class start) { + return new ClassWalker(start); + } + + @Nonnull + @Override + public Iterator> iterator() { + return new Iterator>() { + + private final Set> done = new HashSet<>(); + private final Deque> work = new LinkedList<>(); + + { + work.addLast(clazz); + done.add(end); + } + + @Override + public boolean hasNext() { + return !work.isEmpty(); + } + + @Override + public Class next() { + Class current = work.removeFirst(); + done.add(current); + for (Class parent : current.getInterfaces()) { + if (!done.contains(parent)) + work.addLast(parent); + } + + Class parent = current.getSuperclass(); + if (parent != null && !done.contains(parent)) + work.addLast(parent); + return current; + } + }; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java b/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java new file mode 100644 index 000000000..dc7950c10 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java @@ -0,0 +1,38 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.awt.*; + +import static java.awt.Color.decode; + +public final class Colors { + + private Colors() {} + + public static final Color + ONLINE = decode("#40AC7B"), + DO_NOT_DISTURB = decode("#E84444"), + IDLE = decode("#F09F19"), + OFFLINE = decode("#747F8D"), + STREAMING = decode("#573591"), + + EMBED = decode("#2F3136"), + NO_RANK = decode("#CCD8DE"), + + LIGHT_BLACK = decode("#1c1c1c") + ; + + @Nonnull + @CheckReturnValue + public static String asHex(@Nonnull Color color) { + String red = Integer.toHexString(color.getRed()); + String green = Integer.toHexString(color.getGreen()); + String blue = Integer.toHexString(color.getBlue()); + return "#" + (red.length() == 1 ? "0" + red : red) + + (green.length() == 1 ? "0" + green : green) + + (blue.length() == 1 ? "0" + blue : blue); + } + + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java b/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java new file mode 100644 index 000000000..4625c3347 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java @@ -0,0 +1,93 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.util.Objects; + +public class FontBuilder { + + private Font font; + + public FontBuilder(@Nonnull File file) throws IOException, FontFormatException { + this(file, Font.TRUETYPE_FONT); + } + + public FontBuilder(@Nonnull File file, int type) throws IOException, FontFormatException { + this.font = Font.createFont(type, file); + } + + public FontBuilder(@Nonnull String resource) throws IOException, FontFormatException { + this(resource, Font.TRUETYPE_FONT); + } + + public FontBuilder(@Nonnull String resource, int type) throws IOException, FontFormatException { + this.font = Font.createFont(type, Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(resource))); + } + + @Nonnull + @CheckReturnValue + public FontBuilder bold() { + return style(Font.BOLD); + } + + @Nonnull + @CheckReturnValue + public FontBuilder italic() { + return style(Font.ITALIC); + } + + @Nonnull + @CheckReturnValue + public FontBuilder style(int style) { + font = font.deriveFont(style); + return this; + } + + @Nonnull + @CheckReturnValue + public FontBuilder size(float size) { + font = font.deriveFont(size); + return this; + } + + @Nonnull + @CheckReturnValue + public FontBuilder derive(int style, float size) { + font = font.deriveFont(style, size); + return this; + } + + @Nonnull + public Font build() { + registerFont(font); + return font; + } + + public static void registerFont(@Nonnull Font font) { + GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(font); + } + + @Nonnull + @CheckReturnValue + public static FontBuilder fromFile(@Nonnull String filename) { + try { + return new FontBuilder(new File(filename)); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + public static FontBuilder fromResource(@Nonnull String resource) { + try { + return new FontBuilder(resource); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java b/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java new file mode 100644 index 000000000..54c8675fe --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java @@ -0,0 +1,43 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; + +public final class IOUtils { + + private IOUtils() {} + + public static String toString(@Nonnull String url) throws IOException { + return toString(new URL(url)); + } + + public static String toString(@Nonnull URL url) throws IOException { + InputStream input = url.openStream(); + String string = toString(input); + input.close(); + return string; + } + + public static String toString(@Nonnull InputStream input) throws IOException { + StringBuilder builder = new StringBuilder(); + BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); + reader.lines().forEach(builder::append); + return builder.toString(); + } + + @Nonnull + @CheckReturnValue + public static HttpURLConnection createConnection(@Nonnull String url) throws IOException { + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); + return connection; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java b/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java new file mode 100644 index 000000000..cfd4a96bc --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java @@ -0,0 +1,152 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import java.security.SecureRandom; +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.DoubleStream; +import java.util.stream.IntStream; +import java.util.stream.LongStream; + +public interface IRandom { + + @Nonnull + @CheckReturnValue + static IRandom create() { + return new SeededRandomWrapper(); + } + + @Nonnull + @CheckReturnValue + static IRandom create(long seed) { + return new SeededRandomWrapper(seed); + } + + @Nonnull + @CheckReturnValue + static IRandom wrap(@Nonnull Random random) { + return new RandomWrapper(random); + } + + @Nonnull + @CheckReturnValue + static IRandom threadLocal() { + return wrap(ThreadLocalRandom.current()); + } + + @Nonnull + @CheckReturnValue + static IRandom secure() { + return wrap(new SecureRandom()); + } + + @Nonnull + @CheckReturnValue + static IRandom singleton() { + return SingletonRandom.INSTANCE; + } + + long getSeed(); + + void setSeed(long seed); + + void nextBytes(@Nonnull byte[] bytes); + + boolean nextBoolean(); + + int nextInt(); + + int nextInt(int bound); + + @Nonnull + @CheckReturnValue + IntStream ints(); + + @Nonnull + @CheckReturnValue + IntStream ints(@Nonnegative long streamSize); + + @Nonnull + @CheckReturnValue + IntStream ints(int randomNumberOrigin, int randomNumberBound); + + @Nonnull + @CheckReturnValue + IntStream ints(@Nonnegative long streamSize, int randomNumberOrigin, int randomNumberBound); + + @Nonnull + @CheckReturnValue + LongStream longs(); + + long nextLong(); + + @Nonnull + @CheckReturnValue + LongStream longs(@Nonnegative long streamSize); + + @Nonnull + @CheckReturnValue + LongStream longs(long randomNumberOrigin, long randomNumberBound); + + @Nonnull + @CheckReturnValue + LongStream longs(@Nonnegative long streamSize, long randomNumberOrigin, long randomNumberBound); + + double nextDouble(); + + double nextGaussian(); + + @Nonnull + @CheckReturnValue + DoubleStream doubles(); + + @Nonnull + @CheckReturnValue + DoubleStream doubles(@Nonnegative long streamSize); + + @Nonnull + @CheckReturnValue + DoubleStream doubles(double randomNumberOrigin, double randomNumberBound); + + @Nonnull + @CheckReturnValue + DoubleStream doubles(@Nonnegative long streamSize, double randomNumberOrigin, double randomNumberBound); + + float nextFloat(); + + default T choose(@Nonnull T... array) { + return array[nextInt(array.length)]; + } + + default T choose(@Nonnull List list) { + return list.get(nextInt(list.size())); + } + + default T choose(@Nonnull Collection collection) { + return choose(new ArrayList<>(collection)); + } + + default void shuffle(@Nonnull List list) { + Collections.shuffle(list, asRandom()); + } + + default int around(int value, @Nonnegative int range) { + return range(value - range, value + range); + } + + default int range(int min, int max) { + if (min >= max) throw new IllegalArgumentException("min >= max"); + return nextInt(max - min) + min; + } + + @Nonnull + @CheckReturnValue + default Random asRandom() { + if (!(this instanceof Random)) + throw new IllegalStateException(this.getClass().getName() + " cannot be converted a java.util.Random"); + return (Random) this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java new file mode 100644 index 000000000..624f2508f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java @@ -0,0 +1,37 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.IntFunction; + +public class NamedThreadFactory implements ThreadFactory { + + private static final AtomicInteger poolNumber = new AtomicInteger(1); + + protected final int id = poolNumber.getAndIncrement(); + protected final IntFunction nameFunction; + protected final ThreadGroup group; + protected final AtomicInteger threadNumber = new AtomicInteger(1); + + public NamedThreadFactory(@Nonnull IntFunction nameFunction) { + SecurityManager securityManager = System.getSecurityManager(); + this.group = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup(); + this.nameFunction = nameFunction; + } + + public NamedThreadFactory(@Nonnull String prefix) { + this(id -> prefix + "-" + id); + } + + @Override + public Thread newThread(@Nonnull Runnable task) { + Thread thread = new Thread(group, task, nameFunction.apply(threadNumber.getAndIncrement())); + if (thread.isDaemon()) + thread.setDaemon(false); + if (thread.getPriority() != Thread.NORM_PRIORITY) + thread.setPriority(Thread.NORM_PRIORITY); + return thread; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java new file mode 100644 index 000000000..4a734b55b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java @@ -0,0 +1,357 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.function.Consumer; + +public interface NumberFormatter { + + @Nonnull + @CheckReturnValue + String format(double value); + + @Nonnull + @CheckReturnValue + default String format(float value) { + return format(Float.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(long value) { + return format(Long.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(int value) { + return format(Integer.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(short value) { + return format(Short.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(byte value) { + return format(Byte.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(@Nonnull Number number) { + return format(number.doubleValue()); + } + + public static final NumberFormatter + DEFAULT = fromPattern("0.##", null, false), + INTEGER = value -> (int) value + "", + SPACE_SPLIT = fromPattern("###,##0.###############", null, false, + init -> updateSymbols(init, symbols -> symbols.setGroupingSeparator(' '))), + FLOATING_POINT = fromPattern("0.0", null, false), + DOUBLE_FLOATING_POINT = fromPattern("0.00", null, false), + BIG_FLOATING_POINT = fromPattern("###,##0.00000", null, false), + PERCENTAGE = fromPattern("0.##", "%", true), + FLOATING_PERCENTAGE = fromPattern("0.00", "%", true), + MIDDLE_NUMBER = fromPattern("###,###,##0.#", null, false), + + /** + * days, hours, minutes, seconds + */ + TIME = value -> { + + int seconds = (int) value; + int minutes = seconds / 60; + int hours = minutes / 60; + int days = hours / 24; + int years = days / 365; + + seconds %= 60; + minutes %= 60; + hours %= 24; + days %= 365; + + return ((years > 0 ? years + "y " : "") + + (days > 0 ? days + "d " : "") + + (hours > 0 ? hours + "h " : "") + + (minutes > 0 ? minutes + "m " : "") + + (seconds > 0 || (years == 0 && days == 0 && hours == 0 && minutes == 0) ? seconds + "s" : "")).trim(); + + }, + + /** + * days, hours, minutes + */ + BIG_TIME = value -> { + + int seconds = (int) value; + int minutes = seconds / 60; + int hours = minutes / 60; + int days = hours / 24; + int years = days / 365; + + minutes %= 60; + hours %= 24; + days %= 365; + + return ((years > 0 ? years + "y " : "") + + (days > 0 ? days + "d " : "") + + (hours > 0 ? hours + "h " : "") + + (minutes > 0 || (years == 0 && days == 0 && hours == 0) ? minutes + "m " : "")).trim(); + + }, + + /** + * input: millis + * 1 Tag, H:M:S + */ + GERMAN_TIME = value -> { + + DecimalFormat format = new DecimalFormat("00"); + + long millis = (long) value; + long seconds = millis / 1000; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + seconds %= 60; + minutes %= 60; + hours %= 24; + + return (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 ? format.format(hours) + ":" : "") + + format.format(minutes) + ":" + + format.format(seconds); + + }, + /** + * input: seconds + * 1 Tag, H:M:S + */ + FULL_GERMAN_TIME_HOURS = value -> { + + long seconds = (long) (value); + long minutes = seconds / 60; + long hours = minutes / 60; + seconds %= 60; + minutes %= 60; + + return hours > 0 ? (hours == 1 ? "1 Stunde" : hours + " Stunden") : (minutes == 1 ? "1 Minute" : minutes + " Minuten"); + }, + + FULL_GERMAN_TIME = value -> { + + long seconds = (long) value; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + long years = days / 365; + + seconds %= 60; + minutes %= 60; + hours %= 24; + days %= 265; + + return ((years > 0 ? (years == 1 ? "1 Jahr " : years + " Jahre ") : "") + + (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 ? (hours == 1 ? "1 Stunde " : hours + " Stunden ") : "") + + (minutes > 0 ? (minutes == 1 ? "1 Minute " : minutes + " Minuten ") : "") + + (seconds > 0 || years == 0 && hours == 0 && minutes == 0 ? (seconds == 1 ? "1 Sekunde" : seconds + " Sekunden") : "")).trim(); + + }, + + NORMAL_FULL_GERMAN_TIME = value -> { + + long seconds = (long) value; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + long years = days / 365; + + minutes %= 60; + hours %= 24; + days %= 265; + + return ((years > 0 ? (years == 1 ? "1 Jahr " : years + " Jahre ") : "") + + (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 ? (hours == 1 ? "1 Stunde " : hours + " Stunden ") : "") + + (minutes > 0 || value == 0 ? (minutes == 1 ? "1 Minute " : minutes + " Minuten ") : "")).trim(); + + }, + + BIG_FULL_GERMAN_TIME = value -> { + + long seconds = (long) value; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + long years = days / 365; + + hours %= 24; + days %= 265; + + return ((years > 0 ? (years == 1 ? "1 Jahr " : years + " Jahre ") : "") + + (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 || years == 0 && days == 0 ? (hours == 1 ? "1 Stunde" : hours + " Stunden") : "")).trim(); + + }, + + /** + * billion, million, thousand, number + */ + BIG_NUMBER = value -> { + + DecimalFormat format = new DecimalFormat("0.##"); + double divide; + String ending = ""; + + // Normal number + if (value < 1000) { + divide = 1; + format = new DecimalFormat("0.#"); + // Thousand + } else if (value < 1000000) { + divide = 1000; + ending = "k"; + // Million + } else if (value < 1000000000) { + divide = 1000000; + ending = "m"; + // Billion (Milliarde) + } else if (value < 1000000000000D) { + divide = 1000000000; + ending = "b"; + // Trillion (Billion) + } else { + divide = 1000000000000D; + ending = "t"; + } + + value /= divide; + return format.format(value) + ending; + + }, + + /** + * input in bytes + * kilobyte, megabyte, gigabyte, terrabyte + */ + DATA_SIZE = value -> { + + if (value < 0) value = 0; + + DecimalFormat format = new DecimalFormat("0.##"); + double divide; + String ending; + + // KiloByte + if (value < 1000000L) { + divide = 1000; + format = new DecimalFormat("0.#"); + ending = "KB"; + } else if (value < 1000000000L) { + // MegaByte + divide = 1000000L; + ending = "MB"; + // GigaByte + } else if (value < 1000000000000L) { + divide = 1000000000L; + ending = "GB"; + // TerraByte + } else { + divide = 1000000000000L; + ending = "TB"; + } + + value /= divide; + return format.format(value) + ending; + + }, + + /** + * input in bytes + * gigabyte, terrabyte, petabyte + */ + BIG_DATA_SIZE = value -> { + + if (value < 0) value = 0; + + DecimalFormat format = new DecimalFormat("0.##"); + double divide; + String ending; + + // GigaByte + if (value < 1000000000000L) { + divide = 1000000000L; + ending = "GB"; + // TerraByte + } else if (value < 1000000000000000L) { + divide = 1000000000000L; + ending = "TB"; + // PetaByte + } else { + divide = 1000000000000000L; + ending = "PB"; + } + + value /= divide; + return format.format(value) + ending; + + }, + ORDINAL = value -> { + + String string = String.valueOf(((long) value)); + int number = Integer.parseInt(string.substring(string.length() - 1)); + String ending = "th"; + + if (value != 11 && value != 12 && value != 13) { + switch (number) { + case 1: + ending = "st"; + break; + case 2: + ending = "nd"; + break; + case 3: + ending = "rd"; + break; + } + } + + return string + ending; + + }, + GERMAN_ORDINAL = fromPattern("0", ".", false); + + @Nonnull + @CheckReturnValue + public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive) { + return fromPattern(pattern, ending, positive, null); + } + + @Nonnull + @CheckReturnValue + public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive, Consumer init) { + DecimalFormat format = new DecimalFormat(pattern); + if (init != null) init.accept(format); + return value -> Double.isNaN(value) ? "NaN" : format.format(positive ? (value > 0 ? value : 0) : value) + (ending != null ? ending : ""); + } + + @Nonnull + @CheckReturnValue + public static DecimalFormatSymbols updateSymbols(@Nonnull DecimalFormatSymbols symbols, @Nonnull Consumer action) { + action.accept(symbols); + return symbols; + } + + @CheckReturnValue + public static void updateSymbols(@Nonnull DecimalFormat format, @Nonnull Consumer action) { + format.setDecimalFormatSymbols(updateSymbols(format.getDecimalFormatSymbols(), action)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/PublicSecurityManager.java b/plugin/src/main/java/net/codingarea/commons/common/collection/PublicSecurityManager.java new file mode 100644 index 000000000..b561b6bf8 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/PublicSecurityManager.java @@ -0,0 +1,12 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; + +public class PublicSecurityManager extends SecurityManager { + + @Nonnull + public Class[] getPublicClassContext() { + return getClassContext(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java new file mode 100644 index 000000000..a845fbc10 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java @@ -0,0 +1,149 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.util.Random; +import java.util.stream.DoubleStream; +import java.util.stream.IntStream; +import java.util.stream.LongStream; + +public class RandomWrapper implements IRandom { + + private final Random random; + + public RandomWrapper(@Nonnull Random random) { + this.random = random; + } + + @Override + public long getSeed() { + throw new UnsupportedOperationException("Random.getSeed()"); + } + + @Override + public void setSeed(long seed) { + random.setSeed(seed); + } + + @Override + public void nextBytes(@Nonnull byte[] bytes) { + random.nextBytes(bytes); + } + + @Override + public boolean nextBoolean() { + return random.nextBoolean(); + } + + @Override + public int nextInt() { + return random.nextInt(); + } + + @Override + public int nextInt(int bound) { + return random.nextInt(bound); + } + + @Nonnull + @Override + public IntStream ints() { + return random.ints(); + } + + @Nonnull + @Override + public IntStream ints(long streamSize) { + return random.ints(streamSize); + } + + @Nonnull + @Override + public IntStream ints(int randomNumberOrigin, int randomNumberBound) { + return random.ints(randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound) { + return random.ints(streamSize, randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public LongStream longs() { + return random.longs(); + } + + @Override + public long nextLong() { + return random.nextLong(); + } + + @Nonnull + @Override + public LongStream longs(long streamSize) { + return random.longs(streamSize); + } + + @Nonnull + @Override + public LongStream longs(long randomNumberOrigin, long randomNumberBound) { + return random.longs(randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public LongStream longs(long streamSize, long randomNumberOrigin, long randomNumberBound) { + return random.longs(streamSize, randomNumberOrigin, randomNumberBound); + } + + @Override + public double nextDouble() { + return random.nextDouble(); + } + + @Override + public double nextGaussian() { + return random.nextGaussian(); + } + + @Nonnull + @Override + public DoubleStream doubles() { + return random.doubles(); + } + + @Nonnull + @Override + public DoubleStream doubles(long streamSize) { + return random.doubles(streamSize); + } + + @Nonnull + @Override + public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) { + return random.doubles(randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public DoubleStream doubles(long streamSize, double randomNumberOrigin, double randomNumberBound) { + return random.doubles(streamSize, randomNumberOrigin, randomNumberBound); + } + + @Override + public float nextFloat() { + return random.nextFloat(); + } + + @Nonnull + @Override + public Random asRandom() { + return random; + } + + @Override + public String toString() { + return "Random[wrapped=" + random.getClass().getSimpleName() + "]"; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java b/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java new file mode 100644 index 000000000..e1401ba5e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.util.TreeMap; + +public final class RomanNumerals { + + public static final class IllegalRomanNumeralException extends IllegalArgumentException { + + private IllegalRomanNumeralException(int number) { + super("Number " + number + " out of bounds for 0 to 3999"); + } + + } + + private static final TreeMap values = new TreeMap<>(); + + static { + values.put(1000, "M" ); + values.put(900, "CM"); + values.put(500, "D" ); + values.put(400, "CD"); + values.put(100, "C" ); + values.put(90, "XC"); + values.put(50, "L" ); + values.put(40, "XL"); + values.put(10, "X" ); + values.put(9, "IX"); + values.put(5, "V" ); + values.put(4, "IV"); + values.put(1, "I" ); + } + + private RomanNumerals() {} + + @Nonnull + public static String forNumber(int number) { + if (number < 0 || number > 3999) throw new IllegalRomanNumeralException(number); + if (number == 0) return ""; + int i = values.floorKey(number); + if (number == i) { + return values.get(number); + } + return values.get(i) + forNumber(number - i); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java b/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java new file mode 100644 index 000000000..540c375f1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java @@ -0,0 +1,19 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.util.TimerTask; + +public class RunnableTimerTask extends TimerTask { + + protected final Runnable action; + + public RunnableTimerTask(@Nonnull Runnable action) { + this.action = action; + } + + @Override + public void run() { + action.run(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java new file mode 100644 index 000000000..a9fcb48f2 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java @@ -0,0 +1,35 @@ +package net.codingarea.commons.common.collection; + +import java.util.Random; + +/** + * Since there is no way of getting the seed of a {@link Random} we create a wrapper + * which will save seed. This allows us to save randomization and reload it. + */ +public class SeededRandomWrapper extends Random implements IRandom { + + protected long seed; + + public SeededRandomWrapper() { + super(); + } + + public SeededRandomWrapper(long seed) { + super(seed); + } + + @Override + public void setSeed(long seed) { + super.setSeed(seed); + this.seed = seed; + } + + public long getSeed() { + return seed; + } + + @Override + public String toString() { + return "Random[seed=" + seed + "]"; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/SingletonRandom.java b/plugin/src/main/java/net/codingarea/commons/common/collection/SingletonRandom.java new file mode 100644 index 000000000..93a2ce6ed --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/SingletonRandom.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.common.collection; + +import java.util.Random; + +public class SingletonRandom extends RandomWrapper { + + public static final SingletonRandom INSTANCE = new SingletonRandom(); + + private SingletonRandom() { + super(new Random()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java new file mode 100644 index 000000000..2d0e45d21 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java @@ -0,0 +1,28 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import java.io.PrintWriter; + +/** + * @author org.apache.commons.io + */ +public class StringBuilderPrintWriter extends PrintWriter { + + protected final StringBuilderWriter writer; + + public StringBuilderPrintWriter() { + super(new StringBuilderWriter()); + writer = (StringBuilderWriter) out; + } + + @Nonnull + public StringBuilder getBuilder() { + return writer.getBuilder(); + } + + @Override + public String toString() { + return getBuilder().toString(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java new file mode 100644 index 000000000..5ad40651c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java @@ -0,0 +1,68 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.Writer; + +/** + * @author org.apache.commons.io + */ +public class StringBuilderWriter extends Writer { + + private final StringBuilder builder; + + public StringBuilderWriter() { + this.builder = new StringBuilder(); + } + + public StringBuilderWriter(int capacity) { + this.builder = new StringBuilder(capacity); + } + + public StringBuilderWriter(@Nullable StringBuilder builder) { + this.builder = builder != null ? builder : new StringBuilder(); + } + + public Writer append(char value) { + builder.append(value); + return this; + } + + public Writer append(@Nullable CharSequence value) { + builder.append(value); + return this; + } + + public Writer append(@Nullable CharSequence value, int start, int end) { + builder.append(value, start, end); + return this; + } + + public void close() { + } + + public void flush() { + } + + public void write(@Nonnull String value) { + builder.append(value); + } + + public void write(@Nullable char[] value, int offset, int length) { + if (value != null) { + builder.append(value, offset, length); + } + } + + @Nonnull + public StringBuilder getBuilder() { + return this.builder; + } + + @Override + public String toString() { + return this.builder.toString(); + } + +} + diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java new file mode 100644 index 000000000..b480031d2 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java @@ -0,0 +1,20 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nullable; + +/** + * @param The type of the first value + * @param The type of the second value + * @param The type of the third value + */ +@Deprecated +public class Triple extends net.codingarea.commons.common.collection.pair.Triple { + + public Triple() { + } + + public Triple(@Nullable F first, @Nullable S second, @Nullable T third) { + super(first, second, third); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java new file mode 100644 index 000000000..8e9077907 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java @@ -0,0 +1,19 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nullable; + +/** + * @param The type of the first value + * @param The type of the second value + */ +@Deprecated +public class Tuple extends net.codingarea.commons.common.collection.pair.Tuple { + + public Tuple() { + } + + public Tuple(@Nullable F first, @Nullable S second) { + super(first, second); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java b/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java new file mode 100644 index 000000000..1e8999988 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java @@ -0,0 +1,61 @@ +package net.codingarea.commons.common.collection; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * This class is used to rethrow signed exception as unsigned exceptions. + */ +public class WrappedException extends RuntimeException { + + public static class SilentWrappedException extends WrappedException { + + public SilentWrappedException(@Nullable String message, @Nonnull Throwable cause) { + super(message, cause); + } + + public SilentWrappedException(@Nonnull Throwable cause) { + super(cause); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } + + } + + public WrappedException(@Nullable String message, @Nonnull Throwable cause) { + super(message, cause); + } + + public WrappedException(@Nonnull Throwable cause) { + super(cause); + } + + @Nonnull + @Override + public Throwable getCause() { + return super.getCause(); + } + + @Nonnull + public static RuntimeException rethrow(@Nonnull Throwable ex) { + if (ex instanceof Error) + throw (Error) ex; + if (ex instanceof RuntimeException) + throw (RuntimeException) ex; + throw silent(ex); + } + + @Nonnull + public static WrappedException silent(@Nonnull Throwable cause) { + return new SilentWrappedException(cause); + } + + @Nonnull + public static WrappedException silent(@Nullable String message, @Nonnull Throwable cause) { + return new SilentWrappedException(message, cause); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java new file mode 100644 index 000000000..bb4c23a4a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java @@ -0,0 +1,32 @@ +package net.codingarea.commons.common.collection.pair; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; + +/** + * @see Tuple + * @see Triple + * @see Quadro + */ +public interface Pair { + + /** + * @return The amount of values + */ + @Nonnegative + int amount(); + + @Nonnull + Object[] values(); + + /** + * @return {@code true} when all of the values are null, {@code false} otherwise + */ + boolean allNull(); + + /** + * @return {@code true} when none of the values are null, {@code false} otherwise + */ + boolean noneNull(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java new file mode 100644 index 000000000..df07b890d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java @@ -0,0 +1,139 @@ +package net.codingarea.commons.common.collection.pair; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; +import java.util.function.Function; + +/** + * @param The type of the first value + * @param The type of the second value + * @param The type of the third value + * @param The type of the fourth value + */ +public class Quadro implements Pair { + + protected F first; + protected S second; + protected T third; + protected FF fourth; + + public Quadro() { + } + + public Quadro(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FF fourth) { + this.first = first; + this.second = second; + this.third = third; + this.fourth = fourth; + } + + @Override + public final int amount() { + return 4; + } + + @Nonnull + @Override + public final Object[] values() { + return new Object[] { first, second, third, first }; + } + + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public T getThird() { + return third; + } + + public FF getFourth() { + return fourth; + } + + public void setFirst(@Nullable F first) { + this.first = first; + } + + public void setSecond(@Nullable S second) { + this.second = second; + } + + public void setThird(@Nullable T third) { + this.third = third; + } + + public void setFourth(@Nullable FF fourth) { + this.fourth = fourth; + } + + @Nonnull + @CheckReturnValue + public Quadro map(@Nonnull Function firstMapper, + @Nonnull Function secondMapper, + @Nonnull Function thirdMapper, + @Nonnull Function fourthMapper) { + return of(firstMapper.apply(first), secondMapper.apply(second), thirdMapper.apply(third), fourthMapper.apply(fourth)); + } + + public boolean noneNull() { + return first != null && second != null && third != null && fourth != null; + } + + public boolean allNull() { + return first == null && second == null && third == null && fourth != null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Quadro quadro = (Quadro) o; + return Objects.equals(first, quadro.first) && Objects.equals(second, quadro.second) && Objects.equals(third, quadro.third) && Objects.equals(fourth, quadro.fourth); + } + + @Override + public int hashCode() { + return Objects.hash(first, second, third, fourth); + } + + @Override + public String toString() { + return "Quadro[" + first + ", " + second + ", " + third + ", " + fourth + "]"; + } + + @Nonnull + public static Quadro ofFirst(@Nullable F first) { + return of(first, null, null, null); + } + + @Nonnull + public static Quadro ofSecond(@Nullable S second) { + return of(null, second, null, null); + } + + @Nonnull + public static Quadro ofThird(@Nullable T third) { + return of(null, null, third, null); + } + + @Nonnull + public static Quadro ofFourth(@Nullable FF fourth) { + return of(null, null, null, fourth); + } + + @Nonnull + public static Quadro of(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FF fourth) { + return new Quadro<>(first, second, third, fourth); + } + + @Nonnull + public static Quadro empty() { + return new Quadro<>(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java new file mode 100644 index 000000000..48c8dfcde --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java @@ -0,0 +1,123 @@ +package net.codingarea.commons.common.collection.pair; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; +import java.util.function.Function; + +/** + * @param The type of the first value + * @param The type of the second value + * @param The type of the third value + */ +public class Triple implements Pair { + + protected F first; + protected S second; + protected T third; + + public Triple() { + } + + public Triple(@Nullable F first, @Nullable S second, @Nullable T third) { + this.first = first; + this.second = second; + this.third = third; + } + + @Override + public final int amount() { + return 3; + } + + @Nonnull + @Override + public final Object[] values() { + return new Object[] { first, second, third }; + } + + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public T getThird() { + return third; + } + + public void setFirst(@Nullable F first) { + this.first = first; + } + + public void setSecond(@Nullable S second) { + this.second = second; + } + + public void setThird(@Nullable T third) { + this.third = third; + } + + @Nonnull + @CheckReturnValue + public Triple map(@Nonnull Function firstMapper, + @Nonnull Function secondMapper, + @Nonnull Function thirdMapper) { + return of(firstMapper.apply(first), secondMapper.apply(second), thirdMapper.apply(third)); + } + + public boolean noneNull() { + return first != null && second != null && third != null; + } + + public boolean allNull() { + return first == null && second == null && third == null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Triple triple = (Triple) o; + return Objects.equals(first, triple.first) && Objects.equals(second, triple.second) && Objects.equals(third, triple.third); + } + + @Override + public int hashCode() { + return Objects.hash(first, second, third); + } + + @Override + public String toString() { + return "Triple[" + first + ", " + second + ", " + third + "]"; + } + + @Nonnull + public static Triple ofFirst(@Nullable F first) { + return of(first, null, null); + } + + @Nonnull + public static Triple ofSecond(@Nullable S second) { + return of(null, second, null); + } + + @Nonnull + public static Triple ofThird(@Nullable T third) { + return of(null, null, third); + } + + @Nonnull + public static Triple of(@Nullable F first, @Nullable S second, @Nullable T third) { + return new Triple<>(first, second, third); + } + + @Nonnull + public static Triple empty() { + return new Triple<>(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java new file mode 100644 index 000000000..9d320ba6e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java @@ -0,0 +1,106 @@ +package net.codingarea.commons.common.collection.pair; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; +import java.util.function.Function; + +/** + * @param The type of the first value + * @param The type of the second value + */ +public class Tuple implements Pair { + + protected F first; + protected S second; + + public Tuple() { + } + + public Tuple(@Nullable F first, @Nullable S second) { + this.first = first; + this.second = second; + } + + @Override + public final int amount() { + return 2; + } + + @Nonnull + @Override + public final Object[] values() { + return new Object[] { first, second }; + } + + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public void setFirst(@Nullable F first) { + this.first = first; + } + + public void setSecond(@Nullable S second) { + this.second = second; + } + + @Nonnull + @CheckReturnValue + public Tuple map(@Nonnull Function firstMapper, + @Nonnull Function secondMapper) { + return of(firstMapper.apply(first), secondMapper.apply(second)); + } + + public boolean noneNull() { + return first != null && second != null; + } + + public boolean allNull() { + return first == null && second == null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Tuple tuple = (Tuple) o; + return Objects.equals(first, tuple.first) && Objects.equals(second, tuple.second); + } + + @Override + public int hashCode() { + return Objects.hash(first, second); + } + + @Override + public String toString() { + return "Tuple[" + first + ", " + second + "]"; + } + + @Nonnull + public static Tuple ofFirst(@Nullable F frist) { + return new Tuple<>(frist, null); + } + + @Nonnull + public static Tuple ofSecond(@Nullable S second) { + return new Tuple<>(null, second); + } + + @Nonnull + public static Tuple of(@Nullable F first, @Nullable S second) { + return new Tuple<>(first, second); + } + + @Nonnull + public static Tuple empty() { + return new Tuple<>(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java new file mode 100644 index 000000000..87bf70c77 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java @@ -0,0 +1,118 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.annotations.ReplaceWith; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.misc.SimpleCollectionUtils; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.function.Predicate; + +@Deprecated +@ReplaceWith("com.google.common.cache.LoadingCache") +public class CleanAndWriteDatabaseCache implements DatabaseCache { + + protected final Map> cache = new ConcurrentHashMap<>(); + protected final Predicate check; + protected final Function query; + protected final Function fallback; + protected final BiConsumer writer; + protected final long unusedTimeBeforeClean; + protected final long cleanAndWriteInterval; + protected final ILogger logger; + + public CleanAndWriteDatabaseCache(@Nullable ILogger logger, @Nonnegative long unusedTimeBeforeClean, @Nonnegative long cleanAndWriteInterval, @Nonnull String taskName, + @Nonnull Predicate check, @Nonnull Function fallback, + @Nonnull Function query, @Nonnull BiConsumer writer) { + this.logger = logger; + this.unusedTimeBeforeClean = unusedTimeBeforeClean; + this.cleanAndWriteInterval = cleanAndWriteInterval; + this.check = check; + this.query = query; + this.fallback = fallback; + this.writer = writer; + + EXECUTOR.scheduleAtFixedRate(this::writeCache, cleanAndWriteInterval, cleanAndWriteInterval, TimeUnit.MILLISECONDS); + Runtime.getRuntime().addShutdownHook(new Thread(this::writeCache)); + } + + public void writeCache() { + if (logger != null ) logger.debug("Writing & Cleaning cache"); + cleanAndWrite(cache, unusedTimeBeforeClean, logger, check, writer); + } + + @Nonnull + @Override + public V getData(@Nonnull K key) { + Tuple cached = cache.get(key); + if (cached != null) { + cached.setFirst(System.currentTimeMillis()); + return cached.getSecond(); + } + + try { + V data = query.apply(key); + if (logger != null ) logger.trace("Queried data {} for {}", data, key); + cache.put(key, new Tuple<>(System.currentTimeMillis(), data)); + return data; + } catch (Exception ex) { + if (logger != null ) logger.error("Could not get data for {}", key, ex); + return fallback.apply(key); + } + } + + @Override + public boolean contains(@Nonnull K key) { + return cache.containsKey(key); + } + + @Override + public int size() { + return cache.size(); + } + + @Override + public void clear() { + cache.clear(); + } + + public static void cleanAndWrite(@Nonnull Map> cache, @Nonnegative long unusedTimeBeforeClean, @Nullable ILogger logger, + @Nonnull Predicate check, @Nonnull BiConsumer writer) { + long now = System.currentTimeMillis(); + Collection remove = new ArrayList<>(); + cache.forEach((key, pair) -> { + try { + if (now - pair.getFirst() > unusedTimeBeforeClean) { + if (logger != null ) logger.trace("Removing {} from cache, last usage was {}s ago", key, (now - pair.getFirst()) / 1000); + remove.add(key); + } + + V value = pair.getSecond(); + if (!check.test(value)) return; + + if (logger != null ) logger.trace("Writing {}", value); + writer.accept(key, value); + } catch (Exception ex) { + if (logger != null ) logger.error("Unable to write cache for {}", key, ex); + } + }); + remove.forEach(cache::remove); + } + + @Nonnull + @Override + public Map values() { + return Collections.unmodifiableMap(SimpleCollectionUtils.convertMap(cache, k -> k, Tuple::getSecond)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java new file mode 100644 index 000000000..6cf0779c6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java @@ -0,0 +1,83 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.annotations.ReplaceWith; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.misc.SimpleCollectionUtils; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; + +@Deprecated +@ReplaceWith("com.google.common.cache.Cache") +public class CleanWriteableCache implements WriteableCache { + + protected final Map> cache = new ConcurrentHashMap<>(); + protected final ILogger logger; + protected final long cleanInterval; + protected final long unusedTimeBeforeClean; + + public CleanWriteableCache(@Nullable ILogger logger, @Nonnegative long unusedTimeBeforeClean, @Nonnegative long cleanInterval, @Nonnull String taskName) { + this.logger = logger; + this.cleanInterval = cleanInterval; + this.unusedTimeBeforeClean = unusedTimeBeforeClean; + + EXECUTOR.scheduleAtFixedRate(this::cleanCache, cleanInterval, cleanInterval, TimeUnit.MILLISECONDS); + } + + public void cleanCache() { + if (logger != null ) logger.debug("Cleaning cache"); + long now = System.currentTimeMillis(); + Collection remove = new ArrayList<>(); + cache.forEach((key, pair) -> { + if (now - pair.getFirst() > unusedTimeBeforeClean) { + if (logger != null ) logger.trace("Removing {} from cache, last usage was {}s ago", key, (now - pair.getFirst()) / 1000); + remove.add(key); + } + }); + remove.forEach(cache::remove); + } + + @Nullable + @Override + public V getData(@Nonnull K key) { + Tuple pair = cache.get(key); + if (pair == null) return null; + pair.setFirst(System.currentTimeMillis()); + return pair.getSecond(); + } + + @Override + public void setData(@Nonnull K key, @Nullable V value) { + cache.put(key, new Tuple<>(System.currentTimeMillis(), value)); + } + + @Override + public boolean contains(@Nonnull K key) { + return cache.containsKey(key); + } + + @Override + public int size() { + return cache.size(); + } + + @Override + public void clear() { + cache.clear(); + } + + @Nonnull + @Override + public Map values() { + return Collections.unmodifiableMap(SimpleCollectionUtils.convertMap(cache, k -> k, Tuple::getSecond)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java new file mode 100644 index 000000000..1279ae1f5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java @@ -0,0 +1,83 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.collection.RunnableTimerTask; +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.Timer; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.ToLongFunction; + +public class CoolDownCache { + + protected final Map cache = new ConcurrentHashMap<>(); + protected final ILogger logger; + protected final ToLongFunction cooldownTime; + protected final long cleanInterval; + + public CoolDownCache(@Nonnull ILogger logger, @Nonnegative long cleanInterval, @Nonnull String taskName, @Nonnull ToLongFunction cooldownTime) { + this.logger = logger; + this.cooldownTime = cooldownTime; + this.cleanInterval = cleanInterval; + + new Timer(taskName).schedule(new RunnableTimerTask(this::cleanCache), cleanInterval, cleanInterval); + } + + public void cleanCache() { + logger.debug("Cleaning cooldown cache"); + + long now = System.currentTimeMillis(); + Collection remove = new ArrayList<>(); + cache.forEach((key, time) -> { + if (time == null || !isOnCoolDown(now, time, key)) { + logger.trace("Removing {} from cooldown cache", key); + remove.add(key); + } + }); + remove.forEach(cache::remove); + } + + public boolean isOnCoolDown(long now, long suspect, @Nonnull K key) { + long difference = now - suspect; + return difference < getCoolDownTime(key); + } + + public boolean isOnCoolDown(@Nonnull K key) { + Long time = cache.get(key); + if (time == null) return false; + return isOnCoolDown(System.currentTimeMillis(), time, key); + } + + public boolean checkCoolDown(@Nonnull K key) { + boolean cooldown = isOnCoolDown(key); + if (!cooldown) setOnCoolDown(key); + return cooldown; + } + + public void setOnCoolDown(@Nonnull K key) { + cache.put(key, System.currentTimeMillis()); + } + + public long getCoolDown(@Nonnull K key) { + Long time = cache.get(key); + if (time == null) return 0; + return System.currentTimeMillis() - time; + } + + public float getCoolDownSeconds(@Nonnull K key) { + return getCoolDown(key) / 1000f; + } + + public long getCoolDownTime(@Nonnull K key) { + return cooldownTime.applyAsLong(key); + } + + public int size() { + return cache.size(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java new file mode 100644 index 000000000..5afc4e461 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java @@ -0,0 +1,19 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.annotations.ReplaceWith; + +import javax.annotation.Nonnull; + +/** + * @deprecated Use {@link com.google.common.cache.LoadingCache} instead + * + * @see com.google.common.cache.LoadingCache + */ +@Deprecated +@ReplaceWith("com.google.common.cache.LoadingCache") +public interface DatabaseCache extends ICache { + + @Nonnull + V getData(@Nonnull K key); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java new file mode 100644 index 000000000..4a6b49f7f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java @@ -0,0 +1,40 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.annotations.ReplaceWith; +import net.codingarea.commons.common.collection.NamedThreadFactory; + +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.function.BiConsumer; + +/** + * @deprecated Use {@link com.google.common.cache.Cache} instead + * + * @see com.google.common.cache.Cache + */ +@Deprecated +@ReplaceWith("com.google.common.cache.Cache") +public interface ICache { + + ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(2, new NamedThreadFactory(threadId -> String.format("CacheTask-%s", threadId))); + + boolean contains(@Nonnull K key); + + int size(); + + default boolean isEmpty() { + return size() == 0; + } + + void clear(); + + @Nonnull + Map values(); + + default void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java new file mode 100644 index 000000000..a2c887e25 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.common.concurrent.cache; + +import net.codingarea.commons.common.annotations.ReplaceWith; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +@Deprecated +@ReplaceWith("com.google.common.cache.Cache") +public interface WriteableCache extends ICache { + + @Nullable + V getData(@Nonnull K key); + + void setData(@Nonnull K key, @Nullable V value); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java new file mode 100644 index 000000000..37b71703f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java @@ -0,0 +1,169 @@ +package net.codingarea.commons.common.concurrent.task; + +import net.codingarea.commons.common.collection.NamedThreadFactory; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.concurrent.*; +import java.util.function.Function; + +public class CompletableTask implements Task { + + static final ExecutorService SERVICE = Executors.newCachedThreadPool(new NamedThreadFactory("TaskProcessor")); + + private final Collection> listeners = new ArrayList<>(); + private final CompletableFuture future; + + private Throwable failure; + + public CompletableTask() { + this(new CompletableFuture<>()); + } + + private CompletableTask(@Nonnull CompletableFuture future) { + this.future = future; + this.future.exceptionally(ex -> { + this.failure = ex; + return null; + }); + } + + @Nonnull + public static Task callAsync(@Nonnull Callable callable) { + CompletableTask task = new CompletableTask<>(); + SERVICE.execute(() -> { + try { + task.complete(callable.call()); + } catch (Throwable ex) { + task.fail(ex); + } + }); + return task; + } + + @Nonnull + public static Task callSync(@Nonnull Callable callable) { + CompletableTask task = new CompletableTask<>(); + try { + task.complete(callable.call()); + } catch (Throwable ex) { + task.fail(ex); + } + return task; + } + + @Nonnull + @Override + public Task addListener(@Nonnull TaskListener listener) { + if (future.isDone()) { + V value = future.getNow(null); + if (future.isCancelled() || value != null) { + listener.onCancelled(this); + } else if (failure != null) { + listener.onFailure(this, failure); + } else { + listener.onComplete(this, value); + } + return this; + } + + listeners.add(listener); + return this; + } + + @Nonnull + @Override + public Task clearListeners() { + this.listeners.clear(); + return this; + } + + public void fail(Throwable throwable) { + this.failure = throwable; + this.future.completeExceptionally(throwable); + for (TaskListener listener : this.listeners) { + listener.onFailure(this, throwable); + } + } + + @Override + public V call() { + if (this.future.isDone()) { + return this.future.getNow(null); + } + throw new UnsupportedOperationException("Use #complete in the CompletableTask"); + } + + public void complete(@Nullable V value) { + future.complete(value); + if (value != null) { + for (TaskListener listener : listeners) { + listener.onComplete(this, value); + } + } else { + for (TaskListener listener : listeners) { + listener.onCancelled(this); + } + } + + } + + @Override + public boolean cancel(boolean b) { + if (this.future.isCancelled()) { + return false; + } + + if (this.future.cancel(b)) { + for (TaskListener listener : this.listeners) { + listener.onCancelled(this); + } + return true; + } + return false; + } + + @Override + public boolean isCancelled() { + return this.future.isCancelled(); + } + + @Override + public boolean isDone() { + return this.future.isDone(); + } + + @Override + public V get() throws InterruptedException, ExecutionException { + return future.get(); + } + + @Override + public V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return future.get(timeout, unit); + } + + @Nonnull + @Override + public Task map(@Nullable Function mapper) { + CompletableTask task = new CompletableTask<>(); + this.future.thenAccept(v -> { + try { + task.complete(mapper == null ? null : mapper.apply(v)); + } catch (Throwable ex) { + task.fail(ex); + } + }); + this.onFailure(task.future::completeExceptionally); + this.onCancelled(otherTask -> task.cancel(true)); + return task; + } + + @Nonnull + @Override + public CompletionStage stage() { + return future; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java new file mode 100644 index 000000000..aed5684ba --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java @@ -0,0 +1,108 @@ +package net.codingarea.commons.common.concurrent.task; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.concurrent.*; +import java.util.function.Function; + +public class CompletedTask implements Task { + + private final V value; + private final Throwable failure; + + private CompletableFuture future; + + public CompletedTask(@Nullable V value) { + this.value = value; + this.failure = null; + } + + public CompletedTask(@Nullable Throwable failure) { + this.value = null; + this.failure = failure; + } + + @Nonnull + @Override + public Task addListener(@Nonnull TaskListener listener) { + if (failure != null) { + listener.onFailure(this, failure); + } else if (value != null) { + listener.onComplete(this, value); + } else { + listener.onCancelled(this); + } + + return this; + } + + @Nonnull + @Override + public Task clearListeners() { + return this; + } + + @Nonnull + @Override + public Task map(@Nullable Function mapper) { + if (failure != null) + return new CompletedTask<>(failure); + + return new CompletedTask<>(value == null || mapper == null ? null : mapper.apply(value)); + } + + @Override + public V getOrDefault(long timeout, @Nonnull TimeUnit unit, V def) { + if (value != null) + return value; + + return def; + } + + @Override + public V call() throws Exception { + return value; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public boolean isDone() { + return true; + } + + @Override + public V get() throws InterruptedException, ExecutionException { + return value; + } + + @Override + public V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return value; + } + + @Nonnull + @Override + public CompletionStage stage() { + if (future == null) { + future = new CompletableFuture<>(); + + if (failure != null) { + future.completeExceptionally(failure); + } else { + future.complete(value); + } + } + + return future; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java new file mode 100644 index 000000000..8b43122ec --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java @@ -0,0 +1,228 @@ +package net.codingarea.commons.common.concurrent.task; + +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.function.ExceptionallyFunction; +import net.codingarea.commons.common.function.ExceptionallyRunnable; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.concurrent.*; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * A task that may complete (done / failed / cancelled) in the future or may already be done. + * + * For the completion can be listened by calling {@link #onComplete(Consumer)}, for the cancellation by {@link #onCancelled(Runnable)} and for failure by {@link #onFailure(Consumer)}. + * + * @see #asyncCall(Callable) + * @see #completed(Object) + */ +public interface Task extends Future, Callable { + + @Nonnull + static ExecutorService getAsyncExecutor() { + return CompletableTask.SERVICE; + } + + @Nonnull + static Task empty() { + return completed(null); + } + + @Nonnull + static Task completed(@Nullable V value) { + return new CompletedTask<>(value); + } + + @Nonnull + static Task completedVoid() { + return empty(); + } + + @Nonnull + static Task failed(@Nonnull Throwable failure) { + return new CompletedTask<>(failure); + } + + @Nonnull + static CompletableTask completable() { + return new CompletableTask<>(); + } + + @Nonnull + static Task asyncCall(@Nonnull Callable callable) { + return CompletableTask.callAsync(callable); + } + + @Nonnull + static Task asyncSupply(@Nonnull Supplier supplier) { + return asyncCall(supplier::get); + } + + @Nonnull + static Task asyncRun(@Nonnull Runnable runnable) { + return asyncCall(() -> { runnable.run(); return null; }); + } + + @Nonnull + static Task asyncRunExceptionally(@Nonnull ExceptionallyRunnable runnable) { + return asyncRun(runnable); + } + + @Nonnull + static Task syncCall(@Nonnull Callable callable) { + return CompletableTask.callSync(callable); + } + + @Nonnull + static Task syncSupply(@Nonnull Supplier supplier) { + return syncCall(supplier::get); + } + + @Nonnull + static Task syncRun(@Nonnull Runnable runnable) { + return syncCall(() -> { runnable.run(); return null; }); + } + + @Nonnull + static Task syncRunExceptionally(@Nonnull ExceptionallyRunnable runnable) { + return syncRun(runnable); + } + + @Nonnull + default Task onComplete(@Nonnull Runnable action) { + return onComplete(v -> action.run()); + } + + @Nonnull + default Task onComplete(@Nonnull Consumer action) { + return onComplete((task, value) -> action.accept(value)); + } + + @Nonnull + default Task onComplete(@Nonnull BiConsumer, ? super V> action) { + return addListener(new TaskListener() { + @Override + public void onComplete(@Nonnull Task task, @Nonnull V value) { + action.accept(task, value); + } + }); + } + + @Nonnull + default Task onFailure(@Nonnull Runnable action) { + return onFailure(ex -> action.run()); + } + + @Nonnull + default Task onFailure(@Nonnull Consumer action) { + return onFailure((task, ex) -> action.accept(ex)); + } + + @Nonnull + default Task onFailure(@Nonnull BiConsumer, ? super Throwable> action) { + return addListener(new TaskListener() { + @Override + public void onFailure(@Nonnull Task task, @Nonnull Throwable ex) { + action.accept(task, ex); + } + }); + } + + @Nonnull + default Task throwOnFailure() { + return onFailure(ex -> ex.printStackTrace()); + } + + @Nonnull + default Task onCancelled(@Nonnull Runnable action) { + return onCancelled(task -> action.run()); + } + + @Nonnull + default Task onCancelled(@Nonnull Consumer> action) { + return addListener(new TaskListener() { + @Override + public void onCancelled(@Nonnull Task task) { + action.accept(task); + } + }); + } + + @Nonnull + default Task addListeners(@Nonnull TaskListener... listeners) { + for (TaskListener listener : listeners) + addListener(listener); + + return this; + } + + @Nonnull + Task addListener(@Nonnull TaskListener listener); + + @Nonnull + Task clearListeners(); + + @Override + V get() throws InterruptedException, ExecutionException; + + @Override + V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; + + default V getOrDefault(V def) { + try { + return get(); + } catch (InterruptedException ex) { + throw new WrappedException(ex); + } catch (ExecutionException ex) { + return def; + } + } + + default V getOrDefault(long timeout, @Nonnull TimeUnit unit, V def) { + try { + return this.get(timeout, unit); + } catch (InterruptedException ex) { + throw new WrappedException(ex); + } catch (ExecutionException | TimeoutException ex) { + return def; + } + } + + default V getBeforeTimeout(long timeout, @Nonnull TimeUnit unit) { + try { + return get(timeout, unit); + } catch (ExecutionException | InterruptedException ex) { + throw new WrappedException(ex); + } catch (TimeoutException ex) { + throw new IllegalStateException("Operation timed out (" + timeout + " " + unit + ")"); + } + } + + @Nonnull + Task map(@Nullable Function mapper); + + @Nonnull + default Task mapExceptionally(@Nullable ExceptionallyFunction mapper) { + return map(mapper); + } + + @Nonnull + default Task mapVoid() { + return map(v -> null); + } + + @Nonnull + default Task map(@Nonnull Class target) { + return map(target::cast); + } + + @Nonnull + @CheckReturnValue + CompletionStage stage(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java new file mode 100644 index 000000000..f800ae95a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java @@ -0,0 +1,16 @@ +package net.codingarea.commons.common.concurrent.task; + +import javax.annotation.Nonnull; + +public interface TaskListener { + + default void onComplete(@Nonnull Task task, @Nonnull T value) { + } + + default void onCancelled(@Nonnull Task task) { + } + + default void onFailure(@Nonnull Task task, @Nonnull Throwable ex) { + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Config.java b/plugin/src/main/java/net/codingarea/commons/common/config/Config.java new file mode 100644 index 000000000..54462d54a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Config.java @@ -0,0 +1,97 @@ +package net.codingarea.commons.common.config; + +import net.codingarea.commons.common.config.exceptions.ConfigReadOnlyException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.function.Consumer; + +/** + * @see Document + */ +public interface Config extends Propertyable { + + /** + * Sets the value at the given path. + * + * Setting a value to {@code null} has the same effect as {@link #remove(String) removing} it. + * {@code config.set(path, null)} is equivalent with {@code config.remove(path)} + * + * @param value The value to change to, {@code null} to remove + * @return {@code this} for chaining + * + * @throws ConfigReadOnlyException + * If this is {@link #isReadonly() readonly} + */ + @Nonnull + Config set(@Nonnull String path, @Nullable Object value); + + /** + * @throws ConfigReadOnlyException + * If this is {@link #isReadonly() readonly} + */ + @Nonnull + Config clear(); + + /** + * Removing a value has the same effect as {@link #set(String, Object) setting} it to {@code null} + * {@code config.set(path, null)} is equivalent with {@code config.remove(path)} + * + * @return {@code this} for chaining + * + * @throws ConfigReadOnlyException + * If this is {@link #isReadonly() readonly} + */ + @Nonnull + Config remove(@Nonnull String path); + + boolean isReadonly(); + + /** + * @return A new config which is readonly, or {@code this} if already {@link #isReadonly() readonly} + */ + @Nonnull + @CheckReturnValue + Config readonly(); + + @Nonnull + @Override + default Config apply(@Nonnull Consumer action) { + return (Config) Propertyable.super.apply(action); + } + + @Nonnull + @Override + default Config applyIf(boolean expression, @Nonnull Consumer action) { + return (Config) Propertyable.super.applyIf(expression, action); + } + + @Nonnull + default Config increment(@Nonnull String path, double amount) { + return set(path, getDouble(path) + amount); + } + + @Nonnull + default Config decrement(@Nonnull String path, double amount) { + return set(path, getDouble(path) - amount); + } + + @Nonnull + default Config multiply(@Nonnull String path, double factor) { + return set(path, getDouble(path) * factor); + } + + @Nonnull + default Config divide(@Nonnull String path, double divisor) { + return set(path, getDouble(path) / divisor); + } + + @Nonnull + default Config setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { + if (!contains(path)) + set(path, defaultValue); + return this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Document.java b/plugin/src/main/java/net/codingarea/commons/common/config/Document.java new file mode 100644 index 000000000..17c4a0b4a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Document.java @@ -0,0 +1,345 @@ +package net.codingarea.commons.common.config; + +import com.google.gson.JsonArray; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.config.document.EmptyDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.PropertiesDocument; +import net.codingarea.commons.common.misc.FileUtils; +import net.codingarea.commons.common.misc.GsonUtils; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.*; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; + +public interface Document extends Config, Json { + + /** + * Gets the document located at the given path. + * If there is no document assigned to this path, + * a new document is being created and assigned to this path. + * + * @return the document assigned to this path + */ + @Nonnull + Document getDocument(@Nonnull String path); + + /** + * Returns the list of documents located at the given path. + * The returned list will not contain any null elements. + * If there are no documents, the list will be empty. + * Elements which are no documents in the original list will be skipped. + * If an element is {@code null} an empty document will be added + * if this document is not {@link #isReadonly() readonly}. + * + * @return the list of documents assigned to this path + */ + @Nonnull + List getDocumentList(@Nonnull String path); + + @Nonnull + default List getInstanceList(@Nonnull String path, @Nonnull Class classOfT) { + List documents = getDocumentList(path); + List result = new ArrayList<>(documents.size()); + for (Document document : documents) { + result.add(document.toInstanceOf(classOfT)); + } + return result; + } + + @Nonnull + List getSerializableList(@Nonnull String path, @Nonnull Class classOfT); + + @Nullable + T getSerializable(@Nonnull String path, @Nonnull Class classOfT); + + @Nonnull + T getSerializable(@Nonnull String path, @Nonnull T def); + + @Nonnull + Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper); + + @Nonnull + R mapDocument(@Nonnull String path, @Nonnull Function mapper); + + @Nullable + R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper); + + @Nullable + T toInstanceOf(@Nonnull Class classOfT); + + /** + * Returns the parent document of this document. + * If {@code this} is the {@link #getRoot() root} this method will return {@code null}. + * + * @return the parent document of this document + */ + @Nullable + Document getParent(); + + /** + * Returns the root document of this document. + * If the {@link #getParent() parent} is {@code null} this will return {@code this}. + * + * @return the root document of this document + */ + @Nonnull + Document getRoot(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + Document set(@Nonnull String path, @Nullable Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + Document clear(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + Document remove(@Nonnull String path); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + default Document apply(@Nonnull Consumer action) { + return (Document) Config.super.apply(action); + } + + @Nonnull + @Override + default Document applyIf(boolean expression, @Nonnull Consumer action) { + return (Document) Config.super.applyIf(expression, action); + } + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + default Document setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { + return (Document) Config.super.setIfAbsent(path, defaultValue); + } + + @Nonnull + Document set(@Nonnull Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + @CheckReturnValue + Document readonly(); + + @Nonnull + Map children(); + + boolean isDocument(@Nonnull String path); + + boolean hasChildren(@Nonnull String path); + + void write(@Nonnull Writer writer) throws IOException; + + default void saveToFile(@Nonnull File file) throws IOException { + FileUtils.createFilesIfNecessary(file); + Writer writer = FileUtils.newBufferedWriter(file); + write(writer); + writer.flush(); + writer.close(); + } + + default void saveToFile(@Nonnull Path file) throws IOException { + FileUtils.createFile(file); + Writer writer = FileUtils.newBufferedWriter(file); + write(writer); + writer.flush(); + writer.close(); + } + + @Nonnull + @CheckReturnValue + default FileDocument asFileDocument(@Nonnull File file) { + return (this instanceof FileDocument && ((FileDocument)this).getFile().equals(file)) + ? (FileDocument) this : FileDocument.wrap(this, file); + } + + @Nonnull + @CheckReturnValue + default FileDocument asFileDocument(@Nonnull Path file) { + return asFileDocument(file.toFile()); + } + + @Nonnull + @CheckReturnValue + default Document copyJson() { + Document document = create(); + this.forEach(document::set); + return document; + } + + /** + * @return an empty and immutable document + * + * @see EmptyDocument + */ + @Nonnull + @CheckReturnValue + static Document empty() { + return EmptyDocument.ROOT; + } + + @Nonnull + @CheckReturnValue + static Document readFile(@Nonnull Class classOfDocument, @Nonnull File file) { + try { + if (file.exists()) { + Constructor constructor = classOfDocument.getConstructor(File.class); + return constructor.newInstance(file); + } else { + Constructor constructor = classOfDocument.getConstructor(); + return constructor.newInstance(); + } + } catch (NoSuchMethodException | InstantiationException | IllegalAccessException ex) { + throw new UnsupportedOperationException(classOfDocument.getName() + " does not support File creation"); + } catch (InvocationTargetException ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + static Document readFile(@Nonnull Class classOfDocument, @Nonnull Path file) { + return readFile(classOfDocument, file.toFile()); + } + + /** + * @return a json document parsed by the input + * + * @see GsonDocument + */ + @Nonnull + @CheckReturnValue + static Document parseJson(@Nonnull String jsonInput) { + return new GsonDocument(jsonInput); + } + + @Nonnull + @CheckReturnValue + static Document parseJson(@Nonnull Reader reader) throws IOException { + return new GsonDocument(reader); + } + + @Nonnull + @CheckReturnValue + static Document parseJson(@Nonnull InputStream input) throws IOException { + return new GsonDocument(new InputStreamReader(input, StandardCharsets.UTF_8)); + } + + @Nonnull + @CheckReturnValue + static List parseJsonArray(@Nonnull String jsonInput) { + return GsonDocument.convertArrayToDocuments(GsonDocument.GSON.fromJson(jsonInput, JsonArray.class)); + } + + @Nonnull + @CheckReturnValue + static List parseStringArray(@Nonnull String jsonInput) { + return GsonDocument.convertArrayToStrings(GsonDocument.GSON.fromJson(jsonInput, JsonArray.class)); + } + + static void saveArray(@Nonnull Iterable objects, @Nonnull Path file) throws IOException { + FileUtils.createFile(file); + Writer writer = FileUtils.newBufferedWriter(file); + JsonArray array = GsonUtils.convertIterableToJsonArray(GsonDocument.GSON, objects); + (GsonDocument.isWritePrettyJson() ? GsonDocument.GSON_PRETTY_PRINT : GsonDocument.GSON).toJson(array, writer); + writer.flush(); + writer.close(); + } + + @Nonnull + @CheckReturnValue + static Document readJsonFile(@Nonnull File file) { + return readFile(GsonDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static Document readJsonFile(@Nonnull Path file) { + return readJsonFile(file.toFile()); + } + + @Nonnull + @CheckReturnValue + static List readJsonArrayFile(@Nonnull Path file) { + try { + JsonArray array = GsonDocument.GSON.fromJson(FileUtils.newBufferedReader(file), JsonArray.class); + if (array == null) return new ArrayList<>(); + List documents = new ArrayList<>(array.size()); + array.forEach(element -> documents.add(new GsonDocument(element.getAsJsonObject()))); + return documents; + } catch (IOException ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + static Document readPropertiesFile(@Nonnull File file) { + return readFile(PropertiesDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static Document readPropertiesFile(@Nonnull Path file) { + return readPropertiesFile(file.toFile()); + } + + @Nonnull + @CheckReturnValue + static Document create() { + return new GsonDocument(); + } + + @Nonnull + @CheckReturnValue + static Document of(@Nonnull Object object) { + return new GsonDocument(object); + } + + @Nullable + @CheckReturnValue + static Document ofNullable(@Nullable Object object) { + return object == null ? null : of(object); + } + + @Nonnull + @CheckReturnValue + static List arrayOf(@Nonnull Collection objects) { + List documents = new ArrayList<>(objects.size()); + objects.forEach(object -> documents.add(Document.of(object))); + return documents; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java new file mode 100644 index 000000000..b6d73f26b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java @@ -0,0 +1,172 @@ +package net.codingarea.commons.common.config; + +import net.codingarea.commons.common.concurrent.task.Task; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.PropertiesDocument; +import net.codingarea.commons.common.config.document.wrapper.FileDocumentWrapper; +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.util.function.Consumer; + +public interface FileDocument extends Document { + + /** + * Logger used to log errors which are caught in the safe version of an exceptionally method + */ + ILogger LOGGER = ILogger.forThisClass(); + + default void saveExceptionally() throws IOException { + saveToFile(getFile()); + } + + /** + * Executes {@link #saveExceptionally()} and prints all caught errors to {@link #LOGGER} + * + * @see #saveExceptionally() + */ + default void save() { + try { + saveExceptionally(); + } catch (IOException ex) { + LOGGER.error("Could not save config to file \"{}\"", getFile(), ex); + } + } + + @Nonnull + default Task saveAsync() { + return Task.asyncRunExceptionally(this::save); + } + + /** + * @param async whether this should be saved asynchronously or synchronously + * + * @see #save() + * @see #saveAsync() + */ + default void save(boolean async) { + if (async) saveAsync(); + else save(); + } + + @Nonnull + File getFile(); + + @Nonnull + Path getPath(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument set(@Nonnull String path, @Nullable Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument set(@Nonnull Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument clear(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument remove(@Nonnull String path); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + default FileDocument apply(@Nonnull Consumer action) { + return (FileDocument) Document.super.apply(action); + } + + @Nonnull + @Override + default FileDocument setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { + return (FileDocument) Document.super.setIfAbsent(path, defaultValue); + } + + @Nonnull + @Override + default FileDocument increment(@Nonnull String path, double amount) { + return (FileDocument) Document.super.increment(path, amount); + } + + @Nonnull + @Override + default FileDocument decrement(@Nonnull String path, double amount) { + return (FileDocument) Document.super.decrement(path, amount); + } + + @Nonnull + @Override + default FileDocument multiply(@Nonnull String path, double factor) { + return (FileDocument) Document.super.multiply(path, factor); + } + + @Nonnull + @Override + default FileDocument divide(@Nonnull String path, double divisor) { + return (FileDocument) Document.super.divide(path, divisor); + } + + @Nonnull + @CheckReturnValue + static FileDocument wrap(@Nonnull Document document, @Nonnull File file) { + return new FileDocumentWrapper(file, document); + } + + @Nonnull + @CheckReturnValue + static FileDocument readFile(@Nonnull Class classOfDocument, @Nonnull File file) { + return Document.readFile(classOfDocument, file).asFileDocument(file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readFile(@Nonnull Class classOfDocument, @Nonnull Path file) { + return Document.readFile(classOfDocument, file).asFileDocument(file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readJsonFile(@Nonnull File file) { + return readFile(GsonDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readJsonFile(@Nonnull Path file) { + return readFile(GsonDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readPropertiesFile(@Nonnull File file) { + return readFile(PropertiesDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readPropertiesFile(@Nonnull Path file) { + return readFile(PropertiesDocument.class, file); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Json.java b/plugin/src/main/java/net/codingarea/commons/common/config/Json.java new file mode 100644 index 000000000..efcfb495c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Json.java @@ -0,0 +1,48 @@ +package net.codingarea.commons.common.config; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.util.function.Supplier; + +/** + * @see Document + */ +public interface Json { + + @Nonnull + String toJson(); + + @Nonnull + String toPrettyJson(); + + @Nonnull + @CheckReturnValue + static Json empty() { + return constant("{}", "{}"); + } + + @Nonnull + @CheckReturnValue + static Json supply(@Nonnull Supplier normal, @Nonnull Supplier pretty) { + return new Json() { + @Nonnull + @Override + public String toJson() { + return normal.get(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return pretty.get(); + } + }; + } + + @Nonnull + @CheckReturnValue + static Json constant(@Nonnull String json, @Nonnull String prettyJson) { + return supply(() -> json, () -> prettyJson); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java b/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java new file mode 100644 index 000000000..bab183bc2 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java @@ -0,0 +1,49 @@ +package net.codingarea.commons.common.config; + +import javax.annotation.Nullable; +import java.awt.*; +import java.lang.reflect.Type; +import java.text.DateFormat; +import java.time.OffsetDateTime; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; + +public final class PropertyHelper { + + private PropertyHelper() {} + + private static final Map> getters = new HashMap<>(); + + static { + getters.put(Character.class, Propertyable::getChar); + getters.put(Boolean.class, Propertyable::getBoolean); + getters.put(Byte.class, Propertyable::getByte); + getters.put(Short.class, Propertyable::getShort); + getters.put(Integer.class, Propertyable::getInt); + getters.put(Long.class, Propertyable::getLong); + getters.put(Float.class, Propertyable::getFloat); + getters.put(Double.class, Propertyable::getDouble); + getters.put(String.class, Propertyable::getString); + getters.put(CharSequence.class, Propertyable::getString); + getters.put(List.class, Propertyable::getStringList); + getters.put(Document.class, (BiFunction) Document::getDocument); + getters.put(String[].class, Propertyable::getStringArray); + getters.put(Date.class, Propertyable::getDate); + getters.put(OffsetDateTime.class, Propertyable::getDateTime); + getters.put(Color.class, Propertyable::getColor); + getters.put(byte[].class, Propertyable::getBinary); + } + + @Nullable + public static Date parseDate(@Nullable String string) { + try { + return DateFormat.getDateTimeInstance().parse(string); + } catch (Exception ex) { + return null; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java b/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java new file mode 100644 index 000000000..1149b7be1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java @@ -0,0 +1,199 @@ +package net.codingarea.commons.common.config; + +import net.codingarea.commons.common.version.Version; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; + +/** + * @see Document + * @see Config + */ +public interface Propertyable { + + T getInstance(@Nonnull String path, @Nonnull Class classOfT); + + @Nullable + Object getObject(@Nonnull String path); + + @Nonnull + Object getObject(@Nonnull String path, @Nonnull Object def); + + @Nonnull + @SuppressWarnings("unchecked") + default Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { + return Optional.ofNullable(extractor.apply((O) this, key)); + } + + @Nonnull + @SuppressWarnings("unchecked") + default Propertyable apply(@Nonnull Consumer action) { + action.accept((O) this); + return this; + } + + @Nonnull + default Propertyable applyIf(boolean expression, @Nonnull Consumer action) { + if (expression) + apply(action); + return this; + } + + @Nullable + String getString(@Nonnull String path); + + @Nonnull + String getString(@Nonnull String path, @Nonnull String def); + + @Nullable + byte[] getBinary(@Nonnull String path); + + char getChar(@Nonnull String path); + + char getChar(@Nonnull String path, char def); + + long getLong(@Nonnull String path); + + long getLong(@Nonnull String path, long def); + + int getInt(@Nonnull String path); + + int getInt(@Nonnull String path, int def); + + short getShort(@Nonnull String path); + + short getShort(@Nonnull String path, short def); + + byte getByte(@Nonnull String path); + + byte getByte(@Nonnull String path, byte def); + + float getFloat(@Nonnull String path); + + float getFloat(@Nonnull String path, float def); + + double getDouble(@Nonnull String path); + + double getDouble(@Nonnull String path, double def); + + boolean getBoolean(@Nonnull String path); + + boolean getBoolean(@Nonnull String path, boolean def); + + @Nonnull + List getStringList(@Nonnull String path); + + @Nonnull + String[] getStringArray(@Nonnull String path); + + @Nonnull + > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum); + + @Nonnull + List getUUIDList(@Nonnull String path); + + @Nonnull + List getCharacterList(@Nonnull String path); + + @Nonnull + List getByteList(@Nonnull String path); + + @Nonnull + List getShortList(@Nonnull String path); + + @Nonnull + List getIntegerList(@Nonnull String path); + + @Nonnull + List getLongList(@Nonnull String path); + + @Nonnull + List getFloatList(@Nonnull String path); + + @Nonnull + List getDoubleList(@Nonnull String path); + + @Nullable + UUID getUUID(@Nonnull String path); + + @Nonnull + UUID getUUID(@Nonnull String path, @Nonnull UUID def); + + @Nullable + OffsetDateTime getDateTime(@Nonnull String path); + + @Nonnull + OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def); + + @Nullable + Date getDate(@Nonnull String path); + + @Nonnull + Date getDate(@Nonnull String path, @Nonnull Date def); + + @Nullable + Color getColor(@Nonnull String path); + + @Nonnull + Color getColor(@Nonnull String path, @Nonnull Color def); + + @Nullable + > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum); + + @Nonnull + > E getEnum(@Nonnull String path, @Nonnull E def); + + @Nullable + Class getClass(@Nonnull String path); + + @Nonnull + Class getClass(@Nonnull String path, @Nonnull Class def); + + @Nullable + Version getVersion(@Nonnull String path); + + @Nonnull + Version getVersion(@Nonnull String path, @Nonnull Version def); + + boolean isList(@Nonnull String path); + + boolean isObject(@Nonnull String path); + + boolean contains(@Nonnull String path); + + boolean isEmpty(); + + @Nonnegative + int size(); + + @Nonnull + Map values(); + + @Nonnull + Map valuesAsStrings(); + + @Nonnull + Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper); + + @Nonnull + List mapList(@Nonnull String path, @Nonnull Function mapper); + + @Nonnull + Collection keys(); + + @Nonnull + Set> entrySet(); + + void forEach(@Nonnull BiConsumer action); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java new file mode 100644 index 000000000..cce0be2e8 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java @@ -0,0 +1,278 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.config.Config; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.misc.ReflectionUtils; +import net.codingarea.commons.common.version.Version; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.Function; +import java.util.function.Supplier; + +public abstract class AbstractConfig implements Config { + + protected static final ILogger logger = ILogger.forThisClass(); + + @Nonnull + protected T getDef(@Nonnull T def, @Nonnull Supplier getter) { + T value = getter.get(); + return value == null ? def : value; + } + + @Nonnull + @Override + public Object getObject(@Nonnull String path, @Nonnull Object def) { + Object value = getObject(path); + return value == null ? def : value; + } + + @Nonnull + @Override + public String getString(@Nonnull String path, @Nonnull String def) { + return getDef(def, () -> getString(path)); + } + + @Override + public char getChar(@Nonnull String path) { + return getChar(path, (char) 0); + } + + @Override + public char getChar(@Nonnull String path, char def) { + try { + return getString(path).charAt(0); + } catch (NullPointerException | IndexOutOfBoundsException ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path) { + return getDouble(path, 0); + } + + @Override + public float getFloat(@Nonnull String path) { + return getFloat(path, 0); + } + + @Override + public long getLong(@Nonnull String path) { + return getLong(path, 0); + } + + @Override + public int getInt(@Nonnull String path) { + return getInt(path, 0); + } + + @Override + public short getShort(@Nonnull String path) { + return getShort(path, (short) 0); + } + + @Override + public byte getByte(@Nonnull String path) { + return getByte(path, (byte) 0); + } + + @Override + public boolean getBoolean(@Nonnull String path) { + return getBoolean(path, false); + } + + @Nonnull + @Override + public UUID getUUID(@Nonnull String path, @Nonnull UUID def) { + return getDef(def, () -> getUUID(path)); + } + + @Nonnull + @Override + public OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { + return getDef(def, () -> getDateTime(path)); + } + + @Nonnull + @Override + public Date getDate(@Nonnull String path, @Nonnull Date def) { + return getDef(def, () -> getDate(path)); + } + + @Nonnull + @Override + public Color getColor(@Nonnull String path, @Nonnull Color def) { + return getDef(def, () -> getColor(path)); + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return ReflectionUtils.getEnumOrNull(getString(path), classOfEnum); + } + + @Nonnull + @Override + public > E getEnum(@Nonnull String path, @Nonnull E def) { + E value = getEnum(path, def.getDeclaringClass()); + return value == null ? def : value; + } + + @Nullable + @Override + public Class getClass(@Nonnull String path) { + try { + return Class.forName(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nonnull + @Override + public Class getClass(@Nonnull String path, @Nonnull Class def) { + return getDef(def, () -> getClass(path)); + } + + @Nullable + @Override + public Version getVersion(@Nonnull String path) { + return Version.parse(getString(path), null); + } + + @Nonnull + @Override + public Version getVersion(@Nonnull String path, @Nonnull Version def) { + return getDef(def, () -> getVersion(path)); + } + + @Nullable + @Override + public byte[] getBinary(@Nonnull String path) { + String string = getString(path); + if (string == null) return null; + return Base64.getDecoder().decode(string); + } + + @Nonnull + @Override + public String[] getStringArray(@Nonnull String path) { + return getStringList(path).toArray(new String[0]); + } + + @Nonnull + @Override + public > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { + return mapList(path, name -> ReflectionUtils.getEnumOrNull(name, classOfEnum)); + } + + @Nonnull + @Override + public List getCharacterList(@Nonnull String path) { + return mapList(path, string -> string == null || string.length() == 0 ? (char) 0 : string.charAt(0)); + } + + @Nonnull + @Override + public List getUUIDList(@Nonnull String path) { + return mapList(path, UUID::fromString); + } + + @Nonnull + @Override + public List getByteList(@Nonnull String path) { + return mapList(path, Byte::parseByte); + } + + @Nonnull + @Override + public List getShortList(@Nonnull String path) { + return mapList(path, Short::parseShort); + } + + @Nonnull + @Override + public List getIntegerList(@Nonnull String path) { + return mapList(path, Integer::parseInt); + } + + @Nonnull + @Override + public List getLongList(@Nonnull String path) { + return mapList(path, Long::parseLong); + } + + @Nonnull + @Override + public List getFloatList(@Nonnull String path) { + return mapList(path, Float::parseFloat); + } + + @Nonnull + @Override + public List getDoubleList(@Nonnull String path) { + return mapList(path, Double::parseDouble); + } + + @Nonnull + @Override + public List mapList(@Nonnull String path, @Nonnull Function mapper) { + List list = getStringList(path); + List result = new ArrayList<>(list.size()); + for (String string : list) { + try { + result.add(mapper.apply(string)); + } catch (Exception ex) { + logger.error("Unable to map values for '{}'", string, ex); + } + } + return result; + } + + @Override + public boolean isEmpty() { + return size() == 0; + } + + @Nonnull + @Override + public Map valuesAsStrings() { + Map map = new HashMap<>(); + values().forEach((key, value) -> map.put(key, String.valueOf(value))); + return map; + } + + @Nonnull + @Override + public Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return map(valuesAsStrings(), keyMapper, valueMapper); + } + + @Nonnull + @Override + public Set> entrySet() { + return values().entrySet(); + } + + @Nonnull + public Map map(@Nonnull Map values, + @Nonnull Function keyMapper, + @Nonnull Function valueMapper) { + Map result = new HashMap<>(); + values.forEach((key, value) -> { + try { + result.put(keyMapper.apply(key), valueMapper.apply(value)); + } catch (Exception ex) { + logger.error("Unable to map values for '{}'='{}'", key, value, ex); + } + }); + return result; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java new file mode 100644 index 000000000..6f13c5f75 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java @@ -0,0 +1,162 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.readonly.ReadOnlyDocumentWrapper; +import net.codingarea.commons.common.config.exceptions.ConfigReadOnlyException; +import net.codingarea.commons.common.misc.BukkitReflectionSerializationUtils; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +public abstract class AbstractDocument extends AbstractConfig implements Document { + + protected final Document root, parent; + + public AbstractDocument(@Nonnull Document root, @Nullable Document parent) { + this.root = root; + this.parent = parent; + } + + public AbstractDocument() { + this.root = this; + this.parent = null; + } + + @Nonnull + @Override + public T getSerializable(@Nonnull String path, @Nonnull T def) { + T value = getSerializable(path, (Class) def.getClass()); + return value == null ? def : value; + } + + @Nullable + @Override + public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + if (!contains(path)) return null; + return BukkitReflectionSerializationUtils.deserializeObject(getDocument(path).values(), classOfT); + } + + @Nonnull + @Override + public List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { + return getDocumentList(path).stream() + .map(Document::values) + .map(map -> BukkitReflectionSerializationUtils.deserializeObject(map, classOfT)) + .collect(Collectors.toList()); + } + + @Nonnull + @Override + public Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return map(children(), keyMapper, valueMapper); + } + + @Nonnull + @Override + public R mapDocument(@Nonnull String path, @Nonnull Function mapper) { + Document document = getDocument(path); + return mapper.apply(document); + } + + @Nullable + @Override + public R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { + if (!contains(path)) return null; + return mapDocument(path, mapper); + } + + @Nonnull + @Override + public Document getDocument(@Nonnull String path) { + Document document = getDocument0(path, root, this); + return isReadonly() && !document.isReadonly() ? new ReadOnlyDocumentWrapper(document) : document; + } + + @Nonnull + @Override + public Document set(@Nonnull String path, @Nullable Object value) { + if (isReadonly()) throw new ConfigReadOnlyException("set"); + + if (value instanceof byte[]) + value = Base64.getEncoder().encodeToString((byte[]) value); + + set0(path, value); + return this; + } + + @Nonnull + @Override + public Document set(@Nonnull Object object) { + if (isReadonly()) throw new ConfigReadOnlyException("set"); + + Document.of(object).forEach(this::set); + return this; + } + + @Nonnull + @Override + public Document remove(@Nonnull String path) { + if (isReadonly()) throw new ConfigReadOnlyException("remove"); + remove0(path); + return this; + } + + @Nonnull + @Override + public Document clear() { + if (isReadonly()) throw new ConfigReadOnlyException("clear"); + clear0(); + return this; + } + + @Nonnull + @CheckReturnValue + public Document readonly() { + return isReadonly() ? this : new ReadOnlyDocumentWrapper(this); + } + + @Nonnull + protected abstract Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent); + + protected abstract void set0(@Nonnull String path, @Nullable Object value); + + protected abstract void remove0(@Nonnull String path); + + protected abstract void clear0(); + + @Nonnull + @Override + public Map children() { + Map map = new HashMap<>(); + keys().forEach(key -> { + if (!isDocument(key)) return; + map.put(key, getDocument(key)); + }); + return map; + } + + @Override + public boolean hasChildren(@Nonnull String path) { + return !getDocument(path).isEmpty(); + } + + @Nonnull + @Override + public Document getRoot() { + return root; + } + + @Nullable + @Override + public Document getParent() { + return parent; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java new file mode 100644 index 000000000..21deb8ae5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java @@ -0,0 +1,518 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.Propertyable; +import net.codingarea.commons.common.config.exceptions.ConfigReadOnlyException; +import net.codingarea.commons.common.version.Version; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Function; + +public class EmptyDocument implements Document { + + public static final EmptyDocument ROOT = new EmptyDocument(); + + protected final Document root, parent; + + public EmptyDocument(@Nonnull Document root, @Nullable Document parent) { + this.root = root; + this.parent = parent; + } + + public EmptyDocument() { + this.root = this; + this.parent = null; + } + + @Nonnull + @Override + public Document getDocument(@Nonnull String path) { + return new EmptyDocument(); + } + + @Nonnull + @Override + public R mapDocument(@Nonnull String path, @Nonnull Function mapper) { + return mapper.apply(Document.empty()); + } + + @Nullable + @Override + public R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { + return null; + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public Document set(@Nonnull String path, @Nullable Object value) { + throw new ConfigReadOnlyException("set"); + } + + @Nonnull + @Override + public Document set(@Nonnull Object value) { + throw new ConfigReadOnlyException("set"); + } + + @Nonnull + @Override + public Document clear() { + return this; + } + + @Nonnull + @Override + public Document remove(@Nonnull String path) { + return this; + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + throw new UnsupportedOperationException("EmptyDocument.write(Writer)"); + } + + @Override + public void saveToFile(@Nonnull File file) throws IOException { + throw new UnsupportedOperationException("EmptyDocument.save(File)"); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Object getObject(@Nonnull String path, @Nonnull Object def) { + return def; + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return null; + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + throw new UnsupportedOperationException(); + } + + @Nonnull + @Override + public Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { + return Optional.empty(); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public String getString(@Nonnull String path, @Nonnull String def) { + return def; + } + + @Override + public char getChar(@Nonnull String path) { + return 0; + } + + @Override + public char getChar(@Nonnull String path, char def) { + return def; + } + + @Override + public long getLong(@Nonnull String path) { + return 0; + } + + @Override + public long getLong(@Nonnull String path, long def) { + return def; + } + + @Override + public int getInt(@Nonnull String path) { + return 0; + } + + @Override + public int getInt(@Nonnull String path, int def) { + return def; + } + + @Override + public short getShort(@Nonnull String path) { + return 0; + } + + @Override + public short getShort(@Nonnull String path, short def) { + return def; + } + + @Override + public byte getByte(@Nonnull String path) { + return 0; + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + return def; + } + + @Override + public float getFloat(@Nonnull String path) { + return 0; + } + + @Override + public float getFloat(@Nonnull String path, float def) { + return def; + } + + @Override + public double getDouble(@Nonnull String path) { + return 0; + } + + @Override + public double getDouble(@Nonnull String path, double def) { + return def; + } + + @Override + public boolean getBoolean(@Nonnull String path) { + return false; + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + return def; + } + + @Nullable + @Override + public byte[] getBinary(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public String[] getStringArray(@Nonnull String path) { + return new String[0]; + } + + @Nonnull + @Override + public > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List mapList(@Nonnull String path, @Nonnull Function mapper) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getUUIDList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getCharacterList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getByteList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getShortList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getIntegerList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getLongList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getFloatList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getDoubleList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public UUID getUUID(@Nonnull String path, @Nonnull UUID def) { + return def; + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Date getDate(@Nonnull String path, @Nonnull Date def) { + return def; + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { + return def; + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Color getColor(@Nonnull String path, @Nonnull Color def) { + return def; + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return null; + } + + @Nonnull + @Override + public > E getEnum(@Nonnull String path, @Nonnull E def) { + return def; + } + + @Nullable + @Override + public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + return null; + } + + @Nonnull + @Override + public T getSerializable(@Nonnull String path, @Nonnull T def) { + return def; + } + + @Nullable + @Override + public Class getClass(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Class getClass(@Nonnull String path, @Nonnull Class def) { + return def; + } + + @Nullable + @Override + public Version getVersion(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Version getVersion(@Nonnull String path, @Nonnull Version def) { + return def; + } + + @Override + public boolean contains(@Nonnull String path) { + return false; + } + + @Override + public boolean isEmpty() { + return true; + } + + @Override + public boolean hasChildren(@Nonnull String path) { + return false; + } + + @Override + public boolean isList(@Nonnull String path) { + return false; + } + + @Override + public boolean isObject(@Nonnull String path) { + return false; + } + + @Override + public boolean isDocument(@Nonnull String path) { + return false; + } + + @Override + public int size() { + return 0; + } + + @Nonnull + @Override + public Map values() { + return Collections.emptyMap(); + } + + @Nonnull + @Override + public Map valuesAsStrings() { + return new HashMap<>(); + } + + @Nonnull + @Override + public Map children() { + return new HashMap<>(); + } + + @Nonnull + @Override + public Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return new HashMap<>(); + } + + @Nonnull + @Override + public Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return new HashMap<>(); + } + + @Nonnull + @Override + public Collection keys() { + return Collections.emptyList(); + } + + @Nonnull + @Override + public Set> entrySet() { + return Collections.emptySet(); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + } + + @Nonnull + @Override + public String toJson() { + return "{}"; + } + + @Nonnull + @Override + public String toPrettyJson() { + return "{}"; + } + + @Nonnull + @Override + public String toString() { + return "{}"; + } + + @Override + public boolean isReadonly() { + return true; + } + + @Nonnull + @Override + public Document readonly() { + return this; + } + + @Nullable + @Override + public Document getParent() { + return parent; + } + + @Nonnull + @Override + public Document getRoot() { + return root; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java new file mode 100644 index 000000000..50262eaf0 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java @@ -0,0 +1,508 @@ +package net.codingarea.commons.common.config.document; + +import com.google.gson.*; +import com.google.gson.internal.LazilyParsedNumber; +import com.google.gson.internal.bind.TypeAdapters; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; +import com.google.gson.stream.JsonWriter; +import net.codingarea.commons.common.collection.pair.Pair; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.gson.*; +import net.codingarea.commons.common.misc.BukkitReflectionSerializationUtils; +import net.codingarea.commons.common.misc.FileUtils; +import net.codingarea.commons.common.misc.GsonUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.*; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.Function; + +public class GsonDocument extends AbstractDocument { + + static { + GsonBuilder builder = new GsonBuilder() + .disableHtmlEscaping() + .registerTypeAdapterFactory(GsonTypeAdapter.newPredictableFactory(BukkitReflectionSerializationUtils::isSerializable, new BukkitReflectionSerializableTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Document.class, new DocumentTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Pair.class, new PairTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Class.class, new ClassTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Color.class, new ColorTypeAdapter())) + ; + + GSON = builder.create(); + GSON_PRETTY_PRINT = builder.setPrettyPrinting().create(); + } + + // Not implemented in some versions of gson + TypeAdapter NUMBER = new TypeAdapter() { + @Override + public void write(JsonWriter out, Number value) throws IOException { + out.value(value); + } + @Override + public Number read(JsonReader in) throws IOException { + JsonToken jsonToken = in.peek(); + switch (jsonToken) { + case NUMBER: + case STRING: + return new LazilyParsedNumber(in.nextString()); + case BOOLEAN: + default: + throw new JsonSyntaxException("Expecting number, got: " + jsonToken); + case NULL: + in.nextNull(); + return null; + } + } + }; + + public static final Gson GSON, GSON_PRETTY_PRINT; + + private static boolean cleanupEmptyObjects = false; + private static boolean cleanupEmptyArrays = false; + private static boolean writePrettyJson = true; + + public static void setCleanupEmptyArrays(boolean clean) { + cleanupEmptyArrays = clean; + } + + public static void setCleanupEmptyObjects(boolean clean) { + cleanupEmptyObjects = clean; + } + + public static void setWritePrettyJson(boolean pretty) { + writePrettyJson = pretty; + } + + public static boolean isWritePrettyJson() { + return writePrettyJson; + } + + @Nonnull + public static List convertArrayToDocuments(@Nonnull JsonArray array) { + List list = new ArrayList<>(array.size()); + for (JsonElement element : array) { + if (!element.isJsonObject()) continue; + list.add(new GsonDocument(element.getAsJsonObject())); + } + return list; + } + + @Nonnull + public static List convertArrayToStrings(@Nonnull JsonArray array) { + List list = new ArrayList<>(array.size()); + for (JsonElement element : array) { + if (!element.isJsonObject()) continue; + list.add(element.getAsString()); + } + return list; + } + + protected JsonObject jsonObject; + + public GsonDocument(@Nonnull File file) throws IOException { + this(FileUtils.newBufferedReader(file)); + } + + public GsonDocument(@Nonnull Reader reader) throws IOException { + this(new BufferedReader(reader)); + } + + public GsonDocument(@Nonnull BufferedReader reader) throws IOException { + this(reader.ready() ? GSON.fromJson(reader, JsonObject.class) : new JsonObject()); + } + + public GsonDocument(@Nonnull String json) { + this(GSON.fromJson(json, JsonObject.class)); + } + + public GsonDocument(@Nonnull String json, @Nonnull Document root, @Nullable Document parent) { + this(GSON.fromJson(json, JsonObject.class), root, parent); + } + + public GsonDocument(@Nullable JsonObject jsonObject) { + this.jsonObject = jsonObject == null ? new JsonObject() : jsonObject; + } + + public GsonDocument(@Nullable JsonObject jsonObject, @Nonnull Document root, @Nullable Document parent) { + super(root, parent); + this.jsonObject = jsonObject == null ? new JsonObject() : jsonObject; + } + + public GsonDocument(@Nonnull Map values) { + this(); + GsonUtils.setDocumentProperties(GSON, jsonObject, values); + } + + public GsonDocument() { + this(new JsonObject()); + } + + public GsonDocument(@Nonnull Object object) { + this(GSON.toJsonTree(object).getAsJsonObject()); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + JsonElement element = getElement(path).orElse(null); + return GsonUtils.convertJsonElementToString(element); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + JsonElement element = getElement(path).orElse(null); + return GsonUtils.unpackJsonElement(element); + } + + @Nullable + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfType) { + JsonElement element = getElement(path).orElse(null); + return GSON.fromJson(element, classOfType); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + if (isEmpty()) return null; + return GSON.fromJson(jsonObject, classOfT); + } + + @Nullable + @Override + public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + return getInstance(path, classOfT); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + JsonElement element = getElement(path).orElse(null); + if (element == null || !element.isJsonObject()) setElement(path, element = new JsonObject()); + return new GsonDocument(element.getAsJsonObject(), root, parent); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + JsonElement element = getElement(path).orElse(new JsonArray()); + if (element.isJsonNull()) return new ArrayList<>(); + JsonArray array = element.getAsJsonArray(); + List documents = new ArrayList<>(array.size()); + for (JsonElement current : array) { + if (current == null || current.isJsonNull()) documents.add(new GsonDocument((JsonObject) null, root, this)); + else if (current.isJsonObject()) documents.add(new GsonDocument(current.getAsJsonObject(), root, this)); + } + return documents; + } + + @Override + public char getChar(@Nonnull String path) { + return getChar(path, (char) 0); + } + + @Override + public char getChar(@Nonnull String path, char def) { + return getPrimitive(path).map(JsonPrimitive::getAsCharacter).orElse(def); + } + + @Override + public long getLong(@Nonnull String path, long def) { + return getPrimitive(path).map(JsonPrimitive::getAsLong).orElse(def); + } + + @Override + public int getInt(@Nonnull String path, int def) { + return getPrimitive(path).map(JsonPrimitive::getAsInt).orElse(def); + } + + @Override + public short getShort(@Nonnull String path, short def) { + return getPrimitive(path).map(JsonPrimitive::getAsShort).orElse(def); + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + return getPrimitive(path).map(JsonPrimitive::getAsByte).orElse(def); + } + + @Override + public double getDouble(@Nonnull String path, double def) { + return getPrimitive(path).map(JsonPrimitive::getAsDouble).orElse(def); + } + + @Override + public float getFloat(@Nonnull String path, float def) { + return getPrimitive(path).map(JsonPrimitive::getAsFloat).orElse(def); + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + return getPrimitive(path).map(JsonPrimitive::getAsBoolean).orElse(def); + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + JsonElement element = getElement(path).orElse(null); + if (element == null || element.isJsonNull()) return new ArrayList<>(); + if (element.isJsonPrimitive()) return new ArrayList<>(Collections.singletonList(GsonUtils.convertJsonElementToString(element))); + if (element.isJsonObject()) throw new IllegalStateException("Cannot extract list out of json object at '" + path + "'"); + return GsonUtils.convertJsonArrayToStringList(element.getAsJsonArray()); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + return getInstance(path, UUID.class); + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + return getInstance(path, Date.class); + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + return getInstance(path, OffsetDateTime.class); + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + return getInstance(path, Color.class); + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return getInstance(path, classOfEnum); + } + + @Override + public boolean isList(@Nonnull String path) { + return checkElement(path, JsonElement::isJsonArray); + } + + @Override + public boolean isDocument(@Nonnull String path) { + return checkElement(path, JsonElement::isJsonObject); + } + + @Override + public boolean isObject(@Nonnull String path) { + return checkElement(path, JsonElement::isJsonPrimitive); + } + + private boolean checkElement(@Nonnull String path, @Nonnull Function check) { + return getElement(path).map(check).orElse(false); + } + + @Override + public boolean contains(@Nonnull String path) { + return getElement(path).isPresent(); + } + + @Override + public int size() { + return GsonUtils.getSize(jsonObject); + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + setElement(path, value); + } + + @Nonnull + @Override + public Document set(@Nonnull Object object) { + JsonObject json = GSON.toJsonTree(object).getAsJsonObject(); + for (Entry entry : json.entrySet()) { + jsonObject.add(entry.getKey(), entry.getValue()); + } + return this; + } + + @Override + public void clear0() { + jsonObject = new JsonObject(); + } + + @Override + public void remove0(@Nonnull String path) { + setElement(path, null); + } + + @Nonnull + @Override + public Map values() { + return GsonUtils.convertJsonObjectToMap(jsonObject); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } + + @Nonnull + @Override + public Collection keys() { + Collection keys = new ArrayList<>(size()); + for (Entry entry : jsonObject.entrySet()) { + keys.add(entry.getKey()); + } + return keys; + } + + @Nonnull + private Optional getPrimitive(@Nonnull String path) { + return getElement(path) + .filter(JsonPrimitive.class::isInstance) + .map(JsonPrimitive.class::cast); + } + + @Nonnull + private Optional getElement(@Nonnull String path) { + return getElement(path, jsonObject); + } + + @Nonnull + private Optional getElement(@Nonnull String path, @Nonnull JsonObject object) { + + JsonElement fullPathElement = object.get(path); + if (fullPathElement != null) return Optional.of(fullPathElement); + + int index = path.indexOf('.'); + if (index == -1) return Optional.empty(); + + String child = path.substring(0, index); + String newPath = path.substring(index + 1); + + JsonElement element = object.get(child); + if (element == null || element.isJsonNull()) return Optional.empty(); + + return getElement(newPath, element.getAsJsonObject()); + + } + + private void setElement(@Nonnull String path, @Nullable Object value) { + + LinkedList paths = determinePath(path); + JsonObject object = jsonObject; + + for (int i = 0; i < paths.size() - 1; i++) { + + String current = paths.get(i); + JsonElement element = object.get(current); + if (element == null || element.isJsonNull()) { + if (value == null) return; // There's noting to remove + object.add(current, element = new JsonObject()); + } + + if (!element.isJsonObject()) throw new IllegalArgumentException("Cannot replace '" + current + "' on '" + path + "'; It's not an object (" + element.getClass().getName() + ")"); + object = element.getAsJsonObject(); + + } + + String lastPath = paths.getLast(); + JsonElement jsonValue = + value instanceof JsonElement ? (JsonElement) value + : value == null ? JsonNull.INSTANCE + : value instanceof Number ? NUMBER.toJsonTree((Number) value) + : value instanceof Boolean ? TypeAdapters.BOOLEAN.toJsonTree((boolean) value) + : value instanceof Character ? TypeAdapters.CHARACTER.toJsonTree((char) value) + : GSON.toJsonTree(value); + object.add(lastPath, jsonValue); + + } + + @Nonnull + private LinkedList determinePath(@Nonnull String path) { + + LinkedList paths = new LinkedList<>(); + String pathCopy = path; + int index; + while ((index = pathCopy.indexOf('.')) != -1) { + String child = pathCopy.substring(0, index); + pathCopy = pathCopy.substring(index + 1); + paths.add(child); + } + paths.add(pathCopy); + + return paths; + + } + + @Nonnull + @Override + public String toJson() { + return GSON.toJson(jsonObject); + } + + @Nonnull + @Override + public String toPrettyJson() { + return GSON_PRETTY_PRINT.toJson(jsonObject); + } + + @Override + public String toString() { + return toJson(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + GsonDocument that = (GsonDocument) o; + return jsonObject.equals(that.jsonObject); + } + + @Override + public int hashCode() { + return jsonObject.hashCode(); + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + cleanup(); + (writePrettyJson ? GSON_PRETTY_PRINT : GSON).toJson(jsonObject, writer); + } + + @Nonnull + public JsonObject getJsonObject() { + return jsonObject; + } + + @Override + public boolean isReadonly() { + return false; + } + + public void cleanup() { + cleanup(jsonObject); + } + + public static void cleanup(@Nonnull JsonObject jsonObject) { + Iterator> iterator = jsonObject.entrySet().iterator(); + while (iterator.hasNext()) { + Entry entry = iterator.next(); + JsonElement value = entry.getValue(); + if (value.isJsonObject()) cleanup(value.getAsJsonObject()); +// if (cleanupNulls && value.isJsonNull()) iterator.remove(); + if (cleanupEmptyObjects && value.isJsonObject() && GsonUtils.getSize(value.getAsJsonObject()) == 0) iterator.remove(); + if (cleanupEmptyArrays && value.isJsonArray() && value.getAsJsonArray().size() == 0) iterator.remove(); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java new file mode 100644 index 000000000..b0b194d05 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java @@ -0,0 +1,292 @@ +package net.codingarea.commons.common.config.document; + +import com.google.common.base.Preconditions; +import com.google.gson.JsonArray; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.PropertyHelper; +import net.codingarea.commons.common.misc.GsonUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.IOException; +import java.io.Writer; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.function.BiConsumer; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +/** + * This class is not thread safe. + * Documents of this type are not able to be saved or loaded. + */ +public class MapDocument extends AbstractDocument { + + private final Map values; + + public MapDocument(@Nonnull Map values) { + Preconditions.checkNotNull(values, "Map cannot be null"); + this.values = values; + } + + public MapDocument(@Nonnull Map values, @Nonnull Document root, @Nullable Document parent) { + super(root, parent); + this.values = values; + } + + public MapDocument() { + this(new LinkedHashMap<>()); + } + + @Override + public boolean isReadonly() { + return false; + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + Object value = this.values.computeIfAbsent(path, key -> new HashMap<>()); + if (value instanceof Map) return new MapDocument((Map) value, root, parent); + if (value instanceof Document) return (Document) value; + if (value instanceof String) return new GsonDocument((String) value, root, parent); + throw new IllegalStateException("Expected java.util.Map, found " + values.getClass().getName()); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + List documents = new ArrayList<>(); + Object value = values.get(path); + if (value instanceof List) { + List list = (List) value; + for (Object object : list) { + if (object instanceof Map) documents.add(new MapDocument((Map) object, root, parent)); + if (object instanceof Document) documents.add((Document) object); + if (object instanceof String) documents.add(new GsonDocument((String) object, root, this)); + } + } + return documents; + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + values.put(path, value); + } + + @Override + public void clear0() { + values.clear(); + } + + @Override + public void remove0(@Nonnull String path) { + values.remove(path); + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + new GsonDocument(values).write(writer); + } + + @Nonnull + @Override + public String toJson() { + return new GsonDocument(values).toJson(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return new GsonDocument(values).toPrettyJson(); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return values.get(path); + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return classOfT.cast(getObject(path)); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + Object value = values.get(path); + return value == null ? null : value.toString(); + } + + @Override + public long getLong(@Nonnull String path, long def) { + try { + return Long.parseLong(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public int getInt(@Nonnull String path, int def) { + try { + return Integer.parseInt(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public short getShort(@Nonnull String path, short def) { + try { + return Short.parseShort(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + try { + return Byte.parseByte(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public float getFloat(@Nonnull String path, float def) { + try { + return Float.parseFloat(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path, double def) { + try { + return Double.parseDouble(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + try { + if (!contains(path)) return def; + switch (getString(path).toLowerCase()) { + case "true": + case "1": + return true; + default: + return false; + } + } catch (Exception ex) { + return def; + } + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + Object object = getObject(path); + if (object == null) return Collections.emptyList(); + if (object instanceof Iterable) return StreamSupport.stream(((Iterable)object).spliterator(), false).map(String::valueOf).collect(Collectors.toList()); + if (object instanceof String) return GsonUtils.convertJsonArrayToStringList(GsonDocument.GSON.fromJson((String) object, JsonArray.class)); + throw new IllegalStateException("Cannot convert " + object.getClass() + " to a list"); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + try { + Object object = getObject(path); + if (object instanceof UUID) return (UUID) object; + return UUID.fromString(String.valueOf(object)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + Object object = getObject(path); + if (object instanceof String) return PropertyHelper.parseDate((String) object); + if (object instanceof Date) return (Date) object; + return null; + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + Object object = getObject(path); + if (object instanceof CharSequence) return OffsetDateTime.parse((CharSequence) object); + if (object instanceof OffsetDateTime) return (OffsetDateTime) object; + return null; + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + Object object = getObject(path); + if (object instanceof Color) return (Color) object; + if (object instanceof String) return Color.decode((String) object); + return null; + } + + @Override + public boolean isList(@Nonnull String path) { + Object value = values.get(path); + return value instanceof Iterable || (value != null && value.getClass().isArray()); + } + + @Override + public boolean isObject(@Nonnull String path) { + return !isDocument(path) && !isList(path); + } + + @Override + public boolean isDocument(@Nonnull String path) { + Object value = values.get(path); + return value instanceof Map || value instanceof Document; + } + + @Override + public boolean contains(@Nonnull String path) { + return values.containsKey(path); + } + + @Override + public int size() { + return values.size(); + } + + @Nonnull + @Override + public Map values() { + return Collections.unmodifiableMap(values); + } + + @Nonnull + @Override + public Collection keys() { + return values.keySet(); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values.forEach(action); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java new file mode 100644 index 000000000..58fa7b100 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java @@ -0,0 +1,285 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.collection.Colors; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.PropertyHelper; +import net.codingarea.commons.common.misc.FileUtils; +import net.codingarea.commons.common.misc.PropertiesUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.BiConsumer; + +/** + * This document only supports basic objects like {@link Number numbers}, {@link String strings}, {@link Character characters} and {@link Boolean booleans}. + * You may use more advanced documents which are fully supported like {@link GsonDocument} + */ +public class PropertiesDocument extends AbstractDocument { + + protected final Properties properties; + + public PropertiesDocument(@Nullable Properties properties) { + this.properties = properties == null ? new Properties() : properties; + } + + public PropertiesDocument(@Nonnull File file) throws IOException { + properties = new Properties(); + properties.load(FileUtils.newBufferedReader(file)); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + throw new UnsupportedOperationException("PropertiesDocument.getDocument(String)"); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + throw new UnsupportedOperationException("PropertiesDocument.getDocumentList(String)"); + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + throw new UnsupportedOperationException("PropertiesDocument.getList(String)"); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return properties.get(path); + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return classOfT.cast(getObject(path)); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + return properties.getProperty(path); + } + + @Override + public long getLong(@Nonnull String path, long def) { + try { + return Long.parseLong(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public int getInt(@Nonnull String path, int def) { + try { + return Integer.parseInt(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public short getShort(@Nonnull String path, short def) { + try { + return Short.parseShort(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + try { + return Byte.parseByte(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public float getFloat(@Nonnull String path, float def) { + try { + return Float.parseFloat(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path, double def) { + try { + return Double.parseDouble(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + if (!contains(path)) return def; + return Boolean.parseBoolean(getString(path)); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + try { + return UUID.fromString(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + return PropertyHelper.parseDate(getString(path)); + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + try { + return OffsetDateTime.parse(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + String string = getString(path); + return string == null ? null : Color.decode(string); + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + try { + String name = getString(path); + if (name == null) return null; + return Enum.valueOf(classOfEnum, name); + } catch (Throwable ex) { + return null; + } + } + + @Override + public boolean contains(@Nonnull String path) { + return properties.containsKey(path); + } + + @Override + public boolean isList(@Nonnull String path) { + return false; + } + + @Override + public boolean isObject(@Nonnull String path) { + return true; + } + + @Override + public boolean isDocument(@Nonnull String path) { + return false; + } + + @Override + public int size() { + return properties.size(); + } + + @Nonnull + @Override + public Map values() { + Map map = new LinkedHashMap<>(); + for (Entry entry : properties.entrySet()) { + map.put((String) entry.getKey(), entry.getValue()); + } + return map; + } + + @Nonnull + @Override + public Collection keys() { + return properties.stringPropertyNames(); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + final String asString; + if (value instanceof Color) { + asString = Colors.asHex((Color) value); + } else { + asString = String.valueOf(value); + } + + properties.setProperty(path, asString); + } + + @Override + public void clear0() { + properties.clear(); + } + + @Override + public void remove0(@Nonnull String path) { + properties.remove(path); + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + properties.store(writer, null); + } + + @Nonnull + public Properties getProperties() { + return properties; + } + + @Nonnull + @Override + public String toJson() { + return copyJson().toJson(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return copyJson().toPrettyJson(); + } + + @Nonnull + @Override + public Document copyJson() { + Map map = new HashMap<>(); + PropertiesUtils.setProperties(properties, map); + return new GsonDocument(map); + } + + @Override + public boolean isReadonly() { + return false; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java new file mode 100644 index 000000000..03bdf14d3 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java @@ -0,0 +1,355 @@ +package net.codingarea.commons.common.config.document; + +import net.codingarea.commons.common.config.Document; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.configuration.file.YamlConstructor; +import org.bukkit.configuration.file.YamlRepresenter; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.representer.Representer; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.text.DateFormat; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.function.BiConsumer; + +public class YamlDocument extends AbstractDocument { + + protected final ConfigurationSection config; + + public YamlDocument() { + this.config = new YamlConfiguration(); + } + + public YamlDocument(@Nonnull ConfigurationSection config) { + this.config = config; + } + + public YamlDocument(@Nonnull ConfigurationSection config, @Nonnull Document root, @Nullable Document parent) { + super(root, parent); + this.config = config; + } + + public YamlDocument(@Nonnull File file) { + this(YamlConfiguration.loadConfiguration(file)); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + return config.getString(path); + } + + @Nonnull + @Override + public String getString(@Nonnull String path, @Nonnull String def) { + String string = config.getString(path, def); + return string == null ? def : string; + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return config.get(path); + } + + @Nonnull + @Override + public Object getObject(@Nonnull String path, @Nonnull Object def) { + Object value = config.get(path, def); + return value == null ? def : value; + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return copyJson().getInstance(path, classOfT); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + ConfigurationSection section = config.getConfigurationSection(path); + if (section == null) section = config.createSection(path); + return new YamlDocument(section, root, parent); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + List> maps = config.getMapList(path); + List documents = new ArrayList<>(maps.size()); + for (Map map : maps) { + documents.add(new MapDocument((Map) map, root, this)); + } + return documents; + } + + @Override + public long getLong(@Nonnull String path) { + return config.getLong(path); + } + + @Override + public long getLong(@Nonnull String path, long def) { + return config.getLong(path, def); + } + + @Override + public int getInt(@Nonnull String path) { + return config.getInt(path); + } + + @Override + public int getInt(@Nonnull String path, int def) { + return config.getInt(path, def); + } + + @Override + public short getShort(@Nonnull String path) { + return (short) config.getInt(path); + } + + @Override + public short getShort(@Nonnull String path, short def) { + return (short) config.getInt(path, def); + } + + @Override + public byte getByte(@Nonnull String path) { + return (byte) config.getInt(path); + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + return (byte) config.getInt(path, def); + } + + @Override + public char getChar(@Nonnull String path) { + return getChar(path, (char) 0); + } + + @Override + public char getChar(@Nonnull String path, char def) { + try { + return getString(path).charAt(0); + } catch (NullPointerException | StringIndexOutOfBoundsException ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path) { + return config.getDouble(path); + } + + @Override + public double getDouble(@Nonnull String path, double def) { + return config.getDouble(path, def); + } + + @Override + public float getFloat(@Nonnull String path) { + return (float) config.getDouble(path); + } + + @Override + public float getFloat(@Nonnull String path, float def) { + return (float) config.getDouble(path, def); + } + + @Override + public boolean getBoolean(@Nonnull String path) { + return config.getBoolean(path); + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + return config.getBoolean(path, def); + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + return config.getStringList(path); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + try { + return UUID.fromString(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + try { + return DateFormat.getDateTimeInstance().parse(path); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + try { + return OffsetDateTime.parse(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + try { + return Color.decode(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + try { + String name = getString(path); + if (name == null) return null; + return Enum.valueOf(classOfEnum, name); + } catch (Throwable ex) { + return null; + } + } + + @Override + public boolean isList(@Nonnull String path) { + return config.isList(path); + } + + @Override + public boolean isObject(@Nonnull String path) { + return !isDocument(path) && !isList(path); + } + + @Override + public boolean isDocument(@Nonnull String path) { + return config.get(path) instanceof ConfigurationSection; + } + + @Override + public boolean contains(@Nonnull String path) { + return config.contains(path, true); + } + + @Override + public int size() { + return config.getValues(false).size(); + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + if (value instanceof Enum) { + Enum enun = (Enum) value; + value = enun.name(); + } + config.set(path, value); + } + + @Override + public void remove0(@Nonnull String path) { + config.set(path, null); + } + + @Override + public void clear0() { + for (String key : config.getKeys(true)) { + config.set(key, null); + } + } + + @Nonnull + @Override + public Map values() { + return config.getValues(true); + } + + @Nonnull + @Override + public Collection keys() { + return config.getKeys(false); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } + + @Override + public String toString() { + + DumperOptions yamlOptions = new DumperOptions(); + LoaderOptions loaderOptions = new LoaderOptions(); + Representer yamlRepresenter = new YamlRepresenter(); + Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions, loaderOptions); + + yamlOptions.setIndent(2); + yamlOptions.setDefaultFlowStyle(FlowStyle.BLOCK); + yamlRepresenter.setDefaultFlowStyle(FlowStyle.BLOCK); + String dump = yaml.dump(config.getValues(false)); + if (dump.equals("{}\n")) { + dump = ""; + } + + return dump; + + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + writer.write(toString()); + } + + @Nonnull + @Override + public Document copyJson() { + return new GsonDocument(values()); + } + + @Nonnull + @Override + public String toJson() { + return copyJson().toJson(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return copyJson().toPrettyJson(); + } + + @Override + public boolean isReadonly() { + return false; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java new file mode 100644 index 000000000..ed36fd787 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java @@ -0,0 +1,60 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.internal.bind.TypeAdapters; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import net.codingarea.commons.common.misc.BukkitReflectionSerializationUtils; +import net.codingarea.commons.common.misc.GsonUtils; + +import javax.annotation.Nonnull; +import java.io.IOException; +import java.util.Map; +import java.util.Optional; + +public class BukkitReflectionSerializableTypeAdapter implements GsonTypeAdapter { + + public static final String ALTERNATE_KEY = "classOfType", KEY = "=="; + + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Object object) throws IOException { + + Map map = BukkitReflectionSerializationUtils.serializeObject(object); + if (map == null) return; + + JsonObject json = new JsonObject(); + json.addProperty(KEY, BukkitReflectionSerializationUtils.getSerializationName(object.getClass())); + GsonUtils.setDocumentProperties(gson, json, map); + TypeAdapters.JSON_ELEMENT.write(writer, json); + + } + + @Override + public Object read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + + JsonElement element = TypeAdapters.JSON_ELEMENT.read(reader); + if (element == null || !element.isJsonObject()) return null; + + JsonObject json = element.getAsJsonObject(); + String classOfType = Optional.ofNullable(findClassContainer(json)).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsString).orElse(null); + + Class clazz = null; + try { + clazz = Class.forName(classOfType); + } catch (ClassNotFoundException | NullPointerException ex) { + } + + Map map = GsonUtils.convertJsonObjectToMap(json); + return BukkitReflectionSerializationUtils.deserializeObject(map, clazz); + + } + + private JsonElement findClassContainer(@Nonnull JsonObject json) { + if (json.has(ALTERNATE_KEY)) + return json.get(ALTERNATE_KEY); + return json.get(KEY); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java new file mode 100644 index 000000000..3b85bbd16 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java @@ -0,0 +1,32 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.internal.bind.TypeAdapters; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import javax.annotation.Nonnull; +import java.io.IOException; + +public class ClassTypeAdapter implements GsonTypeAdapter> { + + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Class object) throws IOException { + TypeAdapters.STRING.write(writer, object.getName()); + } + + @Override + public Class read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + try { + + String value = reader.nextString(); + if (value == null) return null; + + return Class.forName(value); + + } catch (ClassNotFoundException ex) { + return null; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java new file mode 100644 index 000000000..6a172a83f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java @@ -0,0 +1,27 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.internal.bind.TypeAdapters; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import net.codingarea.commons.common.collection.Colors; + +import javax.annotation.Nonnull; +import java.awt.*; +import java.io.IOException; + +public class ColorTypeAdapter implements GsonTypeAdapter { + + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Color color) throws IOException { + TypeAdapters.STRING.write(writer, Colors.asHex(color)); + } + + @Override + public Color read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + String value = TypeAdapters.STRING.read(reader); + if (value == null) return null; + return Color.decode(value); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java new file mode 100644 index 000000000..fffa43204 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java @@ -0,0 +1,46 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.internal.bind.TypeAdapters; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; + +import javax.annotation.Nonnull; +import java.io.IOException; + +public class DocumentTypeAdapter implements GsonTypeAdapter { + + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Document document) throws IOException { + if (document instanceof GsonDocument) { + GsonDocument gsonDocument = (GsonDocument) document; + TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); + return; + } + + Document copiedDocument = document.copyJson(); + if (copiedDocument instanceof GsonDocument) { + GsonDocument gsonDocument = (GsonDocument) copiedDocument; + TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); + return; + } + + GsonDocument gsonDocument = new GsonDocument(document.values()); + TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); + + } + + @Override + public Document read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + JsonElement jsonElement = TypeAdapters.JSON_ELEMENT.read(reader); + if (jsonElement != null && jsonElement.isJsonObject()) { + return new GsonDocument(jsonElement.getAsJsonObject()); + } else { + return null; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java new file mode 100644 index 000000000..e8f72f78b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java @@ -0,0 +1,62 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +import javax.annotation.Nonnull; +import java.io.IOException; +import java.util.function.Predicate; + +@SuppressWarnings("unchecked") +public interface GsonTypeAdapter { + + void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull T object) throws IOException; + + T read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException; + + default TypeAdapter toTypeAdapter(@Nonnull Gson gson) { + return new TypeAdapter() { + @Override + public void write(JsonWriter writer, T object) throws IOException { + if (object == null) { + writer.nullValue(); + return; + } + GsonTypeAdapter.this.write(gson, writer, object); + } + + @Override + public T read(JsonReader reader) throws IOException { + return GsonTypeAdapter.this.read(gson, reader); + } + }; + } + + @Nonnull + static TypeAdapterFactory newTypeHierarchyFactory(@Nonnull Class clazz, @Nonnull GsonTypeAdapter adapter) { + return new TypeAdapterFactory() { + @Override + public TypeAdapter create(Gson gson, TypeToken token) { + Class requestedType = token.getRawType(); + if (!clazz.isAssignableFrom(requestedType)) return null; + + return (TypeAdapter) adapter.toTypeAdapter(gson); + } + }; + } + + @Nonnull + static TypeAdapterFactory newPredictableFactory(@Nonnull Predicate> predicate, @Nonnull GsonTypeAdapter adapter) { + return new TypeAdapterFactory() { + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + return predicate.test(type.getRawType()) ? (TypeAdapter) adapter.toTypeAdapter(gson) : null; + } + }; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java new file mode 100644 index 000000000..6b4b393d0 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java @@ -0,0 +1,37 @@ +package net.codingarea.commons.common.config.document.gson; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import net.codingarea.commons.common.collection.pair.Pair; +import net.codingarea.commons.common.collection.pair.Quadro; +import net.codingarea.commons.common.collection.pair.Triple; +import net.codingarea.commons.common.collection.pair.Tuple; + +import javax.annotation.Nonnull; +import java.io.IOException; + +public class PairTypeAdapter implements GsonTypeAdapter { + + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Pair object) throws IOException { + Object[] values = object.values(); + JsonArray array = new JsonArray(values.length); + for (Object value : values) { + array.add(gson.toJsonTree(value)); + } + } + + @Override + public Pair read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + JsonArray array = gson.fromJson(reader, JsonArray.class); + int size = array.size(); + switch (size) { + case 2: return Tuple.of(array.get(0), array.get(1)); + case 3: return Triple.of(array.get(0), array.get(1), array.get(2)); + case 4: return Quadro.of(array.get(0), array.get(1), array.get(2), array.get(3)); + default:throw new IllegalStateException("No Pair known for amount of " + size); + } + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java new file mode 100644 index 000000000..4267a567c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java @@ -0,0 +1,26 @@ +package net.codingarea.commons.common.config.document.readonly; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.wrapper.WrappedDocument; + +import javax.annotation.Nonnull; + +public final class ReadOnlyDocumentWrapper implements WrappedDocument { + + private final Document document; + + public ReadOnlyDocumentWrapper(@Nonnull Document document) { + this.document = document; + } + + @Override + public Document getWrappedDocument() { + return document; + } + + @Override + public boolean isReadonly() { + return true; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java new file mode 100644 index 000000000..4cbb0a0f9 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java @@ -0,0 +1,62 @@ +package net.codingarea.commons.common.config.document.wrapper; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.File; +import java.nio.file.Path; + +public class FileDocumentWrapper implements WrappedDocument, FileDocument { + + protected final Document document; + protected final File file; + + public FileDocumentWrapper(@Nonnull File file, @Nonnull Document document) { + this.file = file; + this.document = document; + } + + @Override + public Document getWrappedDocument() { + return document; + } + + @Nonnull + @Override + public File getFile() { + return file; + } + + @Nonnull + @Override + public Path getPath() { + return file.toPath(); + } + + @Nonnull + @Override + public FileDocument set(@Nonnull String path, @Nullable Object value) { + return WrappedDocument.super.set(path, value); + } + + @Nonnull + @Override + public FileDocument set(@Nonnull Object value) { + return WrappedDocument.super.set(value); + } + + @Nonnull + @Override + public FileDocument clear() { + return WrappedDocument.super.clear(); + } + + @Nonnull + @Override + public FileDocument remove(@Nonnull String path) { + return WrappedDocument.super.remove(path); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java new file mode 100644 index 000000000..989c393e4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java @@ -0,0 +1,510 @@ +package net.codingarea.commons.common.config.document.wrapper; + + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.Propertyable; +import net.codingarea.commons.common.version.Version; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Function; + +public interface WrappedDocument extends Document { + + Document getWrappedDocument(); + + @Override + default boolean isReadonly() { + return getWrappedDocument().isReadonly(); + } + + @Nonnull + @Override + default Document getDocument(@Nonnull String path) { + return getWrappedDocument().getDocument(path); + } + + @Nonnull + @Override + default List getDocumentList(@Nonnull String path) { + return getWrappedDocument().getDocumentList(path); + } + + @Nonnull + @Override + default List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { + return getWrappedDocument().getSerializableList(path, classOfT); + } + + @Nonnull + @Override + default D set(@Nonnull String path, @Nullable Object value) { + getWrappedDocument().set(path, value); + return self(); + } + + @Nonnull + @Override + default D set(@Nonnull Object value) { + getWrappedDocument().set(value); + return self(); + } + + @Nonnull + @Override + default D clear() { + getWrappedDocument().clear(); + return self(); + } + + @Nonnull + @Override + default D remove(@Nonnull String path) { + getWrappedDocument().remove(path); + return self(); + } + + @Override + default void write(@Nonnull Writer writer) throws IOException { + getWrappedDocument().write(writer); + } + + @Override + default void saveToFile(@Nonnull File file) throws IOException { + getWrappedDocument().saveToFile(file); + } + + @Nonnull + @Override + default String toJson() { + return getWrappedDocument().toJson(); + } + + @Nonnull + @Override + default String toPrettyJson() { + return getWrappedDocument().toPrettyJson(); + } + + @Override + default T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return getWrappedDocument().getInstance(path, classOfT); + } + + @Override + default T toInstanceOf(@Nonnull Class classOfT) { + return getWrappedDocument().toInstanceOf(classOfT); + } + + @Nullable + @Override + default Object getObject(@Nonnull String path) { + return getWrappedDocument().getObject(path); + } + + @Nonnull + @Override + default Object getObject(@Nonnull String path, @Nonnull Object def) { + return getWrappedDocument().getObject(path, def); + } + + @Nonnull + @Override + default Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { + return getWrappedDocument().getOptional(key, extractor); + } + + @Nullable + @Override + default String getString(@Nonnull String path) { + return getWrappedDocument().getString(path); + } + + @Nonnull + @Override + default String getString(@Nonnull String path, @Nonnull String def) { + return getWrappedDocument().getString(path, def); + } + + @Override + default char getChar(@Nonnull String path) { + return getWrappedDocument().getChar(path); + } + + @Override + default char getChar(@Nonnull String path, char def) { + return getWrappedDocument().getChar(path, def); + } + + @Override + default long getLong(@Nonnull String path) { + return getWrappedDocument().getLong(path); + } + + @Override + default long getLong(@Nonnull String path, long def) { + return getWrappedDocument().getLong(path, def); + } + + @Override + default int getInt(@Nonnull String path) { + return getWrappedDocument().getInt(path); + } + + @Override + default int getInt(@Nonnull String path, int def) { + return getWrappedDocument().getInt(path, def); + } + + @Override + default short getShort(@Nonnull String path) { + return getWrappedDocument().getShort(path); + } + + @Override + default short getShort(@Nonnull String path, short def) { + return getWrappedDocument().getShort(path, def); + } + + @Override + default byte getByte(@Nonnull String path) { + return getWrappedDocument().getByte(path); + } + + @Override + default byte getByte(@Nonnull String path, byte def) { + return getWrappedDocument().getByte(path, def); + } + + @Override + default float getFloat(@Nonnull String path) { + return getWrappedDocument().getFloat(path); + } + + @Override + default float getFloat(@Nonnull String path, float def) { + return getWrappedDocument().getFloat(path, def); + } + + @Override + default double getDouble(@Nonnull String path) { + return getWrappedDocument().getDouble(path); + } + + @Override + default double getDouble(@Nonnull String path, double def) { + return getWrappedDocument().getDouble(path, def); + } + + @Override + default boolean getBoolean(@Nonnull String path) { + return getWrappedDocument().getBoolean(path); + } + + @Override + default boolean getBoolean(@Nonnull String path, boolean def) { + return getWrappedDocument().getBoolean(path, def); + } + + @Nonnull + @Override + default List getStringList(@Nonnull String path) { + return getWrappedDocument().getStringList(path); + } + + @Nonnull + @Override + default String[] getStringArray(@Nonnull String path) { + return getWrappedDocument().getStringArray(path); + } + + @Nonnull + @Override + default List mapList(@Nonnull String path, @Nonnull Function mapper) { + return getWrappedDocument().mapList(path, mapper); + } + + @Nonnull + @Override + default > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { + return getWrappedDocument().getEnumList(path, classOfEnum); + } + + @Nonnull + @Override + default List getUUIDList(@Nonnull String path) { + return getWrappedDocument().getUUIDList(path); + } + + @Nonnull + @Override + default List getCharacterList(@Nonnull String path) { + return getWrappedDocument().getCharacterList(path); + } + + @Nonnull + @Override + default List getByteList(@Nonnull String path) { + return getWrappedDocument().getByteList(path); + } + + @Nonnull + @Override + default List getShortList(@Nonnull String path) { + return getWrappedDocument().getShortList(path); + } + + @Nonnull + @Override + default List getIntegerList(@Nonnull String path) { + return getWrappedDocument().getIntegerList(path); + } + + @Nonnull + @Override + default List getLongList(@Nonnull String path) { + return getWrappedDocument().getLongList(path); + } + + @Nonnull + @Override + default List getFloatList(@Nonnull String path) { + return getWrappedDocument().getFloatList(path); + } + + @Nonnull + @Override + default List getDoubleList(@Nonnull String path) { + return getWrappedDocument().getDoubleList(path); + } + + @Nullable + @Override + default UUID getUUID(@Nonnull String path) { + return getWrappedDocument().getUUID(path); + } + + @Nonnull + @Override + default UUID getUUID(@Nonnull String path, @Nonnull UUID def) { + return getWrappedDocument().getUUID(path, def); + } + + @Nullable + @Override + default Date getDate(@Nonnull String path) { + return getWrappedDocument().getDate(path); + } + + @Nonnull + @Override + default Date getDate(@Nonnull String path, @Nonnull Date def) { + return getWrappedDocument().getDate(path, def); + } + + @Nullable + @Override + default OffsetDateTime getDateTime(@Nonnull String path) { + return getWrappedDocument().getDateTime(path); + } + + @Nonnull + @Override + default OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { + return getWrappedDocument().getDateTime(path, def); + } + + @Nullable + @Override + default Color getColor(@Nonnull String path) { + return getWrappedDocument().getColor(path); + } + + @Nonnull + @Override + default Color getColor(@Nonnull String path, @Nonnull Color def) { + return getWrappedDocument().getColor(path, def); + } + + @Nullable + @Override + default > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return getWrappedDocument().getEnum(path, classOfEnum); + } + + @Nonnull + @Override + default > E getEnum(@Nonnull String path, @Nonnull E def) { + return getWrappedDocument().getEnum(path, def); + } + + @Nullable + @Override + default T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + return getWrappedDocument().getSerializable(path, classOfT); + } + + @Nonnull + @Override + default T getSerializable(@Nonnull String path, @Nonnull T def) { + return getWrappedDocument().getSerializable(path, def); + } + + @Nullable + @Override + default Class getClass(@Nonnull String path) { + return getWrappedDocument().getClass(path); + } + + @Nonnull + @Override + default Class getClass(@Nonnull String path, @Nonnull Class def) { + return getWrappedDocument().getClass(path, def); + } + + @Nullable + @Override + default Version getVersion(@Nonnull String path) { + return getWrappedDocument().getVersion(path); + } + + @Nonnull + @Override + default Version getVersion(@Nonnull String path, @Nonnull Version def) { + return getWrappedDocument().getVersion(path, def); + } + + @Nullable + @Override + default byte[] getBinary(@Nonnull String path) { + return getWrappedDocument().getBinary(path); + } + + @Override + default boolean contains(@Nonnull String path) { + return getWrappedDocument().contains(path); + } + + @Override + default boolean hasChildren(@Nonnull String path) { + return getWrappedDocument().hasChildren(path); + } + + @Override + default boolean isObject(@Nonnull String path) { + return getWrappedDocument().isObject(path); + } + + @Override + default boolean isList(@Nonnull String path) { + return getWrappedDocument().isList(path); + } + + @Override + default boolean isDocument(@Nonnull String path) { + return getWrappedDocument().isDocument(path); + } + + @Override + default boolean isEmpty() { + return getWrappedDocument().isEmpty(); + } + + @Override + default int size() { + return getWrappedDocument().size(); + } + + @Nonnull + @Override + default Map values() { + return getWrappedDocument().values(); + } + + @Nonnull + @Override + default Map valuesAsStrings() { + return getWrappedDocument().valuesAsStrings(); + } + + @Nonnull + @Override + default Map children() { + return getWrappedDocument().children(); + } + + @Nonnull + @Override + default Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return getWrappedDocument().mapValues(keyMapper, valueMapper); + } + + @Nonnull + @Override + default Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return getWrappedDocument().mapDocuments(keyMapper, valueMapper); + } + + @Nonnull + @Override + default R mapDocument(@Nonnull String path, @Nonnull Function mapper) { + return getWrappedDocument().mapDocument(path, mapper); + } + + @Nullable + @Override + default R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { + return getWrappedDocument().mapDocumentNullable(path, mapper); + } + + @Nonnull + @Override + default Collection keys() { + return getWrappedDocument().keys(); + } + + @Nonnull + @Override + default Set> entrySet() { + return getWrappedDocument().entrySet(); + } + + @Override + default void forEach(@Nonnull BiConsumer action) { + getWrappedDocument().forEach(action); + } + + @Nonnull + @Override + default Document readonly() { + return getWrappedDocument().readonly(); + } + + @Nullable + @Override + default Document getParent() { + return getWrappedDocument().getParent(); + } + + @Nonnull + @Override + default Document getRoot() { + return getWrappedDocument().getRoot(); + } + + @SuppressWarnings("unchecked") + default D self() { + return (D) this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java b/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java new file mode 100644 index 000000000..7fa62c991 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java @@ -0,0 +1,11 @@ +package net.codingarea.commons.common.config.exceptions; + +import javax.annotation.Nonnull; + +public final class ConfigReadOnlyException extends IllegalStateException { + + public ConfigReadOnlyException(@Nonnull String action) { + super("Config." + action); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java b/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java new file mode 100644 index 000000000..2af90f2c1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java @@ -0,0 +1,50 @@ +package net.codingarea.commons.common.debug; + +import net.codingarea.commons.common.collection.NumberFormatter; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.misc.ReflectionUtils; + +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public final class TimingsHelper { + + public static final ILogger LOGGER = ILogger.forThisClass(); + private static final Map timings = new ConcurrentHashMap<>(); + + private TimingsHelper() {} + + public static void start(@Nonnull String id) { + timings.put(id, System.currentTimeMillis()); + } + + public static void stop(@Nonnull String id) { + Long start = timings.remove(id); + if (start == null) { + LOGGER.warn("Stopped timing {} which was not started before", id); + return; + } + + long time = System.currentTimeMillis() - start; + LOGGER.debug("Finished timings '{}' within {}ms ({}s)", id, time, NumberFormatter.DOUBLE_FLOATING_POINT.format(time / 1000d)); + } + + public static void restart(@Nonnull String id) { + stop(id); + start(id); + } + + public static void start() { + start(ReflectionUtils.getCallerName()); + } + + public static void stop() { + stop(ReflectionUtils.getCallerName()); + } + + public static void restart() { + restart(ReflectionUtils.getCallerName()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java new file mode 100644 index 000000000..49eeec955 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java @@ -0,0 +1,498 @@ +package net.codingarea.commons.common.discord; + +import net.codingarea.commons.common.config.Document; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.net.ssl.HttpsURLConnection; +import java.awt.*; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.function.Function; + +public class DiscordWebhook { + + protected String url; + protected String content; + protected String username; + protected String avatarUrl; + protected boolean tts; + protected List embeds = new ArrayList<>(); + + private DiscordWebhook() { + } + + /** + * Constructs a new DiscordWebhook instance + * + * @param url The webhook URL obtained in Discord + */ + public DiscordWebhook(@Nonnull String url) { + this.url = url; + } + + public DiscordWebhook(@Nonnull String url, @Nonnull String username) { + this.url = url; + this.username = username; + } + + public DiscordWebhook(@Nonnull String url, @Nonnull String username, @Nonnull String avatarUrl) { + this.url = url; + this.username = username; + this.avatarUrl = avatarUrl; + } + + public DiscordWebhook(@Nonnull String url, @Nonnull String username, @Nonnull String avatarUrl, @Nonnull String content, @Nonnull List embeds, boolean tts) { + this.url = url; + this.username = username; + this.avatarUrl = avatarUrl; + this.content = content; + this.embeds = embeds; + this.tts = tts; + } + + @Nonnull + public DiscordWebhook setUrl(@Nonnull String url) { + this.url = url; + return this; + } + + @Nonnull + public DiscordWebhook setContent(@Nullable String content) { + this.content = content; + return this; + } + + @Nonnull + public DiscordWebhook setUsername(@Nullable String username) { + this.username = username; + return this; + } + + @Nonnull + public DiscordWebhook setAvatarUrl(@Nullable String avatarUrl) { + this.avatarUrl = avatarUrl; + return this; + } + + @Nonnull + public DiscordWebhook setTts(boolean tts) { + this.tts = tts; + return this; + } + + @Nonnull + public DiscordWebhook addEmbed(EmbedObject embed) { + this.embeds.add(embed); + return this; + } + + public void execute() throws IOException { + if (content == null && embeds.isEmpty()) + throw new IllegalArgumentException("Set content or add at least one EmbedObject"); + + Document json = Document.create(); + + json.set("content", content); + json.set("username", username); + json.set("avatar_url", avatarUrl); + json.set("tts", tts); + + if (!embeds.isEmpty()) { + List embedObjects = new ArrayList<>(); + + for (EmbedObject embed : embeds) { + Document jsonEmbed = Document.create(); + + jsonEmbed.set("title", embed.getTitle()); + jsonEmbed.set("description", embed.getDescription()); + jsonEmbed.set("url", embed.getUrl()); + + if (embed.getColor() != null) { + Color color = embed.getColor(); + int rgb = color.getRed(); + rgb = (rgb << 8) + color.getGreen(); + rgb = (rgb << 8) + color.getBlue(); + + jsonEmbed.set("color", rgb); + } + + EmbedObject.Footer footer = embed.getFooter(); + EmbedObject.Image image = embed.getImage(); + EmbedObject.Thumbnail thumbnail = embed.getThumbnail(); + EmbedObject.Author author = embed.getAuthor(); + List fields = embed.getFields(); + + if (footer != null) { + Document jsonFooter =Document.create(); + + jsonFooter.set("text", footer.getText()); + jsonFooter.set("icon_url", footer.getIconUrl()); + jsonEmbed.set("footer", jsonFooter); + } + + if (image != null) { + Document jsonImage = Document.create(); + + jsonImage.set("url", image.getUrl()); + jsonEmbed.set("image", jsonImage); + } + + if (thumbnail != null) { + Document jsonThumbnail = Document.create(); + + jsonThumbnail.set("url", thumbnail.getUrl()); + jsonEmbed.set("thumbnail", jsonThumbnail); + } + + if (author != null) { + Document jsonAuthor = Document.create(); + + jsonAuthor.set("name", author.getName()); + jsonAuthor.set("url", author.getUrl()); + jsonAuthor.set("icon_url", author.getIconUrl()); + jsonEmbed.set("author", jsonAuthor); + } + + List jsonFields = new ArrayList<>(); + for (EmbedObject.Field field : fields) { + Document jsonField = Document.create(); + + jsonField.set("name", field.getName()); + jsonField.set("value", field.getValue()); + jsonField.set("inline", field.isInline()); + + jsonFields.add(jsonField); + } + + jsonEmbed.set("fields", jsonFields.toArray()); + embedObjects.add(jsonEmbed); + } + + json.set("embeds", embedObjects.toArray()); + } + + URL url = new URL(this.url); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setDoInput(true); + connection.setConnectTimeout(2500); + connection.setReadTimeout(1000); + connection.setRequestProperty("User-Agent", "Mozilla/5.0"); + connection.setRequestProperty("Accept", "*/*"); + connection.setRequestProperty("Content-Type", "application/json"); + + OutputStream output = connection.getOutputStream(); + output.write(json.toString().getBytes(StandardCharsets.UTF_8)); + output.flush(); + output.close(); + + connection.getInputStream().close(); + connection.disconnect(); + } + + @Nonnull + public DiscordWebhook replaceEverywhere(@Nonnull String trigger, @Nonnull String replacement) { + if (content != null) content = content.replace(trigger, replacement); + if (username != null) username = username.replace(trigger, replacement); + for (EmbedObject embed : embeds) { + if (embed.author.name != null) embed.author.name = embed.author.name.replace(trigger, replacement); + if (embed.description != null) embed.description = embed.description.replace(trigger, replacement); + if (embed.title != null) embed.title = embed.title.replace(trigger, replacement); + if (embed.footer.text != null) embed.footer.text = embed.footer.text.replace(trigger, replacement); + for (EmbedObject.Field field : embed.fields) { + if (field.name != null) field.name = field.name.replace(trigger, replacement); + if (field.value != null) field.value = field.value.replace(trigger, replacement); + } + } + return this; + } + + public static class EmbedObject { + + protected String title; + protected String description; + protected String url; + protected Color color; + + protected Footer footer; + protected Thumbnail thumbnail; + protected Image image; + protected Author author; + protected List fields = new ArrayList<>(); + + public EmbedObject() { + } + + public EmbedObject(@Nullable String title, @Nullable String description, @Nullable String url, @Nullable Color color, + @Nullable Footer footer, @Nullable Thumbnail thumbnail, @Nullable Image image, @Nullable Author author, + @Nonnull List fields) { + this.title = title; + this.description = description; + this.url = url; + this.color = color; + this.footer = footer; + this.thumbnail = thumbnail; + this.image = image; + this.author = author; + this.fields = fields; + } + + public String getTitle() { + return title; + } + + public String getDescription() { + return description; + } + + public String getUrl() { + return url; + } + + public Color getColor() { + return color; + } + + public Footer getFooter() { + return footer; + } + + public Thumbnail getThumbnail() { + return thumbnail; + } + + public Image getImage() { + return image; + } + + public Author getAuthor() { + return author; + } + + public List getFields() { + return fields; + } + + @Nonnull + public EmbedObject setTitle(String title) { + this.title = title; + return this; + } + + @Nonnull + public EmbedObject setDescription(String description) { + this.description = description; + return this; + } + + @Nonnull + public EmbedObject setUrl(String url) { + this.url = url; + return this; + } + + @Nonnull + public EmbedObject setColor(Color color) { + this.color = color; + return this; + } + + @Nonnull + public EmbedObject setFooter(String text, String icon) { + this.footer = new Footer(text, icon); + return this; + } + + @Nonnull + public EmbedObject setThumbnail(String url) { + this.thumbnail = new Thumbnail(url); + return this; + } + + @Nonnull + public EmbedObject setImage(String url) { + this.image = new Image(url); + return this; + } + + @Nonnull + public EmbedObject setAuthor(String name, String url, String icon) { + this.author = new Author(name, url, icon); + return this; + } + + @Nonnull + public EmbedObject addField(String name, String value, boolean inline) { + this.fields.add(new Field(name, value, inline)); + return this; + } + + @Override + public EmbedObject clone() { + return new EmbedObject( + title, description, url, color, + footer == null ? null : footer.clone(), + thumbnail == null ? null : thumbnail.clone(), + image == null ? null : image.clone(), + author == null ? null : author.clone(), + DiscordWebhook.clone(fields, Field::clone) + ); + } + + public static class Footer { + + protected String text; + protected String iconUrl; + + private Footer() { + } + + public Footer(String text, String iconUrl) { + this.text = text; + this.iconUrl = iconUrl; + } + + private String getText() { + return text; + } + + private String getIconUrl() { + return iconUrl; + } + + @Override + protected Footer clone() { + return new Footer(text, iconUrl); + } + } + + public static class Thumbnail { + + private String url; + + private Thumbnail() { + } + + public Thumbnail(String url) { + this.url = url; + } + + private String getUrl() { + return url; + } + + @Override + protected Thumbnail clone() { + return new Thumbnail(url); + } + } + + public static class Image { + + private String url; + + private Image() { + } + + public Image(String url) { + this.url = url; + } + + private String getUrl() { + return url; + } + + @Override + public Image clone() { + return new Image(url); + } + } + + public static class Author { + + private String name; + private String url; + private String iconUrl; + + private Author() { + } + + public Author(String name, String url, String iconUrl) { + this.name = name; + this.url = url; + this.iconUrl = iconUrl; + } + + private String getName() { + return name; + } + + private String getUrl() { + return url; + } + + private String getIconUrl() { + return iconUrl; + } + + @Override + protected Author clone() { + return new Author(name, url, iconUrl); + } + } + + public static class Field { + + private String name; + private String value; + private boolean inline; + + private Field() { + } + + private Field(String name, String value, boolean inline) { + this.name = name; + this.value = value; + this.inline = inline; + } + + private String getName() { + return name; + } + + private String getValue() { + return value; + } + + private boolean isInline() { + return inline; + } + + @Override + protected Field clone() { + return new Field(name, value, inline); + } + } + } + + @Override + public DiscordWebhook clone() { + return new DiscordWebhook(url, username, avatarUrl, content, clone(embeds, EmbedObject::clone), tts); + } + + @Nonnull + protected static List clone(@Nonnull Collection collection, @Nonnull Function cloner) { + List list = new ArrayList<>(collection.size()); + for (T current : collection) { + list.add(cloner.apply(current)); + } + return list; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiConsumer.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiConsumer.java new file mode 100644 index 000000000..5bca8f733 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiConsumer.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.BiConsumer; + +@FunctionalInterface +public interface ExceptionallyBiConsumer extends BiConsumer { + + @Override + default void accept(T t, U u) { + try { + acceptExceptionally(t, u); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + void acceptExceptionally(T t, U u) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiFunction.java new file mode 100644 index 000000000..6977e1ea6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.BiFunction; + +@FunctionalInterface +public interface ExceptionallyBiFunction extends BiFunction { + + @Override + default R apply(T t, U u) { + try { + return applyExceptionally(t, u); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + R applyExceptionally(T t, U u) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyConsumer.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyConsumer.java new file mode 100644 index 000000000..99f90b68d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyConsumer.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.Consumer; + +@FunctionalInterface +public interface ExceptionallyConsumer extends Consumer { + + @Override + default void accept(T t) { + try { + acceptExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + void acceptExceptionally(T t) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyDoubleFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyDoubleFunction.java new file mode 100644 index 000000000..007c6d3e7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyDoubleFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.DoubleFunction; + +@FunctionalInterface +public interface ExceptionallyDoubleFunction extends DoubleFunction { + + @Override + default R apply(double value) { + try { + return applyExceptionally(value); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + R applyExceptionally(double value) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java new file mode 100644 index 000000000..182afce47 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java @@ -0,0 +1,29 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.util.function.Function; + +@FunctionalInterface +public interface ExceptionallyFunction extends Function { + + @Override + default R apply(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + R applyExceptionally(T t) throws Exception; + + @Nonnull + @CheckReturnValue + static ExceptionallyFunction identity() { + return t -> t; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyIntFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyIntFunction.java new file mode 100644 index 000000000..c15637c63 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyIntFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.IntFunction; + +@FunctionalInterface +public interface ExceptionallyIntFunction extends IntFunction { + + @Override + default R apply(int value) { + try { + return applyExceptionally(value); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + R applyExceptionally(int value) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyLongFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyLongFunction.java new file mode 100644 index 000000000..e3cd46a66 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyLongFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.LongFunction; + +@FunctionalInterface +public interface ExceptionallyLongFunction extends LongFunction { + + @Override + default R apply(long value) { + try { + return applyExceptionally(value); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + R applyExceptionally(long value) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyRunnable.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyRunnable.java new file mode 100644 index 000000000..b15ce02c7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyRunnable.java @@ -0,0 +1,27 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.concurrent.Callable; + +@FunctionalInterface +public interface ExceptionallyRunnable extends Runnable, Callable { + + @Override + default void run() { + try { + runExceptionally(); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + @Override + default Void call() throws Exception { + runExceptionally(); + return null; + } + + void runExceptionally() throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallySupplier.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallySupplier.java new file mode 100644 index 000000000..5aab4b750 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallySupplier.java @@ -0,0 +1,27 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.concurrent.Callable; +import java.util.function.Supplier; + +@FunctionalInterface +public interface ExceptionallySupplier extends Supplier, Callable { + + @Override + default T get() { + try { + return getExceptionally(); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + @Override + default T call() throws Exception { + return getExceptionally(); + } + + T getExceptionally() throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToDoubleFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToDoubleFunction.java new file mode 100644 index 000000000..759fd6f38 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToDoubleFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.ToDoubleFunction; + +@FunctionalInterface +public interface ExceptionallyToDoubleFunction extends ToDoubleFunction { + + @Override + default double applyAsDouble(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + double applyExceptionally(T T) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToIntFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToIntFunction.java new file mode 100644 index 000000000..98e5520e9 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToIntFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.ToIntFunction; + +@FunctionalInterface +public interface ExceptionallyToIntFunction extends ToIntFunction { + + @Override + default int applyAsInt(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + int applyExceptionally(T t) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToLongFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToLongFunction.java new file mode 100644 index 000000000..6ace6ef31 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToLongFunction.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.common.function; + +import net.codingarea.commons.common.collection.WrappedException; + +import java.util.function.ToLongFunction; + +@FunctionalInterface +public interface ExceptionallyToLongFunction extends ToLongFunction { + + @Override + default long applyAsLong(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } + + long applyExceptionally(T t) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java new file mode 100644 index 000000000..02ec550a7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java @@ -0,0 +1,282 @@ +package net.codingarea.commons.common.logging; + +import com.google.common.base.Preconditions; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.logging.internal.FallbackLogger; +import net.codingarea.commons.common.logging.internal.JavaLoggerWrapper; +import net.codingarea.commons.common.logging.internal.SimpleLogger; +import net.codingarea.commons.common.logging.internal.Slf4jLoggerWrapper; +import net.codingarea.commons.common.logging.internal.factory.ConstantLoggerFactory; +import net.codingarea.commons.common.logging.internal.factory.DefaultLoggerFactory; +import net.codingarea.commons.common.logging.internal.factory.Slf4jLoggerFactory; +import net.codingarea.commons.common.logging.lib.JavaILogger; +import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import net.codingarea.commons.common.misc.ReflectionUtils; +import org.slf4j.LoggerFactory; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.util.ServiceLoader; + +public interface ILogger { + + final class Holder { + + private static ILoggerFactory factory; + private static Data data; + + private static class Data { + private boolean slf4j, slf4jApi; + } + + @Nonnull + private static Data getData() { + if (data == null) + createData(); + + return data; + } + + private static synchronized void createData() { + boolean slf4j = false; + boolean slf4jApi = true; + + try { + Class.forName("org.slf4j.impl.StaticLoggerBinder"); + slf4j = true; + } catch (ClassNotFoundException eStatic) { // there was no static logger binder (SLF4J pre-1.8.x) + try { + Class serviceProviderInterface = Class.forName("org.slf4j.spi.SLF4JServiceProvider"); + // check if there is a service implementation for the service, indicating a provider for SLF4J 1.8.x+ is installed + slf4j = ServiceLoader.load(serviceProviderInterface).iterator().hasNext(); + } catch (ClassNotFoundException eService) { // there was no service provider interface (SLF4J 1.8.x+) + try { + // prints warning of missing implementation + LoggerFactory.getLogger(ILogger.class); + } catch (NoClassDefFoundError eApi) { + slf4jApi = false; + } + } + } + + data = new Data(); + data.slf4j = slf4j; + data.slf4jApi = slf4jApi; + } + + @Nonnull + public static ILoggerFactory getFactory() { + if (factory == null) + factory = getFallbackFactory(); + + return factory; + } + + @Nonnull + private static ILoggerFactory getFallbackFactory() { + return isSlf4jImplAvailable() ? new Slf4jLoggerFactory() : + isSlf4jApiAvailable() ? new DefaultLoggerFactory(SimpleLogger::new) : + new DefaultLoggerFactory(FallbackLogger::new); + } + + private Holder() {} + + } + + static boolean isSlf4jImplAvailable() { + return Holder.getData().slf4j; + } + + static boolean isSlf4jApiAvailable() { + return Holder.getData().slf4jApi; + } + + @Nonnull + @CheckReturnValue + static ILogger forName(@Nullable String name) { + return getFactory().forName(name); + } + + @Nonnull + @CheckReturnValue + static ILogger forClass(@Nullable Class clazz) { + return forName(clazz == null ? null : clazz.getSimpleName()); + } + + @Nonnull + @CheckReturnValue + static ILogger forClassOf(@Nonnull Object object) { + return forClass(object.getClass()); + } + + @Nonnull + @CheckReturnValue + static ILogger forThisClass() { + return forClass(ReflectionUtils.getCaller()); + } + + @Nonnull + @CheckReturnValue + static JavaILogger forJavaLogger(@Nonnull java.util.logging.Logger logger) { + return new JavaLoggerWrapper(logger); + } + + @Nonnull + @CheckReturnValue + static ILogger forSlf4jLogger(@Nonnull org.slf4j.Logger logger) { + return logger instanceof ILogger ? (ILogger) logger : new Slf4jLoggerWrapper(logger); + } + + static void setFactory(@Nonnull ILoggerFactory factory) { + Preconditions.checkNotNull(factory); + Holder.factory = factory; + } + + static void setConstantFactory(@Nonnull ILogger logger) { + setFactory(new ConstantLoggerFactory(logger)); + } + + @Nonnull + static ILoggerFactory getFactory() { + return Holder.getFactory(); + } + + void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args); + + default void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + log(level, String.valueOf(message), args); + } + + default void error(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + default void error(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + default void warn(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + default void warn(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + default void info(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + default void info(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + default void status(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + default void status(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + default void extended(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.EXTENDED, message, args); + } + + default void extended(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.EXTENDED, message, args); + } + + default void debug(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + default void debug(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + default void trace(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.TRACE, message, args); + } + + default void trace(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.TRACE, message, args); + } + + default boolean isLevelEnabled(@Nonnull LogLevel level) { + return level.isShownAtLoggerLevel(getMinLevel()); + } + + default boolean isTraceEnabled() { + return isLevelEnabled(LogLevel.TRACE); + } + + default boolean isDebugEnabled() { + return isLevelEnabled(LogLevel.DEBUG); + } + + default boolean isExtendedEnabled() { + return isLevelEnabled(LogLevel.EXTENDED); + } + + default boolean isInfoEnabled() { + return isLevelEnabled(LogLevel.INFO); + } + + default boolean isWarnEnabled() { + return isLevelEnabled(LogLevel.WARN); + } + + default boolean isErrorEnabled() { + return isLevelEnabled(LogLevel.ERROR); + } + + @Nonnull + LogLevel getMinLevel(); + + @Nonnull + ILogger setMinLevel(@Nonnull LogLevel level); + + @Nonnull + @CheckReturnValue + default Slf4jILogger slf4j() { + if (this instanceof Slf4jILogger) + return (Slf4jILogger) this; + throw new IllegalStateException(this.getClass().getName() + " cannot be converted to Slf4jILogger"); + } + + @Nonnull + @CheckReturnValue + default JavaILogger java() { + if (this instanceof JavaILogger) + return (JavaILogger) this; + throw new IllegalStateException(this.getClass().getName() + " cannot be converted to JavaILogger"); + } + + @Nonnull + @CheckReturnValue + default PrintStream asPrintStream(@Nonnull LogLevel level) { + try { + return new PrintStream(new LogOutputStream(this, level), true, StandardCharsets.UTF_8.name()); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + static String formatMessage(@Nullable Object messageObject, @Nonnull Object... args) { + StringBuilder message = new StringBuilder(String.valueOf(messageObject)); + for (Object arg : args) { + if (arg instanceof Throwable) continue; + int index = message.indexOf("{}"); + if (index == -1) break; + message.replace(index, index+2, String.valueOf(arg)); + } + return message.toString(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java new file mode 100644 index 000000000..fed7742e6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java @@ -0,0 +1,15 @@ +package net.codingarea.commons.common.logging; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface ILoggerFactory { + + @Nonnull + @CheckReturnValue + ILogger forName(@Nullable String name); + + void setDefaultLevel(@Nonnull LogLevel level); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java new file mode 100644 index 000000000..ddf6d01c8 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java @@ -0,0 +1,82 @@ +package net.codingarea.commons.common.logging; + +import javax.annotation.Nonnull; +import java.util.logging.Level; + +public enum LogLevel { + + TRACE (0, "TRACE", "trace", Level.FINEST, false), + DEBUG (2, "DEBUG", "debug", Level.FINER, false), + EXTENDED(5, "EXTENDED", "extended", Level.FINE, false), + STATUS (7, "STATUS", "status", Level.CONFIG, false), + INFO (10, "INFO", "info", Level.INFO, false), + WARN (15, "WARN", "warn", Level.WARNING, true), + ERROR (25, "ERROR", "error", Level.SEVERE, true); + + private final String uppercaseName, lowercaseName; + private final Level javaLevel; + private final int value; + private final boolean highlighted; + + LogLevel(int value, @Nonnull String uppercaseName, @Nonnull String lowercaseName, @Nonnull Level javaLevel, boolean highlighted) { + this.uppercaseName = uppercaseName; + this.lowercaseName = lowercaseName; + this.javaLevel = javaLevel; + this.value = value; + this.highlighted = highlighted; + } + + @Nonnull + public Level getJavaUtilLevel() { + return javaLevel; + } + + public boolean isShownAtLoggerLevel(@Nonnull LogLevel loggerLevel) { + return this.getValue() >= loggerLevel.getValue(); + } + + public int getValue() { + return value; + } + + @Nonnull + public String getLowerCaseName() { + return lowercaseName; + } + + @Nonnull + public String getUpperCaseName() { + return uppercaseName; + } + + public boolean isHighlighted() { + return highlighted; + } + + @Nonnull + public static LogLevel fromJavaLevel(@Nonnull Level level) { + for (LogLevel logLevel : values()) { + if (logLevel.getJavaUtilLevel().intValue() == level.intValue()) + return logLevel; + } + return INFO; + } + + @Nonnull + public static LogLevel fromValue(int value) { + for (LogLevel level : values()) { + if (level.getValue() == value) + return level; + } + return INFO; + } + + @Nonnull + public static LogLevel fromName(@Nonnull String name) { + for (LogLevel level : values()) { + if (level.getUpperCaseName().equalsIgnoreCase(name)) + return level; + } + return INFO; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java new file mode 100644 index 000000000..7095492ed --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java @@ -0,0 +1,28 @@ +package net.codingarea.commons.common.logging; + +import javax.annotation.Nonnull; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +public class LogOutputStream extends ByteArrayOutputStream { + + private final ILogger logger; + private final LogLevel level; + + public LogOutputStream(@Nonnull ILogger logger, @Nonnull LogLevel level) { + this.logger = logger; + this.level = level; + } + + @Override + public void flush() throws IOException { + String input = this.toString(StandardCharsets.UTF_8.name()); + this.reset(); + + if (input != null && !input.isEmpty() && !input.equals(System.lineSeparator())) { + logger.log(level, input); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java new file mode 100644 index 000000000..06deb942a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.common.logging; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface LoggingApiUser { + + @Nonnull + ILogger getTargetLogger(); + + default void error(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().error(message, args); + } + + default void warn(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().warn(message, args); + } + + default void info(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().info(message, args); + } + + default void status(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().status(message, args); + } + + default void extended(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().extended(message, args); + } + + default void debug(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().debug(message, args); + } + + default void trace(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().trace(message, args); + } + + default boolean isTraceEnabled() { + return getTargetLogger().isTraceEnabled(); + } + + default boolean isDebugEnabled() { + return getTargetLogger().isDebugEnabled(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java new file mode 100644 index 000000000..c4731eead --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java @@ -0,0 +1,159 @@ +package net.codingarea.commons.common.logging; + +import net.codingarea.commons.common.logging.lib.JavaILogger; +import net.codingarea.commons.common.logging.lib.Slf4jILogger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.PrintStream; + +public interface WrappedILogger extends ILogger { + + @Nonnull + ILogger getWrappedLogger(); + + @Override + default void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + getWrappedLogger().log(level, message, args); + } + + @Override + default void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().log(level, message, args); + } + + @Override + default void error(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().error(message, args); + } + + @Override + default void error(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().error(message, args); + } + + @Override + default void warn(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().warn(message, args); + } + + @Override + default void warn(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().warn(message, args); + } + + @Override + default void info(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().info(message, args); + } + + @Override + default void info(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().info(message, args); + } + + @Override + default void status(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().status(message, args); + } + + @Override + default void status(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().status(message, args); + } + + @Override + default void extended(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().extended(message, args); + } + + @Override + default void extended(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().extended(message, args); + } + + @Override + default void debug(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().debug(message, args); + } + + @Override + default void debug(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().debug(message, args); + } + + @Override + default void trace(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().trace(message, args); + } + + @Override + default void trace(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().trace(message, args); + } + + @Override + default boolean isLevelEnabled(@Nonnull LogLevel level) { + return getWrappedLogger().isLevelEnabled(level); + } + + @Override + default boolean isTraceEnabled() { + return getWrappedLogger().isTraceEnabled(); + } + + @Override + default boolean isDebugEnabled() { + return getWrappedLogger().isDebugEnabled(); + } + + @Override + default boolean isExtendedEnabled() { + return getWrappedLogger().isExtendedEnabled(); + } + + @Override + default boolean isInfoEnabled() { + return getWrappedLogger().isInfoEnabled(); + } + + @Override + default boolean isWarnEnabled() { + return getWrappedLogger().isWarnEnabled(); + } + + @Override + default boolean isErrorEnabled() { + return getWrappedLogger().isErrorEnabled(); + } + + @Nonnull + @Override + default LogLevel getMinLevel() { + return getWrappedLogger().getMinLevel(); + } + + @Nonnull + @Override + default ILogger setMinLevel(@Nonnull LogLevel level) { + return getWrappedLogger().setMinLevel(level); + } + + @Nonnull + @Override + default Slf4jILogger slf4j() { + return getWrappedLogger().slf4j(); + } + + @Nonnull + @Override + default JavaILogger java() { + return getWrappedLogger().java(); + } + + @Nonnull + @Override + default PrintStream asPrintStream(@Nonnull LogLevel level) { + return getWrappedLogger().asPrintStream(level); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java new file mode 100644 index 000000000..e19b07015 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java @@ -0,0 +1,23 @@ +package net.codingarea.commons.common.logging.handler; + +import net.codingarea.commons.common.collection.NamedThreadFactory; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +public class HandledAsyncLogger extends HandledLogger { + + protected final Executor executor = Executors.newSingleThreadExecutor(new NamedThreadFactory("AsyncLogTask")); + + public HandledAsyncLogger(@Nonnull LogLevel initialLevel) { + super(initialLevel); + } + + @Override + protected void log0(@Nonnull LogEntry entry) { + executor.execute(() -> logNow(entry)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java new file mode 100644 index 000000000..cde16aac4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java @@ -0,0 +1,69 @@ +package net.codingarea.commons.common.logging.handler; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.time.Instant; +import java.util.Arrays; +import java.util.Collection; +import java.util.concurrent.CopyOnWriteArrayList; + +public abstract class HandledLogger implements ILogger { + + protected final Collection handlers = new CopyOnWriteArrayList<>(); + protected LogLevel level; + + public HandledLogger(@Nonnull LogLevel initialLevel) { + this.level = initialLevel; + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + if (!level.isShownAtLoggerLevel(this.level)) return; + Throwable exception = null; + for (Object arg : args) { + if (arg instanceof Throwable) + exception = (Throwable) arg; + } + log0(new LogEntry(Instant.now(), Thread.currentThread().getName(), ILogger.formatMessage(message, args), level, exception)); + } + + public void log(@Nonnull LogEntry entry) { + if (!entry.getLevel().isShownAtLoggerLevel(this.level)) return; + log0(entry); + } + + protected abstract void log0(@Nonnull LogEntry entry); + + protected void logNow(@Nonnull LogEntry entry) { + for (LogHandler handler : handlers) { + try { + handler.handle(entry); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + @Nonnull + public HandledLogger addHandler(@Nonnull LogHandler... handler) { + handlers.addAll(Arrays.asList(handler)); + return this; + } + + @Nonnull + @Override + public LogLevel getMinLevel() { + return level; + } + + @Nonnull + @Override + public ILogger setMinLevel(@Nonnull LogLevel level) { + this.level = level; + return this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java new file mode 100644 index 000000000..0a62ac68b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java @@ -0,0 +1,17 @@ +package net.codingarea.commons.common.logging.handler; + +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; + +public class HandledSyncLogger extends HandledLogger { + + public HandledSyncLogger(@Nonnull LogLevel initialLevel) { + super(initialLevel); + } + + @Override + protected void log0(@Nonnull LogEntry entry) { + logNow(entry); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java new file mode 100644 index 000000000..5068d301b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java @@ -0,0 +1,49 @@ +package net.codingarea.commons.common.logging.handler; + +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.time.Instant; + +public class LogEntry { + + private Instant timestamp; + private String threadName; + private String message; + private LogLevel level; + private Throwable exception; + + public LogEntry(@Nonnull Instant timestamp, @Nonnull String threadName, @Nonnull String message, @Nonnull LogLevel level, @Nullable Throwable exception) { + this.timestamp = timestamp; + this.threadName = threadName; + this.message = message; + this.level = level; + this.exception = exception; + } + + @Nonnull + public Instant getTimestamp() { + return timestamp; + } + + @Nonnull + public String getThreadName() { + return threadName; + } + + @Nonnull + public String getMessage() { + return message; + } + + @Nonnull + public LogLevel getLevel() { + return level; + } + + @Nullable + public Throwable getException() { + return exception; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java new file mode 100644 index 000000000..36141fed5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.common.logging.handler; + +import javax.annotation.Nonnull; +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +public interface LogHandler { + + DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss.SSS"); + + void handle(@Nonnull LogEntry entry) throws Exception; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java new file mode 100644 index 000000000..711a8ab54 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java @@ -0,0 +1,25 @@ +package net.codingarea.commons.common.logging.internal; + +import javax.annotation.Nonnull; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Because you can't change the level of a plugin logger properly, we create a wrapper for the plugin logger + * and map all levels below {@link Level#INFO} to {@link Level#INFO}, if they are loggable. + */ +public class BukkitLoggerWrapper extends JavaLoggerWrapper { + + public BukkitLoggerWrapper(@Nonnull Logger logger) { + super(logger); + } + + @Nonnull + @Override + protected Level mapLevel(@Nonnull Level level) { + if (isLoggable(level) && level.intValue() < Level.INFO.intValue()) + return Level.INFO; + return level; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java new file mode 100644 index 000000000..4a5e83e9c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java @@ -0,0 +1,62 @@ +package net.codingarea.commons.common.logging.internal; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.PrintStream; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; + +public class FallbackLogger implements ILogger { + + protected final PrintStream stream = System.err; + protected final String name; + + protected LogLevel level = LogLevel.INFO; + + public FallbackLogger(@Nullable String name) { + this.name = name; + } + + public FallbackLogger() { + this(null); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + if (!isLevelEnabled(level)) return; + stream.println(getLogMessage(level, ILogger.formatMessage(message, args), name)); + for (Object arg : args) { + if (!(arg instanceof Throwable)) continue; + ((Throwable)arg).printStackTrace(stream); + } + } + + @Nonnull + @Override + public FallbackLogger setMinLevel(@Nonnull LogLevel level) { + this.level = level; + return this; + } + + @Nonnull + @Override + public LogLevel getMinLevel() { + return level; + } + + @Nonnull + @CheckReturnValue + public static String getLogMessage(@Nonnull LogLevel level, @Nonnull String message, @Nullable String name) { + Thread thread = Thread.currentThread(); + String threadName = thread.getName(); + String time = OffsetDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")); + return name == null ? + String.format("[%s: %s/%s]: %s", time, threadName, level.getUpperCaseName(), message) : + String.format("[%s: %s/%s] %s: %s", time, threadName, level.getUpperCaseName(), name, message); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java new file mode 100644 index 000000000..f0c64bf8d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java @@ -0,0 +1,666 @@ +package net.codingarea.commons.common.logging.internal; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; +import net.codingarea.commons.common.logging.lib.JavaILogger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ResourceBundle; +import java.util.function.Supplier; +import java.util.logging.*; + +public class JavaLoggerWrapper extends JavaILogger { + + protected final Logger logger; + + public JavaLoggerWrapper(@Nonnull Logger logger) { + super(null, null); + this.logger = logger; + } + + @Override + public boolean getUseParentHandlers() { + return logger.getUseParentHandlers(); + } + + @Override + public Filter getFilter() { + return logger.getFilter(); + } + + @Override + public Handler[] getHandlers() { + return logger.getHandlers(); + } + + @Override + public Level getLevel() { + return logger.getLevel(); + } + + @Override + public Logger getParent() { + return logger.getParent(); + } + + @Override + public ResourceBundle getResourceBundle() { + return logger.getResourceBundle(); + } + + @Override + public String getResourceBundleName() { + return logger.getResourceBundleName(); + } + + @Override + public void log(LogRecord record) { + mapLevel(record); + logger.log(record); + } + + @Override + public void log(Level level, String msg, Object[] params) { + logger.log(mapLevel(level), msg, params); + } + + @Override + public void log(Level level, String msg, Object param1) { + logger.log(mapLevel(level), msg, param1); + } + + @Override + public void log(Level level, Supplier msgSupplier) { + logger.log(mapLevel(level), msgSupplier); + } + + @Override + public void log(Level level, String msg) { + logger.log(mapLevel(level), msg); + } + + @Override + public void log(Level level, String msg, Throwable thrown) { + logger.log(mapLevel(level), msg, thrown); + } + + @Override + public void log(Level level, Throwable thrown, Supplier msgSupplier) { + logger.log(mapLevel(level), thrown, msgSupplier); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, Supplier msgSupplier) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msgSupplier); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg, param1); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object[] params) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg, params); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg, thrown); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, Throwable thrown, Supplier msgSupplier) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, thrown, msgSupplier); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, ResourceBundle bundle, String msg, Object... params) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundle, msg, params); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, ResourceBundle bundle, String msg, Throwable thrown) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundle, msg, thrown); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object param1) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg, param1); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object[] params) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg, params); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Throwable thrown) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg, thrown); + } + + @Override + public boolean isLoggable(Level level) { + return logger.isLoggable(level); + } + + @Override + public void setLevel(Level newLevel) throws SecurityException { + logger.setLevel(newLevel); + } + + @Override + public void setFilter(Filter newFilter) throws SecurityException { + logger.setFilter(newFilter); + } + + @Override + public void setParent(Logger parent) { + logger.setParent(parent); + } + + @Override + public void setResourceBundle(ResourceBundle bundle) { + logger.setResourceBundle(bundle); + } + + @Override + public void setUseParentHandlers(boolean useParentHandlers) { + logger.setUseParentHandlers(useParentHandlers); + } + + @Override + public void severe(String msg) { + logger.severe(msg); + } + + @Override + public void severe(Supplier msgSupplier) { + logger.severe(msgSupplier); + } + + @Override + public void entering(String sourceClass, String sourceMethod) { + logger.entering(sourceClass, sourceMethod); + } + + @Override + public void entering(String sourceClass, String sourceMethod, Object param1) { + logger.entering(sourceClass, sourceMethod, param1); + } + + @Override + public void entering(String sourceClass, String sourceMethod, Object[] params) { + logger.entering(sourceClass, sourceMethod, params); + } + + @Override + public void exiting(String sourceClass, String sourceMethod) { + logger.exiting(sourceClass, sourceMethod); + } + + @Override + public void exiting(String sourceClass, String sourceMethod, Object result) { + logger.exiting(sourceClass, sourceMethod, result); + } + + @Override + public void throwing(String sourceClass, String sourceMethod, Throwable thrown) { + logger.throwing(sourceClass, sourceMethod, thrown); + } + + @Override + public void warning(String msg) { + logger.warning(msg); + } + + @Override + public void info(String msg) { + logger.info(msg); + } + + @Override + public void config(String msg) { + logger.config(msg); + } + + @Override + public void fine(String msg) { + logger.fine(msg); + } + + @Override + public void finer(String msg) { + logger.finer(msg); + } + + @Override + public void finest(String msg) { + logger.finest(msg); + } + + @Override + public void warning(Supplier msgSupplier) { + logger.warning(msgSupplier); + } + + @Override + public void info(Supplier msgSupplier) { + logger.info(msgSupplier); + } + + @Override + public void config(Supplier msgSupplier) { + logger.config(msgSupplier); + } + + @Override + public void fine(Supplier msgSupplier) { + logger.fine(msgSupplier); + } + + @Override + public void finer(Supplier msgSupplier) { + logger.finer(msgSupplier); + } + + @Override + public void finest(Supplier msgSupplier) { + logger.finest(msgSupplier); + } + + @Override + public void addHandler(Handler handler) throws SecurityException { + logger.addHandler(handler); + } + + @Override + public void removeHandler(Handler handler) throws SecurityException { + logger.removeHandler(handler); + } + + @Override + public int hashCode() { + return logger.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return logger.equals(obj); + } + + @Override + public String toString() { + return logger.toString(); + } + + protected void mapLevel(@Nonnull LogRecord record) { + record.setLevel(mapLevel(record.getLevel())); + } + + @Nonnull + protected Level mapLevel(@Nonnull Level level) { + return level; + } + + @Nonnull + @Override + public JavaILogger setMinLevel(@Nonnull LogLevel level) { + setLevel(level.getJavaUtilLevel()); + return this; + } + + @Nonnull + @Override + public LogLevel getMinLevel() { + return LogLevel.fromJavaLevel(logger.getLevel()); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + Throwable thrown = null; + for (Object arg : args) { + if (arg instanceof Throwable) + thrown = (Throwable) arg; + } + log(level.getJavaUtilLevel(), ILogger.formatMessage(message, args), thrown); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + log(level, String.valueOf(message), args); + } + + @Override + public void error(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + @Override + public void error(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + @Override + public void warn(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + @Override + public void warn(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + @Override + public void info(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + @Override + public void info(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + @Override + public void status(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + @Override + public void status(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + @Override + public void debug(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + @Override + public void debug(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + + @Override + public boolean isTraceEnabled() { + return isLevelEnabled(LogLevel.TRACE); + } + +// @Override +// public void trace(String msg) { +// trace(msg, new Object[0]); +// } +// +// @Override +// public void trace(String format, Object arg) { +// trace(format, new Object[] { arg }); +// } +// +// @Override +// public void trace(String format, Object arg1, Object arg2) { +// trace(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void trace(String msg, Throwable t) { +// trace(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isTraceEnabled(Marker marker) { +// return isTraceEnabled(); +// } +// +// @Override +// public void trace(Marker marker, String msg) { +// trace(msg); +// } +// +// @Override +// public void trace(Marker marker, String format, Object arg) { +// trace(format, arg); +// } +// +// @Override +// public void trace(Marker marker, String format, Object arg1, Object arg2) { +// trace(format, arg1, arg2); +// } +// +// @Override +// public void trace(Marker marker, String format, Object... argArray) { +// trace(format, argArray); +// } +// +// @Override +// public void trace(Marker marker, String msg, Throwable t) { +// trace(msg, t); +// } +// +// @Override +// public boolean isDebugEnabled() { +// return isLevelEnabled(LogLevel.DEBUG); +// } +// +// @Override +// public void debug(String msg) { +// debug(msg, new Object[0]); +// } +// +// @Override +// public void debug(String format, Object arg) { +// debug(format, new Object[] { arg }); +// } +// +// @Override +// public void debug(String format, Object arg1, Object arg2) { +// debug(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void debug(String msg, Throwable t) { +// debug(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isDebugEnabled(Marker marker) { +// return isDebugEnabled(); +// } +// +// @Override +// public void debug(Marker marker, String msg) { +// debug(msg); +// } +// +// @Override +// public void debug(Marker marker, String format, Object arg) { +// debug(format, arg); +// } +// +// @Override +// public void debug(Marker marker, String format, Object arg1, Object arg2) { +// debug(format, arg1, arg2); +// } +// +// @Override +// public void debug(Marker marker, String format, Object... arguments) { +// debug(format, arguments); +// } +// +// @Override +// public void debug(Marker marker, String msg, Throwable t) { +// debug(msg, t); +// } +// +// @Override +// public boolean isInfoEnabled() { +// return isLevelEnabled(LogLevel.INFO); +// } +// +// @Override +// public void info(String format, Object arg) { +// info(format, new Object[] { arg }); +// } +// +// @Override +// public void info(String format, Object arg1, Object arg2) { +// info(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void info(String msg, Throwable t) { +// info(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isInfoEnabled(Marker marker) { +// return isInfoEnabled(); +// } +// +// @Override +// public void info(Marker marker, String msg) { +// info(msg); +// } +// +// @Override +// public void info(Marker marker, String format, Object arg) { +// info(format, arg); +// } +// +// @Override +// public void info(Marker marker, String format, Object arg1, Object arg2) { +// info(format, arg1, arg2); +// } +// +// @Override +// public void info(Marker marker, String format, Object... arguments) { +// info(format, arguments); +// } +// +// @Override +// public void info(Marker marker, String msg, Throwable t) { +// info(msg, t); +// } +// +// @Override +// public boolean isWarnEnabled() { +// return isLevelEnabled(LogLevel.WARN); +// } +// +// @Override +// public void warn(String msg) { +// warn(msg, new Object[0]); +// } +// +// @Override +// public void warn(String format, Object arg) { +// warn(format, new Object[] { arg }); +// } +// +// @Override +// public void warn(String format, Object arg1, Object arg2) { +// warn(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void warn(String msg, Throwable t) { +// warn(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isWarnEnabled(Marker marker) { +// return isWarnEnabled(); +// } +// +// @Override +// public void warn(Marker marker, String msg) { +// warn(marker); +// } +// +// @Override +// public void warn(Marker marker, String format, Object arg) { +// warn(format, arg); +// } +// +// @Override +// public void warn(Marker marker, String format, Object arg1, Object arg2) { +// warn(format, arg1, arg2); +// } +// +// @Override +// public void warn(Marker marker, String format, Object... arguments) { +// warn(format, arguments); +// } +// +// @Override +// public void warn(Marker marker, String msg, Throwable t) { +// warn(msg, t); +// } +// +// @Override +// public boolean isErrorEnabled() { +// return isLevelEnabled(LogLevel.ERROR); +// } +// +// @Override +// public void error(String msg) { +// error(msg, new Object[0]); +// } +// +// @Override +// public void error(String format, Object arg) { +// error(format, new Object[] { arg }); +// } +// +// @Override +// public void error(String format, Object arg1, Object arg2) { +// error(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void error(String msg, Throwable t) { +// error(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isErrorEnabled(Marker marker) { +// return isErrorEnabled(); +// } +// +// @Override +// public void error(Marker marker, String msg) { +// error(msg); +// } +// +// @Override +// public void error(Marker marker, String format, Object arg) { +// error(format, arg); +// } +// +// @Override +// public void error(Marker marker, String format, Object arg1, Object arg2) { +// error(format, arg1, arg2); +// } +// +// @Override +// public void error(Marker marker, String format, Object... arguments) { +// error(format, arguments); +// } +// +// @Override +// public void error(Marker marker, String msg, Throwable t) { +// error(msg, t); +// } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java new file mode 100644 index 000000000..d99ca1fa4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java @@ -0,0 +1,365 @@ +package net.codingarea.commons.common.logging.internal; + +import net.codingarea.commons.common.logging.LogLevel; +import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import org.slf4j.Marker; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class SimpleLogger extends FallbackLogger implements Slf4jILogger { + + public SimpleLogger(@Nullable String name) { + super(name); + } + + public SimpleLogger() { + super(); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + super.log(level, message, args); + } + + @Override + public void error(@Nullable String message, @Nonnull Object... args) { + super.error(message, args); + } + + @Override + public void error(@Nullable Object message, @Nonnull Object... args) { + super.error(message, args); + } + + @Override + public void warn(@Nullable String message, @Nonnull Object... args) { + super.warn(message, args); + } + + @Override + public void warn(@Nullable Object message, @Nonnull Object... args) { + super.warn(message, args); + } + + @Override + public void info(@Nullable String message, @Nonnull Object... args) { + super.info(message, args); + } + + @Override + public void info(@Nullable Object message, @Nonnull Object... args) { + super.info(message, args); + } + + @Override + public void status(@Nullable String message, @Nonnull Object... args) { + super.status(message, args); + } + + @Override + public void status(@Nullable Object message, @Nonnull Object... args) { + super.status(message, args); + } + + @Override + public void debug(@Nullable String message, @Nonnull Object... args) { + super.debug(message, args); + } + + @Override + public void debug(@Nullable Object message, @Nonnull Object... args) { + super.debug(message, args); + } + + @Override + public void trace(@Nullable String message, @Nonnull Object... args) { + super.trace(message, args); + } + + @Override + public void trace(@Nullable Object message, @Nonnull Object... args) { + super.trace(message, args); + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean isTraceEnabled() { + return isLevelEnabled(LogLevel.TRACE); + } + + @Override + public void trace(String msg) { + trace(msg, new Object[0]); + } + + @Override + public void trace(String format, Object arg) { + trace(format, new Object[] { arg }); + } + + @Override + public void trace(String format, Object arg1, Object arg2) { + trace(format, new Object[] { arg1, arg2 }); + } + + @Override + public void trace(String msg, Throwable t) { + trace(msg, new Object[] { t }); + } + + @Override + public boolean isTraceEnabled(Marker marker) { + return isTraceEnabled(); + } + + @Override + public void trace(Marker marker, String msg) { + trace(msg); + } + + @Override + public void trace(Marker marker, String format, Object arg) { + trace(format, arg); + } + + @Override + public void trace(Marker marker, String format, Object arg1, Object arg2) { + trace(format, arg1, arg2); + } + + @Override + public void trace(Marker marker, String format, Object... argArray) { + trace(format, argArray); + } + + @Override + public void trace(Marker marker, String msg, Throwable t) { + trace(msg, t); + } + + @Override + public boolean isDebugEnabled() { + return isLevelEnabled(LogLevel.DEBUG); + } + + @Override + public void debug(String msg) { + debug(msg, new Object[0]); + } + + @Override + public void debug(String format, Object arg) { + debug(format, new Object[] { arg }); + } + + @Override + public void debug(String format, Object arg1, Object arg2) { + debug(format, new Object[] { arg1, arg2 }); + } + + @Override + public void debug(String msg, Throwable t) { + debug(msg, new Object[] { t }); + } + + @Override + public boolean isDebugEnabled(Marker marker) { + return isDebugEnabled(); + } + + @Override + public void debug(Marker marker, String msg) { + debug(msg); + } + + @Override + public void debug(Marker marker, String format, Object arg) { + debug(format, arg); + } + + @Override + public void debug(Marker marker, String format, Object arg1, Object arg2) { + debug(format, arg1, arg2); + } + + @Override + public void debug(Marker marker, String format, Object... arguments) { + debug(format, arguments); + } + + @Override + public void debug(Marker marker, String msg, Throwable t) { + debug(msg, t); + } + + @Override + public boolean isInfoEnabled() { + return isLevelEnabled(LogLevel.INFO); + } + + @Override + public void info(String msg) { + info(msg, new Object[0]); + } + + @Override + public void info(String format, Object arg) { + info(format, new Object[] { arg }); + } + + @Override + public void info(String format, Object arg1, Object arg2) { + info(format, new Object[] { arg1, arg2 }); + } + + @Override + public void info(String msg, Throwable t) { + info(msg, new Object[] { t }); + } + + @Override + public boolean isInfoEnabled(Marker marker) { + return isInfoEnabled(); + } + + @Override + public void info(Marker marker, String msg) { + info(msg); + } + + @Override + public void info(Marker marker, String format, Object arg) { + info(format, arg); + } + + @Override + public void info(Marker marker, String format, Object arg1, Object arg2) { + info(format, arg1, arg2); + } + + @Override + public void info(Marker marker, String format, Object... arguments) { + info(format, arguments); + } + + @Override + public void info(Marker marker, String msg, Throwable t) { + info(msg, t); + } + + @Override + public boolean isWarnEnabled() { + return isLevelEnabled(LogLevel.WARN); + } + + @Override + public void warn(String msg) { + warn(msg, new Object[0]); + } + + @Override + public void warn(String format, Object arg) { + warn(format, new Object[] { arg }); + } + + @Override + public void warn(String format, Object arg1, Object arg2) { + warn(format, new Object[] { arg1, arg2 }); + } + + @Override + public void warn(String msg, Throwable t) { + warn(msg, new Object[] { t }); + } + + @Override + public boolean isWarnEnabled(Marker marker) { + return isWarnEnabled(); + } + + @Override + public void warn(Marker marker, String msg) { + warn(marker); + } + + @Override + public void warn(Marker marker, String format, Object arg) { + warn(format, arg); + } + + @Override + public void warn(Marker marker, String format, Object arg1, Object arg2) { + warn(format, arg1, arg2); + } + + @Override + public void warn(Marker marker, String format, Object... arguments) { + warn(format, arguments); + } + + @Override + public void warn(Marker marker, String msg, Throwable t) { + warn(msg, t); + } + + @Override + public boolean isErrorEnabled() { + return isLevelEnabled(LogLevel.ERROR); + } + + @Override + public void error(String msg) { + error(msg, new Object[0]); + } + + @Override + public void error(String format, Object arg) { + error(format, new Object[] { arg }); + } + + @Override + public void error(String format, Object arg1, Object arg2) { + error(format, new Object[] { arg1, arg2 }); + } + + @Override + public void error(String msg, Throwable t) { + error(msg, new Object[] { t }); + } + + @Override + public boolean isErrorEnabled(Marker marker) { + return isErrorEnabled(); + } + + @Override + public void error(Marker marker, String msg) { + error(msg); + } + + @Override + public void error(Marker marker, String format, Object arg) { + error(format, arg); + } + + @Override + public void error(Marker marker, String format, Object arg1, Object arg2) { + error(format, arg1, arg2); + } + + @Override + public void error(Marker marker, String format, Object... arguments) { + error(format, arguments); + } + + @Override + public void error(Marker marker, String msg, Throwable t) { + error(msg, t); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java new file mode 100644 index 000000000..cc1b66a52 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java @@ -0,0 +1,173 @@ +package net.codingarea.commons.common.logging.internal; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.WrappedILogger; +import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import org.slf4j.helpers.MarkerIgnoringBase; + +import javax.annotation.Nonnull; + +public class Slf4jILoggerWrapper extends MarkerIgnoringBase implements WrappedILogger, Slf4jILogger { + + private final ILogger logger; + + public Slf4jILoggerWrapper(@Nonnull ILogger logger) { + this.logger = logger; + } + + @Nonnull + @Override + public ILogger getWrappedLogger() { + return logger; + } + + @Override + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + @Override + public void trace(String message) { + logger.trace(message); + } + + @Override + public void trace(String message, Object arg) { + logger.trace(message, arg); + } + + @Override + public void trace(String message, Object arg1, Object arg2) { + logger.trace(message, arg1, arg2); + } + + @Override + public void trace(String message, Object... args) { + logger.trace(message, args); + } + + @Override + public void trace(String message, Throwable ex) { + logger.trace(message, ex); + } + + @Override + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + @Override + public void debug(String message) { + logger.debug(message); + } + + @Override + public void debug(String message, Object arg) { + logger.debug(message, arg); + } + + @Override + public void debug(String message, Object arg1, Object arg2) { + logger.debug(message, arg1, arg2); + } + + @Override + public void debug(String message, Object... args) { + logger.debug(message, args); + } + + @Override + public void debug(String message, Throwable ex) { + logger.debug(message, ex); + } + + @Override + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + @Override + public void info(String message) { + logger.info(message); + } + + @Override + public void info(String message, Object arg) { + logger.info(message, arg); + } + + @Override + public void info(String message, Object arg1, Object arg2) { + logger.info(message, arg1, arg2); + } + + @Override + public void info(String message, Object... args) { + logger.info(message, args); + } + + @Override + public void info(String message, Throwable ex) { + logger.info(message, ex); + } + + @Override + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + @Override + public void warn(String message) { + logger.warn(message); + } + + @Override + public void warn(String message, Object arg) { + logger.warn(message, arg); + } + + @Override + public void warn(String message, Object... args) { + logger.warn(message, args); + } + + @Override + public void warn(String message, Object arg1, Object arg2) { + logger.warn(message, arg1, arg2); + } + + @Override + public void warn(String message, Throwable ex) { + logger.warn(message, ex); + } + + @Override + public boolean isErrorEnabled() { + return logger.isWarnEnabled(); + } + + @Override + public void error(String message) { + logger.error(message); + } + + @Override + public void error(String message, Object arg) { + logger.error(message, arg); + } + + @Override + public void error(String message, Object arg1, Object arg2) { + logger.error(message, arg1, arg2); + } + + @Override + public void error(String message, Object... args) { + logger.error(message, args); + } + + @Override + public void error(String message, Throwable ex) { + logger.error(message, ex); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java new file mode 100644 index 000000000..079877479 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java @@ -0,0 +1,369 @@ +package net.codingarea.commons.common.logging.internal; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; +import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import org.slf4j.Logger; +import org.slf4j.Marker; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class Slf4jLoggerWrapper implements Slf4jILogger { + + protected final Logger logger; + + public Slf4jLoggerWrapper(@Nonnull Logger logger) { + this.logger = logger; + } + + @Override + public String getName() { + return logger.getName(); + } + + @Override + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + @Override + public void trace(String msg) { + logger.trace(msg); + } + + @Override + public void trace(String format, Object arg) { + logger.trace(format, arg); + } + + @Override + public void trace(String format, Object arg1, Object arg2) { + logger.trace(format, arg1, arg2); + } + + @Override + public void trace(String format, Object... arguments) { + logger.trace(format, arguments); + } + + @Override + public void trace(String msg, Throwable t) { + logger.trace(msg, t); + } + + @Override + public boolean isTraceEnabled(Marker marker) { + return logger.isTraceEnabled(marker); + } + + @Override + public void trace(Marker marker, String msg) { + logger.trace(marker, msg); + } + + @Override + public void trace(Marker marker, String format, Object arg) { + logger.trace(marker, format, arg); + } + + @Override + public void trace(Marker marker, String format, Object arg1, Object arg2) { + logger.trace(marker, format, arg1, arg2); + } + + @Override + public void trace(Marker marker, String format, Object... argArray) { + logger.trace(marker, format, argArray); + } + + @Override + public void trace(Marker marker, String msg, Throwable t) { + logger.trace(marker, msg, t); + } + + @Override + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + @Override + public void debug(String msg) { + logger.debug(msg); + } + + @Override + public void debug(String format, Object arg) { + logger.debug(format, arg); + } + + @Override + public void debug(String format, Object arg1, Object arg2) { + logger.debug(format, arg1, arg2); + } + + @Override + public void debug(String format, Object... arguments) { + logger.debug(format, arguments); + } + + @Override + public void debug(String msg, Throwable t) { + logger.debug(msg, t); + } + + @Override + public boolean isDebugEnabled(Marker marker) { + return logger.isDebugEnabled(marker); + } + + @Override + public void debug(Marker marker, String msg) { + logger.debug(marker, msg); + } + + @Override + public void debug(Marker marker, String format, Object arg) { + logger.debug(marker, format, arg); + } + + @Override + public void debug(Marker marker, String format, Object arg1, Object arg2) { + logger.debug(marker, format, arg1, arg2); + } + + @Override + public void debug(Marker marker, String format, Object... arguments) { + logger.debug(marker, format, arguments); + } + + @Override + public void debug(Marker marker, String msg, Throwable t) { + logger.debug(marker, msg, t); + } + + @Override + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + @Override + public void info(String msg) { + logger.info(msg); + } + + @Override + public void info(String format, Object arg) { + logger.info(format, arg); + } + + @Override + public void info(String format, Object arg1, Object arg2) { + logger.info(format, arg1, arg2); + } + + @Override + public void info(String format, Object... arguments) { + logger.info(format, arguments); + } + + @Override + public void info(String msg, Throwable t) { + logger.info(msg, t); + } + + @Override + public boolean isInfoEnabled(Marker marker) { + return logger.isInfoEnabled(marker); + } + + @Override + public void info(Marker marker, String msg) { + logger.info(marker, msg); + } + + @Override + public void info(Marker marker, String format, Object arg) { + logger.info(marker, format, arg); + } + + @Override + public void info(Marker marker, String format, Object arg1, Object arg2) { + logger.info(marker, format, arg1, arg2); + } + + @Override + public void info(Marker marker, String format, Object... arguments) { + logger.info(marker, format, arguments); + } + + @Override + public void info(Marker marker, String msg, Throwable t) { + logger.info(marker, msg, t); + } + + @Override + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + @Override + public void warn(String msg) { + logger.warn(msg); + } + + @Override + public void warn(String format, Object arg) { + logger.warn(format, arg); + } + + @Override + public void warn(String format, Object... arguments) { + logger.warn(format, arguments); + } + + @Override + public void warn(String format, Object arg1, Object arg2) { + logger.warn(format, arg1, arg2); + } + + @Override + public void warn(String msg, Throwable t) { + logger.warn(msg, t); + } + + @Override + public boolean isWarnEnabled(Marker marker) { + return logger.isWarnEnabled(marker); + } + + @Override + public void warn(Marker marker, String msg) { + logger.warn(marker, msg); + } + + @Override + public void warn(Marker marker, String format, Object arg) { + logger.warn(marker, format, arg); + } + + @Override + public void warn(Marker marker, String format, Object arg1, Object arg2) { + logger.warn(marker, format, arg1, arg2); + } + + @Override + public void warn(Marker marker, String format, Object... arguments) { + logger.warn(marker, format, arguments); + } + + @Override + public void warn(Marker marker, String msg, Throwable t) { + logger.warn(marker, msg, t); + } + + @Override + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } + + @Override + public void error(String msg) { + logger.error(msg); + } + + @Override + public void error(String format, Object arg) { + logger.error(format, arg); + } + + @Override + public void error(String format, Object arg1, Object arg2) { + logger.error(format, arg1, arg2); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + switch (level) { + case TRACE: + trace(message, args); + return; + case DEBUG: + case EXTENDED: + debug(message, args); + return; + case STATUS: + case INFO: + info(message, args); + return; + case WARN: + warn(message, args); + return; + case ERROR: + error(message, args); + } + } + + @Override + public void error(String format, Object... arguments) { + logger.error(format, arguments); + } + + @Override + public void error(String msg, Throwable t) { + logger.error(msg, t); + } + + @Override + public boolean isErrorEnabled(Marker marker) { + return logger.isErrorEnabled(marker); + } + + @Override + public void error(Marker marker, String msg) { + logger.error(marker, msg); + } + + @Override + public void error(Marker marker, String format, Object arg) { + logger.error(marker, format, arg); + } + + @Override + public void error(Marker marker, String format, Object arg1, Object arg2) { + logger.error(marker, format, arg1, arg2); + } + + @Override + public void error(Marker marker, String format, Object... arguments) { + logger.error(marker, format, arguments); + } + + @Override + public void error(Marker marker, String msg, Throwable t) { + logger.error(marker, msg, t); + } + + @Nonnull + @Override + public LogLevel getMinLevel() { + if (logger.isTraceEnabled()) { + return LogLevel.TRACE; + } else if (logger.isDebugEnabled()) { + return LogLevel.DEBUG; + } else if (logger.isInfoEnabled()) { + return LogLevel.INFO; + } else if (logger.isWarnEnabled()) { + return LogLevel.WARN; + } else { + return LogLevel.ERROR; + } + } + + @Nonnull + @Override + public ILogger setMinLevel(@Nonnull LogLevel level) { + return this; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java new file mode 100644 index 000000000..2f4a6067d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java @@ -0,0 +1,29 @@ +package net.codingarea.commons.common.logging.internal.factory; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.ILoggerFactory; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class ConstantLoggerFactory implements ILoggerFactory { + + protected final ILogger logger; + + public ConstantLoggerFactory(@Nonnull ILogger logger) { + this.logger = logger; + } + + @Nonnull + @Override + public ILogger forName(@Nullable String name) { + return logger; + } + + @Override + public void setDefaultLevel(@Nonnull LogLevel level) { + logger.setMinLevel(level); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java new file mode 100644 index 000000000..7825389f4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java @@ -0,0 +1,36 @@ +package net.codingarea.commons.common.logging.internal.factory; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.ILoggerFactory; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; + +public class DefaultLoggerFactory implements ILoggerFactory { + + protected final Map loggers = new ConcurrentHashMap<>(); + protected final Function creator; + protected LogLevel level = LogLevel.DEBUG; + + public DefaultLoggerFactory(@Nonnull Function creator) { + this.creator = creator; + } + + @Nonnull + @Override + @CheckReturnValue + public synchronized ILogger forName(@Nullable String name) { + return loggers.computeIfAbsent(name == null ? "anonymous" : name, unused -> creator.apply(name).setMinLevel(level)); + } + + @Override + public void setDefaultLevel(@Nonnull LogLevel level) { + this.level = level; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java new file mode 100644 index 000000000..e3948466a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java @@ -0,0 +1,25 @@ +package net.codingarea.commons.common.logging.internal.factory; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.ILoggerFactory; +import net.codingarea.commons.common.logging.LogLevel; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class Slf4jLoggerFactory implements ILoggerFactory { + + @Nonnull + @Override + public ILogger forName(@Nullable String name) { + return ILogger.forSlf4jLogger( + LoggerFactory.getLogger(name == null ? "Logger" : name) + ); + } + + @Override + public void setDefaultLevel(@Nonnull LogLevel level) { + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java new file mode 100644 index 000000000..fde8ffb8d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java @@ -0,0 +1,19 @@ +package net.codingarea.commons.common.logging.lib; + +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.Nonnull; +import java.util.logging.Logger; + +public abstract class JavaILogger extends Logger implements ILogger { + + protected JavaILogger(String name, String resourceBundleName) { + super(name, resourceBundleName); + } + + @Nonnull + @Override + public abstract JavaILogger setMinLevel(@Nonnull LogLevel level); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java new file mode 100644 index 000000000..05afb6c81 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java @@ -0,0 +1,41 @@ +package net.codingarea.commons.common.logging.lib; + +import net.codingarea.commons.common.logging.ILogger; +import org.slf4j.Logger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface Slf4jILogger extends ILogger, Logger { + + @Override + boolean isTraceEnabled(); + + @Override + boolean isDebugEnabled(); + + @Override + boolean isInfoEnabled(); + + @Override + boolean isWarnEnabled(); + + @Override + boolean isErrorEnabled(); + + @Override + void trace(@Nullable String message, @Nonnull Object... args); + + @Override + void debug(@Nullable String message, @Nonnull Object... args); + + @Override + void info(@Nullable String message, @Nonnull Object... args); + + @Override + void warn(@Nullable String message, @Nonnull Object... args); + + @Override + void error(@Nullable String message, @Nonnull Object... args); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java new file mode 100644 index 000000000..fc9a86c16 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java @@ -0,0 +1,101 @@ +package net.codingarea.commons.common.misc; + +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.Map; + +public final class BukkitReflectionSerializationUtils { + + private BukkitReflectionSerializationUtils() {} + + protected static final ILogger logger = ILogger.forThisClass(); + + public static boolean isSerializable(@Nonnull Class clazz) { + try { + clazz.getMethod("serialize"); + return true; + } catch (Throwable ex) { + return false; + } + } + + @Nullable + public static Map serializeObject(@Nonnull Object object) { + Class classOfObject = object.getClass(); + try { + + Method method = classOfObject.getMethod("serialize"); + method.setAccessible(true); + Object serialized = method.invoke(object); + + if (!(serialized instanceof Map)) throw new IllegalArgumentException(method + " does not return a Map"); + + @SuppressWarnings("unchecked") + Map map = (Map) serialized; + return map; + + } catch (Throwable ex) { + logger.error("Could not serialize object of type {}", classOfObject, ex); + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static T deserializeObject(@Nonnull Map map, @Nullable Class classOfT) { + try { + + Class configurationSerializationClass = Class.forName("org.bukkit.configuration.serialization.ConfigurationSerialization"); + Method method = configurationSerializationClass.getMethod("deserializeObject", Map.class); + method.setAccessible(true); + Object object = method.invoke(null, map); + + return (T) object; + + } catch (Throwable ex) { + } + + if (classOfT == null) + return null; + + try { + + Method method = classOfT.getMethod("deserialize", Map.class); + method.setAccessible(true); + Object object = method.invoke(null, map); + + if (!classOfT.isInstance(object)) throw new IllegalStateException("Deserialization of " + classOfT.getName() + " failed: returned " + (object == null ? null : object.getClass().getName())); + return classOfT.cast(object); + + } catch (Throwable ex) { + logger.error("Could not deserialize object of type {}", classOfT, ex); + return null; + } + } + + @Nonnull + public static String getSerializationName(@Nonnull Class clazz) { + for (Annotation annotation : clazz.getAnnotations()) { + Class annotationType = annotation.annotationType(); + Object value = ReflectionUtils.getAnnotationValue(annotation); + switch (annotationType.getSimpleName()) { + case "DelegateDeserialization": + case "DelegateSerialization": + case "SerializableAs": + if (value instanceof Class) { + return getSerializationName((Class) value); + } else if (value instanceof String) { + return (String) value; + } + break; + } + } + + return clazz.getName(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java new file mode 100644 index 000000000..b8733488f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java @@ -0,0 +1,565 @@ +package net.codingarea.commons.common.misc; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.function.ExceptionallyConsumer; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.io.*; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.nio.file.FileSystem; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.Map; +import java.util.UUID; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; + +public final class FileUtils { + + public static final InputStream EMPTY_STREAM = new ByteArrayInputStream(new byte[0]); + private static final Map ZIP_FILE_SYSTEM_PROPERTIES = ImmutableMap + .of("create", "false", "encoding", "UTF-8"); + private static Path tempDirectory; + + private FileUtils() {} + + @Nullable + public static Path getTempDirectory() { + return tempDirectory; + } + + public static void setTempDirectory(@Nullable Path tempDirectory) { + FileUtils.tempDirectory = tempDirectory; + } + + @Nonnull + public static BufferedWriter newBufferedWriter(@Nonnull File file) throws IOException { + return newBufferedWriter(file.toPath()); + } + + @Nonnull + public static BufferedReader newBufferedReader(@Nonnull File file) throws IOException { + return newBufferedReader(file.toPath()); + } + + @Nonnull + public static BufferedWriter newBufferedWriter(@Nonnull Path file) throws IOException { + return Files.newBufferedWriter(file, StandardCharsets.UTF_8); + } + + @Nonnull + public static BufferedReader newBufferedReader(@Nonnull Path file) throws IOException { + return Files.newBufferedReader(file, StandardCharsets.UTF_8); + } + + @Nonnull + public static String getFileExtension(@Nonnull File file) { + return getFileExtension(file.getName()); + } + + @Nonnull + public static String getFileExtension(@Nonnull Path file) { + return getFileExtension(file.toString()); + } + + @Nonnull + public static String getFileExtension(@Nonnull String filename) { + return StringUtils.getAfterLastIndex(filename, ".").toLowerCase(); + } + + @Nonnull + public static String getFileName(@Nonnull File file) { + return getFileName(file.getName()); + } + + @Nonnull + public static String getFileName(@Nonnull Path file) { + return getFileName(file.toString()); + } + + @Nonnull + public static String getFileName(@Nonnull String filename) { + filename = stripFolders(filename); + int index = filename.lastIndexOf('.'); + if (index == -1) return filename; + return filename.substring(0, index); + } + + @Nonnull + @CheckReturnValue + public static String getRealFileName(@Nonnull File file) { + return getRealFileName(file.getName()); + } + + @Nonnull + @CheckReturnValue + public static String getRealFileName(@Nonnull Path file) { + return getRealFileName(file.toString()); + } + + @Nonnull + @CheckReturnValue + public static String getRealFileName(@Nonnull String filename) { + return stripFolders(filename); + } + + @Nonnull + @CheckReturnValue + private static String stripFolders(@Nonnull String filename) { + int index = filename.lastIndexOf(File.pathSeparator); + if (index == -1) return filename; + return filename.substring(index + 1); + } + + public static void createFilesIfNecessary(@Nonnull File file) throws IOException { + if (file.exists()) return; + + if (file.isDirectory()) { + file.mkdirs(); + } else if (file.getParentFile() != null) { + file.getParentFile().mkdirs(); + } + + file.createNewFile(); + } + + public static void deleteWorldFolder(@Nonnull File path) { + if (path.exists()) { + File[] files = path.listFiles(); + if (files == null) return; + for (File currentFile : files) { + if (currentFile.isDirectory()) { + // Don't delete directories or we'Ll minecraft won't create them again + deleteWorldFolder(currentFile); + } else { + if (currentFile.getName().equals("session.lock")) continue; // Don't delete or we'll get lots of exceptions + currentFile.delete(); + } + } + } + } + + public static byte[] toByteArray(@Nullable InputStream inputStream) { + return toByteArray(inputStream, new byte[8192]); + } + + public static byte[] toByteArray(@Nullable InputStream inputStream, byte[] buffer) { + if (inputStream == null) { + return null; + } + + try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { + copy(inputStream, byteArrayOutputStream, buffer); + return byteArrayOutputStream.toByteArray(); + } catch (IOException exception) { + exception.printStackTrace(); + } + + return null; + } + + public static void openZipFileSystem(@Nonnull Path path, @Nonnull ExceptionallyConsumer consumer) { + try (FileSystem fileSystem = FileSystems + .newFileSystem(URI.create("jar:" + path.toUri()), ZIP_FILE_SYSTEM_PROPERTIES)) { + consumer.accept(fileSystem); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } + } + + public static void copy(InputStream inputStream, OutputStream outputStream) throws IOException { + copy(inputStream, outputStream, new byte[8192]); + } + + public static void copy(InputStream inputStream, OutputStream outputStream, byte[] buffer) throws IOException { + copy(inputStream, outputStream, buffer, null); + } + + public static void copy(InputStream inputStream, OutputStream outputStream, byte[] buffer, + Consumer lengthInputListener) throws IOException { + int len; + while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) { + if (lengthInputListener != null) { + lengthInputListener.accept(len); + } + + outputStream.write(buffer, 0, len); + outputStream.flush(); + } + } + + public static void copy(Path from, Path to) throws IOException { + copy(from, to, new byte[8192]); + } + + public static void copy(Path from, Path to, byte[] buffer) throws IOException { + if (from == null || to == null || !Files.exists(from)) { + return; + } + + if (Files.notExists(to)) { + createDirectory(to.getParent()); + } + + try (InputStream stream = Files.newInputStream(from); OutputStream target = Files.newOutputStream(to)) { + copy(stream, target, buffer); + } + } + + public static void copyFilesToDirectory(Path from, Path to) { + walkFileTree(from, (root, current) -> { + if (!Files.isDirectory(current)) { + try { + FileUtils.copy(current, to.resolve(from.relativize(current))); + } catch (IOException exception) { + exception.printStackTrace(); + } + } + }); + } + + public static void copyFilesToDirectory(Path from, Path to, DirectoryStream.Filter filter) { + if (filter == null) { + copyFilesToDirectory(from, to); + } else { + walkFileTree(from, (root, current) -> { + if (!Files.isDirectory(current)) { + try { + FileUtils.copy(current, to.resolve(from.relativize(current))); + } catch (IOException exception) { + exception.printStackTrace(); + } + } + }, true, filter); + } + } + + public static void delete(Path file) { + if (file == null || Files.notExists(file)) { + return; + } + + if (Files.isDirectory(file)) { + walkFileTree(file, (root, current) -> FileUtils.deleteFile(current)); + } + + FileUtils.deleteFile(file); + } + + public static long size(@Nonnull Path path) { + try { + return Files.size(path); + } catch (IOException ex) { + throw new WrappedException(ex); + } + } + + /** + * Converts a bunch of directories to a byte array + * + * @param directories The directories which should get converted + * @return A byte array of a zip file created from the provided directories + * @deprecated May cause a heap space (over)load + */ + @Deprecated + public static byte[] convert(Path... directories) { + if (directories == null) { + return emptyZipByteArray(); + } + + try (ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream()) { + try (ZipOutputStream zipOutputStream = new ZipOutputStream(byteBuffer, StandardCharsets.UTF_8)) { + for (Path directory : directories) { + zipDir(zipOutputStream, directory, null); + } + } + + return byteBuffer.toByteArray(); + + } catch (IOException ex) { + ex.printStackTrace(); + } + + return emptyZipByteArray(); + } + + @Nonnull + public static Path createTempFile() { + if (tempDirectory != null) + return createTempFile(UUID.randomUUID()); + + try { + File file = File.createTempFile(UUID.randomUUID().toString(), null); + file.deleteOnExit(); + return file.toPath(); + } catch (IOException ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + public static Path createTempFile(@Nonnull UUID uuid) { + Preconditions.checkNotNull(tempDirectory, "The temp directory cannot be null"); + Path file = tempDirectory.resolve(uuid.toString()); + createFile(file); + return file; + } + + public static void setAttribute(@Nonnull Path path, @Nonnull String attribute, @Nullable Object value, @Nonnull LinkOption... options) { + try { + Files.setAttribute(path, attribute, value, options); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + public static void setHiddenAttribute(@Nonnull Path path, boolean hidden) { + setAttribute(path, "dos:hidden", hidden, LinkOption.NOFOLLOW_LINKS); + } + + @Nonnull + public static InputStream zipToStream(@Nonnull Path directory) throws IOException { + return zipToStream(directory, null); + } + + @Nonnull + public static InputStream zipToStream(@Nonnull Path directory, @Nullable Predicate fileFilter) throws IOException { + Path target = createTempFile(); + zipToFile(directory, target, path -> !target.equals(path) && (fileFilter == null || fileFilter.test(path))); + return Files.newInputStream(target, StandardOpenOption.DELETE_ON_CLOSE, LinkOption.NOFOLLOW_LINKS); + } + + @Nullable + public static Path zipToFile(Path directory, Path target) { + return zipToFile(directory, target, null); + } + + @Nullable + public static Path zipToFile(Path directory, Path target, Predicate fileFilter) { + if (directory == null || !Files.exists(directory)) { + return null; + } + + delete(target); + try (OutputStream outputStream = Files.newOutputStream(target, StandardOpenOption.CREATE)) { + zipStream(directory, outputStream, fileFilter); + return target; + } catch (IOException ex) { + ex.printStackTrace(); + } + + return null; + } + + private static void zipStream(Path source, OutputStream buffer, Predicate fileFilter) throws IOException { + try (ZipOutputStream zipOutputStream = new ZipOutputStream(buffer, StandardCharsets.UTF_8)) { + if (Files.exists(source)) { + zipDir(zipOutputStream, source, fileFilter); + } + } + } + + private static void zipDir(ZipOutputStream zipOutputStream, Path directory, Predicate fileFilter) throws IOException { + Files.walkFileTree( + directory, + new SimpleFileVisitor() { + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + if (fileFilter != null && !fileFilter.test(file)) { + return FileVisitResult.CONTINUE; + } + + try { + zipOutputStream.putNextEntry(new ZipEntry(directory.relativize(file).toString().replace("\\", "/"))); + Files.copy(file, zipOutputStream); + zipOutputStream.closeEntry(); + } catch (IOException ex) { + zipOutputStream.closeEntry(); + throw ex; + } + return FileVisitResult.CONTINUE; + } + } + ); + } + + public static Path extract(Path zipPath, Path targetDirectory) throws IOException { + if (zipPath == null || targetDirectory == null || !Files.exists(zipPath)) { + return targetDirectory; + } + + try (InputStream input = Files.newInputStream(zipPath)) { + return extract(input, targetDirectory); + } + } + + public static Path extract(InputStream input, Path targetDirectory) throws IOException { + if (input == null || targetDirectory == null) { + return targetDirectory; + } + + extract0(new ZipInputStream(input, StandardCharsets.UTF_8), targetDirectory); + + return targetDirectory; + } + + public static Path extract(byte[] zipData, Path targetDirectory) throws IOException { + if (zipData == null || zipData.length == 0 || targetDirectory == null) { + return targetDirectory; + } + + try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(zipData)) { + extract0(new ZipInputStream(byteArrayInputStream, StandardCharsets.UTF_8), targetDirectory); + } + + return targetDirectory; + } + + public static void extract0(ZipInputStream zipInputStream, Path targetDirectory) throws IOException { + ZipEntry zipEntry; + while ((zipEntry = zipInputStream.getNextEntry()) != null) { + extractEntry(zipInputStream, zipEntry, targetDirectory); + zipInputStream.closeEntry(); + } + } + + public static byte[] emptyZipByteArray() { + byte[] bytes = null; + + try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { + ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream, StandardCharsets.UTF_8); + zipOutputStream.close(); + + bytes = byteArrayOutputStream.toByteArray(); + } catch (IOException exception) { + exception.printStackTrace(); + } + + return bytes; + } + + private static void extractEntry(ZipInputStream zipInputStream, ZipEntry zipEntry, Path targetDirectory) + throws IOException { + Path file = targetDirectory.resolve(zipEntry.getName()); + ensureChild(targetDirectory, file); + + if (zipEntry.isDirectory()) { + if (!Files.exists(file)) { + Files.createDirectories(file); + } + } else { + Path parent = file.getParent(); + if (!Files.exists(parent)) { + Files.createDirectories(parent); + } + + if (Files.exists(file)) { + Files.delete(file); + } + + Files.createFile(file); + try (OutputStream outputStream = Files.newOutputStream(file)) { + copy(zipInputStream, outputStream); + } + } + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer) { + walkFileTree(rootDirectoryPath, consumer, true); + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer, boolean visitDirectories) { + walkFileTree(rootDirectoryPath, consumer, visitDirectories, "*"); + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer, boolean visitDirectories, + String glob) { + if (Files.notExists(rootDirectoryPath)) { + return; + } + try (DirectoryStream stream = Files.newDirectoryStream(rootDirectoryPath, glob)) { + for (Path path : stream) { + if (Files.isDirectory(path) && visitDirectories) { + walkFileTree(path, consumer, true, glob); + } + consumer.accept(rootDirectoryPath, path); + } + } catch (IOException exception) { + exception.printStackTrace(); + } + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer, boolean visitDirectories, + DirectoryStream.Filter filter) { + if (Files.notExists(rootDirectoryPath)) { + return; + } + try (DirectoryStream stream = Files.newDirectoryStream(rootDirectoryPath, filter)) { + for (Path path : stream) { + if (Files.isDirectory(path) && visitDirectories) { + walkFileTree(path, consumer, true, filter); + } + consumer.accept(rootDirectoryPath, path); + } + } catch (IOException exception) { + exception.printStackTrace(); + } + } + + public static void createDirectory(@Nullable Path directoryPath) { + if (directoryPath != null && Files.notExists(directoryPath)) { + try { + Files.createDirectories(directoryPath); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + + public static void createFile(@Nullable Path filePath) { + if (filePath != null && Files.notExists(filePath)) { + try { + if (filePath.getParent() != null) + Files.createDirectories(filePath.getParent()); + Files.createFile(filePath); + } catch (IOException ex) { + } + } + } + + public static void deleteFile(Path file) { + try { + Files.deleteIfExists(file); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + private static void ensureChild(Path root, Path child) { + Path rootNormal = root.normalize().toAbsolutePath(); + Path childNormal = child.normalize().toAbsolutePath(); + + if (childNormal.getNameCount() <= rootNormal.getNameCount() || !childNormal.startsWith(rootNormal)) { + throw new IllegalStateException("Child " + childNormal + " is not in root path " + rootNormal); + } + } + + @Nonnull + public static Stream list(@Nonnull Path directory) { + try { + return Files.list(directory); + } catch (IOException ex) { + throw new WrappedException(ex); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java new file mode 100644 index 000000000..ce3988f94 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java @@ -0,0 +1,127 @@ +package net.codingarea.commons.common.misc; + +import com.google.gson.*; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +@SuppressWarnings("unchecked") +public final class GsonUtils { + + private GsonUtils() {} + + @Nullable + public static Object unpackJsonElement(@Nullable JsonElement element) { + if (element == null || element.isJsonNull()) + return null; + if (element.isJsonObject()) + return convertJsonObjectToMap(element.getAsJsonObject()); + if (element.isJsonArray()) + return convertJsonArrayToStringList(element.getAsJsonArray()); + if (element.isJsonPrimitive()) { + JsonPrimitive primitive = element.getAsJsonPrimitive(); + if (primitive.isNumber()) return primitive.getAsNumber(); + if (primitive.isString()) return primitive.getAsString(); + if (primitive.isBoolean()) return primitive.getAsBoolean(); + } + return element; + } + + @Nullable + public static String convertJsonElementToString(@Nullable JsonElement element) { + if (element == null || element.isJsonNull()) + return null; + if (element.isJsonPrimitive()) { + JsonPrimitive primitive = element.getAsJsonPrimitive(); + if (primitive.isString()) return primitive.getAsString(); + if (primitive.isNumber()) return primitive.getAsNumber() + ""; + if (primitive.isBoolean()) return primitive.getAsBoolean() + ""; + } + return element.toString(); + } + + @Nonnull + public static Map convertJsonObjectToMap(@Nonnull JsonObject object) { + Map map = new LinkedHashMap<>(); + convertJsonObjectToMap(object, map); + return map; + } + + public static void convertJsonObjectToMap(@Nonnull JsonObject object, @Nonnull Map map) { + for (Entry entry : object.entrySet()) { + map.put(entry.getKey(), unpackJsonElement(entry.getValue())); + } + } + + + @Nonnull + public static List convertJsonArrayToStringList(@Nonnull JsonArray array) { + List list = new ArrayList<>(array.size()); + for (JsonElement element : array) { + list.add(convertJsonElementToString(element)); + } + return list; + } + + @Nonnull + public static String[] convertJsonArrayToStringArray(@Nonnull JsonArray array) { + String[] list = new String[array.size()]; + for (int i = 0; i < array.size(); i++) { + list[i] = convertJsonElementToString(array.get(i)); + } + return list; + } + + @Nonnull + public static JsonArray convertIterableToJsonArray(@Nonnull Gson gson, @Nonnull Iterable iterable) { + JsonArray array = new JsonArray(); + iterable.forEach(object -> array.add(gson.toJsonTree(object))); + return array; + } + + @Nonnull + public static JsonArray convertArrayToJsonArray(@Nonnull Gson gson, @Nonnull Object array) { + JsonArray jsonArray = new JsonArray(); + ReflectionUtils.forEachInArray(array, object -> jsonArray.add(gson.toJsonTree(object))); + return jsonArray; + } + + public static void setDocumentProperties(@Nonnull Gson gson, @Nonnull JsonObject object, @Nonnull Map values) { + for (Entry entry : values.entrySet()) { + Object value = entry.getValue(); + + if (value == null) { + object.add(entry.getKey(), null); + } else if (value instanceof JsonElement) { + object.add(entry.getKey(), (JsonElement) value); + } else if (value instanceof Iterable) { + Iterable iterable = (Iterable) value; + object.add(entry.getKey(), convertIterableToJsonArray(gson, iterable)); + } else if (value.getClass().isArray()) { + object.add(entry.getKey(), convertArrayToJsonArray(gson, value)); + } else if (value instanceof Map) { + Map map = (Map) value; + JsonObject newObject = new JsonObject(); + object.add(entry.getKey(), newObject); + setDocumentProperties(gson, newObject, map); + } else { + object.add(entry.getKey(), gson.toJsonTree(value)); + } + } + } + + public static int getSize(@Nonnull JsonObject object) { + try { + return object.size(); + } catch (NoSuchMethodError ex) { + } + + return object.entrySet().size(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java new file mode 100644 index 000000000..6be9f8af1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java @@ -0,0 +1,109 @@ +package net.codingarea.commons.common.misc; + +import net.codingarea.commons.common.collection.IOUtils; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.font.TextLayout; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URLConnection; + +public final class ImageUtils { + + private ImageUtils() {} + + /** + * @param height The y-position of the text + * @return The width of the text added in pixels + */ + public static int addCenteredText(@Nonnull Graphics2D graphics, @Nonnull String text, int height) { + TextLayout layout = getTextLayout(graphics, text); + int lineWidth = (int) layout.getBounds().getWidth(); + graphics.drawString(text, graphics.getDeviceConfiguration().getBounds().width / 2 - lineWidth / 2, height); + return lineWidth; + + } + + /** + * @return The ending position of the text + */ + public static int addText(@Nonnull Graphics2D graphics, @Nonnull String text, int height, int x) { + TextLayout layout = getTextLayout(graphics, text); + graphics.drawString(text, x, height); + return (int) (x + layout.getBounds().getWidth()); + } + + /** + * @return Returns where the text has started + */ + public static int addTextEndingAt(@Nonnull Graphics2D graphics, @Nonnull String text, int height, int endX) { + TextLayout layout = getTextLayout(graphics, text); + int position = (int) (endX - layout.getBounds().getWidth()); + graphics.drawString(text, position, height); + return position; + } + + /** + * @param height The y-position of the text + */ + public static void addTextEndingAtMid(@Nonnull Graphics2D graphics, @Nonnull String text, int height) { + TextLayout layout = getTextLayout(graphics, text); + int lineWidth = (int) layout.getBounds().getWidth(); + graphics.drawString(text, graphics.getClipBounds().width / 2 - lineWidth, height); + } + + /** + * Reads a image from url using {@link ImageIO#read(InputStream)} and returns it + * + * @param url The URL the image is stored to + * + * @throws IOException + * When something goes wrong while connecting or reading the image + */ + public static BufferedImage loadUrl(@Nonnull String url) throws IOException { + URLConnection connection = IOUtils.createConnection(url); + return ImageIO.read(connection.getInputStream()); + } + + public static BufferedImage loadResource(@Nonnull String path) throws IOException { + InputStream stream = ImageUtils.class.getClassLoader().getResourceAsStream(path); + return ImageIO.read(stream); + } + + public static BufferedImage loadFile(@Nonnull File file) throws IOException { + return ImageIO.read(file); + } + + @Nonnull + public static TextLayout getTextLayout(@Nonnull Graphics2D graphics, @Nonnull String text) { + return new TextLayout(text, graphics.getFont(), graphics.getFontRenderContext()); + } + + public static void darkenImage(@Nonnull BufferedImage image) { + for (int i = 0; i < image.getWidth(); i++) { + for (int j = 0; j < image.getHeight(); j++) { + image.setRGB(i, j, new Color(image.getRGB(i, j)).darker().getRGB()); + } + } + } + + @Nonnull + @CheckReturnValue + public static BufferedImage replaceTransparency(@Nonnull BufferedImage image, @Nullable Color replacementColor) { + if (replacementColor == null) replacementColor = new Color(0, 0, 0, 0); + BufferedImage created = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = created.createGraphics(); + graphics.setColor(replacementColor); + graphics.fillRect(0, 0, image.getWidth(), image.getHeight()); + graphics.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null); + graphics.dispose(); + return created; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/MathHelper.java b/plugin/src/main/java/net/codingarea/commons/common/misc/MathHelper.java new file mode 100644 index 000000000..1663748b7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/MathHelper.java @@ -0,0 +1,12 @@ +package net.codingarea.commons.common.misc; + +public final class MathHelper { + + private MathHelper() {} + + public static double percentage(double total, double proportion) { + if (proportion == 0) return 0; + return (proportion * 100) / total; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java new file mode 100644 index 000000000..8b84e8f64 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java @@ -0,0 +1,18 @@ +package net.codingarea.commons.common.misc; + +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; + +public final class PropertiesUtils { + + private PropertiesUtils() {} + + public static void setProperties(@Nonnull Properties properties, @Nonnull Map map) { + for (Entry entry : properties.entrySet()) { + map.put((String) entry.getKey(), entry.getValue()); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java new file mode 100644 index 000000000..2c4566199 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java @@ -0,0 +1,258 @@ +package net.codingarea.commons.common.misc; + +import net.codingarea.commons.common.collection.ArrayWalker; +import net.codingarea.commons.common.collection.ClassWalker; +import net.codingarea.commons.common.collection.PublicSecurityManager; +import net.codingarea.commons.common.collection.WrappedException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.lang.annotation.Annotation; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; + +public final class ReflectionUtils { + + private ReflectionUtils() {} + + @Nonnull + public static Collection getPublicMethodsAnnotatedWith(@Nonnull Class clazz, @Nonnull Class classOfAnnotation) { + List annotatedMethods = new ArrayList<>(); + for (Method method : clazz.getMethods()) { + if (!method.isAnnotationPresent(classOfAnnotation)) continue; + annotatedMethods.add(method); + } + return annotatedMethods; + } + + @Nonnull + public static Collection getMethodsAnnotatedWith(@Nonnull Class clazz, @Nonnull Class classOfAnnotation) { + List annotatedMethods = new ArrayList<>(); + for (Class currentClass : ClassWalker.walk(clazz)) { + for (Method method : currentClass.getDeclaredMethods()) { + if (!method.isAnnotationPresent(classOfAnnotation)) continue; + annotatedMethods.add(method); + } + } + return annotatedMethods; + } + + @Nonnull + public static Method getInheritedPrivateMethod(@Nonnull Class clazz, @Nonnull String name, @Nonnull Class... parameterTypes) throws NoSuchMethodException { + for (Class current : ClassWalker.walk(clazz)) { + try { + return current.getDeclaredMethod(name, parameterTypes); + } catch (Throwable ex) { + } + } + + throw new NoSuchMethodException(name); + } + + @Nonnull + public static Field getInheritedPrivateField(@Nonnull Class clazz, @Nonnull String name) throws NoSuchFieldException { + for (Class current : ClassWalker.walk(clazz)) { + try { + return current.getDeclaredField(name); + } catch (Throwable ex) { + } + } + + throw new NoSuchFieldException(name); + } + + /** + * @param classOfEnum The class containing the enum constants + * @return The first enum found by the given names + */ + @Nonnull + public static > E getFirstEnumByNames(@Nonnull Class classOfEnum, @Nonnull String... names) { + for (String name : names) { + try { + return Enum.valueOf(classOfEnum, name); + } catch (IllegalArgumentException | NoSuchFieldError ex) { } + } + throw new IllegalArgumentException("No enum found in " + classOfEnum.getName() + " for " + Arrays.toString(names)); + } + + /** + * Iterates through an array which may contain primitive data types or non primitive data types and performs the given action on each element. + * Because we can't just cast such an array to {@code Object[]}, we have to use some reflections. + * + * @param array The target array, as {@link Object}; Can't use an array type here. + * @param The type of data we will cast the content to. Use {@link Object} if the it's unknown. + * + * @throws IllegalArgumentException + * If the {@code array} is not an actual array + * + * @see Array + * @see Array#getLength(Object) + * @see Array#get(Object, int) + */ + public static void forEachInArray(@Nonnull Object array, @Nonnull Consumer action) { + ReflectionUtils.iterableArray(array).forEach(action); + } + + @Nonnull + @CheckReturnValue + public static Iterable iterableArray(@Nonnull Object array) { + return ArrayWalker.walk(array); + } + + @CheckReturnValue + public static Class getCaller(int index) { + try { + return new PublicSecurityManager().getPublicClassContext()[index + 2]; + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @CheckReturnValue + public static Class getCaller() { + return getCaller(2); + } + + @Nonnull + public static String getCallerName() { + StackTraceElement[] trace = Thread.currentThread().getStackTrace(); + StackTraceElement element = trace[3]; + + String className = StringUtils.getAfterLastIndex(element.getClassName(), "."); + return className + "." + element.getMethodName(); + } + + /** + * Takes a {@link Enum} and returns the corresponding {@link Field} using {@link Class#getField(String)} + * + * @see Class#getField(String) + */ + @Nonnull + public static Field getEnumAsField(@Nonnull Enum enun) { + Class classOfEnum = enun.getClass(); + + try { + return classOfEnum.getField(enun.name()); + } catch (NoSuchFieldException ex) { + throw new WrappedException(ex); + } + } + + /** + * @see Field#getAnnotations() + */ + @Nonnull + public static > Annotation[] getEnumAnnotations(@Nonnull E enun) { + Field field = getEnumAsField(enun); + return field.getAnnotations(); + } + + /** + * @return Returns {@code null} if no annotation of this class is present + * + * @see Field#getAnnotation(Class) + */ + public static , A extends Annotation> A getEnumAnnotation(@Nonnull E enun, Class classOfAnnotation) { + Field field = getEnumAsField(enun); + return field.getAnnotation(classOfAnnotation); + } + + @Nullable + public static > E getEnumOrNull(@Nullable String name, @Nonnull Class classOfEnum) { + try { + if (name == null) return null; + return Enum.valueOf(classOfEnum, name); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static Class getClassOrNull(@Nullable String name) { + try { + if (name == null) return null; + return (Class) Class.forName(name); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static Class getClassOrNull(@Nullable String name, boolean initialize, @Nonnull ClassLoader classLoader) { + try { + if (name == null) return null; + return (Class) Class.forName(name, initialize, classLoader); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static T invokeMethodOrNull(@Nullable Object instance, @Nonnull Method method) { + try { + if (!method.isAccessible()) method.setAccessible(true); + return (T) method.invoke(instance); + } catch (Throwable ex) { + return null; + } + } + + @Nullable + public static T invokeStaticMethodOrNull(@Nonnull Class clazz, @Nonnull String method) { + try { + return invokeMethodOrNull(null, clazz.getMethod(method)); + } catch (NoSuchMethodException ex) { + return null; + } + } + + @Nullable + public static T invokeMethodOrNull(@Nonnull Object instance, @Nonnull String method) { + try { + return invokeMethodOrNull(instance, instance.getClass().getDeclaredMethod(method)); + } catch (NoSuchMethodException ex) { + return null; + } + } + + @Nullable + public static T getAnnotationValue(@Nonnull Annotation annotation) { + return invokeMethodOrNull(annotation, "value"); + } + + @Nullable + public static > E getEnumByAlternateNames(@Nonnull Class classOfE, @Nonnull String input) { + E[] values = invokeStaticMethodOrNull(classOfE, "values"); + String[] methodNames = { "getName", "getNames", "getAlias", "getAliases", "getKey", "getKeys", "name", "toString", "ordinal", "getId", "id" }; + for (E value : values) { + for (String method : methodNames) { + if (check(input, invokeMethodOrNull(value, method))) + return value; + } + } + + return null; + } + + private static boolean check(@Nonnull String input, @Nullable Object value) { + if (value == null) return false; + if (value.getClass().isArray()) { + for (Object key : iterableArray(value)) { + if (input.equalsIgnoreCase(String.valueOf(key))) + return true; + } + } + return input.equalsIgnoreCase(String.valueOf(value)); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java new file mode 100644 index 000000000..66faae82d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java @@ -0,0 +1,143 @@ +package net.codingarea.commons.common.misc; + +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; +import java.util.Map.Entry; +import java.util.function.Function; + +public final class SimpleCollectionUtils { + + @Deprecated + public static final String REGEX_1 = ",", + REGEX_2 = "="; + private static final ILogger logger = ILogger.forThisClass(); + private static boolean logMappingError = true; + + private SimpleCollectionUtils() {} + + public static void disableErrorLogging() { + logMappingError = false; + } + + /** + * You should not use this to serialize maps due to it's unsafe because of strings which may contain the regex chars = or , + * Use better and safer serialization strategies like json. + * + * @deprecated Unsafe because of strings containing , or = + */ + @Nonnull + @Deprecated + @CheckReturnValue + public static String convertMapToString(@Nonnull Map map, @Nonnull Function key, @Nonnull Function value) { + StringBuilder builder = new StringBuilder(); + for (Entry entry : map.entrySet()) { + if (builder.length() != 0) builder.append(REGEX_1); + builder.append(key.apply(entry.getKey())); + builder.append(REGEX_2); + builder.append(value.apply(entry.getValue())); + } + return builder.toString(); + } + + /** + * You should not use this to serialize maps due to it's unsafe because of strings which may contain the regex chars = or , + * Use better and safer serialization strategies like json. + * + * @deprecated Unsafe because of strings containing , or = + */ + @Nonnull + @Deprecated + @CheckReturnValue + public static Map convertStringToMap(@Nullable String string, @Nonnull Function key, @Nonnull Function value) { + + Map map = new HashMap<>(); + if (string == null) return map; + + String[] args = string.split(REGEX_1); + for (String arg : args) { + try { + + String[] elements = arg.split(REGEX_2); + K keyElement = key.apply(elements[0]); + V valueElement = value.apply(elements[1]); + + if (keyElement == null || valueElement == null) + throw new NullPointerException(); + + map.put(keyElement, valueElement); + + } catch (Exception ex) { + if (logMappingError) + logger.error("Cannot generate key/value: " + ex.getClass().getName() + ": " + ex.getMessage()); + } + } + + return map; + + } + + @Nonnull + @CheckReturnValue + public static Map convertMap(@Nonnull Map map, + @Nonnull Function keyMapper, + @Nonnull Function valueMapper) { + Map result = new HashMap<>(); + map.forEach((key, value) -> { + try { + result.put(keyMapper.apply(key), valueMapper.apply(value)); + } catch (Exception ex) { + if (logMappingError) + logger.error("Unable to map '{}'='{}'", key, value, ex); + } + }); + return result; + } + + @Nonnull + @CheckReturnValue + public static List convert(@Nonnull Collection collection, + @Nonnull Function mapper) { + List result = new ArrayList<>(collection.size()); + collection.forEach(value -> { + try { + result.add(mapper.apply(value)); + } catch (Exception ex) { + if (logMappingError) + logger.error("Unable map '{}'", value, ex); + } + }); + return result; + } + + public static V getMostFrequentValue(@Nonnull Map map) { + Collection values = map.values(); + List list = new ArrayList<>(values); + Set set = new HashSet<>(values); + + V valueMax = null; + int max = 0; + for (V value : set) { + int frequency = Collections.frequency(list, value); + if (frequency > max) { + max = frequency; + valueMax = value; + } + } + + return valueMax; + } + + @SafeVarargs + public static Set setOf(@Nonnull Collection... collections) { + Set set = new HashSet<>(); + for (Collection collection : collections) { + set.addAll(collection); + } + return set; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java new file mode 100644 index 000000000..fdae424a0 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java @@ -0,0 +1,181 @@ +package net.codingarea.commons.common.misc; + +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Optional; +import java.util.concurrent.Callable; +import java.util.function.Function; +import java.util.function.Supplier; + +public final class StringUtils { + + private static final ILogger logger = ILogger.forThisClass(); + + private StringUtils() {} + + @Nonnull + public static String getEnumName(@Nonnull Enum enun) { + return getEnumName(enun.name()); + } + + @Nonnull + public static String getEnumName(@Nonnull String name) { + StringBuilder builder = new StringBuilder(); + boolean nextUpperCase = true; + for (char letter : name.toCharArray()) { + // Replace _ with space + if (letter == '_') { + builder.append(' '); + nextUpperCase = true; + continue; + } + builder.append(nextUpperCase ? Character.toUpperCase(letter) : Character.toLowerCase(letter)); + nextUpperCase = false; + } + return builder.toString(); + } + + @Nonnull + public static String format(@Nonnull String sequence, @Nonnull Object... args) { + char start = '{', end = '}'; + boolean inArgument = false; + StringBuilder argument = new StringBuilder(); + StringBuilder builder = new StringBuilder(); + for (char c : sequence.toCharArray()) { + if (c == end && inArgument) { + inArgument = false; + try { + int arg = Integer.parseInt(argument.toString()); + Object current = args[arg]; + Object replacement = + current instanceof Supplier ? ((Supplier)current).get() : + current instanceof Callable ? ((Callable)current).call() : + current; + builder.append(replacement); + } catch (NumberFormatException | IndexOutOfBoundsException ex) { + logger.warn("Invalid argument index '{}'", argument); + builder.append(start).append(argument).append(end); + } catch (Exception ex) { + throw new WrappedException(ex); + } + argument = new StringBuilder(); + continue; + } + if (c == start && !inArgument) { + inArgument = true; + continue; + } + if (inArgument) { + argument.append(c); + continue; + } + builder.append(c); + } + if (argument.length() > 0) builder.append(start).append(argument); + return builder.toString(); + } + + @Nonnull + public static String getAfterLastIndex(@Nonnull String input, @Nonnull String separator) { + return Optional.of(input) + .filter(name -> name.contains(separator)) + .map(name -> name.substring(name.lastIndexOf(separator) + separator.length())) + .orElse(""); + } + + @Nonnull + public static String[] format(@Nonnull String[] array, @Nonnull Object... args) { + String[] result = new String[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = format(array[i], args); + } + return result; + } + + @Nonnull + public static String getArrayAsString(@Nonnull String[] array, @Nonnull String separator) { + StringBuilder builder = new StringBuilder(); + for (String string : array) { + if (builder.length() != 0) builder.append(separator); + builder.append(string); + } + return builder.toString(); + } + + @Nonnull + public static String[] getStringAsArray(@Nonnull String string) { + return string.split("\n"); + } + + @Nonnull + public static String getIterableAsString(@Nonnull Iterable iterable, @Nonnull String separator, @Nonnull Function mapper) { + StringBuilder builder = new StringBuilder(); + for (T t : iterable) { + if (builder.length() > 0) builder.append(separator); + String string = mapper.apply(t); + builder.append(string); + } + return builder.toString(); + } + + @Nonnull + public static String repeat(@Nullable Object sequence, int amount) { + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < amount; i++) builder.append(sequence); + return builder.toString(); + } + + private static int getMultiplier(char c) { + switch (Character.toLowerCase(c)) { + default: return 1; + case 'm': return 60; + case 'h': return 60*60; + case 'd': return 24*60*60; + case 'w': return 7*24*60*60; + case 'y': return 365*24*60*60; + } + } + + public static long parseSeconds(@Nonnull String input) { + if (input.toLowerCase().startsWith("perm")) return -1; + long current = 0; + long seconds = 0; + for (char c : input.toCharArray()) { + try { + long i = Long.parseUnsignedLong(String.valueOf(c)); + current *= 10; + current += i; + } catch (Exception ignored) { + int multiplier = getMultiplier(c); + seconds += current * multiplier; + current = 0; + } + } + seconds += current; + return seconds; + } + + public static boolean isNumber(@Nonnull String sequence) { + try { + Double.parseDouble(sequence); + return true; + } catch (Exception ex) { + return false; + } + } + + private static int indexOf(@Nonnull String string, @Nonnull String pattern, int occurrenceIndex) { + int lastIndex = 0; + for (int currentLayer = 0; currentLayer <= occurrenceIndex; currentLayer++) { + int index = string.indexOf(pattern, (lastIndex > 0) ? lastIndex + 1 : 0); + if (index == -1) return -1; + lastIndex = index + 1; + } + + return lastIndex; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/Version.java b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java new file mode 100644 index 000000000..d9e31fedd --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java @@ -0,0 +1,105 @@ +package net.codingarea.commons.common.version; + +import net.codingarea.commons.common.annotations.Since; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; + +public interface Version { + + @Nonnegative + int getMajor(); + + @Nonnegative + int getMinor(); + + @Nonnegative + int getRevision(); + + default boolean isNewerThan(@Nonnull Version other) { + return this.intValue() > other.intValue(); + } + + default boolean isNewerOrEqualThan(@Nonnull Version other) { + return this.intValue() >= other.intValue(); + } + + default boolean isOlderThan(@Nonnull Version other) { + return this.intValue() < other.intValue(); + } + + default boolean isOlderOrEqualThan(@Nonnull Version other) { + return this.intValue() <= other.intValue(); + } + + default boolean equals(@Nonnull Version other) { + return this.intValue() == other.intValue(); + } + + @Nonnull + default String format() { + int revision = getRevision(); + return revision > 0 ? String.format("%s.%s.%s", getMajor(), getMinor(), revision) + : String.format("%s.%s", getMajor(), getMinor()); + } + + default int intValue() { + int major = getMajor(); + int minor = getMinor(); + int revision = getRevision(); + + if (major > 99) throw new IllegalStateException("Malformed version: major is greater than 99"); + if (minor > 99) throw new IllegalStateException("Malformed version: minor is greater than 99"); + if (revision > 99) throw new IllegalStateException("Malformed version: revision is greater than 99"); + + return revision + + minor * 100 + + major * 10000; + } + + @Nonnull + @CheckReturnValue + static Version parse(@Nullable String input) { + return parse(input, new VersionInfo(1, 0, 0)); + } + + @CheckReturnValue + static Version parse(@Nullable String input, Version def) { + return VersionInfo.parse(input, def); + } + + @Nonnull + @CheckReturnValue + static Version parseExceptionally(@Nullable String input) { + return VersionInfo.parseExceptionally(input); + } + + @Nonnull + @CheckReturnValue + static Version getAnnotatedSince(@Nonnull Object object) { + if (!object.getClass().isAnnotationPresent(Since.class)) return new VersionInfo(1, 0, 0); + return parse(object.getClass().getAnnotation(Since.class).value()); + } + + @Nonnull + @CheckReturnValue + static V findNearest(@Nonnull Version target, @Nonnull V[] sortedVersionsArray) { + List versions = new ArrayList<>(Arrays.asList(sortedVersionsArray)); + Collections.reverse(versions); + for (V version : versions) { + if (version.isNewerThan(target)) continue; + return version; + } + throw new IllegalArgumentException("No version found for '" + target + "'"); + } + + @Nonnull + @CheckReturnValue + static Comparator comparator() { + return new VersionComparator(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java new file mode 100644 index 000000000..14a6a89c7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.common.version; + +import javax.annotation.Nonnull; +import java.util.Comparator; + +public class VersionComparator implements Comparator { + + @Override + public int compare(@Nonnull Version v1, @Nonnull Version v2) { + return v1.equals(v2) ? 0 : v1.isNewerThan(v2) ? 1 : -1; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java new file mode 100644 index 000000000..29dbac10b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java @@ -0,0 +1,80 @@ +package net.codingarea.commons.common.version; + +import net.codingarea.commons.common.logging.ILogger; + +import javax.annotation.Nullable; +import java.util.Objects; + +public class VersionInfo implements Version { + + protected static final ILogger logger = ILogger.forThisClass(); + + private final int major, minor, revision; + + public VersionInfo() { + this(1, 0, 0); + } + + public VersionInfo(int major, int minor, int revision) { + this.major = major; + this.minor = minor; + this.revision = revision; + } + + public int getMajor() { + return major; + } + + public int getMinor() { + return minor; + } + + public int getRevision() { + return revision; + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof Version)) return false; + return this.equals((Version) other); + } + + @Override + public int hashCode() { + return Objects.hash(major, minor, revision); + } + + @Override + public String toString() { + return this.format(); + } + + /** + * @throws IllegalArgumentException + * If the version could not be parsed + */ + public static Version parseExceptionally(@Nullable String input) { + if (input == null) throw new IllegalArgumentException("Version cannot be null"); + String[] array = input.split("\\."); + if (array.length == 0) throw new IllegalArgumentException("Version cannot be empty"); + try { + int major = Integer.parseInt(array[0]); + int minor = array.length >= 2 ? Integer.parseInt(array[1]) : 0; + int revision = array.length >= 3 ? Integer.parseInt(array[2]) : 0; + return new VersionInfo(major, minor, revision); + } catch (Exception ex) { + throw new IllegalArgumentException("Cannot parse Version: " + input + " (" + ex.getMessage() + ")"); + } + } + + public static Version parse(@Nullable String input, Version def) { + try { + return parseExceptionally(input); + } catch (Exception ex) { + logger.error("Could not parse version for input {}", ex.getMessage()); + return def; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/Database.java b/plugin/src/main/java/net/codingarea/commons/database/Database.java new file mode 100644 index 000000000..9092f3c1f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/Database.java @@ -0,0 +1,110 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.common.concurrent.task.Task; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.database.action.*; +import net.codingarea.commons.database.exceptions.DatabaseAlreadyConnectedException; +import net.codingarea.commons.database.exceptions.DatabaseConnectionClosedException; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; + +public interface Database { + + ILogger LOGGER = ILogger.forThisClass(); + + @Nonnull + @CheckReturnValue + static Database empty() { + return new EmptyDatabase(true); + } + + @Nonnull + @CheckReturnValue + static Database unsupported() { + return new EmptyDatabase(false); + } + + boolean isConnected(); + + /** + * Creates the connection to the database synchronously. + * + * @throws DatabaseException + * If the connection could not be established + * @throws DatabaseAlreadyConnectedException + * If this database is already {@link #isConnected() connected} + */ + void connect() throws DatabaseException; + + /** + * Creates the connection to the database synchronously. + * No exceptions will be thrown if the process fails. + * + * @return {@code true} if the connection was established successfully + */ + boolean connectSafely(); + + /** + * Closes the connection to the database synchronously. + * + * @throws DatabaseException + * If something went wrong while closing the connection to the database + * @throws DatabaseConnectionClosedException + * If this database is not {@link #isConnected() connected} + */ + void disconnect() throws DatabaseException; + + /** + * Closes the connection to the database synchronously. + * No exceptions will be thrown if the process fails. + * + * @return {@code true} if the connection was closed without errors + */ + boolean disconnectSafely(); + + void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException; + void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns); + + @Nonnull + default Task createTableAsync(@Nonnull String name, @Nonnull SQLColumn... columns) { + return Task.asyncRunExceptionally(() -> createTable(name, columns)); + } + + @Nonnull + @CheckReturnValue + DatabaseListTables listTables(); + + @Nonnull + @CheckReturnValue + DatabaseCountEntries countEntries(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseQuery query(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseUpdate update(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseInsertion insert(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseDeletion delete(@Nonnull String table); + + @Nonnull + @CheckReturnValue + SpecificDatabase getSpecificDatabase(@Nonnull String name); + + @Nonnull + DatabaseConfig getConfig(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java new file mode 100644 index 000000000..8c67b2b87 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java @@ -0,0 +1,105 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.common.config.Propertyable; + +import javax.annotation.Nonnull; + +public final class DatabaseConfig { + + private final String host; + private final String database; + private final String authDatabase; + private final String password; + private final String user; + private final String file; + private final int port; + private final boolean portIsSet; + + public DatabaseConfig(String host, String database, String password, String user, int port) { + this(host, database, null, password, user, port, true, null); + } + public DatabaseConfig(String host, String database, String password, String user) { + this(host, database, null, password, user, 0, false, null); + } + + public DatabaseConfig(String host, String database, String authDatabase, String password, String user, int port) { + this(host, database, authDatabase, password, user, port, true, null); + } + public DatabaseConfig(String host, String database, String authDatabase, String password, String user) { + this(host, database, authDatabase, password, user, 0, false, null); + } + + public DatabaseConfig(String database, String file) { + this(null, database, null, null, null, 0, false, file); + } + + public DatabaseConfig(String host, String database, String authDatabase, String password, String user, int port, boolean portIsSet, String file) { + this.host = host; + this.database = database; + this.authDatabase = authDatabase; + this.password = password; + this.user = user; + this.port = port; + this.portIsSet = portIsSet; + this.file = file; + } + + public DatabaseConfig(@Nonnull Propertyable config) { + this( + config.getString("host"), + config.getString("database"), + config.getString("auth-database"), + config.getString("password"), + config.getString("user"), + config.getInt("port"), + config.contains("port"), + config.getString("file") + ); + } + + public int getPort() { + return port; + } + + public String getAuthDatabase() { + return authDatabase; + } + + public String getDatabase() { + return database; + } + + public String getHost() { + return host; + } + + public String getPassword() { + return password; + } + + public String getUser() { + return user; + } + + public boolean isPortSet() { + return portIsSet; + } + + public String getFile() { + return file; + } + + @Override + public String toString() { + return "DatabaseConfig{" + + "host='" + host + '\'' + + ", database='" + database + '\'' + + ", authDatabase='" + authDatabase + '\'' + + ", user='" + user + '\'' + + ", file='" + file + '\'' + + ", port=" + port + + ", portIsSet=" + portIsSet + + '}'; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java new file mode 100644 index 000000000..0770c8b67 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java @@ -0,0 +1,288 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.common.concurrent.task.Task; +import net.codingarea.commons.database.action.*; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.abstraction.DefaultExecutedQuery; +import net.codingarea.commons.database.abstraction.DefaultSpecificDatabase; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Collections; +import java.util.List; + +public class EmptyDatabase implements Database { + + private final boolean silent; + + public EmptyDatabase(boolean silent) { + this.silent = silent; + } + + public boolean isSilent() { + return silent; + } + + protected void exception(@Nonnull String message) { + throw new UnsupportedOperationException(message); + } + + @Override + public boolean isConnected() { + return false; + } + + @Override + public void connect() throws DatabaseException { + if (!silent) + exception("Cannot connect with a NOP Database"); + } + + @Override + public boolean connectSafely() { + return false; + } + + @Override + public void disconnect() throws DatabaseException { + if (!silent) + exception("Cannot disconnect from a NOP Database"); + } + + @Override + public boolean disconnectSafely() { + return false; + } + + @Override + public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { + if (!silent) + exception("Cannot create tables from a NOP Database"); + } + + @Override + public void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns) { + } + + @Nonnull + @Override + public DatabaseListTables listTables() { + if (!silent) + exception("Cannot list tables of a NOP Database"); + + return new EmptyListTables(); + } + + @Nonnull + @Override + public DatabaseCountEntries countEntries(@Nonnull String table) { + if (!silent) + exception("Cannot count entries of a NOP Database"); + + return new EmptyCountEntries(); + } + + @Nonnull + @Override + public DatabaseQuery query(@Nonnull String table) { + if (!silent) + exception("Cannot query in a NOP Database"); + + return new EmptyDatabaseQuery(); + } + + @Nonnull + @Override + public DatabaseUpdate update(@Nonnull String table) { + if (!silent) + exception("Cannot update in a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public DatabaseInsertion insert(@Nonnull String table) { + if (!silent) + exception("Cannot insert into a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { + if (!silent) + exception("Cannot inset or update into a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public DatabaseDeletion delete(@Nonnull String table) { + if (!silent) + exception("Cannot delete from a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public SpecificDatabase getSpecificDatabase(@Nonnull String name) { + return new DefaultSpecificDatabase(this, name); + } + + @Nonnull + @Override + public DatabaseConfig getConfig() { + throw new UnsupportedOperationException(); + } + + @Override + public String toString() { + return "EmptyDatabase[silent=" + silent + "]"; + } + + public static class EmptyDatabaseQuery implements DatabaseQuery { + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable Object object) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable Number value) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable String value) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery select(@Nonnull String... selection) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery orderBy(@Nonnull String field, @Nonnull Order order) { + return this; + } + + @Nonnull + @Override + public ExecutedQuery execute() throws DatabaseException { + return new DefaultExecutedQuery(Collections.emptyList()); + } + + @Nonnull + @Override + public Task executeAsync() { + return Task.syncCall(this::execute); + } + + } + + public static class EmptyVoidAction implements DatabaseDeletion, DatabaseInsertion, DatabaseUpdate, DatabaseInsertionOrUpdate { + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable Number value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable String value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction whereNot(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction set(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Override + public Void execute() throws DatabaseException { + return null; + } + + @Nonnull + @Override + public Task executeAsync() { + return Task.completedVoid(); + } + + } + + public static class EmptyCountEntries implements DatabaseCountEntries { + + @Nonnull + @Override + public Long execute() throws DatabaseException { + return 0L; + } + + @Nonnull + @Override + public Task executeAsync() { + return Task.completed(0L); + } + + } + + public static class EmptyListTables implements DatabaseListTables { + + @Nonnull + @Override + public List execute() throws DatabaseException { + return Collections.emptyList(); + } + + @Nonnull + @Override + public Task> executeAsync() { + return Task.completed(Collections.emptyList()); + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/Order.java b/plugin/src/main/java/net/codingarea/commons/database/Order.java new file mode 100644 index 000000000..8165ecb8e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/Order.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.database.action.hierarchy.OrderedAction; + +/** + * @see OrderedAction#orderBy(String, Order) + */ +public enum Order { + + HIGHEST, + LOWEST + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java b/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java new file mode 100644 index 000000000..f58d9d0aa --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java @@ -0,0 +1,134 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.common.misc.ReflectionUtils; +import net.codingarea.commons.common.misc.StringUtils; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Arrays; + +public final class SQLColumn { + + public enum Type { + /** A FIXED length string (can contain letters, numbers, and special characters). The size parameter specifies the column length in characters - can be from 0 to 255. Default is 1 */ + CHAR, + /** A VARIABLE length string (can contain letters, numbers, and special characters). The size parameter specifies the maximum column length in characters - can be from 0 to 65535 */ + VARCHAR, + /** Equal to {@link #CHAR}, but stores binary byte strings. The size parameter specifies the column length in bytes. Default is 1 */ + BINARY, + /** Equal to {@link #VARCHAR}, but stores binary byte strings. The size parameter specifies the maximum column length in bytes. */ + VARBINARY, + /** For BLOBs (Binary Large OBjects). Max length: 255 bytes */ + TINYBLOB, + /** Holds a string with a maximum length of 255 characters */ + TINYTEXT, + /** Holds a string with a maximum length of 65,535 bytes */ + TEXT, + /** For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data */ + BLOB, + /** For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data */ + MEDIUMTEXT, + /** For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data */ + MEDIUMBLOB, + /** Holds a string with a maximum length of 4,294,967,295 characters */ + LONGTEXT, + /** For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data */ + LONGBLOB, + /** A string object that can have only one value, chosen from a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. The values are sorted in the order you enter them */ + ENUM, + /** A string object that can have 0 or more values, chosen from a list of possible values. You can list up to 64 values in a SET list */ + SET, + /** A bit-value type. The number of bits per value is specified in size. The size parameter can hold a value from 1 to 64. The default value for size is 1. */ + BIT, + /** A very small integer. Signed range is from -128 to 127. Unsigned range is from 0 to 255. The size parameter specifies the maximum display width (which is 255) */ + TINYINT, + /** Zero is considered as false, nonzero values are considered as true. */ + BOOLEAN, + /** A small integer. Signed range is from -32768 to 32767. Unsigned range is from 0 to 65535. The size parameter specifies the maximum display width (which is 255) */ + SMALLINT, + /** A medium integer. Signed range is from -8388608 to 8388607. Unsigned range is from 0 to 16777215. The size parameter specifies the maximum display width (which is 255) */ + MEDIUMINT, + /** A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range is from 0 to 4294967295. The size parameter specifies the maximum display width (which is 255) */ + INT, + /** A large integer. Signed range is from -9223372036854775808 to 9223372036854775807. Unsigned range is from 0 to 18446744073709551615. The size parameter specifies the maximum display width (which is 255) */ + BIGINT, + /** A floating point number. MySQL uses the p value to determine whether to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to 24, the data type becomes FLOAT(). If p is from 25 to 53, the data type becomes DOUBLE() */ + FLOAT, + /** A normal-size floating point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter */ + DOUBLE, + /** An exact fixed-point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter. The maximum number for size is 65. The maximum number for d is 30. The default value for size is 10. The default value for d is 0.*/ + DECIMAL + } + + private final String name; + private final String type; + private final String param; + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nullable String param) { + if (name.contains(" ")) throw new IllegalArgumentException("Column name cannot contain spaces"); + if (type.contains(" ")) throw new IllegalArgumentException("Column type cannot contain spaces"); + + this.name = name; + this.type = type; + this.param = param; + } + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnegative int size) { + this(name, type, String.valueOf(size)); + } + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnegative int size, @Nonnegative int d) { + this(name, type, String.valueOf(size), String.valueOf(d)); + } + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnull String... params) { + this(name, type, StringUtils.getArrayAsString(params, ", ")); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nullable String param) { + this(name, type.name(), param); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnegative int size) { + this(name, type.name(), size); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnegative int size, @Nonnegative int d) { + this(name, type.name(), size, d); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnull String... params) { + this(name, type.name(), params); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnull Type... types) { + this(name, type, Arrays.stream(types).map(Type::name).toArray(String[]::new)); + } + + @Nonnull + public String getName() { + return name; + } + + @Nonnull + public String getType() { + return type; + } + + @Nullable + public Type findType() { + return ReflectionUtils.getEnumOrNull(type.toUpperCase(), Type.class); + } + + @Nullable + public String getParam() { + return param; + } + + @Override + public String toString() { + return name + " " + type + (param == null ? "" : "(" + param + ")"); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java b/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java new file mode 100644 index 000000000..56ae16184 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java @@ -0,0 +1,39 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.common.misc.ReflectionUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; + +public final class SimpleDatabaseTypeResolver { + + private SimpleDatabaseTypeResolver() {} + + private static final Map registry = new HashMap<>(); + static { + registerType("mongodb", "net.codingarea.commons.database.mongodb.MongoDBDatabase"); + registerType("mysql", "net.codingarea.commons.database.sql.mysql.MySQLDatabase"); + registerType("sqlite", "net.codingarea.commons.database.sql.sqlite.SQLiteDatabase"); + } + + @Nullable + public static Class findDatabaseType(@Nonnull String name) { + return ReflectionUtils.getClassOrNull(registry.get(name)); + } + + @Nullable + public static Class findDatabaseType(@Nonnull String name, boolean initialize, @Nonnull ClassLoader classLoader) { + return ReflectionUtils.getClassOrNull(registry.get(name), initialize, classLoader); + } + + public static void registerType(@Nonnull String name, @Nonnull String className) { + registry.put(name, className); + } + + public static void registerType(@Nonnull String name, @Nonnull Class databaseClass) { + registerType(name, databaseClass.getName()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java new file mode 100644 index 000000000..3ef75df74 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java @@ -0,0 +1,66 @@ +package net.codingarea.commons.database; + +import net.codingarea.commons.database.action.*; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; + +/** + * Represents a table/collection of a database + * + * @see Database + * @see Database#getSpecificDatabase(String) + */ +public interface SpecificDatabase { + + boolean isConnected(); + + @Nonnull + String getName(); + + /** + * @see Database#countEntries(String) + */ + @Nonnull + @CheckReturnValue + DatabaseCountEntries countEntries(); + + /** + * @see Database#query(String) + */ + @Nonnull + @CheckReturnValue + DatabaseQuery query(); + + /** + * @see Database#update(String) + */ + @Nonnull + @CheckReturnValue + DatabaseUpdate update(); + + /** + * @see Database#insert(String) + */ + @Nonnull + @CheckReturnValue + DatabaseInsertion insert(); + + /** + * @see Database#insertOrUpdate(String) + */ + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate insertOrUpdate(); + + /** + * @see Database#delete(String) + */ + @Nonnull + @CheckReturnValue + DatabaseDeletion delete(); + + @Nonnull + Database getParent(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java new file mode 100644 index 000000000..755ddeedd --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java @@ -0,0 +1,100 @@ +package net.codingarea.commons.database.abstraction; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.SQLColumn; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.exceptions.DatabaseAlreadyConnectedException; +import net.codingarea.commons.database.exceptions.DatabaseConnectionClosedException; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnull; + +public abstract class AbstractDatabase implements Database { + + protected final DatabaseConfig config; + + public AbstractDatabase(@Nonnull DatabaseConfig config) { + this.config = config; + } + + @Override + public boolean disconnectSafely() { + try { + disconnect(); + LOGGER.info("Successfully closed connection to database of type " + this.getClass().getSimpleName()); + return true; + } catch (DatabaseException ex) { + LOGGER.error("Could not disconnect from database (" + this.getClass().getSimpleName() + ")", ex); + return false; + } + } + + @Override + public void disconnect() throws DatabaseException { + checkConnection(); + try { + disconnect0(); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + protected abstract void disconnect0() throws Exception; + + @Override + public boolean connectSafely() { + try { + connect(); + LOGGER.status("Successfully created connection to database of type " + this.getClass().getSimpleName()); + return true; + } catch (DatabaseException ex) { + LOGGER.error("Could not connect to database (" + this.getClass().getSimpleName() + ")", ex); + return false; + } + } + + @Override + public void connect() throws DatabaseException { + if (isConnected()) throw new DatabaseAlreadyConnectedException(); + try { + connect0(); + } catch (Exception ex) { + if (ex instanceof DatabaseException) throw (DatabaseException) ex; + throw new DatabaseException(ex); + } + } + + protected abstract void connect0() throws Exception; + + @Override + public void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns) { + try { + createTable(name, columns); + } catch (DatabaseException ex) { + LOGGER.error("Could not create table (" + this.getClass().getSimpleName() + ")", ex); + } + } + + @Nonnull + @Override + public SpecificDatabase getSpecificDatabase(@Nonnull String name) { + return new DefaultSpecificDatabase(this, name); + } + + @Nonnull + @Override + public DatabaseConfig getConfig() { + return config; + } + + protected final void checkConnection() throws DatabaseConnectionClosedException { + if (!isConnected()) + throw new DatabaseConnectionClosedException(); + } + + @Override + public String toString() { + return this.getClass().getSimpleName() + "[connected=" + isConnected() + "]"; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java new file mode 100644 index 000000000..dd437cfb5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java @@ -0,0 +1,124 @@ +package net.codingarea.commons.database.abstraction; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.database.action.ExecutedQuery; + +import javax.annotation.Nonnull; +import java.io.PrintStream; +import java.util.*; +import java.util.function.IntFunction; +import java.util.function.Predicate; +import java.util.stream.Stream; + +public class DefaultExecutedQuery implements ExecutedQuery { + + protected final List results; + + public DefaultExecutedQuery(@Nonnull List results) { + this.results = results; + } + + @Nonnull + @Override + public Optional first() { + if (results.isEmpty()) return Optional.empty(); + return Optional.ofNullable(results.get(0)); + } + + @Nonnull + @Override + public Optional get(int index) { + if (index >= results.size()) return Optional.empty(); + return Optional.ofNullable(results.get(index)); + } + + @Nonnull + @Override + public Stream all() { + return results.stream(); + } + + @Nonnull + @Override + public > C toCollection(@Nonnull C collection) { + collection.addAll(results); + return collection; + } + + @Nonnull + @Override + public Document[] toArray(@Nonnull IntFunction arraySupplier) { + Document[] array = arraySupplier.apply(size()); + for (int i = 0; i < size(); i++) { + array[i] = results.get(i); + } + return array; + } + + @Override + public int index(@Nonnull Predicate filter) { + int index = 0; + for (Document result : results) { + if (filter.test(result)) + return index; + index++; + } + return -1; + } + + @Override + public boolean isEmpty() { + return results.isEmpty(); + } + + @Override + public boolean isSet() { + return !results.isEmpty(); + } + + @Override + public int size() { + return results.size(); + } + + @Override + public void print(@Nonnull PrintStream out) { + if (results.isEmpty()) { + out.println(""); + return; + } + + int index = 0; + for (Document result : results) { + out.print(index + " | "); + result.forEach((key, value) -> { + out.print(key + " = '" + value + "' "); + }); + out.println(); + index++; + } + } + + @Override + public Iterator iterator() { + return Collections.unmodifiableCollection(results).iterator(); + } + + @Override + public String toString() { + return "ExecutedQuery[size=" + size() + "]"; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DefaultExecutedQuery documents = (DefaultExecutedQuery) o; + return Objects.equals(results, documents.results); + } + + @Override + public int hashCode() { + return Objects.hash(results); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java new file mode 100644 index 000000000..52496f6c6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java @@ -0,0 +1,90 @@ +package net.codingarea.commons.database.abstraction; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.action.*; + +import javax.annotation.Nonnull; +import java.util.Objects; + +public class DefaultSpecificDatabase implements SpecificDatabase { + + protected final Database parent; + protected final String name; + + public DefaultSpecificDatabase(@Nonnull Database parent, @Nonnull String name) { + this.parent = parent; + this.name = name; + } + + @Override + public boolean isConnected() { + return parent.isConnected(); + } + + @Nonnull + @Override + public String getName() { + return name; + } + + @Nonnull + @Override + public DatabaseCountEntries countEntries() { + return parent.countEntries(name); + } + + @Nonnull + @Override + public DatabaseQuery query() { + return parent.query(name); + } + + @Nonnull + @Override + public DatabaseUpdate update() { + return parent.update(name); + } + + @Nonnull + @Override + public DatabaseInsertion insert() { + return parent.insert(name); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate() { + return parent.insertOrUpdate(name); + } + + @Nonnull + @Override + public DatabaseDeletion delete() { + return parent.delete(name); + } + + @Nonnull + @Override + public Database getParent() { + return parent; + } + + @Override + public String toString() { + return "SpecificDatabase[" + name + "]"; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DefaultSpecificDatabase that = (DefaultSpecificDatabase) o; + return Objects.equals(parent, that.parent) && Objects.equals(name, that.name); + } + + @Override + public int hashCode() { + return Objects.hash(parent, name); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java b/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java new file mode 100644 index 000000000..118141f4e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java @@ -0,0 +1,85 @@ +package net.codingarea.commons.database.access; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.Propertyable; +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiFunction; + +public class CachedDatabaseAccess extends DirectDatabaseAccess { + + protected final Map cache = new ConcurrentHashMap<>(); + + public CachedDatabaseAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config, @Nonnull BiFunction mapper) { + super(database, config, mapper); + } + + @Nullable + @Override + public V getValue(@Nonnull String key) throws DatabaseException { + V value = cache.get(key); + if (value != null) return value; + + value = super.getValue(key); + cache.put(key, value); + return value; + } + + @Nonnull + @Override + public V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException { + V value = cache.get(key); + if (value != null) return value; + + value = super.getValue(key, def); + cache.put(key, value); + return value; + } + + @Nonnull + @Override + public Optional getValueOptional(@Nonnull String key) throws DatabaseException { + V cached = cache.get(key); + if (cached != null) return Optional.of(cached); + + return super.getValueOptional(key); + } + + @Override + public void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException { + cache.put(key, value); + super.setValue(key, value); + } + + @Nonnull + public static CachedDatabaseAccess newStringAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getString); + } + + @Nonnull + public static CachedDatabaseAccess newIntAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getInt); + } + + @Nonnull + public static CachedDatabaseAccess newLongAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getLong); + } + + @Nonnull + public static CachedDatabaseAccess newDoubleAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getDouble); + } + + @Nonnull + public static CachedDatabaseAccess newDocumentAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Document::getDocument); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java new file mode 100644 index 000000000..9215c50cd --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java @@ -0,0 +1,33 @@ +package net.codingarea.commons.database.access; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Optional; + +public interface DatabaseAccess { + + @Nullable + V getValue(@Nonnull String key) throws DatabaseException; + + @Nonnull + V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException; + + @Nonnull + Optional getValueOptional(@Nonnull String key) throws DatabaseException; + + void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException; + + default boolean hasValue(@Nonnull String key) throws DatabaseException { + return getValueOptional(key).isPresent(); + } + + @Nonnull + Database getDatabase(); + + @Nonnull + DatabaseAccessConfig getConfig(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java new file mode 100644 index 000000000..824b8bbdd --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java @@ -0,0 +1,32 @@ +package net.codingarea.commons.database.access; + +import javax.annotation.Nonnull; + +public final class DatabaseAccessConfig { + + private final String table; + private final String keyField; + private final String valueField; + + public DatabaseAccessConfig(@Nonnull String table, @Nonnull String keyField, @Nonnull String valueField) { + this.table = table; + this.keyField = keyField; + this.valueField = valueField; + } + + @Nonnull + public String getTable() { + return table; + } + + @Nonnull + public String getKeyField() { + return keyField; + } + + @Nonnull + public String getValueField() { + return valueField; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java b/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java new file mode 100644 index 000000000..e2213d1bc --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java @@ -0,0 +1,69 @@ +package net.codingarea.commons.database.access; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Optional; +import java.util.function.BiFunction; + +public class DirectDatabaseAccess implements DatabaseAccess { + + protected final Database database; + protected final DatabaseAccessConfig config; + protected final BiFunction mapper; + + public DirectDatabaseAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config, @Nonnull BiFunction mapper) { + this.database = database; + this.config = config; + this.mapper = mapper; + } + + @Nullable + @Override + public V getValue(@Nonnull String key) throws DatabaseException { + return getValue0(key).orElse(null); + } + + @Nonnull + @Override + public V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException { + return getValue0(key).orElse(def); + } + + @Nonnull + @Override + public Optional getValueOptional(@Nonnull String key) throws DatabaseException { + return getValue0(key); + } + + @Nonnull + protected Optional getValue0(@Nonnull String key) throws DatabaseException { + return database.query(config.getTable()) + .where(config.getKeyField(), key) + .execute().first() + .map(document -> mapper.apply(document, config.getValueField())); + } + + @Override + public void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException { + database.insertOrUpdate(config.getTable()) + .set(config.getValueField(), value) + .where(config.getKeyField(), key) + .execute(); + } + + @Nonnull + @Override + public Database getDatabase() { + return database; + } + + @Nonnull + @Override + public DatabaseAccessConfig getConfig() { + return config; + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java new file mode 100644 index 000000000..da7a8ee61 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java @@ -0,0 +1,82 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.common.concurrent.task.Task; +import net.codingarea.commons.database.action.hierarchy.OrderedAction; +import net.codingarea.commons.database.action.hierarchy.SetAction; +import net.codingarea.commons.database.action.hierarchy.WhereAction; +import net.codingarea.commons.database.exceptions.DatabaseConnectionClosedException; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.exceptions.UnsignedDatabaseException; + +import javax.annotation.Nonnull; + +/** + * Some action which will be executed on a database. + * + * This action is only prepared. + * + * It will be executed synchronously by calling {@link #execute()}, + * a {@link DatabaseException} will be thrown when something goes from or + * a {@link DatabaseConnectionClosedException} will be thrown + * when the connection to the database is already closed. + * + * It will also be executed synchronously by calling {@link #executeUnsigned()} but this method has no signed exceptions ({@code throws} declaration), + * so when an exception occurs it will be rethrown as a {@link UnsignedDatabaseException}. + * + * Calling {@link #executeAsync()} will return a new {@link Task} which will complete when the action is done or fail if something went wrong (a {@link DatabaseException} was thrown). + * + * @param The type of the result this action will return + * + * @see WhereAction + * @see SetAction + * @see OrderedAction + * + * @see DatabaseListTables + * @see DatabaseCountEntries + * @see DatabaseDeletion + * @see DatabaseUpdate + * @see DatabaseInsertion + * @see DatabaseInsertionOrUpdate + * @see DatabaseQuery + */ +public interface DatabaseAction { + + /** + * Executes this action synchronously + * + * @return the result of type {@link R} returned by the database + * + * @throws DatabaseException + * If a database error occurs + * @throws DatabaseConnectionClosedException + * If the database is no longer connected + */ + R execute() throws DatabaseException; + + /** + * Executes this action synchronously without any signed exceptions + * + * @return the result of type {@link R} returned by the database + * + * @throws UnsignedDatabaseException + * If a database error occurs + */ + default R executeUnsigned() { + try { + return execute(); + } catch (DatabaseException ex) { + throw new UnsignedDatabaseException(ex); + } + } + + /** + * Executes this action asynchronous + * + * @return a new {@link Task} which will be completed when the action was executed + */ + @Nonnull + default Task executeAsync() { + return Task.asyncCall(this::execute); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java new file mode 100644 index 000000000..70bedb389 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java @@ -0,0 +1,21 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; + +/** + * @see Database#countEntries(String) + * @see SpecificDatabase#countEntries() + */ +public interface DatabaseCountEntries extends DatabaseAction { + + @Nonnull + @Override + @Nonnegative + Long execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java new file mode 100644 index 000000000..3c3b20fe1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java @@ -0,0 +1,42 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.action.hierarchy.WhereAction; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * @see Database#delete(String) + * @see SpecificDatabase#delete() + */ +public interface DatabaseDeletion extends DatabaseAction, WhereAction { + + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable String value); + + @Nonnull + @CheckReturnValue + DatabaseDeletion whereNot(@Nonnull String field, @Nullable Object value); + + @Nullable + @Override + Void execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java new file mode 100644 index 000000000..ef0d7b8ca --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java @@ -0,0 +1,26 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.action.hierarchy.SetAction; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * @see Database#insert(String) + * @see SpecificDatabase#insert() + */ +public interface DatabaseInsertion extends DatabaseAction, SetAction { + + @Nonnull + @CheckReturnValue + DatabaseInsertion set(@Nonnull String field, @Nullable Object value); + + @Nullable + @Override + Void execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java new file mode 100644 index 000000000..000f76a09 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java @@ -0,0 +1,45 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * @see Database#insertOrUpdate(String) + * @see SpecificDatabase#insertOrUpdate() + */ +public interface DatabaseInsertionOrUpdate extends DatabaseUpdate, DatabaseInsertion { + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value); + + @Nonnull + @Override + DatabaseInsertionOrUpdate whereNot(@Nonnull String field, @Nullable Object value); + + @Nonnull + @Override + DatabaseInsertionOrUpdate set(@Nonnull String field, @Nullable Object value); + + @Nullable + @Override + Void execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java new file mode 100644 index 000000000..be7173659 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java @@ -0,0 +1,18 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.Nonnull; +import java.util.List; + +/** + * @see Database#listTables() + */ +public interface DatabaseListTables extends DatabaseAction> { + + @Nonnull + @Override + List execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java new file mode 100644 index 000000000..770b8b542 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java @@ -0,0 +1,53 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.Order; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.action.hierarchy.OrderedAction; +import net.codingarea.commons.database.action.hierarchy.WhereAction; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * @see Database#query(String) + * @see SpecificDatabase#query() + */ +public interface DatabaseQuery extends DatabaseAction, WhereAction, OrderedAction { + + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable Object object); + + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable String value); + + @Nonnull + @CheckReturnValue + DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseQuery select(@Nonnull String... selection); + + @Nonnull + @CheckReturnValue + DatabaseQuery orderBy(@Nonnull String field, @Nonnull Order order); + + @Nonnull + @Override + @CheckReturnValue + ExecutedQuery execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java new file mode 100644 index 000000000..83073b113 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java @@ -0,0 +1,47 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.database.Database; +import net.codingarea.commons.database.SpecificDatabase; +import net.codingarea.commons.database.action.hierarchy.SetAction; +import net.codingarea.commons.database.action.hierarchy.WhereAction; +import net.codingarea.commons.database.exceptions.DatabaseException; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +/** + * @see Database#update(String) + * @see SpecificDatabase#update() + */ +public interface DatabaseUpdate extends DatabaseAction, WhereAction, SetAction { + + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable String value); + + @Nonnull + @CheckReturnValue + DatabaseUpdate whereNot(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseUpdate set(@Nonnull String field, @Nullable Object value); + + @Nullable + @Override + Void execute() throws DatabaseException; + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java b/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java new file mode 100644 index 000000000..37cf98630 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java @@ -0,0 +1,86 @@ +package net.codingarea.commons.database.action; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.logging.ILogger; +import net.codingarea.commons.common.logging.LogLevel; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import java.io.PrintStream; +import java.util.*; +import java.util.function.IntFunction; +import java.util.function.Predicate; +import java.util.stream.Stream; + +/** + * @see DatabaseQuery#execute() + */ +public interface ExecutedQuery extends Iterable { + + @Nonnull + @CheckReturnValue + Optional first(); + + @Nonnull + @CheckReturnValue + default Document firstOrEmpty() { + return first().orElse(Document.empty()); + } + + @Nonnull + @CheckReturnValue + Optional get(int index); + + @Nonnull + @CheckReturnValue + default Document getOrEmpty(int index) { + return get(index).orElse(Document.empty()); + } + + @Nonnull + @CheckReturnValue + Stream all(); + + @Nonnull + @CheckReturnValue + default List toList() { + return toCollection((IntFunction>) ArrayList::new); + } + + @Nonnull + @CheckReturnValue + default Set toSet() { + return toCollection((IntFunction>) HashSet::new); + } + + @Nonnull + > C toCollection(@Nonnull C collection); + + @Nonnull + @CheckReturnValue + default > C toCollection(@Nonnull IntFunction collectionSupplier) { + return toCollection(collectionSupplier.apply(size())); + } + + @Nonnull + Document[] toArray(@Nonnull IntFunction arraySupplier); + + int index(@Nonnull Predicate filter); + + boolean isEmpty(); + + boolean isSet(); + + int size(); + + void print(@Nonnull PrintStream out); + + default void print(@Nonnull ILogger logger) { + print(logger.asPrintStream(LogLevel.INFO)); + } + + default void print() { + print(System.out); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java new file mode 100644 index 000000000..edfdc29b1 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.database.action.hierarchy; + +import net.codingarea.commons.database.Order; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface OrderedAction { + + @Nullable + OrderedAction orderBy(@Nonnull String field, @Nonnull Order order); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java new file mode 100644 index 000000000..cb395773b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java @@ -0,0 +1,11 @@ +package net.codingarea.commons.database.action.hierarchy; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface SetAction { + + @Nonnull + SetAction set(@Nonnull String field, @Nullable Object value); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java new file mode 100644 index 000000000..5e5d69c9d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java @@ -0,0 +1,29 @@ +package net.codingarea.commons.database.action.hierarchy; + +import javax.annotation.CheckReturnValue; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public interface WhereAction { + + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable String value); + + @Nonnull + @CheckReturnValue + WhereAction whereNot(@Nonnull String field, @Nullable Object value); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseAlreadyConnectedException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseAlreadyConnectedException.java new file mode 100644 index 000000000..192f891f6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseAlreadyConnectedException.java @@ -0,0 +1,12 @@ +package net.codingarea.commons.database.exceptions; + +/** + * This exception in thrown, when a database tries to connect but is already connected. + */ +public class DatabaseAlreadyConnectedException extends DatabaseException { + + public DatabaseAlreadyConnectedException() { + super("Database already connected"); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseConnectionClosedException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseConnectionClosedException.java new file mode 100644 index 000000000..f3563f241 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseConnectionClosedException.java @@ -0,0 +1,12 @@ +package net.codingarea.commons.database.exceptions; + +/** + * This exception is thrown, when a database operation is tried which requires a active connection, but the database is not connected. + */ +public class DatabaseConnectionClosedException extends DatabaseException { + + public DatabaseConnectionClosedException() { + super("Database connection closed"); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java new file mode 100644 index 000000000..d42805661 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java @@ -0,0 +1,31 @@ +package net.codingarea.commons.database.exceptions; + +import net.codingarea.commons.database.action.DatabaseAction; + +import javax.annotation.Nonnull; + +/** + * @see DatabaseAlreadyConnectedException + * @see DatabaseConnectionClosedException + * @see DatabaseUnsupportedFeatureException + * + * @see DatabaseAction#execute() + */ +public class DatabaseException extends Exception { + + protected DatabaseException() { + super(); + } + + public DatabaseException(@Nonnull String message) { + super(message); + } + + public DatabaseException(@Nonnull Throwable cause) { + super(cause); + } + + public DatabaseException(@Nonnull String message, @Nonnull Throwable cause) { + super(message, cause); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java new file mode 100644 index 000000000..0f57f6827 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java @@ -0,0 +1,14 @@ +package net.codingarea.commons.database.exceptions; + +import javax.annotation.Nonnull; + +public class DatabaseUnsupportedFeatureException extends DatabaseException { + + public DatabaseUnsupportedFeatureException() { + } + + public DatabaseUnsupportedFeatureException(@Nonnull String message) { + super(message); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java new file mode 100644 index 000000000..a5f96d5f9 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java @@ -0,0 +1,24 @@ +package net.codingarea.commons.database.exceptions; + +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.database.action.DatabaseAction; + +import javax.annotation.Nonnull; + +/** + * @see DatabaseException + * + * @see DatabaseAction#executeUnsigned() + */ +public class UnsignedDatabaseException extends WrappedException { + + public UnsignedDatabaseException(@Nonnull DatabaseException cause) { + super(cause); + } + + @Nonnull + @Override + public DatabaseException getCause() { + return (DatabaseException) super.getCause(); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java new file mode 100644 index 000000000..10887b6c3 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java @@ -0,0 +1,134 @@ +package net.codingarea.commons.database.sql.abstraction; + +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.SQLColumn; +import net.codingarea.commons.database.action.*; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.abstraction.AbstractDatabase; +import net.codingarea.commons.database.sql.abstraction.count.SQLCountEntries; +import net.codingarea.commons.database.sql.abstraction.deletion.SQLDeletion; +import net.codingarea.commons.database.sql.abstraction.insertion.SQLInsertion; +import net.codingarea.commons.database.sql.abstraction.insertorupdate.SQLInsertionOrUpdate; +import net.codingarea.commons.database.sql.abstraction.query.SQLQuery; +import net.codingarea.commons.database.sql.abstraction.update.SQLUpdate; +import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; + +import javax.annotation.Nonnull; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Map; + +public abstract class AbstractSQLDatabase extends AbstractDatabase { + + protected Connection connection; + + public AbstractSQLDatabase(@Nonnull DatabaseConfig config) { + super(config); + } + + @Override + public void disconnect0() throws Exception { + connection.close(); + connection = null; + } + + @Override + public void connect0() throws Exception { + connection = DriverManager.getConnection(createUrl(), config.getUser(), config.getPassword()); + } + + protected abstract String createUrl(); + + @Override + public boolean isConnected() { + try { + if (connection == null) return false; + connection.isClosed(); + return true; + } catch (SQLException ex) { + LOGGER.error("Could not check connection state: " + ex.getMessage()); + return false; + } + } + + @Override + public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { + try { + StringBuilder command = new StringBuilder(); + command.append("CREATE TABLE IF NOT EXISTS `"); + command.append(name); + command.append("` ("); + { + int index = 0; + for (SQLColumn column : columns) { + if (index > 0) command.append(", "); + command.append(column); + index++; + } + } + command.append(")"); + + PreparedStatement statement = prepare(command.toString()); + statement.execute(); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Nonnull + @Override + public DatabaseCountEntries countEntries(@Nonnull String table) { + return new SQLCountEntries(this, table); + } + + @Nonnull + @Override + public DatabaseQuery query(@Nonnull String table) { + return new SQLQuery(this, table); + } + + @Nonnull + public DatabaseQuery query(@Nonnull String table, @Nonnull Map where) { + return new SQLQuery(this, table, where); + } + + @Nonnull + @Override + public DatabaseUpdate update(@Nonnull String table) { + return new SQLUpdate(this, table); + } + + @Nonnull + @Override + public DatabaseInsertion insert(@Nonnull String table) { + return new SQLInsertion(this, table); + } + + @Nonnull + public DatabaseInsertion insert(@Nonnull String table, @Nonnull Map values) { + return new SQLInsertion(this, table, values); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { + return new SQLInsertionOrUpdate(this, table); + } + + @Nonnull + @Override + public DatabaseDeletion delete(@Nonnull String table) { + return new SQLDeletion(this, table); + } + + @Nonnull + public PreparedStatement prepare(@Nonnull CharSequence command, @Nonnull Object... args) throws SQLException, DatabaseException { + checkConnection(); + PreparedStatement statement = connection.prepareStatement(command.toString()); + SQLHelper.fillParams(statement, args); + return statement; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java new file mode 100644 index 000000000..9fdf86b6c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java @@ -0,0 +1,37 @@ +package net.codingarea.commons.database.sql.abstraction; + +import net.codingarea.commons.common.config.Json; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.misc.GsonUtils; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Map; + +public final class SQLHelper { + + private SQLHelper() {} + + public static void fillParams(@Nonnull PreparedStatement statement, @Nonnull Object... params) throws SQLException { + for (int i = 0; i < params.length; i++) { + Object param = serializeObject(params[i]); + statement.setObject(i + 1 /* in sql we count from 1 */, param); + } + } + + @Nullable + public static Object serializeObject(@Nullable Object object) { + if (object == null) return null; + if (object instanceof Number) return object; + if (object instanceof Boolean) return object; + if (object instanceof Enum) return ((Enum)object).name(); + if (object instanceof Json) return ((Json)object).toJson(); + if (object instanceof Map) return new GsonDocument((Map) object).toJson(); + if (object instanceof Iterable) return GsonUtils.convertIterableToJsonArray(GsonDocument.GSON, (Iterable) object).toString(); + if (object.getClass().isArray()) return GsonUtils.convertArrayToJsonArray(GsonDocument.GSON, object).toString(); + return object.toString(); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java new file mode 100644 index 000000000..dbf6aa821 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java @@ -0,0 +1,54 @@ +package net.codingarea.commons.database.sql.abstraction.count; + +import net.codingarea.commons.database.action.DatabaseCountEntries; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; + +import javax.annotation.Nonnull; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.Objects; + +public class SQLCountEntries implements DatabaseCountEntries { + + protected final AbstractSQLDatabase database; + protected final String table; + + public SQLCountEntries(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + } + + @Nonnull + @Override + public Long execute() throws DatabaseException { + try { + PreparedStatement statement = database.prepare("SELECT COUNT(*) FROM `" + table + "`"); + ResultSet result = statement.executeQuery(); + + if (!result.next()) { + result.close(); + return 0L; + } + + long count = result.getLong(1); + result.close(); + return count; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLCountEntries that = (SQLCountEntries) o; + return Objects.equals(database, that.database) && Objects.equals(table, that.table); + } + + @Override + public int hashCode() { + return Objects.hash(database, table); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java new file mode 100644 index 000000000..d1dfeaf9b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java @@ -0,0 +1,110 @@ +package net.codingarea.commons.database.sql.abstraction.deletion; + +import net.codingarea.commons.database.action.DatabaseDeletion; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.abstraction.where.ObjectWhere; +import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; +import net.codingarea.commons.database.sql.abstraction.where.StringIgnoreCaseWhere; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.*; +import java.util.Map.Entry; + +public class SQLDeletion implements DatabaseDeletion { + + protected final AbstractSQLDatabase database; + protected final String table; + protected final Map where = new HashMap<>(); + + public SQLDeletion(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "=")); + return this; + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @Nonnull + @Override + public DatabaseDeletion whereNot(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "!=")); + return this; + } + + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + StringBuilder command = new StringBuilder(); + List args = new ArrayList<>(); + + command.append("DELETE FROM "); + command.append(table); + + if (!where.isEmpty()) { + command.append(" WHERE "); + int index = 0; + for (Entry entry : where.entrySet()) { + SQLWhere where = entry.getValue(); + if (index > 0) command.append(" AND "); + command.append(where.getAsSQLString()); + args.addAll(Arrays.asList(where.getArgs())); + index++; + } + } + + return database.prepare(command.toString(),args.toArray()); + } + + @Override + public Void execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + statement.execute(); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLDeletion that = (SQLDeletion) o; + return database.equals(that.database) && table.equals(that.table) && where.equals(that.where); + } + + @Override + public int hashCode() { + return Objects.hash(database, table, where); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java new file mode 100644 index 000000000..6af25eaa4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java @@ -0,0 +1,95 @@ +package net.codingarea.commons.database.sql.abstraction.insertion; + +import net.codingarea.commons.database.action.DatabaseInsertion; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.*; + +public class SQLInsertion implements DatabaseInsertion { + + protected final Map values; + protected final AbstractSQLDatabase database; + protected final String table; + + public SQLInsertion(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + this.values = new HashMap<>(); + } + + public SQLInsertion(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map values) { + this.database = database; + this.table = table; + this.values = values; + } + + @Nonnull + @Override + public DatabaseInsertion set(@Nonnull String field, @Nullable Object value) { + values.put(field, value); + return this; + } + + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + if (values.isEmpty()) throw new IllegalArgumentException("Cannot insert nothing"); + + StringBuilder command = new StringBuilder(); + List args = new ArrayList<>(values.size()); + + command.append("INSERT INTO "); + command.append(table); + command.append(" ("); + { + int index = 0; + for (String column : values.keySet()) { + if (index > 0) command.append(", "); + command.append(column); + index++; + } + } + command.append(") VALUES ("); + { + int index = 0; + for (Object value : values.values()) { + if (index > 0) command.append(", "); + command.append("?"); + args.add(value); + index++; + } + } + command.append(")"); + + return database.prepare(command.toString(), args.toArray()); + } + + @Override + public Void execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + statement.execute(); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLInsertion that = (SQLInsertion) o; + return values.equals(that.values) && database.equals(that.database) && table.equals(that.table); + } + + @Override + public int hashCode() { + return Objects.hash(values, database, table); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java new file mode 100644 index 000000000..f89cbc135 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java @@ -0,0 +1,85 @@ +package net.codingarea.commons.database.sql.abstraction.insertorupdate; + +import net.codingarea.commons.database.action.DatabaseInsertionOrUpdate; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.abstraction.update.SQLUpdate; +import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +public class SQLInsertionOrUpdate extends SQLUpdate implements DatabaseInsertionOrUpdate { + + public SQLInsertionOrUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + super(database, table); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable Object value) { + super.where(column, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable Number value) { + super.where(column, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + super.where(column, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable String value) { + super.where(column, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate whereNot(@Nonnull String column, @Nullable Object value) { + super.whereNot(column, value); + return this; + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate set(@Nonnull String column, @Nullable Object value) { + super.set(column, value); + return this; + } + + @Override + public Void execute() throws DatabaseException { + if (database.query(table, where).execute().isSet()) { + return super.execute(); + } else { + Map insert = new HashMap<>(values); + for (Entry entry : where.entrySet()) { + Object[] args = entry.getValue().getArgs(); + if (args.length == 0) continue; + insert.put(entry.getKey(), args[0]); + } + + database.insert(table, insert).execute(); + return null; + } + } + + @Override + public boolean equals(Object o) { + return super.equals(o); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java new file mode 100644 index 000000000..75536fe81 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java @@ -0,0 +1,176 @@ +package net.codingarea.commons.database.sql.abstraction.query; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.database.Order; +import net.codingarea.commons.database.action.DatabaseQuery; +import net.codingarea.commons.database.action.ExecutedQuery; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.abstraction.DefaultExecutedQuery; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.abstraction.where.ObjectWhere; +import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; +import net.codingarea.commons.database.sql.abstraction.where.StringIgnoreCaseWhere; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.util.*; +import java.util.Map.Entry; + +public class SQLQuery implements DatabaseQuery { + + protected final AbstractSQLDatabase database; + protected final String table; + protected final Map where; + protected String[] selection = { "*" }; + protected String orderBy; + protected Order order; + + public SQLQuery(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + this.where = new HashMap<>(); + } + + public SQLQuery(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map where) { + this.database = database; + this.table = table; + this.where = where; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, "=")); + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @Nonnull + @Override + public DatabaseQuery whereNot(@Nonnull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, "!=")); + return this; + } + + @Nonnull + @Override + public DatabaseQuery orderBy(@Nonnull String column, @Nonnull Order order) { + this.orderBy = column; + this.order = order; + return this; + } + + @Nonnull + @Override + public DatabaseQuery select(@Nonnull String... selection) { + if (selection.length == 0) throw new IllegalArgumentException("Cannot select noting"); + this.selection = selection; + return this; + } + + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + StringBuilder command = new StringBuilder(); + List args = new LinkedList<>(); + + command.append("SELECT "); + for (int i = 0; i < selection.length; i++) { + if (i > 0) command.append(", "); + command.append(selection[i]); + } + command.append(" FROM "); + command.append(table); + + if (!where.isEmpty()) { + command.append(" WHERE "); + int index = 0; + for (Entry entry : where.entrySet()) { + SQLWhere where = entry.getValue(); + if (index > 0) command.append(" AND "); + command.append(where.getAsSQLString()); + args.addAll(Arrays.asList(where.getArgs())); + index++; + } + } + + if (orderBy != null) { + command.append(" ORDER BY "); + command.append(orderBy); + if (order != null) + command.append(" " + (order == Order.HIGHEST ? "DESC" : "ASC")); + command.append(" "); + } + + return database.prepare(command.toString(), args.toArray()); + } + + @Nonnull + @Override + public ExecutedQuery execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + ResultSet result = statement.executeQuery(); + return createExecutedQuery(result); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Nonnull + private ExecutedQuery createExecutedQuery(@Nonnull ResultSet result) throws SQLException { + List results = new ArrayList<>(); + ResultSetMetaData data = result.getMetaData(); + while (result.next()) { + Map map = new HashMap<>(); + for (int i = 1; i <= data.getColumnCount(); i++) { + Object value = result.getObject(i); + map.put(data.getColumnLabel(i), value); + } + Document row = new SQLResult(map); + results.add(row); + } + result.close(); + + return new DefaultExecutedQuery(results); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLQuery sqlQuery = (SQLQuery) o; + return database.equals(sqlQuery.database) && table.equals(sqlQuery.table) && where.equals(sqlQuery.where) && Arrays.equals(selection, sqlQuery.selection) && Objects.equals(orderBy, sqlQuery.orderBy) && order == sqlQuery.order; + } + + @Override + public int hashCode() { + int result = Objects.hash(database, table, where, orderBy, order); + result = 31 * result + Arrays.hashCode(selection); + return result; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java new file mode 100644 index 000000000..2d6536855 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java @@ -0,0 +1,33 @@ +package net.codingarea.commons.database.sql.abstraction.query; + +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.EmptyDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.MapDocument; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Map; + +public final class SQLResult extends MapDocument { + + public SQLResult(@Nonnull Map values) { + super(values); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + try { + return new GsonDocument(getString(path), this, this).readonly(); + } catch (Exception ex) { + return new EmptyDocument(this, null); + } + } + + @Override + public boolean isReadonly() { + return true; + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java new file mode 100644 index 000000000..d3b4cd844 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java @@ -0,0 +1,140 @@ +package net.codingarea.commons.database.sql.abstraction.update; + +import net.codingarea.commons.database.action.DatabaseUpdate; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.abstraction.where.ObjectWhere; +import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; +import net.codingarea.commons.database.sql.abstraction.where.StringIgnoreCaseWhere; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.*; +import java.util.Map.Entry; + +public class SQLUpdate implements DatabaseUpdate { + + protected final AbstractSQLDatabase database; + protected final String table; + protected final Map where; + protected final Map values; + + public SQLUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + this.where = new HashMap<>(); + this.values = new HashMap<>(); + } + + public SQLUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map where, @Nonnull Map values) { + this.database = database; + this.table = table; + this.where = where; + this.values = values; + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "=")); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate whereNot(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "!=")); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate set(@Nonnull String column, @Nullable Object value) { + values.put(column, value); + return this; + } + + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + if (values.isEmpty()) throw new IllegalArgumentException("Can't update nothing"); + + StringBuilder command = new StringBuilder(); + List args = new ArrayList<>(); + + command.append("UPDATE "); + command.append(table); + command.append(" SET "); + + { + int index = 0; + for (Entry entry : values.entrySet()) { + if (index > 0) command.append(", "); + command.append("`" + entry.getKey() + "` = ?"); + args.add(entry.getValue()); + index++; + } + } + + if (!where.isEmpty()) { + command.append(" WHERE "); + int index = 0; + for (Entry entry : where.entrySet()) { + SQLWhere where = entry.getValue(); + if (index > 0) command.append(" AND "); + command.append(where.getAsSQLString()); + args.addAll(Arrays.asList(where.getArgs())); + index++; + } + } + + return database.prepare(command.toString(), args.toArray()); + } + + @Override + public Void execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + statement.executeUpdate(); + return null; + } catch (SQLException ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLUpdate sqlUpdate = (SQLUpdate) o; + return database.equals(sqlUpdate.database) && table.equals(sqlUpdate.table) && where.equals(sqlUpdate.where) && values.equals(sqlUpdate.values); + } + + @Override + public int hashCode() { + return Objects.hash(database, table, where, values); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java new file mode 100644 index 000000000..f398190fc --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java @@ -0,0 +1,44 @@ +package net.codingarea.commons.database.sql.abstraction.where; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Objects; + +public class ObjectWhere implements SQLWhere { + + protected final String column; + protected final Object value; + protected final String comparator; + + public ObjectWhere(@Nonnull String column, @Nullable Object value, @Nonnull String comparator) { + this.column = column; + this.value = value; + this.comparator = comparator; + } + + @Nonnull + @Override + public Object[] getArgs() { + return new Object[] { value }; + } + + @Nonnull + @Override + public String getAsSQLString() { + return String.format("`%s` %s ?", column, comparator); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ObjectWhere that = (ObjectWhere) o; + return column.equals(that.column) && Objects.equals(value, that.value); + } + + @Override + public int hashCode() { + return Objects.hash(column, value); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java new file mode 100644 index 000000000..a16075f93 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java @@ -0,0 +1,13 @@ +package net.codingarea.commons.database.sql.abstraction.where; + +import javax.annotation.Nonnull; + +public interface SQLWhere { + + @Nonnull + Object[] getArgs(); + + @Nonnull + String getAsSQLString(); + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java new file mode 100644 index 000000000..7a3fe07b6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java @@ -0,0 +1,41 @@ +package net.codingarea.commons.database.sql.abstraction.where; + +import javax.annotation.Nonnull; +import java.util.Objects; + +public class StringIgnoreCaseWhere implements SQLWhere { + + protected final String column; + protected final String value; + + public StringIgnoreCaseWhere(@Nonnull String column, @Nonnull String value) { + this.column = column; + this.value = value; + } + + @Nonnull + @Override + public Object[] getArgs() { + return new Object[] { value }; + } + + @Nonnull + @Override + public String getAsSQLString() { + return String.format("LOWER(%s) = LOWER(?)", column); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + StringIgnoreCaseWhere that = (StringIgnoreCaseWhere) o; + return column.equals(that.column) && value.equals(that.value); + } + + @Override + public int hashCode() { + return Objects.hash(column, value); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java new file mode 100644 index 000000000..627b39e20 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java @@ -0,0 +1,36 @@ +package net.codingarea.commons.database.sql.mysql; + +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.action.DatabaseListTables; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.mysql.list.MySQLListTables; + +import javax.annotation.Nonnull; + +public class MySQLDatabase extends AbstractSQLDatabase { + + static { + try { + Class.forName("com.mysql.cj.jdbc.Driver"); + } catch (ClassNotFoundException ex) { + LOGGER.error("Could not load mysql driver"); + } + } + + public MySQLDatabase(@Nonnull DatabaseConfig config) { + super(config); + } + + @Nonnull + @Override + protected String createUrl() { + return "jdbc:mysql://" + config.getHost() + (config.isPortSet() ? ":" + config.getPort() : "") + "/" + config.getDatabase(); + } + + @Nonnull + @Override + public DatabaseListTables listTables() { + return new MySQLListTables(this); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java new file mode 100644 index 000000000..2d60ee58b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java @@ -0,0 +1,38 @@ +package net.codingarea.commons.database.sql.mysql.list; + +import net.codingarea.commons.database.action.DatabaseListTables; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; + +import javax.annotation.Nonnull; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; + +public class MySQLListTables implements DatabaseListTables { + + protected final AbstractSQLDatabase database; + + public MySQLListTables(@Nonnull AbstractSQLDatabase database) { + this.database = database; + } + + @Nonnull + @Override + public List execute() throws DatabaseException { + try { + PreparedStatement statement = database.prepare("SHOW TABLES"); + ResultSet result = statement.executeQuery(); + + List tables = new ArrayList<>(); + while (result.next()) { + tables.add(result.getString(1)); + } + return tables; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java new file mode 100644 index 000000000..70fbe6953 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java @@ -0,0 +1,53 @@ +package net.codingarea.commons.database.sql.sqlite; + +import net.codingarea.commons.common.misc.FileUtils; +import net.codingarea.commons.database.DatabaseConfig; +import net.codingarea.commons.database.action.DatabaseListTables; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import net.codingarea.commons.database.sql.sqlite.list.SQLiteListTables; + +import javax.annotation.Nonnull; +import java.io.File; +import java.io.IOException; + +public class SQLiteDatabase extends AbstractSQLDatabase { + + static { + try { + Class.forName("org.sqlite.JDBC"); + } catch (ClassNotFoundException ex) { + LOGGER.error("Could not load sqlite driver"); + } + } + + protected final File file; + + public SQLiteDatabase(@Nonnull DatabaseConfig config) { + super(config); + file = new File(config.getFile()); + } + + @Override + public void connect() throws DatabaseException { + try { + FileUtils.createFilesIfNecessary(file); + } catch (IOException ex) { + throw new DatabaseException(ex); + } + + super.connect(); + } + + @Override + protected String createUrl() { + return "jdbc:sqlite:" + file; + } + + @Nonnull + @Override + public DatabaseListTables listTables() { + return new SQLiteListTables(this); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java new file mode 100644 index 000000000..f7a4c48d6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java @@ -0,0 +1,38 @@ +package net.codingarea.commons.database.sql.sqlite.list; + +import net.codingarea.commons.database.action.DatabaseListTables; +import net.codingarea.commons.database.exceptions.DatabaseException; +import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; + +import javax.annotation.Nonnull; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.util.ArrayList; +import java.util.List; + +public class SQLiteListTables implements DatabaseListTables { + + protected final AbstractSQLDatabase database; + + public SQLiteListTables(@Nonnull AbstractSQLDatabase database) { + this.database = database; + } + + @Nonnull + @Override + public List execute() throws DatabaseException { + try { + PreparedStatement statement = database.prepare("SELECT name FROM sqlite_master WHERE type = 'table'"); + ResultSet result = statement.executeQuery(); + + List tables = new ArrayList<>(); + while (result.next()) { + tables.add(result.getString(1)); + } + return tables; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + +} diff --git a/pom.xml b/pom.xml index 43f00b0da..810fb27fb 100644 --- a/pom.xml +++ b/pom.xml @@ -17,7 +17,6 @@ - 1.3.15 1.21.4-R0.1-SNAPSHOT From f0c4d9d76b5290be7bb26ed61d499640da57649f Mon Sep 17 00:00:00 2001 From: qodana-bot Date: Sat, 19 Apr 2025 10:33:22 +0000 Subject: [PATCH 061/119] =?UTF-8?q?=F0=9F=A4=96=20Apply=20quick-fixes=20by?= =?UTF-8?q?=20Qodana?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/config/document/BsonDocument.java | 16 +- .../commons/common/misc/BsonUtils.java | 2 +- .../commons/common/misc/MongoUtils.java | 2 +- .../effect/RandomPotionEffectChallenge.java | 2 +- .../inventory/PermanentItemChallenge.java | 3 +- .../miscellaneous/EnderGamesChallenge.java | 2 +- .../challenge/quiz/QuizChallenge.java | 2 +- .../randomizer/HotBarRandomizerChallenge.java | 3 +- .../challenge/world/SnakeChallenge.java | 2 +- .../type/abstraction/CollectionGoal.java | 2 +- .../menu/generator/MenuGenerator.java | 3 +- .../menu/info/ChallengeMenuClickInfo.java | 10 - .../plugin/management/team/TeamProvider.java | 1 - .../plugin/spigot/listener/CheatListener.java | 3 +- .../utils/bukkit/misc/BukkitStringUtils.java | 2 +- .../plugin/utils/bukkit/nms/NMSProvider.java | 1 - .../plugin/utils/item/ItemBuilder.java | 3 +- .../plugin/utils/misc/ImageUtils.java | 4 +- .../commons/bukkit/core/BukkitModule.java | 18 +- .../bukkit/core/RequirementsChecker.java | 3 +- .../utils/animation/AnimationFrame.java | 6 +- .../bukkit/utils/animation/SoundSample.java | 15 +- .../utils/bstats/JsonObjectBuilder.java | 17 +- .../bukkit/utils/item/ItemBuilder.java | 10 +- .../bukkit/utils/menu/MenuClickInfo.java | 26 +- .../utils/misc/BukkitReflectionUtils.java | 2 +- .../bukkit/utils/wrapper/ActionListener.java | 8 +- .../common/collection/ClassWalker.java | 2 +- .../common/collection/NumberFormatter.java | 2 +- .../collection/SeededRandomWrapper.java | 9 +- .../common/collection/pair/Quadro.java | 21 +- .../common/collection/pair/Triple.java | 17 +- .../commons/common/collection/pair/Tuple.java | 13 +- .../concurrent/task/CompletableTask.java | 2 +- .../config/document/AbstractConfig.java | 4 +- .../common/config/document/MapDocument.java | 14 +- .../config/document/PropertiesDocument.java | 16 +- .../common/config/document/YamlDocument.java | 12 +- ...kkitReflectionSerializableTypeAdapter.java | 2 +- .../common/discord/DiscordWebhook.java | 71 ++--- .../commons/common/logging/ILogger.java | 2 +- .../commons/common/logging/LogLevel.java | 20 +- .../common/logging/LogOutputStream.java | 2 +- .../common/logging/handler/LogEntry.java | 10 +- .../logging/internal/JavaLoggerWrapper.java | 270 ------------------ .../BukkitReflectionSerializationUtils.java | 4 +- .../commons/common/misc/FileUtils.java | 2 +- .../commons/common/misc/GsonUtils.java | 2 +- .../commons/common/misc/ImageUtils.java | 3 +- .../commons/common/misc/ReflectionUtils.java | 9 +- .../common/misc/SimpleCollectionUtils.java | 2 +- .../commons/common/version/VersionInfo.java | 16 +- .../commons/database/DatabaseConfig.java | 54 ++-- .../commons/database/EmptyDatabase.java | 8 +- .../sql/abstraction/query/SQLQuery.java | 2 +- .../sql/abstraction/query/SQLResult.java | 3 +- .../sql/abstraction/update/SQLUpdate.java | 2 +- 57 files changed, 191 insertions(+), 573 deletions(-) diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java index f801ab556..e44ad0bd5 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java @@ -80,7 +80,7 @@ public String getString(@Nonnull String path) { @Override public long getLong(@Nonnull String path, long def) { try { - return Long.parseLong(getString(path)); + return Long.parseLong(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -89,7 +89,7 @@ public long getLong(@Nonnull String path, long def) { @Override public int getInt(@Nonnull String path, int def) { try { - return Integer.parseInt(getString(path)); + return Integer.parseInt(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -98,7 +98,7 @@ public int getInt(@Nonnull String path, int def) { @Override public short getShort(@Nonnull String path, short def) { try { - return Short.parseShort(getString(path)); + return Short.parseShort(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -107,7 +107,7 @@ public short getShort(@Nonnull String path, short def) { @Override public byte getByte(@Nonnull String path, byte def) { try { - return Byte.parseByte(getString(path)); + return Byte.parseByte(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -116,7 +116,7 @@ public byte getByte(@Nonnull String path, byte def) { @Override public double getDouble(@Nonnull String path, double def) { try { - return Double.parseDouble(getString(path)); + return Double.parseDouble(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -125,7 +125,7 @@ public double getDouble(@Nonnull String path, double def) { @Override public float getFloat(@Nonnull String path, float def) { try { - return Float.parseFloat(getString(path)); + return Float.parseFloat(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -137,7 +137,7 @@ public boolean getBoolean(@Nonnull String path, boolean def) { Object value = bsonDocument.get(path); if (value instanceof Boolean) return (Boolean) value; if (value instanceof String) return Boolean.parseBoolean((String) value); - } catch (Exception ex) { + } catch (Exception ignored) { } return def; } @@ -161,7 +161,7 @@ public UUID getUUID(@Nonnull String path) { Object value = bsonDocument.get(path); if (value instanceof UUID) return (UUID) value; if (value instanceof String) return UUID.fromString((String) value); - } catch (Exception ex) { + } catch (Exception ignored) { } return null; } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java index 05611a0b0..6df6ce127 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java @@ -16,7 +16,7 @@ public final class BsonUtils { - protected static final ILogger logger = ILogger.forThisClass(); + private static final ILogger logger = ILogger.forThisClass(); private BsonUtils() { } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java index d0c2c4a37..32e03109f 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java @@ -57,7 +57,7 @@ public static Object packObject(@Nullable Object value) { BsonUtils.setDocumentProperties(bson, values); return bson; } else if (value instanceof UUID) { - return ((UUID) value).toString(); + return value.toString(); } else { return value; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index 5b15d051e..2cd31b223 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -65,7 +65,7 @@ public RandomPotionEffectChallenge() { @Nullable public static PotionEffectType getNewRandomEffect(@Nonnull LivingEntity entity) { - List activeEffects = entity.getActivePotionEffects().stream().map(PotionEffect::getType).collect(Collectors.toList()); + List activeEffects = entity.getActivePotionEffects().stream().map(PotionEffect::getType).toList(); ArrayList possibleEffects = new ArrayList<>(Arrays.asList(PotionEffectType.values())); possibleEffects.removeAll(activeEffects); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java index 6b86b70af..99d8ccdb6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java @@ -17,6 +17,7 @@ import org.bukkit.inventory.Inventory; import javax.annotation.Nonnull; +import java.util.Objects; @Since("2.0") public class PermanentItemChallenge extends Setting { @@ -40,7 +41,7 @@ public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { Inventory clickedInventory = event.getClickedInventory(); if (event.getCursor() == null) return; if (clickedInventory == null) return; - InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); + InventoryType type = Objects.requireNonNull(CompatibilityUtils.getTopInventory(player)).getType(); if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.PLAYER) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 899c446cc..8a11d2c29 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -64,7 +64,7 @@ private void teleportRandom(@Nonnull Player player) { List list = player.getWorld().getNearbyEntities(player.getLocation(), 200, 200, 200).stream() .filter(entity -> !(entity instanceof Player)) .filter(entity -> entity instanceof LivingEntity) - .collect(Collectors.toList()); + .toList(); Entity targetEntity = list.get(globalRandom.nextInt(list.size())); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index 90b44a7e9..aa48d502b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -423,7 +423,7 @@ class DocumentCountStatistic extends DocumentStatistic { } } - List newAnswers = answers.stream().map(StringUtils::getEnumName).collect(Collectors.toList()); + List newAnswers = answers.stream().map(StringUtils::getEnumName).toList(); answers.clear(); answers.addAll(newAnswers); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 32c31c8f6..2b621dc6f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -29,6 +29,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; +import java.util.Objects; @Since("2.1.2") public class HotBarRandomizerChallenge extends TimedChallenge { @@ -117,7 +118,7 @@ public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { Inventory clickedInventory = event.getClickedInventory(); if (event.getCursor() == null) return; if (clickedInventory == null) return; - InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); + InventoryType type = Objects.requireNonNull(CompatibilityUtils.getTopInventory(player)).getType(); if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.PLAYER) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index 28ae22550..26f25a80c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -56,7 +56,7 @@ public void writeGameState(@Nonnull Document document) { public void loadGameState(@Nonnull Document document) { super.loadGameState(document); - blocks.addAll(document.getSerializableList("blocks", Location.class).stream().map(Location::getBlock).collect(Collectors.toList())); + blocks.addAll(document.getSerializableList("blocks", Location.class).stream().map(Location::getBlock).toList()); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java index 2ad3bacf4..c9f19f248 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java @@ -70,7 +70,7 @@ protected void collect(@Nonnull Player player, @Nonnull Object item, @Nonnull Ru } protected List getCollectionFiltered(@Nonnull UUID uuid) { - List targetStringList = Arrays.stream(target).map(Object::toString).collect(Collectors.toList()); + List targetStringList = Arrays.stream(target).map(Object::toString).toList(); return collections.computeIfAbsent(uuid, key -> new ArrayList<>()).stream().filter(targetStringList::contains).collect(Collectors.toList()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java index 5fadbe3f4..bf7090a65 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java @@ -14,6 +14,7 @@ import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import java.util.List; +import java.util.Objects; @Getter @Setter @@ -31,7 +32,7 @@ public abstract class MenuGenerator { public boolean hasInventoryOpen(Player player) { MenuPosition menuPosition = MenuPosition.get(player); return menuPosition instanceof GeneratorMenuPosition - && CompatibilityUtils.getTopInventory(player).getType() != InventoryType.CRAFTING + && Objects.requireNonNull(CompatibilityUtils.getTopInventory(player)).getType() != InventoryType.CRAFTING && ((GeneratorMenuPosition) menuPosition).getGenerator() == this; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java index 53b285c9d..9df0dc49b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java @@ -30,14 +30,4 @@ public boolean isLowerItemClick() { return !upperItem; } - @Nonnull - public Player getPlayer() { - return player; - } - - @Nonnull - public Inventory getInventory() { - return inventory; - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java index a633ec0d7..f3f6db16f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java @@ -2,7 +2,6 @@ import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; import java.util.LinkedList; import java.util.List; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java index 00de88ed9..2251cdd1b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java @@ -33,8 +33,7 @@ public void onGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { @EventHandler(priority = EventPriority.MONITOR) public void onSneak(PlayerToggleSneakEvent event) { - if (!event.isSneaking()) { - } + event.isSneaking(); //// Structure structure = entry.getValue(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java index c5f73691e..37e6f5fbc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java @@ -149,7 +149,7 @@ public static List format(@Nonnull String sequence, @Nonnull Obje if (!currentText.getText().isEmpty()) { results.add(currentText); } - if (argument.length() > 0) { + if (!argument.isEmpty()) { results.add(new TextComponent(String.valueOf(start))); results.add(new TextComponent(String.valueOf(argument))); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java index 4b941e688..32bb95dfa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java @@ -19,7 +19,6 @@ public class NMSProvider { /** * -- GETTER -- * - * @return A border packet factory */ @Getter private static final BorderPacketFactory borderPacketFactory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index b457a897e..42523ce79 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -214,7 +214,8 @@ public ItemDescription getBuiltByItemDescription() { @Override public ItemBuilder clone() { - ItemBuilder builder = new ItemBuilder(item.clone(), getMeta().clone()); + ItemBuilder itemBuilder = (ItemBuilder) super.clone(); + ItemBuilder builder = new ItemBuilder(item.clone(), getMeta().clone()); builder.builtByItemDescription = builtByItemDescription; return builder; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java index f81f27ba2..e94c8cf0d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.utils.misc; +import net.codingarea.commons.common.collection.IOUtils; import org.bukkit.entity.Player; import javax.annotation.Nonnull; @@ -20,8 +21,7 @@ private ImageUtils() { @Nullable public static BufferedImage getImage(@Nonnull String url) throws IOException { - HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); - connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); + HttpURLConnection connection = IOUtils.createConnection(url); return ImageIO.read(connection.getInputStream()); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java index c90eea42b..31f3e41cb 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java @@ -1,6 +1,7 @@ package net.codingarea.commons.bukkit.core; import com.google.common.base.Charsets; +import lombok.Getter; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.commons.bukkit.utils.menu.MenuPositionListener; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; @@ -54,7 +55,8 @@ public abstract class BukkitModule extends JavaPlugin { private ExecutorService executorService; private Document config, pluginConfig; private Version version; - private boolean devMode; + @Getter + private boolean devMode; private boolean firstInstall; private boolean isReloaded; private boolean isLoaded; @@ -75,10 +77,10 @@ public final void onLoad() { ILogger.setConstantFactory(this.getILogger()); trySaveDefaultConfig(); if (wasShutdown) isReloaded = true; - if (firstInstall = !getDataFolder().exists()) { + if (firstInstall == !getDataFolder().exists()) { getILogger().info("Detected first install!"); } - if (devMode = getConfigDocument().getBoolean("dev-mode") || getConfigDocument().getBoolean("dev-mode.enabled")) { + if (devMode == getConfigDocument().getBoolean("dev-mode") || getConfigDocument().getBoolean("dev-mode.enabled")) { getILogger().setLevel(Level.ALL); getILogger().debug("Devmode is enabled: Showing debug messages. This can be disabled in the plugin.yml ('dev-mode')"); } else { @@ -142,11 +144,7 @@ protected void handleLoad() throws Exception {} protected void handleEnable() throws Exception {} protected void handleDisable() throws Exception {} - public boolean isDevMode() { - return devMode; - } - - public final boolean isFirstInstall() { + public final boolean isFirstInstall() { return firstInstall; } @@ -185,7 +183,7 @@ public void reloadConfig() { @Nonnull public Document getPluginDocument() { return pluginConfig != null ? pluginConfig : - (pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(getResource("plugin.yml"), Charsets.UTF_8)))); + (pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(Objects.requireNonNull(getResource("plugin.yml")), Charsets.UTF_8)))); } @Nonnull @@ -344,7 +342,7 @@ private void injectInstance() { Field instanceField = this.getClass().getDeclaredField("instance"); instanceField.setAccessible(true); instanceField.set(null, this); - } catch (Throwable ex) { + } catch (Throwable ignored) { } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java index 87cae1721..8b380040c 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java @@ -6,6 +6,7 @@ import org.bukkit.Bukkit; import javax.annotation.Nonnull; +import java.util.Objects; public final class RequirementsChecker { @@ -18,7 +19,7 @@ public RequirementsChecker(@Nonnull BukkitModule module) { public void checkExceptionally(@Nonnull Document requirements) throws IllegalStateException { if (requirements.getBoolean("spigot")) requireSpigot(); if (requirements.getBoolean("paper")) requirePaper(); - if (requirements.contains("version")) requireVersion(requirements.getVersion("version")); + if (requirements.contains("version")) requireVersion(Objects.requireNonNull(requirements.getVersion("version"))); } public boolean checkBoolean(@Nonnull Document requirements) { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java index 130785522..b91add45e 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java @@ -7,6 +7,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Arrays; +import java.util.Objects; public class AnimationFrame implements Cloneable { @@ -59,7 +60,7 @@ public ItemStack getItem(int slot) { @Nullable public Material getItemType(int slot) { - return getItem(slot) == null ? Material.AIR : getItem(slot).getType(); + return getItem(slot) == null ? Material.AIR : Objects.requireNonNull(getItem(slot)).getType(); } @Nonnull @@ -78,7 +79,8 @@ public int getSize() { @Nonnull @Override public AnimationFrame clone() { - return new AnimationFrame(content); + AnimationFrame animationFrame = (AnimationFrame) super.clone(); + return new AnimationFrame(content); } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java index 8991960e0..47441780a 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java @@ -1,5 +1,6 @@ package net.codingarea.commons.bukkit.utils.animation; +import lombok.Getter; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Sound; @@ -35,7 +36,9 @@ public static void playStatusSound(@Nonnull Player player, boolean enabled) { private static final class SoundFrame { - private final float pitch, volume; + @Getter + @Getter + private final float pitch, volume; private final Sound sound; public SoundFrame(@Nonnull Sound sound, float volume, float pitch) { @@ -52,15 +55,7 @@ public void play(@Nonnull Player player, @Nonnull Location location) { player.playSound(location, sound, volume, pitch); } - public float getPitch() { - return pitch; - } - - public float getVolume() { - return volume; - } - - @Nonnull + @Nonnull public Sound getSound() { return sound; } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java index 172e2e4ff..e156c6284 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java @@ -160,14 +160,15 @@ public JsonObject build() { } /** - * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. - * - *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. - * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). - * - * @param value The value to escape. - * @return The escaped value. - */ + * Escapes the given string like stated in .... + * + *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. + * Compact escapes are not used (e.g., '\n' is escaped as " + " and not as "\n"). + * + * @param value The value to escape. + * @return The escaped value. + */ private static String escape(String value) { final StringBuilder builder = new StringBuilder(); for (int i = 0; i < value.length(); i++) { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java index 339bbaba2..868ad8110 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java @@ -14,10 +14,7 @@ import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; +import java.util.*; public class ItemBuilder { @@ -67,7 +64,7 @@ public ItemMeta getMeta() { @Nonnull @SuppressWarnings("unchecked") public final M getCastedMeta() { - return (M) (meta == null ? meta = item.getItemMeta() : meta); + return (M) (meta == null ? Objects.requireNonNull(meta = item.getItemMeta()) : meta); } @Nonnull @@ -254,7 +251,8 @@ public ItemStack toItem() { @Override public ItemBuilder clone() { - return new ItemBuilder(item.clone(), getMeta().clone()); + ItemBuilder itemBuilder = (ItemBuilder) super.clone(); + return new ItemBuilder(item.clone(), getMeta().clone()); } public static class BannerBuilder extends ItemBuilder { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java index 5753ad174..0d2e9236d 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java @@ -1,5 +1,6 @@ package net.codingarea.commons.bukkit.utils.menu; +import lombok.Getter; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; @@ -13,9 +14,12 @@ public class MenuClickInfo { protected final Player player; protected final Inventory inventory; - protected final boolean shiftClick; - protected final boolean rightClick; - protected final int slot; + @Getter + protected final boolean shiftClick; + @Getter + protected final boolean rightClick; + @Getter + protected final int slot; public MenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boolean shiftClick, boolean rightClick, @Nonnegative int slot) { this.player = player; @@ -35,23 +39,11 @@ public Inventory getInventory() { return inventory; } - public boolean isRightClick() { - return rightClick; - } - - public boolean isLeftClick() { + public boolean isLeftClick() { return !rightClick; } - public boolean isShiftClick() { - return shiftClick; - } - - public int getSlot() { - return slot; - } - - @Nullable + @Nullable public ItemStack getClickedItem() { return inventory.getItem(slot); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java index 36284f5e3..46b72210b 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java @@ -136,7 +136,7 @@ public static NamespacedKey fromString(@Nonnull String key) { */ @Nullable public static NamespacedKey fromString(@Nonnull String string, @Nullable Plugin defaultNamespace) { - Preconditions.checkArgument(string != null && !string.isEmpty(), "Input string must not be empty or null"); + Preconditions.checkArgument(!string.isEmpty(), "Input string must not be empty or null"); String[] components = string.split(":", 3); if (components.length > 2) { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java index 8faa0993b..c53353706 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java @@ -1,5 +1,6 @@ package net.codingarea.commons.bukkit.utils.wrapper; +import lombok.Getter; import org.bukkit.event.Event; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @@ -13,7 +14,8 @@ public final class ActionListener implements Listener { private final Class classOfEvent; private final Consumer listener; private final EventPriority priority; - private final boolean ignoreCancelled; + @Getter + private final boolean ignoreCancelled; public ActionListener(@Nonnull Class classOfEvent, @Nonnull Consumer listener, @Nonnull EventPriority priority, boolean ignoreCancelled) { this.classOfEvent = classOfEvent; @@ -50,8 +52,4 @@ public Class getClassOfEvent() { return classOfEvent; } - public boolean isIgnoreCancelled() { - return ignoreCancelled; - } - } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java index d71f0df71..49018ec35 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java @@ -4,7 +4,7 @@ import java.util.*; /** - * @author JDA | https://github.com/DV8FromTheWorld/JDA/blob/development/src/main/java/net/dv8tion/jda/internal/utils/ClassWalker.java + * @author JDA | ... */ public class ClassWalker implements Iterable> { diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java index 4a734b55b..013c092c1 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java @@ -48,7 +48,7 @@ default String format(@Nonnull Number number) { return format(number.doubleValue()); } - public static final NumberFormatter + NumberFormatter DEFAULT = fromPattern("0.##", null, false), INTEGER = value -> (int) value + "", SPACE_SPLIT = fromPattern("###,##0.###############", null, false, diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java index a9fcb48f2..0c0f90e5e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java @@ -1,11 +1,14 @@ package net.codingarea.commons.common.collection; +import lombok.Getter; + import java.util.Random; /** * Since there is no way of getting the seed of a {@link Random} we create a wrapper * which will save seed. This allows us to save randomization and reload it. */ +@Getter public class SeededRandomWrapper extends Random implements IRandom { protected long seed; @@ -24,11 +27,7 @@ public void setSeed(long seed) { this.seed = seed; } - public long getSeed() { - return seed; - } - - @Override + @Override public String toString() { return "Random[seed=" + seed + "]"; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java index df07b890d..734f5cf16 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java @@ -1,5 +1,7 @@ package net.codingarea.commons.common.collection.pair; +import lombok.Getter; + import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -12,6 +14,7 @@ * @param The type of the third value * @param The type of the fourth value */ +@Getter public class Quadro implements Pair { protected F first; @@ -40,23 +43,7 @@ public final Object[] values() { return new Object[] { first, second, third, first }; } - public F getFirst() { - return first; - } - - public S getSecond() { - return second; - } - - public T getThird() { - return third; - } - - public FF getFourth() { - return fourth; - } - - public void setFirst(@Nullable F first) { + public void setFirst(@Nullable F first) { this.first = first; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java index 48c8dfcde..b62f55777 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java @@ -1,5 +1,7 @@ package net.codingarea.commons.common.collection.pair; +import lombok.Getter; + import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -11,6 +13,7 @@ * @param The type of the second value * @param The type of the third value */ +@Getter public class Triple implements Pair { protected F first; @@ -37,19 +40,7 @@ public final Object[] values() { return new Object[] { first, second, third }; } - public F getFirst() { - return first; - } - - public S getSecond() { - return second; - } - - public T getThird() { - return third; - } - - public void setFirst(@Nullable F first) { + public void setFirst(@Nullable F first) { this.first = first; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java index 9d320ba6e..ce1901dbf 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java @@ -1,5 +1,7 @@ package net.codingarea.commons.common.collection.pair; +import lombok.Getter; + import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -10,6 +12,7 @@ * @param The type of the first value * @param The type of the second value */ +@Getter public class Tuple implements Pair { protected F first; @@ -34,15 +37,7 @@ public final Object[] values() { return new Object[] { first, second }; } - public F getFirst() { - return first; - } - - public S getSecond() { - return second; - } - - public void setFirst(@Nullable F first) { + public void setFirst(@Nullable F first) { this.first = first; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java index 37b71703f..08ab891a7 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java @@ -64,7 +64,7 @@ public Task addListener(@Nonnull TaskListener listener) { } else if (failure != null) { listener.onFailure(this, failure); } else { - listener.onComplete(this, value); + listener.onComplete(this, null); } return this; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java index cce0be2e8..2f9fec69b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java @@ -46,7 +46,7 @@ public char getChar(@Nonnull String path) { @Override public char getChar(@Nonnull String path, char def) { try { - return getString(path).charAt(0); + return Objects.requireNonNull(getString(path)).charAt(0); } catch (NullPointerException | IndexOutOfBoundsException ex) { return def; } @@ -175,7 +175,7 @@ public > List getEnumList(@Nonnull String path, @Nonnull Cl @Nonnull @Override public List getCharacterList(@Nonnull String path) { - return mapList(path, string -> string == null || string.length() == 0 ? (char) 0 : string.charAt(0)); + return mapList(path, string -> string == null || string.isEmpty() ? (char) 0 : string.charAt(0)); } @Nonnull diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java index b0b194d05..eabc2e1a7 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java @@ -129,7 +129,7 @@ public String getString(@Nonnull String path) { @Override public long getLong(@Nonnull String path, long def) { try { - return Long.parseLong(getString(path)); + return Long.parseLong(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -138,7 +138,7 @@ public long getLong(@Nonnull String path, long def) { @Override public int getInt(@Nonnull String path, int def) { try { - return Integer.parseInt(getString(path)); + return Integer.parseInt(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -147,7 +147,7 @@ public int getInt(@Nonnull String path, int def) { @Override public short getShort(@Nonnull String path, short def) { try { - return Short.parseShort(getString(path)); + return Short.parseShort(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -156,7 +156,7 @@ public short getShort(@Nonnull String path, short def) { @Override public byte getByte(@Nonnull String path, byte def) { try { - return Byte.parseByte(getString(path)); + return Byte.parseByte(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -165,7 +165,7 @@ public byte getByte(@Nonnull String path, byte def) { @Override public float getFloat(@Nonnull String path, float def) { try { - return Float.parseFloat(getString(path)); + return Float.parseFloat(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -174,7 +174,7 @@ public float getFloat(@Nonnull String path, float def) { @Override public double getDouble(@Nonnull String path, double def) { try { - return Double.parseDouble(getString(path)); + return Double.parseDouble(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -184,7 +184,7 @@ public double getDouble(@Nonnull String path, double def) { public boolean getBoolean(@Nonnull String path, boolean def) { try { if (!contains(path)) return def; - switch (getString(path).toLowerCase()) { + switch (Objects.requireNonNull(getString(path)).toLowerCase()) { case "true": case "1": return true; diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java index 58fa7b100..7f5213806 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java @@ -78,7 +78,7 @@ public String getString(@Nonnull String path) { @Override public long getLong(@Nonnull String path, long def) { try { - return Long.parseLong(getString(path)); + return Long.parseLong(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -87,7 +87,7 @@ public long getLong(@Nonnull String path, long def) { @Override public int getInt(@Nonnull String path, int def) { try { - return Integer.parseInt(getString(path)); + return Integer.parseInt(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -96,7 +96,7 @@ public int getInt(@Nonnull String path, int def) { @Override public short getShort(@Nonnull String path, short def) { try { - return Short.parseShort(getString(path)); + return Short.parseShort(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -105,7 +105,7 @@ public short getShort(@Nonnull String path, short def) { @Override public byte getByte(@Nonnull String path, byte def) { try { - return Byte.parseByte(getString(path)); + return Byte.parseByte(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -114,7 +114,7 @@ public byte getByte(@Nonnull String path, byte def) { @Override public float getFloat(@Nonnull String path, float def) { try { - return Float.parseFloat(getString(path)); + return Float.parseFloat(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -123,7 +123,7 @@ public float getFloat(@Nonnull String path, float def) { @Override public double getDouble(@Nonnull String path, double def) { try { - return Double.parseDouble(getString(path)); + return Double.parseDouble(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return def; } @@ -139,7 +139,7 @@ public boolean getBoolean(@Nonnull String path, boolean def) { @Override public UUID getUUID(@Nonnull String path) { try { - return UUID.fromString(getString(path)); + return UUID.fromString(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return null; } @@ -155,7 +155,7 @@ public Date getDate(@Nonnull String path) { @Override public OffsetDateTime getDateTime(@Nonnull String path) { try { - return OffsetDateTime.parse(getString(path)); + return OffsetDateTime.parse(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return null; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java index 03bdf14d3..faf4fe162 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java @@ -54,7 +54,7 @@ public String getString(@Nonnull String path) { @Override public String getString(@Nonnull String path, @Nonnull String def) { String string = config.getString(path, def); - return string == null ? def : string; + return string; } @Nullable @@ -67,7 +67,7 @@ public Object getObject(@Nonnull String path) { @Override public Object getObject(@Nonnull String path, @Nonnull Object def) { Object value = config.get(path, def); - return value == null ? def : value; + return value; } @Override @@ -147,7 +147,7 @@ public char getChar(@Nonnull String path) { @Override public char getChar(@Nonnull String path, char def) { try { - return getString(path).charAt(0); + return Objects.requireNonNull(getString(path)).charAt(0); } catch (NullPointerException | StringIndexOutOfBoundsException ex) { return def; } @@ -193,7 +193,7 @@ public List getStringList(@Nonnull String path) { @Override public UUID getUUID(@Nonnull String path) { try { - return UUID.fromString(getString(path)); + return UUID.fromString(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return null; } @@ -213,7 +213,7 @@ public Date getDate(@Nonnull String path) { @Override public OffsetDateTime getDateTime(@Nonnull String path) { try { - return OffsetDateTime.parse(getString(path)); + return OffsetDateTime.parse(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return null; } @@ -223,7 +223,7 @@ public OffsetDateTime getDateTime(@Nonnull String path) { @Override public Color getColor(@Nonnull String path) { try { - return Color.decode(getString(path)); + return Color.decode(Objects.requireNonNull(getString(path))); } catch (Exception ex) { return null; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java index ed36fd787..71f9f7744 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java @@ -43,7 +43,7 @@ public Object read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOExce Class clazz = null; try { clazz = Class.forName(classOfType); - } catch (ClassNotFoundException | NullPointerException ex) { + } catch (ClassNotFoundException | NullPointerException ignored) { } Map map = GsonUtils.convertJsonObjectToMap(json); diff --git a/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java index 49eeec955..b75f88549 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java +++ b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java @@ -1,5 +1,6 @@ package net.codingarea.commons.common.discord; +import lombok.Getter; import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnull; @@ -214,7 +215,8 @@ public DiscordWebhook replaceEverywhere(@Nonnull String trigger, @Nonnull String return this; } - public static class EmbedObject { + @Getter + public static class EmbedObject { protected String title; protected String description; @@ -244,43 +246,7 @@ public EmbedObject(@Nullable String title, @Nullable String description, @Nullab this.fields = fields; } - public String getTitle() { - return title; - } - - public String getDescription() { - return description; - } - - public String getUrl() { - return url; - } - - public Color getColor() { - return color; - } - - public Footer getFooter() { - return footer; - } - - public Thumbnail getThumbnail() { - return thumbnail; - } - - public Image getImage() { - return image; - } - - public Author getAuthor() { - return author; - } - - public List getFields() { - return fields; - } - - @Nonnull + @Nonnull public EmbedObject setTitle(String title) { this.title = title; return this; @@ -336,7 +302,8 @@ public EmbedObject addField(String name, String value, boolean inline) { @Override public EmbedObject clone() { - return new EmbedObject( + EmbedObject embedObject = (EmbedObject) super.clone(); + return new EmbedObject( title, description, url, color, footer == null ? null : footer.clone(), thumbnail == null ? null : thumbnail.clone(), @@ -368,8 +335,9 @@ private String getIconUrl() { } @Override - protected Footer clone() { - return new Footer(text, iconUrl); + protected Footer clone() throws CloneNotSupportedException { + Footer footer1 = (Footer) super.clone(); + return new Footer(text, iconUrl); } } @@ -389,8 +357,9 @@ private String getUrl() { } @Override - protected Thumbnail clone() { - return new Thumbnail(url); + protected Thumbnail clone() throws CloneNotSupportedException { + Thumbnail thumbnail1 = (Thumbnail) super.clone(); + return new Thumbnail(url); } } @@ -411,7 +380,8 @@ private String getUrl() { @Override public Image clone() { - return new Image(url); + Image image1 = (Image) super.clone(); + return new Image(url); } } @@ -443,8 +413,9 @@ private String getIconUrl() { } @Override - protected Author clone() { - return new Author(name, url, iconUrl); + protected Author clone() throws CloneNotSupportedException { + Author author1 = (Author) super.clone(); + return new Author(name, url, iconUrl); } } @@ -476,15 +447,17 @@ private boolean isInline() { } @Override - protected Field clone() { - return new Field(name, value, inline); + protected Field clone() throws CloneNotSupportedException { + Field field = (Field) super.clone(); + return new Field(name, value, inline); } } } @Override public DiscordWebhook clone() { - return new DiscordWebhook(url, username, avatarUrl, content, clone(embeds, EmbedObject::clone), tts); + DiscordWebhook discordWebhook = (DiscordWebhook) super.clone(); + return new DiscordWebhook(url, username, avatarUrl, content, clone(embeds, EmbedObject::clone), tts); } @Nonnull diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java index 02ec550a7..eb337e206 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java @@ -260,7 +260,7 @@ default JavaILogger java() { @CheckReturnValue default PrintStream asPrintStream(@Nonnull LogLevel level) { try { - return new PrintStream(new LogOutputStream(this, level), true, StandardCharsets.UTF_8.name()); + return new PrintStream(new LogOutputStream(this, level), true, StandardCharsets.UTF_8); } catch (Exception ex) { throw new WrappedException(ex); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java index ddf6d01c8..58d6c7262 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java @@ -1,5 +1,7 @@ package net.codingarea.commons.common.logging; +import lombok.Getter; + import javax.annotation.Nonnull; import java.util.logging.Level; @@ -15,8 +17,10 @@ public enum LogLevel { private final String uppercaseName, lowercaseName; private final Level javaLevel; - private final int value; - private final boolean highlighted; + @Getter + private final int value; + @Getter + private final boolean highlighted; LogLevel(int value, @Nonnull String uppercaseName, @Nonnull String lowercaseName, @Nonnull Level javaLevel, boolean highlighted) { this.uppercaseName = uppercaseName; @@ -35,11 +39,7 @@ public boolean isShownAtLoggerLevel(@Nonnull LogLevel loggerLevel) { return this.getValue() >= loggerLevel.getValue(); } - public int getValue() { - return value; - } - - @Nonnull + @Nonnull public String getLowerCaseName() { return lowercaseName; } @@ -49,11 +49,7 @@ public String getUpperCaseName() { return uppercaseName; } - public boolean isHighlighted() { - return highlighted; - } - - @Nonnull + @Nonnull public static LogLevel fromJavaLevel(@Nonnull Level level) { for (LogLevel logLevel : values()) { if (logLevel.getJavaUtilLevel().intValue() == level.intValue()) diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java index 7095492ed..c747fbf1a 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java @@ -17,7 +17,7 @@ public LogOutputStream(@Nonnull ILogger logger, @Nonnull LogLevel level) { @Override public void flush() throws IOException { - String input = this.toString(StandardCharsets.UTF_8.name()); + String input = this.toString(StandardCharsets.UTF_8); this.reset(); if (input != null && !input.isEmpty() && !input.equals(System.lineSeparator())) { diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java index 5068d301b..3212680b9 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java @@ -8,11 +8,11 @@ public class LogEntry { - private Instant timestamp; - private String threadName; - private String message; - private LogLevel level; - private Throwable exception; + private final Instant timestamp; + private final String threadName; + private final String message; + private final LogLevel level; + private final Throwable exception; public LogEntry(@Nonnull Instant timestamp, @Nonnull String threadName, @Nonnull String message, @Nonnull LogLevel level, @Nullable Throwable exception) { this.timestamp = timestamp; diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java index f0c64bf8d..b9c95d540 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java @@ -393,274 +393,4 @@ public void debug(@Nullable Object message, @Nonnull Object... args) { } - @Override - public boolean isTraceEnabled() { - return isLevelEnabled(LogLevel.TRACE); - } - -// @Override -// public void trace(String msg) { -// trace(msg, new Object[0]); -// } -// -// @Override -// public void trace(String format, Object arg) { -// trace(format, new Object[] { arg }); -// } -// -// @Override -// public void trace(String format, Object arg1, Object arg2) { -// trace(format, new Object[] { arg1, arg2 }); -// } -// -// @Override -// public void trace(String msg, Throwable t) { -// trace(msg, new Object[] { t }); -// } -// -// @Override -// public boolean isTraceEnabled(Marker marker) { -// return isTraceEnabled(); -// } -// -// @Override -// public void trace(Marker marker, String msg) { -// trace(msg); -// } -// -// @Override -// public void trace(Marker marker, String format, Object arg) { -// trace(format, arg); -// } -// -// @Override -// public void trace(Marker marker, String format, Object arg1, Object arg2) { -// trace(format, arg1, arg2); -// } -// -// @Override -// public void trace(Marker marker, String format, Object... argArray) { -// trace(format, argArray); -// } -// -// @Override -// public void trace(Marker marker, String msg, Throwable t) { -// trace(msg, t); -// } -// -// @Override -// public boolean isDebugEnabled() { -// return isLevelEnabled(LogLevel.DEBUG); -// } -// -// @Override -// public void debug(String msg) { -// debug(msg, new Object[0]); -// } -// -// @Override -// public void debug(String format, Object arg) { -// debug(format, new Object[] { arg }); -// } -// -// @Override -// public void debug(String format, Object arg1, Object arg2) { -// debug(format, new Object[] { arg1, arg2 }); -// } -// -// @Override -// public void debug(String msg, Throwable t) { -// debug(msg, new Object[] { t }); -// } -// -// @Override -// public boolean isDebugEnabled(Marker marker) { -// return isDebugEnabled(); -// } -// -// @Override -// public void debug(Marker marker, String msg) { -// debug(msg); -// } -// -// @Override -// public void debug(Marker marker, String format, Object arg) { -// debug(format, arg); -// } -// -// @Override -// public void debug(Marker marker, String format, Object arg1, Object arg2) { -// debug(format, arg1, arg2); -// } -// -// @Override -// public void debug(Marker marker, String format, Object... arguments) { -// debug(format, arguments); -// } -// -// @Override -// public void debug(Marker marker, String msg, Throwable t) { -// debug(msg, t); -// } -// -// @Override -// public boolean isInfoEnabled() { -// return isLevelEnabled(LogLevel.INFO); -// } -// -// @Override -// public void info(String format, Object arg) { -// info(format, new Object[] { arg }); -// } -// -// @Override -// public void info(String format, Object arg1, Object arg2) { -// info(format, new Object[] { arg1, arg2 }); -// } -// -// @Override -// public void info(String msg, Throwable t) { -// info(msg, new Object[] { t }); -// } -// -// @Override -// public boolean isInfoEnabled(Marker marker) { -// return isInfoEnabled(); -// } -// -// @Override -// public void info(Marker marker, String msg) { -// info(msg); -// } -// -// @Override -// public void info(Marker marker, String format, Object arg) { -// info(format, arg); -// } -// -// @Override -// public void info(Marker marker, String format, Object arg1, Object arg2) { -// info(format, arg1, arg2); -// } -// -// @Override -// public void info(Marker marker, String format, Object... arguments) { -// info(format, arguments); -// } -// -// @Override -// public void info(Marker marker, String msg, Throwable t) { -// info(msg, t); -// } -// -// @Override -// public boolean isWarnEnabled() { -// return isLevelEnabled(LogLevel.WARN); -// } -// -// @Override -// public void warn(String msg) { -// warn(msg, new Object[0]); -// } -// -// @Override -// public void warn(String format, Object arg) { -// warn(format, new Object[] { arg }); -// } -// -// @Override -// public void warn(String format, Object arg1, Object arg2) { -// warn(format, new Object[] { arg1, arg2 }); -// } -// -// @Override -// public void warn(String msg, Throwable t) { -// warn(msg, new Object[] { t }); -// } -// -// @Override -// public boolean isWarnEnabled(Marker marker) { -// return isWarnEnabled(); -// } -// -// @Override -// public void warn(Marker marker, String msg) { -// warn(marker); -// } -// -// @Override -// public void warn(Marker marker, String format, Object arg) { -// warn(format, arg); -// } -// -// @Override -// public void warn(Marker marker, String format, Object arg1, Object arg2) { -// warn(format, arg1, arg2); -// } -// -// @Override -// public void warn(Marker marker, String format, Object... arguments) { -// warn(format, arguments); -// } -// -// @Override -// public void warn(Marker marker, String msg, Throwable t) { -// warn(msg, t); -// } -// -// @Override -// public boolean isErrorEnabled() { -// return isLevelEnabled(LogLevel.ERROR); -// } -// -// @Override -// public void error(String msg) { -// error(msg, new Object[0]); -// } -// -// @Override -// public void error(String format, Object arg) { -// error(format, new Object[] { arg }); -// } -// -// @Override -// public void error(String format, Object arg1, Object arg2) { -// error(format, new Object[] { arg1, arg2 }); -// } -// -// @Override -// public void error(String msg, Throwable t) { -// error(msg, new Object[] { t }); -// } -// -// @Override -// public boolean isErrorEnabled(Marker marker) { -// return isErrorEnabled(); -// } -// -// @Override -// public void error(Marker marker, String msg) { -// error(msg); -// } -// -// @Override -// public void error(Marker marker, String format, Object arg) { -// error(format, arg); -// } -// -// @Override -// public void error(Marker marker, String format, Object arg1, Object arg2) { -// error(format, arg1, arg2); -// } -// -// @Override -// public void error(Marker marker, String format, Object... arguments) { -// error(format, arguments); -// } -// -// @Override -// public void error(Marker marker, String msg, Throwable t) { -// error(msg, t); -// } - } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java index fc9a86c16..b01426a87 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java @@ -12,7 +12,7 @@ public final class BukkitReflectionSerializationUtils { private BukkitReflectionSerializationUtils() {} - protected static final ILogger logger = ILogger.forThisClass(); + private static final ILogger logger = ILogger.forThisClass(); public static boolean isSerializable(@Nonnull Class clazz) { try { @@ -56,7 +56,7 @@ public static T deserializeObject(@Nonnull Map map, @Nullabl return (T) object; - } catch (Throwable ex) { + } catch (Throwable ignored) { } if (classOfT == null) diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java index b8733488f..e3438e1fe 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java @@ -531,7 +531,7 @@ public static void createFile(@Nullable Path filePath) { if (filePath.getParent() != null) Files.createDirectories(filePath.getParent()); Files.createFile(filePath); - } catch (IOException ex) { + } catch (IOException ignored) { } } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java index ce3988f94..4f7d07eee 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java @@ -118,7 +118,7 @@ public static void setDocumentProperties(@Nonnull Gson gson, @Nonnull JsonObject public static int getSize(@Nonnull JsonObject object) { try { return object.size(); - } catch (NoSuchMethodError ex) { + } catch (NoSuchMethodError ignored) { } return object.entrySet().size(); diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java index 6be9f8af1..a19e89e89 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java @@ -73,7 +73,8 @@ public static BufferedImage loadUrl(@Nonnull String url) throws IOException { public static BufferedImage loadResource(@Nonnull String path) throws IOException { InputStream stream = ImageUtils.class.getClassLoader().getResourceAsStream(path); - return ImageIO.read(stream); + assert stream != null; + return ImageIO.read(stream); } public static BufferedImage loadFile(@Nonnull File file) throws IOException { diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java index 2c4566199..4fb6cb7a4 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java @@ -49,7 +49,7 @@ public static Method getInheritedPrivateMethod(@Nonnull Class clazz, @Nonnull for (Class current : ClassWalker.walk(clazz)) { try { return current.getDeclaredMethod(name, parameterTypes); - } catch (Throwable ex) { + } catch (Throwable ignored) { } } @@ -61,7 +61,7 @@ public static Field getInheritedPrivateField(@Nonnull Class clazz, @Nonnull S for (Class current : ClassWalker.walk(clazz)) { try { return current.getDeclaredField(name); - } catch (Throwable ex) { + } catch (Throwable ignored) { } } @@ -77,7 +77,7 @@ public static > E getFirstEnumByNames(@Nonnull Class classO for (String name : names) { try { return Enum.valueOf(classOfEnum, name); - } catch (IllegalArgumentException | NoSuchFieldError ex) { } + } catch (IllegalArgumentException | NoSuchFieldError ignored) { } } throw new IllegalArgumentException("No enum found in " + classOfEnum.getName() + " for " + Arrays.toString(names)); } @@ -234,7 +234,8 @@ public static T getAnnotationValue(@Nonnull Annotation annotation) { public static > E getEnumByAlternateNames(@Nonnull Class classOfE, @Nonnull String input) { E[] values = invokeStaticMethodOrNull(classOfE, "values"); String[] methodNames = { "getName", "getNames", "getAlias", "getAliases", "getKey", "getKeys", "name", "toString", "ordinal", "getId", "id" }; - for (E value : values) { + assert values != null; + for (E value : values) { for (String method : methodNames) { if (check(input, invokeMethodOrNull(value, method))) return value; diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java index 66faae82d..e92d8938e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java @@ -35,7 +35,7 @@ public static void disableErrorLogging() { public static String convertMapToString(@Nonnull Map map, @Nonnull Function key, @Nonnull Function value) { StringBuilder builder = new StringBuilder(); for (Entry entry : map.entrySet()) { - if (builder.length() != 0) builder.append(REGEX_1); + if (!builder.isEmpty()) builder.append(REGEX_1); builder.append(key.apply(entry.getKey())); builder.append(REGEX_2); builder.append(value.apply(entry.getValue())); diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java index 29dbac10b..b24f8cd0b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java @@ -1,10 +1,12 @@ package net.codingarea.commons.common.version; +import lombok.Getter; import net.codingarea.commons.common.logging.ILogger; import javax.annotation.Nullable; import java.util.Objects; +@Getter public class VersionInfo implements Version { protected static final ILogger logger = ILogger.forThisClass(); @@ -21,19 +23,7 @@ public VersionInfo(int major, int minor, int revision) { this.revision = revision; } - public int getMajor() { - return major; - } - - public int getMinor() { - return minor; - } - - public int getRevision() { - return revision; - } - - @Override + @Override public boolean equals(Object other) { if (this == other) return true; if (!(other instanceof Version)) return false; diff --git a/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java index 8c67b2b87..2c169866d 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java +++ b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java @@ -1,18 +1,26 @@ package net.codingarea.commons.database; +import lombok.Getter; import net.codingarea.commons.common.config.Propertyable; import javax.annotation.Nonnull; public final class DatabaseConfig { - private final String host; - private final String database; - private final String authDatabase; - private final String password; - private final String user; - private final String file; - private final int port; + @Getter + private final String host; + @Getter + private final String database; + @Getter + private final String authDatabase; + @Getter + private final String password; + @Getter + private final String user; + @Getter + private final String file; + @Getter + private final int port; private final boolean portIsSet; public DatabaseConfig(String host, String database, String password, String user, int port) { @@ -57,39 +65,11 @@ public DatabaseConfig(@Nonnull Propertyable config) { ); } - public int getPort() { - return port; - } - - public String getAuthDatabase() { - return authDatabase; - } - - public String getDatabase() { - return database; - } - - public String getHost() { - return host; - } - - public String getPassword() { - return password; - } - - public String getUser() { - return user; - } - - public boolean isPortSet() { + public boolean isPortSet() { return portIsSet; } - public String getFile() { - return file; - } - - @Override + @Override public String toString() { return "DatabaseConfig{" + "host='" + host + '\'' + diff --git a/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java index 0770c8b67..ea78c59a7 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java @@ -1,5 +1,6 @@ package net.codingarea.commons.database; +import lombok.Getter; import net.codingarea.commons.common.concurrent.task.Task; import net.codingarea.commons.database.action.*; import net.codingarea.commons.database.exceptions.DatabaseException; @@ -11,6 +12,7 @@ import java.util.Collections; import java.util.List; +@Getter public class EmptyDatabase implements Database { private final boolean silent; @@ -19,11 +21,7 @@ public EmptyDatabase(boolean silent) { this.silent = silent; } - public boolean isSilent() { - return silent; - } - - protected void exception(@Nonnull String message) { + protected void exception(@Nonnull String message) { throw new UnsupportedOperationException(message); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java index 75536fe81..66f00bfbb 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java @@ -121,7 +121,7 @@ protected PreparedStatement prepare() throws SQLException, DatabaseException { command.append(" ORDER BY "); command.append(orderBy); if (order != null) - command.append(" " + (order == Order.HIGHEST ? "DESC" : "ASC")); + command.append(" ").append(order == Order.HIGHEST ? "DESC" : "ASC"); command.append(" "); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java index 2d6536855..b0cb9da9c 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java @@ -8,6 +8,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Map; +import java.util.Objects; public final class SQLResult extends MapDocument { @@ -19,7 +20,7 @@ public SQLResult(@Nonnull Map values) { @Override public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { try { - return new GsonDocument(getString(path), this, this).readonly(); + return new GsonDocument(Objects.requireNonNull(getString(path)), this, this).readonly(); } catch (Exception ex) { return new EmptyDocument(this, null); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java index d3b4cd844..47dae0851 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java @@ -92,7 +92,7 @@ protected PreparedStatement prepare() throws SQLException, DatabaseException { int index = 0; for (Entry entry : values.entrySet()) { if (index > 0) command.append(", "); - command.append("`" + entry.getKey() + "` = ?"); + command.append("`").append(entry.getKey()).append("` = ?"); args.add(entry.getValue()); index++; } From 09b9655510c793ada4d4d6858701cd84706bf501 Mon Sep 17 00:00:00 2001 From: qodana-bot Date: Sat, 19 Apr 2025 10:37:39 +0000 Subject: [PATCH 062/119] =?UTF-8?q?=F0=9F=A4=96=20Apply=20quick-fixes=20by?= =?UTF-8?q?=20Qodana?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../challenge/effect/RandomPotionEffectChallenge.java | 1 - .../challenge/miscellaneous/EnderGamesChallenge.java | 1 - .../challenges/plugin/utils/misc/ImageUtils.java | 1 - .../commons/common/collection/NumberFormatter.java | 11 +++++------ .../commons/common/config/document/YamlDocument.java | 6 ++---- 5 files changed, 7 insertions(+), 13 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index 2cd31b223..728e12152 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -22,7 +22,6 @@ import java.util.Arrays; import java.util.List; import java.util.Random; -import java.util.stream.Collectors; @Since("2.0") public class RandomPotionEffectChallenge extends MenuSetting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 8a11d2c29..5ada48f48 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -18,7 +18,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; -import java.util.stream.Collectors; @Since("2.0") public class EnderGamesChallenge extends TimedChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java index e94c8cf0d..a8cce7289 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java @@ -10,7 +10,6 @@ import java.awt.image.BufferedImage; import java.io.IOException; import java.net.HttpURLConnection; -import java.net.URL; public final class ImageUtils { diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java index 013c092c1..f9ed17251 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java @@ -138,8 +138,7 @@ default String format(@Nonnull Number number) { long seconds = (long) (value); long minutes = seconds / 60; long hours = minutes / 60; - seconds %= 60; - minutes %= 60; + minutes %= 60; return hours > 0 ? (hours == 1 ? "1 Stunde" : hours + " Stunden") : (minutes == 1 ? "1 Minute" : minutes + " Minuten"); }, @@ -330,13 +329,13 @@ default String format(@Nonnull Number number) { @Nonnull @CheckReturnValue - public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive) { + static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive) { return fromPattern(pattern, ending, positive, null); } @Nonnull @CheckReturnValue - public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive, Consumer init) { + static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive, Consumer init) { DecimalFormat format = new DecimalFormat(pattern); if (init != null) init.accept(format); return value -> Double.isNaN(value) ? "NaN" : format.format(positive ? (value > 0 ? value : 0) : value) + (ending != null ? ending : ""); @@ -344,13 +343,13 @@ public static NumberFormatter fromPattern(@Nonnull String pattern, String ending @Nonnull @CheckReturnValue - public static DecimalFormatSymbols updateSymbols(@Nonnull DecimalFormatSymbols symbols, @Nonnull Consumer action) { + static DecimalFormatSymbols updateSymbols(@Nonnull DecimalFormatSymbols symbols, @Nonnull Consumer action) { action.accept(symbols); return symbols; } @CheckReturnValue - public static void updateSymbols(@Nonnull DecimalFormat format, @Nonnull Consumer action) { + static void updateSymbols(@Nonnull DecimalFormat format, @Nonnull Consumer action) { format.setDecimalFormatSymbols(updateSymbols(format.getDecimalFormatSymbols(), action)); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java index faf4fe162..4bb41d219 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java @@ -53,8 +53,7 @@ public String getString(@Nonnull String path) { @Nonnull @Override public String getString(@Nonnull String path, @Nonnull String def) { - String string = config.getString(path, def); - return string; + return config.getString(path, def); } @Nullable @@ -66,8 +65,7 @@ public Object getObject(@Nonnull String path) { @Nonnull @Override public Object getObject(@Nonnull String path, @Nonnull Object def) { - Object value = config.get(path, def); - return value; + return config.get(path, def); } @Override From b8f93ebdebd8bfca82583110dc328da637c4a12e Mon Sep 17 00:00:00 2001 From: Dominik Date: Mon, 21 Apr 2025 22:13:41 +0200 Subject: [PATCH 063/119] =?UTF-8?q?Revert=20"=F0=9F=A4=96=20Apply=20quick-?= =?UTF-8?q?fixes=20by=20Qodana"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 09b9655510c793ada4d4d6858701cd84706bf501. --- .../challenge/effect/RandomPotionEffectChallenge.java | 1 + .../challenge/miscellaneous/EnderGamesChallenge.java | 1 + .../challenges/plugin/utils/misc/ImageUtils.java | 1 + .../commons/common/collection/NumberFormatter.java | 11 ++++++----- .../commons/common/config/document/YamlDocument.java | 6 ++++-- 5 files changed, 13 insertions(+), 7 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index 728e12152..2cd31b223 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -22,6 +22,7 @@ import java.util.Arrays; import java.util.List; import java.util.Random; +import java.util.stream.Collectors; @Since("2.0") public class RandomPotionEffectChallenge extends MenuSetting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 5ada48f48..8a11d2c29 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -18,6 +18,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; +import java.util.stream.Collectors; @Since("2.0") public class EnderGamesChallenge extends TimedChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java index a8cce7289..e94c8cf0d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java @@ -10,6 +10,7 @@ import java.awt.image.BufferedImage; import java.io.IOException; import java.net.HttpURLConnection; +import java.net.URL; public final class ImageUtils { diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java index f9ed17251..013c092c1 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java @@ -138,7 +138,8 @@ default String format(@Nonnull Number number) { long seconds = (long) (value); long minutes = seconds / 60; long hours = minutes / 60; - minutes %= 60; + seconds %= 60; + minutes %= 60; return hours > 0 ? (hours == 1 ? "1 Stunde" : hours + " Stunden") : (minutes == 1 ? "1 Minute" : minutes + " Minuten"); }, @@ -329,13 +330,13 @@ default String format(@Nonnull Number number) { @Nonnull @CheckReturnValue - static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive) { + public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive) { return fromPattern(pattern, ending, positive, null); } @Nonnull @CheckReturnValue - static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive, Consumer init) { + public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive, Consumer init) { DecimalFormat format = new DecimalFormat(pattern); if (init != null) init.accept(format); return value -> Double.isNaN(value) ? "NaN" : format.format(positive ? (value > 0 ? value : 0) : value) + (ending != null ? ending : ""); @@ -343,13 +344,13 @@ static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boole @Nonnull @CheckReturnValue - static DecimalFormatSymbols updateSymbols(@Nonnull DecimalFormatSymbols symbols, @Nonnull Consumer action) { + public static DecimalFormatSymbols updateSymbols(@Nonnull DecimalFormatSymbols symbols, @Nonnull Consumer action) { action.accept(symbols); return symbols; } @CheckReturnValue - static void updateSymbols(@Nonnull DecimalFormat format, @Nonnull Consumer action) { + public static void updateSymbols(@Nonnull DecimalFormat format, @Nonnull Consumer action) { format.setDecimalFormatSymbols(updateSymbols(format.getDecimalFormatSymbols(), action)); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java index 4bb41d219..faf4fe162 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java @@ -53,7 +53,8 @@ public String getString(@Nonnull String path) { @Nonnull @Override public String getString(@Nonnull String path, @Nonnull String def) { - return config.getString(path, def); + String string = config.getString(path, def); + return string; } @Nullable @@ -65,7 +66,8 @@ public Object getObject(@Nonnull String path) { @Nonnull @Override public Object getObject(@Nonnull String path, @Nonnull Object def) { - return config.get(path, def); + Object value = config.get(path, def); + return value; } @Override From b9d4bfb2ad06dd0266490244393eacfadedf50c1 Mon Sep 17 00:00:00 2001 From: Dominik Date: Mon, 21 Apr 2025 22:13:44 +0200 Subject: [PATCH 064/119] =?UTF-8?q?Revert=20"=F0=9F=A4=96=20Apply=20quick-?= =?UTF-8?q?fixes=20by=20Qodana"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit f0c4d9d76b5290be7bb26ed61d499640da57649f. --- .../common/config/document/BsonDocument.java | 16 +- .../commons/common/misc/BsonUtils.java | 2 +- .../commons/common/misc/MongoUtils.java | 2 +- .../effect/RandomPotionEffectChallenge.java | 2 +- .../inventory/PermanentItemChallenge.java | 3 +- .../miscellaneous/EnderGamesChallenge.java | 2 +- .../challenge/quiz/QuizChallenge.java | 2 +- .../randomizer/HotBarRandomizerChallenge.java | 3 +- .../challenge/world/SnakeChallenge.java | 2 +- .../type/abstraction/CollectionGoal.java | 2 +- .../menu/generator/MenuGenerator.java | 3 +- .../menu/info/ChallengeMenuClickInfo.java | 10 + .../plugin/management/team/TeamProvider.java | 1 + .../plugin/spigot/listener/CheatListener.java | 3 +- .../utils/bukkit/misc/BukkitStringUtils.java | 2 +- .../plugin/utils/bukkit/nms/NMSProvider.java | 1 + .../plugin/utils/item/ItemBuilder.java | 3 +- .../plugin/utils/misc/ImageUtils.java | 4 +- .../commons/bukkit/core/BukkitModule.java | 18 +- .../bukkit/core/RequirementsChecker.java | 3 +- .../utils/animation/AnimationFrame.java | 6 +- .../bukkit/utils/animation/SoundSample.java | 15 +- .../utils/bstats/JsonObjectBuilder.java | 17 +- .../bukkit/utils/item/ItemBuilder.java | 10 +- .../bukkit/utils/menu/MenuClickInfo.java | 26 +- .../utils/misc/BukkitReflectionUtils.java | 2 +- .../bukkit/utils/wrapper/ActionListener.java | 8 +- .../common/collection/ClassWalker.java | 2 +- .../common/collection/NumberFormatter.java | 2 +- .../collection/SeededRandomWrapper.java | 9 +- .../common/collection/pair/Quadro.java | 21 +- .../common/collection/pair/Triple.java | 17 +- .../commons/common/collection/pair/Tuple.java | 13 +- .../concurrent/task/CompletableTask.java | 2 +- .../config/document/AbstractConfig.java | 4 +- .../common/config/document/MapDocument.java | 14 +- .../config/document/PropertiesDocument.java | 16 +- .../common/config/document/YamlDocument.java | 12 +- ...kkitReflectionSerializableTypeAdapter.java | 2 +- .../common/discord/DiscordWebhook.java | 71 +++-- .../commons/common/logging/ILogger.java | 2 +- .../commons/common/logging/LogLevel.java | 20 +- .../common/logging/LogOutputStream.java | 2 +- .../common/logging/handler/LogEntry.java | 10 +- .../logging/internal/JavaLoggerWrapper.java | 270 ++++++++++++++++++ .../BukkitReflectionSerializationUtils.java | 4 +- .../commons/common/misc/FileUtils.java | 2 +- .../commons/common/misc/GsonUtils.java | 2 +- .../commons/common/misc/ImageUtils.java | 3 +- .../commons/common/misc/ReflectionUtils.java | 9 +- .../common/misc/SimpleCollectionUtils.java | 2 +- .../commons/common/version/VersionInfo.java | 16 +- .../commons/database/DatabaseConfig.java | 54 ++-- .../commons/database/EmptyDatabase.java | 8 +- .../sql/abstraction/query/SQLQuery.java | 2 +- .../sql/abstraction/query/SQLResult.java | 3 +- .../sql/abstraction/update/SQLUpdate.java | 2 +- 57 files changed, 573 insertions(+), 191 deletions(-) diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java index e44ad0bd5..f801ab556 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java @@ -80,7 +80,7 @@ public String getString(@Nonnull String path) { @Override public long getLong(@Nonnull String path, long def) { try { - return Long.parseLong(Objects.requireNonNull(getString(path))); + return Long.parseLong(getString(path)); } catch (Exception ex) { return def; } @@ -89,7 +89,7 @@ public long getLong(@Nonnull String path, long def) { @Override public int getInt(@Nonnull String path, int def) { try { - return Integer.parseInt(Objects.requireNonNull(getString(path))); + return Integer.parseInt(getString(path)); } catch (Exception ex) { return def; } @@ -98,7 +98,7 @@ public int getInt(@Nonnull String path, int def) { @Override public short getShort(@Nonnull String path, short def) { try { - return Short.parseShort(Objects.requireNonNull(getString(path))); + return Short.parseShort(getString(path)); } catch (Exception ex) { return def; } @@ -107,7 +107,7 @@ public short getShort(@Nonnull String path, short def) { @Override public byte getByte(@Nonnull String path, byte def) { try { - return Byte.parseByte(Objects.requireNonNull(getString(path))); + return Byte.parseByte(getString(path)); } catch (Exception ex) { return def; } @@ -116,7 +116,7 @@ public byte getByte(@Nonnull String path, byte def) { @Override public double getDouble(@Nonnull String path, double def) { try { - return Double.parseDouble(Objects.requireNonNull(getString(path))); + return Double.parseDouble(getString(path)); } catch (Exception ex) { return def; } @@ -125,7 +125,7 @@ public double getDouble(@Nonnull String path, double def) { @Override public float getFloat(@Nonnull String path, float def) { try { - return Float.parseFloat(Objects.requireNonNull(getString(path))); + return Float.parseFloat(getString(path)); } catch (Exception ex) { return def; } @@ -137,7 +137,7 @@ public boolean getBoolean(@Nonnull String path, boolean def) { Object value = bsonDocument.get(path); if (value instanceof Boolean) return (Boolean) value; if (value instanceof String) return Boolean.parseBoolean((String) value); - } catch (Exception ignored) { + } catch (Exception ex) { } return def; } @@ -161,7 +161,7 @@ public UUID getUUID(@Nonnull String path) { Object value = bsonDocument.get(path); if (value instanceof UUID) return (UUID) value; if (value instanceof String) return UUID.fromString((String) value); - } catch (Exception ignored) { + } catch (Exception ex) { } return null; } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java index 6df6ce127..05611a0b0 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java @@ -16,7 +16,7 @@ public final class BsonUtils { - private static final ILogger logger = ILogger.forThisClass(); + protected static final ILogger logger = ILogger.forThisClass(); private BsonUtils() { } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java index 32e03109f..d0c2c4a37 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java @@ -57,7 +57,7 @@ public static Object packObject(@Nullable Object value) { BsonUtils.setDocumentProperties(bson, values); return bson; } else if (value instanceof UUID) { - return value.toString(); + return ((UUID) value).toString(); } else { return value; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index 2cd31b223..5b15d051e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -65,7 +65,7 @@ public RandomPotionEffectChallenge() { @Nullable public static PotionEffectType getNewRandomEffect(@Nonnull LivingEntity entity) { - List activeEffects = entity.getActivePotionEffects().stream().map(PotionEffect::getType).toList(); + List activeEffects = entity.getActivePotionEffects().stream().map(PotionEffect::getType).collect(Collectors.toList()); ArrayList possibleEffects = new ArrayList<>(Arrays.asList(PotionEffectType.values())); possibleEffects.removeAll(activeEffects); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java index 99d8ccdb6..6b86b70af 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java @@ -17,7 +17,6 @@ import org.bukkit.inventory.Inventory; import javax.annotation.Nonnull; -import java.util.Objects; @Since("2.0") public class PermanentItemChallenge extends Setting { @@ -41,7 +40,7 @@ public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { Inventory clickedInventory = event.getClickedInventory(); if (event.getCursor() == null) return; if (clickedInventory == null) return; - InventoryType type = Objects.requireNonNull(CompatibilityUtils.getTopInventory(player)).getType(); + InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.PLAYER) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 8a11d2c29..899c446cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -64,7 +64,7 @@ private void teleportRandom(@Nonnull Player player) { List list = player.getWorld().getNearbyEntities(player.getLocation(), 200, 200, 200).stream() .filter(entity -> !(entity instanceof Player)) .filter(entity -> entity instanceof LivingEntity) - .toList(); + .collect(Collectors.toList()); Entity targetEntity = list.get(globalRandom.nextInt(list.size())); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index aa48d502b..90b44a7e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -423,7 +423,7 @@ class DocumentCountStatistic extends DocumentStatistic { } } - List newAnswers = answers.stream().map(StringUtils::getEnumName).toList(); + List newAnswers = answers.stream().map(StringUtils::getEnumName).collect(Collectors.toList()); answers.clear(); answers.addAll(newAnswers); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 2b621dc6f..32c31c8f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -29,7 +29,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.Objects; @Since("2.1.2") public class HotBarRandomizerChallenge extends TimedChallenge { @@ -118,7 +117,7 @@ public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { Inventory clickedInventory = event.getClickedInventory(); if (event.getCursor() == null) return; if (clickedInventory == null) return; - InventoryType type = Objects.requireNonNull(CompatibilityUtils.getTopInventory(player)).getType(); + InventoryType type = CompatibilityUtils.getTopInventory(player).getType(); if (type == InventoryType.WORKBENCH || type == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.CRAFTING) return; if (clickedInventory.getType() == InventoryType.PLAYER) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index 26f25a80c..28ae22550 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -56,7 +56,7 @@ public void writeGameState(@Nonnull Document document) { public void loadGameState(@Nonnull Document document) { super.loadGameState(document); - blocks.addAll(document.getSerializableList("blocks", Location.class).stream().map(Location::getBlock).toList()); + blocks.addAll(document.getSerializableList("blocks", Location.class).stream().map(Location::getBlock).collect(Collectors.toList())); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java index c9f19f248..2ad3bacf4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java @@ -70,7 +70,7 @@ protected void collect(@Nonnull Player player, @Nonnull Object item, @Nonnull Ru } protected List getCollectionFiltered(@Nonnull UUID uuid) { - List targetStringList = Arrays.stream(target).map(Object::toString).toList(); + List targetStringList = Arrays.stream(target).map(Object::toString).collect(Collectors.toList()); return collections.computeIfAbsent(uuid, key -> new ArrayList<>()).stream().filter(targetStringList::contains).collect(Collectors.toList()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java index bf7090a65..5fadbe3f4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java @@ -14,7 +14,6 @@ import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import java.util.List; -import java.util.Objects; @Getter @Setter @@ -32,7 +31,7 @@ public abstract class MenuGenerator { public boolean hasInventoryOpen(Player player) { MenuPosition menuPosition = MenuPosition.get(player); return menuPosition instanceof GeneratorMenuPosition - && Objects.requireNonNull(CompatibilityUtils.getTopInventory(player)).getType() != InventoryType.CRAFTING + && CompatibilityUtils.getTopInventory(player).getType() != InventoryType.CRAFTING && ((GeneratorMenuPosition) menuPosition).getGenerator() == this; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java index 9df0dc49b..53b285c9d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java @@ -30,4 +30,14 @@ public boolean isLowerItemClick() { return !upperItem; } + @Nonnull + public Player getPlayer() { + return player; + } + + @Nonnull + public Inventory getInventory() { + return inventory; + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java index f3f6db16f..a633ec0d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java @@ -2,6 +2,7 @@ import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.LinkedList; import java.util.List; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java index 2251cdd1b..00de88ed9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java @@ -33,7 +33,8 @@ public void onGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { @EventHandler(priority = EventPriority.MONITOR) public void onSneak(PlayerToggleSneakEvent event) { - event.isSneaking(); + if (!event.isSneaking()) { + } //// Structure structure = entry.getValue(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java index 37e6f5fbc..c5f73691e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java @@ -149,7 +149,7 @@ public static List format(@Nonnull String sequence, @Nonnull Obje if (!currentText.getText().isEmpty()) { results.add(currentText); } - if (!argument.isEmpty()) { + if (argument.length() > 0) { results.add(new TextComponent(String.valueOf(start))); results.add(new TextComponent(String.valueOf(argument))); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java index 32bb95dfa..4b941e688 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java @@ -19,6 +19,7 @@ public class NMSProvider { /** * -- GETTER -- * + * @return A border packet factory */ @Getter private static final BorderPacketFactory borderPacketFactory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index 42523ce79..b457a897e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -214,8 +214,7 @@ public ItemDescription getBuiltByItemDescription() { @Override public ItemBuilder clone() { - ItemBuilder itemBuilder = (ItemBuilder) super.clone(); - ItemBuilder builder = new ItemBuilder(item.clone(), getMeta().clone()); + ItemBuilder builder = new ItemBuilder(item.clone(), getMeta().clone()); builder.builtByItemDescription = builtByItemDescription; return builder; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java index e94c8cf0d..f81f27ba2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.codingarea.commons.common.collection.IOUtils; import org.bukkit.entity.Player; import javax.annotation.Nonnull; @@ -21,7 +20,8 @@ private ImageUtils() { @Nullable public static BufferedImage getImage(@Nonnull String url) throws IOException { - HttpURLConnection connection = IOUtils.createConnection(url); + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); return ImageIO.read(connection.getInputStream()); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java index 31f3e41cb..c90eea42b 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java @@ -1,7 +1,6 @@ package net.codingarea.commons.bukkit.core; import com.google.common.base.Charsets; -import lombok.Getter; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.commons.bukkit.utils.menu.MenuPositionListener; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; @@ -55,8 +54,7 @@ public abstract class BukkitModule extends JavaPlugin { private ExecutorService executorService; private Document config, pluginConfig; private Version version; - @Getter - private boolean devMode; + private boolean devMode; private boolean firstInstall; private boolean isReloaded; private boolean isLoaded; @@ -77,10 +75,10 @@ public final void onLoad() { ILogger.setConstantFactory(this.getILogger()); trySaveDefaultConfig(); if (wasShutdown) isReloaded = true; - if (firstInstall == !getDataFolder().exists()) { + if (firstInstall = !getDataFolder().exists()) { getILogger().info("Detected first install!"); } - if (devMode == getConfigDocument().getBoolean("dev-mode") || getConfigDocument().getBoolean("dev-mode.enabled")) { + if (devMode = getConfigDocument().getBoolean("dev-mode") || getConfigDocument().getBoolean("dev-mode.enabled")) { getILogger().setLevel(Level.ALL); getILogger().debug("Devmode is enabled: Showing debug messages. This can be disabled in the plugin.yml ('dev-mode')"); } else { @@ -144,7 +142,11 @@ protected void handleLoad() throws Exception {} protected void handleEnable() throws Exception {} protected void handleDisable() throws Exception {} - public final boolean isFirstInstall() { + public boolean isDevMode() { + return devMode; + } + + public final boolean isFirstInstall() { return firstInstall; } @@ -183,7 +185,7 @@ public void reloadConfig() { @Nonnull public Document getPluginDocument() { return pluginConfig != null ? pluginConfig : - (pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(Objects.requireNonNull(getResource("plugin.yml")), Charsets.UTF_8)))); + (pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(getResource("plugin.yml"), Charsets.UTF_8)))); } @Nonnull @@ -342,7 +344,7 @@ private void injectInstance() { Field instanceField = this.getClass().getDeclaredField("instance"); instanceField.setAccessible(true); instanceField.set(null, this); - } catch (Throwable ignored) { + } catch (Throwable ex) { } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java index 8b380040c..87cae1721 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java @@ -6,7 +6,6 @@ import org.bukkit.Bukkit; import javax.annotation.Nonnull; -import java.util.Objects; public final class RequirementsChecker { @@ -19,7 +18,7 @@ public RequirementsChecker(@Nonnull BukkitModule module) { public void checkExceptionally(@Nonnull Document requirements) throws IllegalStateException { if (requirements.getBoolean("spigot")) requireSpigot(); if (requirements.getBoolean("paper")) requirePaper(); - if (requirements.contains("version")) requireVersion(Objects.requireNonNull(requirements.getVersion("version"))); + if (requirements.contains("version")) requireVersion(requirements.getVersion("version")); } public boolean checkBoolean(@Nonnull Document requirements) { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java index b91add45e..130785522 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java @@ -7,7 +7,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Arrays; -import java.util.Objects; public class AnimationFrame implements Cloneable { @@ -60,7 +59,7 @@ public ItemStack getItem(int slot) { @Nullable public Material getItemType(int slot) { - return getItem(slot) == null ? Material.AIR : Objects.requireNonNull(getItem(slot)).getType(); + return getItem(slot) == null ? Material.AIR : getItem(slot).getType(); } @Nonnull @@ -79,8 +78,7 @@ public int getSize() { @Nonnull @Override public AnimationFrame clone() { - AnimationFrame animationFrame = (AnimationFrame) super.clone(); - return new AnimationFrame(content); + return new AnimationFrame(content); } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java index 47441780a..8991960e0 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java @@ -1,6 +1,5 @@ package net.codingarea.commons.bukkit.utils.animation; -import lombok.Getter; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Sound; @@ -36,9 +35,7 @@ public static void playStatusSound(@Nonnull Player player, boolean enabled) { private static final class SoundFrame { - @Getter - @Getter - private final float pitch, volume; + private final float pitch, volume; private final Sound sound; public SoundFrame(@Nonnull Sound sound, float volume, float pitch) { @@ -55,7 +52,15 @@ public void play(@Nonnull Player player, @Nonnull Location location) { player.playSound(location, sound, volume, pitch); } - @Nonnull + public float getPitch() { + return pitch; + } + + public float getVolume() { + return volume; + } + + @Nonnull public Sound getSound() { return sound; } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java index e156c6284..172e2e4ff 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java @@ -160,15 +160,14 @@ public JsonObject build() { } /** - * Escapes the given string like stated in .... - * - *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. - * Compact escapes are not used (e.g., '\n' is escaped as " - " and not as "\n"). - * - * @param value The value to escape. - * @return The escaped value. - */ + * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. + * + *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. + * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). + * + * @param value The value to escape. + * @return The escaped value. + */ private static String escape(String value) { final StringBuilder builder = new StringBuilder(); for (int i = 0; i < value.length(); i++) { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java index 868ad8110..339bbaba2 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java @@ -14,7 +14,10 @@ import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; public class ItemBuilder { @@ -64,7 +67,7 @@ public ItemMeta getMeta() { @Nonnull @SuppressWarnings("unchecked") public final M getCastedMeta() { - return (M) (meta == null ? Objects.requireNonNull(meta = item.getItemMeta()) : meta); + return (M) (meta == null ? meta = item.getItemMeta() : meta); } @Nonnull @@ -251,8 +254,7 @@ public ItemStack toItem() { @Override public ItemBuilder clone() { - ItemBuilder itemBuilder = (ItemBuilder) super.clone(); - return new ItemBuilder(item.clone(), getMeta().clone()); + return new ItemBuilder(item.clone(), getMeta().clone()); } public static class BannerBuilder extends ItemBuilder { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java index 0d2e9236d..5753ad174 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java @@ -1,6 +1,5 @@ package net.codingarea.commons.bukkit.utils.menu; -import lombok.Getter; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; @@ -14,12 +13,9 @@ public class MenuClickInfo { protected final Player player; protected final Inventory inventory; - @Getter - protected final boolean shiftClick; - @Getter - protected final boolean rightClick; - @Getter - protected final int slot; + protected final boolean shiftClick; + protected final boolean rightClick; + protected final int slot; public MenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boolean shiftClick, boolean rightClick, @Nonnegative int slot) { this.player = player; @@ -39,11 +35,23 @@ public Inventory getInventory() { return inventory; } - public boolean isLeftClick() { + public boolean isRightClick() { + return rightClick; + } + + public boolean isLeftClick() { return !rightClick; } - @Nullable + public boolean isShiftClick() { + return shiftClick; + } + + public int getSlot() { + return slot; + } + + @Nullable public ItemStack getClickedItem() { return inventory.getItem(slot); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java index 46b72210b..36284f5e3 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java @@ -136,7 +136,7 @@ public static NamespacedKey fromString(@Nonnull String key) { */ @Nullable public static NamespacedKey fromString(@Nonnull String string, @Nullable Plugin defaultNamespace) { - Preconditions.checkArgument(!string.isEmpty(), "Input string must not be empty or null"); + Preconditions.checkArgument(string != null && !string.isEmpty(), "Input string must not be empty or null"); String[] components = string.split(":", 3); if (components.length > 2) { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java index c53353706..8faa0993b 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java @@ -1,6 +1,5 @@ package net.codingarea.commons.bukkit.utils.wrapper; -import lombok.Getter; import org.bukkit.event.Event; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; @@ -14,8 +13,7 @@ public final class ActionListener implements Listener { private final Class classOfEvent; private final Consumer listener; private final EventPriority priority; - @Getter - private final boolean ignoreCancelled; + private final boolean ignoreCancelled; public ActionListener(@Nonnull Class classOfEvent, @Nonnull Consumer listener, @Nonnull EventPriority priority, boolean ignoreCancelled) { this.classOfEvent = classOfEvent; @@ -52,4 +50,8 @@ public Class getClassOfEvent() { return classOfEvent; } + public boolean isIgnoreCancelled() { + return ignoreCancelled; + } + } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java index 49018ec35..d71f0df71 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java @@ -4,7 +4,7 @@ import java.util.*; /** - * @author JDA | ... + * @author JDA | https://github.com/DV8FromTheWorld/JDA/blob/development/src/main/java/net/dv8tion/jda/internal/utils/ClassWalker.java */ public class ClassWalker implements Iterable> { diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java index 013c092c1..4a734b55b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java @@ -48,7 +48,7 @@ default String format(@Nonnull Number number) { return format(number.doubleValue()); } - NumberFormatter + public static final NumberFormatter DEFAULT = fromPattern("0.##", null, false), INTEGER = value -> (int) value + "", SPACE_SPLIT = fromPattern("###,##0.###############", null, false, diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java index 0c0f90e5e..a9fcb48f2 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java @@ -1,14 +1,11 @@ package net.codingarea.commons.common.collection; -import lombok.Getter; - import java.util.Random; /** * Since there is no way of getting the seed of a {@link Random} we create a wrapper * which will save seed. This allows us to save randomization and reload it. */ -@Getter public class SeededRandomWrapper extends Random implements IRandom { protected long seed; @@ -27,7 +24,11 @@ public void setSeed(long seed) { this.seed = seed; } - @Override + public long getSeed() { + return seed; + } + + @Override public String toString() { return "Random[seed=" + seed + "]"; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java index 734f5cf16..df07b890d 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java @@ -1,7 +1,5 @@ package net.codingarea.commons.common.collection.pair; -import lombok.Getter; - import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -14,7 +12,6 @@ * @param The type of the third value * @param The type of the fourth value */ -@Getter public class Quadro implements Pair { protected F first; @@ -43,7 +40,23 @@ public final Object[] values() { return new Object[] { first, second, third, first }; } - public void setFirst(@Nullable F first) { + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public T getThird() { + return third; + } + + public FF getFourth() { + return fourth; + } + + public void setFirst(@Nullable F first) { this.first = first; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java index b62f55777..48c8dfcde 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java @@ -1,7 +1,5 @@ package net.codingarea.commons.common.collection.pair; -import lombok.Getter; - import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -13,7 +11,6 @@ * @param The type of the second value * @param The type of the third value */ -@Getter public class Triple implements Pair { protected F first; @@ -40,7 +37,19 @@ public final Object[] values() { return new Object[] { first, second, third }; } - public void setFirst(@Nullable F first) { + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public T getThird() { + return third; + } + + public void setFirst(@Nullable F first) { this.first = first; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java index ce1901dbf..9d320ba6e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java @@ -1,7 +1,5 @@ package net.codingarea.commons.common.collection.pair; -import lombok.Getter; - import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -12,7 +10,6 @@ * @param The type of the first value * @param The type of the second value */ -@Getter public class Tuple implements Pair { protected F first; @@ -37,7 +34,15 @@ public final Object[] values() { return new Object[] { first, second }; } - public void setFirst(@Nullable F first) { + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public void setFirst(@Nullable F first) { this.first = first; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java index 08ab891a7..37b71703f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java @@ -64,7 +64,7 @@ public Task addListener(@Nonnull TaskListener listener) { } else if (failure != null) { listener.onFailure(this, failure); } else { - listener.onComplete(this, null); + listener.onComplete(this, value); } return this; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java index 2f9fec69b..cce0be2e8 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java @@ -46,7 +46,7 @@ public char getChar(@Nonnull String path) { @Override public char getChar(@Nonnull String path, char def) { try { - return Objects.requireNonNull(getString(path)).charAt(0); + return getString(path).charAt(0); } catch (NullPointerException | IndexOutOfBoundsException ex) { return def; } @@ -175,7 +175,7 @@ public > List getEnumList(@Nonnull String path, @Nonnull Cl @Nonnull @Override public List getCharacterList(@Nonnull String path) { - return mapList(path, string -> string == null || string.isEmpty() ? (char) 0 : string.charAt(0)); + return mapList(path, string -> string == null || string.length() == 0 ? (char) 0 : string.charAt(0)); } @Nonnull diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java index eabc2e1a7..b0b194d05 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java @@ -129,7 +129,7 @@ public String getString(@Nonnull String path) { @Override public long getLong(@Nonnull String path, long def) { try { - return Long.parseLong(Objects.requireNonNull(getString(path))); + return Long.parseLong(getString(path)); } catch (Exception ex) { return def; } @@ -138,7 +138,7 @@ public long getLong(@Nonnull String path, long def) { @Override public int getInt(@Nonnull String path, int def) { try { - return Integer.parseInt(Objects.requireNonNull(getString(path))); + return Integer.parseInt(getString(path)); } catch (Exception ex) { return def; } @@ -147,7 +147,7 @@ public int getInt(@Nonnull String path, int def) { @Override public short getShort(@Nonnull String path, short def) { try { - return Short.parseShort(Objects.requireNonNull(getString(path))); + return Short.parseShort(getString(path)); } catch (Exception ex) { return def; } @@ -156,7 +156,7 @@ public short getShort(@Nonnull String path, short def) { @Override public byte getByte(@Nonnull String path, byte def) { try { - return Byte.parseByte(Objects.requireNonNull(getString(path))); + return Byte.parseByte(getString(path)); } catch (Exception ex) { return def; } @@ -165,7 +165,7 @@ public byte getByte(@Nonnull String path, byte def) { @Override public float getFloat(@Nonnull String path, float def) { try { - return Float.parseFloat(Objects.requireNonNull(getString(path))); + return Float.parseFloat(getString(path)); } catch (Exception ex) { return def; } @@ -174,7 +174,7 @@ public float getFloat(@Nonnull String path, float def) { @Override public double getDouble(@Nonnull String path, double def) { try { - return Double.parseDouble(Objects.requireNonNull(getString(path))); + return Double.parseDouble(getString(path)); } catch (Exception ex) { return def; } @@ -184,7 +184,7 @@ public double getDouble(@Nonnull String path, double def) { public boolean getBoolean(@Nonnull String path, boolean def) { try { if (!contains(path)) return def; - switch (Objects.requireNonNull(getString(path)).toLowerCase()) { + switch (getString(path).toLowerCase()) { case "true": case "1": return true; diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java index 7f5213806..58fa7b100 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java @@ -78,7 +78,7 @@ public String getString(@Nonnull String path) { @Override public long getLong(@Nonnull String path, long def) { try { - return Long.parseLong(Objects.requireNonNull(getString(path))); + return Long.parseLong(getString(path)); } catch (Exception ex) { return def; } @@ -87,7 +87,7 @@ public long getLong(@Nonnull String path, long def) { @Override public int getInt(@Nonnull String path, int def) { try { - return Integer.parseInt(Objects.requireNonNull(getString(path))); + return Integer.parseInt(getString(path)); } catch (Exception ex) { return def; } @@ -96,7 +96,7 @@ public int getInt(@Nonnull String path, int def) { @Override public short getShort(@Nonnull String path, short def) { try { - return Short.parseShort(Objects.requireNonNull(getString(path))); + return Short.parseShort(getString(path)); } catch (Exception ex) { return def; } @@ -105,7 +105,7 @@ public short getShort(@Nonnull String path, short def) { @Override public byte getByte(@Nonnull String path, byte def) { try { - return Byte.parseByte(Objects.requireNonNull(getString(path))); + return Byte.parseByte(getString(path)); } catch (Exception ex) { return def; } @@ -114,7 +114,7 @@ public byte getByte(@Nonnull String path, byte def) { @Override public float getFloat(@Nonnull String path, float def) { try { - return Float.parseFloat(Objects.requireNonNull(getString(path))); + return Float.parseFloat(getString(path)); } catch (Exception ex) { return def; } @@ -123,7 +123,7 @@ public float getFloat(@Nonnull String path, float def) { @Override public double getDouble(@Nonnull String path, double def) { try { - return Double.parseDouble(Objects.requireNonNull(getString(path))); + return Double.parseDouble(getString(path)); } catch (Exception ex) { return def; } @@ -139,7 +139,7 @@ public boolean getBoolean(@Nonnull String path, boolean def) { @Override public UUID getUUID(@Nonnull String path) { try { - return UUID.fromString(Objects.requireNonNull(getString(path))); + return UUID.fromString(getString(path)); } catch (Exception ex) { return null; } @@ -155,7 +155,7 @@ public Date getDate(@Nonnull String path) { @Override public OffsetDateTime getDateTime(@Nonnull String path) { try { - return OffsetDateTime.parse(Objects.requireNonNull(getString(path))); + return OffsetDateTime.parse(getString(path)); } catch (Exception ex) { return null; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java index faf4fe162..03bdf14d3 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java @@ -54,7 +54,7 @@ public String getString(@Nonnull String path) { @Override public String getString(@Nonnull String path, @Nonnull String def) { String string = config.getString(path, def); - return string; + return string == null ? def : string; } @Nullable @@ -67,7 +67,7 @@ public Object getObject(@Nonnull String path) { @Override public Object getObject(@Nonnull String path, @Nonnull Object def) { Object value = config.get(path, def); - return value; + return value == null ? def : value; } @Override @@ -147,7 +147,7 @@ public char getChar(@Nonnull String path) { @Override public char getChar(@Nonnull String path, char def) { try { - return Objects.requireNonNull(getString(path)).charAt(0); + return getString(path).charAt(0); } catch (NullPointerException | StringIndexOutOfBoundsException ex) { return def; } @@ -193,7 +193,7 @@ public List getStringList(@Nonnull String path) { @Override public UUID getUUID(@Nonnull String path) { try { - return UUID.fromString(Objects.requireNonNull(getString(path))); + return UUID.fromString(getString(path)); } catch (Exception ex) { return null; } @@ -213,7 +213,7 @@ public Date getDate(@Nonnull String path) { @Override public OffsetDateTime getDateTime(@Nonnull String path) { try { - return OffsetDateTime.parse(Objects.requireNonNull(getString(path))); + return OffsetDateTime.parse(getString(path)); } catch (Exception ex) { return null; } @@ -223,7 +223,7 @@ public OffsetDateTime getDateTime(@Nonnull String path) { @Override public Color getColor(@Nonnull String path) { try { - return Color.decode(Objects.requireNonNull(getString(path))); + return Color.decode(getString(path)); } catch (Exception ex) { return null; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java index 71f9f7744..ed36fd787 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java @@ -43,7 +43,7 @@ public Object read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOExce Class clazz = null; try { clazz = Class.forName(classOfType); - } catch (ClassNotFoundException | NullPointerException ignored) { + } catch (ClassNotFoundException | NullPointerException ex) { } Map map = GsonUtils.convertJsonObjectToMap(json); diff --git a/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java index b75f88549..49eeec955 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java +++ b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java @@ -1,6 +1,5 @@ package net.codingarea.commons.common.discord; -import lombok.Getter; import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnull; @@ -215,8 +214,7 @@ public DiscordWebhook replaceEverywhere(@Nonnull String trigger, @Nonnull String return this; } - @Getter - public static class EmbedObject { + public static class EmbedObject { protected String title; protected String description; @@ -246,7 +244,43 @@ public EmbedObject(@Nullable String title, @Nullable String description, @Nullab this.fields = fields; } - @Nonnull + public String getTitle() { + return title; + } + + public String getDescription() { + return description; + } + + public String getUrl() { + return url; + } + + public Color getColor() { + return color; + } + + public Footer getFooter() { + return footer; + } + + public Thumbnail getThumbnail() { + return thumbnail; + } + + public Image getImage() { + return image; + } + + public Author getAuthor() { + return author; + } + + public List getFields() { + return fields; + } + + @Nonnull public EmbedObject setTitle(String title) { this.title = title; return this; @@ -302,8 +336,7 @@ public EmbedObject addField(String name, String value, boolean inline) { @Override public EmbedObject clone() { - EmbedObject embedObject = (EmbedObject) super.clone(); - return new EmbedObject( + return new EmbedObject( title, description, url, color, footer == null ? null : footer.clone(), thumbnail == null ? null : thumbnail.clone(), @@ -335,9 +368,8 @@ private String getIconUrl() { } @Override - protected Footer clone() throws CloneNotSupportedException { - Footer footer1 = (Footer) super.clone(); - return new Footer(text, iconUrl); + protected Footer clone() { + return new Footer(text, iconUrl); } } @@ -357,9 +389,8 @@ private String getUrl() { } @Override - protected Thumbnail clone() throws CloneNotSupportedException { - Thumbnail thumbnail1 = (Thumbnail) super.clone(); - return new Thumbnail(url); + protected Thumbnail clone() { + return new Thumbnail(url); } } @@ -380,8 +411,7 @@ private String getUrl() { @Override public Image clone() { - Image image1 = (Image) super.clone(); - return new Image(url); + return new Image(url); } } @@ -413,9 +443,8 @@ private String getIconUrl() { } @Override - protected Author clone() throws CloneNotSupportedException { - Author author1 = (Author) super.clone(); - return new Author(name, url, iconUrl); + protected Author clone() { + return new Author(name, url, iconUrl); } } @@ -447,17 +476,15 @@ private boolean isInline() { } @Override - protected Field clone() throws CloneNotSupportedException { - Field field = (Field) super.clone(); - return new Field(name, value, inline); + protected Field clone() { + return new Field(name, value, inline); } } } @Override public DiscordWebhook clone() { - DiscordWebhook discordWebhook = (DiscordWebhook) super.clone(); - return new DiscordWebhook(url, username, avatarUrl, content, clone(embeds, EmbedObject::clone), tts); + return new DiscordWebhook(url, username, avatarUrl, content, clone(embeds, EmbedObject::clone), tts); } @Nonnull diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java index eb337e206..02ec550a7 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java @@ -260,7 +260,7 @@ default JavaILogger java() { @CheckReturnValue default PrintStream asPrintStream(@Nonnull LogLevel level) { try { - return new PrintStream(new LogOutputStream(this, level), true, StandardCharsets.UTF_8); + return new PrintStream(new LogOutputStream(this, level), true, StandardCharsets.UTF_8.name()); } catch (Exception ex) { throw new WrappedException(ex); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java index 58d6c7262..ddf6d01c8 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java @@ -1,7 +1,5 @@ package net.codingarea.commons.common.logging; -import lombok.Getter; - import javax.annotation.Nonnull; import java.util.logging.Level; @@ -17,10 +15,8 @@ public enum LogLevel { private final String uppercaseName, lowercaseName; private final Level javaLevel; - @Getter - private final int value; - @Getter - private final boolean highlighted; + private final int value; + private final boolean highlighted; LogLevel(int value, @Nonnull String uppercaseName, @Nonnull String lowercaseName, @Nonnull Level javaLevel, boolean highlighted) { this.uppercaseName = uppercaseName; @@ -39,7 +35,11 @@ public boolean isShownAtLoggerLevel(@Nonnull LogLevel loggerLevel) { return this.getValue() >= loggerLevel.getValue(); } - @Nonnull + public int getValue() { + return value; + } + + @Nonnull public String getLowerCaseName() { return lowercaseName; } @@ -49,7 +49,11 @@ public String getUpperCaseName() { return uppercaseName; } - @Nonnull + public boolean isHighlighted() { + return highlighted; + } + + @Nonnull public static LogLevel fromJavaLevel(@Nonnull Level level) { for (LogLevel logLevel : values()) { if (logLevel.getJavaUtilLevel().intValue() == level.intValue()) diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java index c747fbf1a..7095492ed 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java @@ -17,7 +17,7 @@ public LogOutputStream(@Nonnull ILogger logger, @Nonnull LogLevel level) { @Override public void flush() throws IOException { - String input = this.toString(StandardCharsets.UTF_8); + String input = this.toString(StandardCharsets.UTF_8.name()); this.reset(); if (input != null && !input.isEmpty() && !input.equals(System.lineSeparator())) { diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java index 3212680b9..5068d301b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java @@ -8,11 +8,11 @@ public class LogEntry { - private final Instant timestamp; - private final String threadName; - private final String message; - private final LogLevel level; - private final Throwable exception; + private Instant timestamp; + private String threadName; + private String message; + private LogLevel level; + private Throwable exception; public LogEntry(@Nonnull Instant timestamp, @Nonnull String threadName, @Nonnull String message, @Nonnull LogLevel level, @Nullable Throwable exception) { this.timestamp = timestamp; diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java index b9c95d540..f0c64bf8d 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java @@ -393,4 +393,274 @@ public void debug(@Nullable Object message, @Nonnull Object... args) { } + @Override + public boolean isTraceEnabled() { + return isLevelEnabled(LogLevel.TRACE); + } + +// @Override +// public void trace(String msg) { +// trace(msg, new Object[0]); +// } +// +// @Override +// public void trace(String format, Object arg) { +// trace(format, new Object[] { arg }); +// } +// +// @Override +// public void trace(String format, Object arg1, Object arg2) { +// trace(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void trace(String msg, Throwable t) { +// trace(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isTraceEnabled(Marker marker) { +// return isTraceEnabled(); +// } +// +// @Override +// public void trace(Marker marker, String msg) { +// trace(msg); +// } +// +// @Override +// public void trace(Marker marker, String format, Object arg) { +// trace(format, arg); +// } +// +// @Override +// public void trace(Marker marker, String format, Object arg1, Object arg2) { +// trace(format, arg1, arg2); +// } +// +// @Override +// public void trace(Marker marker, String format, Object... argArray) { +// trace(format, argArray); +// } +// +// @Override +// public void trace(Marker marker, String msg, Throwable t) { +// trace(msg, t); +// } +// +// @Override +// public boolean isDebugEnabled() { +// return isLevelEnabled(LogLevel.DEBUG); +// } +// +// @Override +// public void debug(String msg) { +// debug(msg, new Object[0]); +// } +// +// @Override +// public void debug(String format, Object arg) { +// debug(format, new Object[] { arg }); +// } +// +// @Override +// public void debug(String format, Object arg1, Object arg2) { +// debug(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void debug(String msg, Throwable t) { +// debug(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isDebugEnabled(Marker marker) { +// return isDebugEnabled(); +// } +// +// @Override +// public void debug(Marker marker, String msg) { +// debug(msg); +// } +// +// @Override +// public void debug(Marker marker, String format, Object arg) { +// debug(format, arg); +// } +// +// @Override +// public void debug(Marker marker, String format, Object arg1, Object arg2) { +// debug(format, arg1, arg2); +// } +// +// @Override +// public void debug(Marker marker, String format, Object... arguments) { +// debug(format, arguments); +// } +// +// @Override +// public void debug(Marker marker, String msg, Throwable t) { +// debug(msg, t); +// } +// +// @Override +// public boolean isInfoEnabled() { +// return isLevelEnabled(LogLevel.INFO); +// } +// +// @Override +// public void info(String format, Object arg) { +// info(format, new Object[] { arg }); +// } +// +// @Override +// public void info(String format, Object arg1, Object arg2) { +// info(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void info(String msg, Throwable t) { +// info(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isInfoEnabled(Marker marker) { +// return isInfoEnabled(); +// } +// +// @Override +// public void info(Marker marker, String msg) { +// info(msg); +// } +// +// @Override +// public void info(Marker marker, String format, Object arg) { +// info(format, arg); +// } +// +// @Override +// public void info(Marker marker, String format, Object arg1, Object arg2) { +// info(format, arg1, arg2); +// } +// +// @Override +// public void info(Marker marker, String format, Object... arguments) { +// info(format, arguments); +// } +// +// @Override +// public void info(Marker marker, String msg, Throwable t) { +// info(msg, t); +// } +// +// @Override +// public boolean isWarnEnabled() { +// return isLevelEnabled(LogLevel.WARN); +// } +// +// @Override +// public void warn(String msg) { +// warn(msg, new Object[0]); +// } +// +// @Override +// public void warn(String format, Object arg) { +// warn(format, new Object[] { arg }); +// } +// +// @Override +// public void warn(String format, Object arg1, Object arg2) { +// warn(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void warn(String msg, Throwable t) { +// warn(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isWarnEnabled(Marker marker) { +// return isWarnEnabled(); +// } +// +// @Override +// public void warn(Marker marker, String msg) { +// warn(marker); +// } +// +// @Override +// public void warn(Marker marker, String format, Object arg) { +// warn(format, arg); +// } +// +// @Override +// public void warn(Marker marker, String format, Object arg1, Object arg2) { +// warn(format, arg1, arg2); +// } +// +// @Override +// public void warn(Marker marker, String format, Object... arguments) { +// warn(format, arguments); +// } +// +// @Override +// public void warn(Marker marker, String msg, Throwable t) { +// warn(msg, t); +// } +// +// @Override +// public boolean isErrorEnabled() { +// return isLevelEnabled(LogLevel.ERROR); +// } +// +// @Override +// public void error(String msg) { +// error(msg, new Object[0]); +// } +// +// @Override +// public void error(String format, Object arg) { +// error(format, new Object[] { arg }); +// } +// +// @Override +// public void error(String format, Object arg1, Object arg2) { +// error(format, new Object[] { arg1, arg2 }); +// } +// +// @Override +// public void error(String msg, Throwable t) { +// error(msg, new Object[] { t }); +// } +// +// @Override +// public boolean isErrorEnabled(Marker marker) { +// return isErrorEnabled(); +// } +// +// @Override +// public void error(Marker marker, String msg) { +// error(msg); +// } +// +// @Override +// public void error(Marker marker, String format, Object arg) { +// error(format, arg); +// } +// +// @Override +// public void error(Marker marker, String format, Object arg1, Object arg2) { +// error(format, arg1, arg2); +// } +// +// @Override +// public void error(Marker marker, String format, Object... arguments) { +// error(format, arguments); +// } +// +// @Override +// public void error(Marker marker, String msg, Throwable t) { +// error(msg, t); +// } + } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java index b01426a87..fc9a86c16 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java @@ -12,7 +12,7 @@ public final class BukkitReflectionSerializationUtils { private BukkitReflectionSerializationUtils() {} - private static final ILogger logger = ILogger.forThisClass(); + protected static final ILogger logger = ILogger.forThisClass(); public static boolean isSerializable(@Nonnull Class clazz) { try { @@ -56,7 +56,7 @@ public static T deserializeObject(@Nonnull Map map, @Nullabl return (T) object; - } catch (Throwable ignored) { + } catch (Throwable ex) { } if (classOfT == null) diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java index e3438e1fe..b8733488f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java @@ -531,7 +531,7 @@ public static void createFile(@Nullable Path filePath) { if (filePath.getParent() != null) Files.createDirectories(filePath.getParent()); Files.createFile(filePath); - } catch (IOException ignored) { + } catch (IOException ex) { } } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java index 4f7d07eee..ce3988f94 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java @@ -118,7 +118,7 @@ public static void setDocumentProperties(@Nonnull Gson gson, @Nonnull JsonObject public static int getSize(@Nonnull JsonObject object) { try { return object.size(); - } catch (NoSuchMethodError ignored) { + } catch (NoSuchMethodError ex) { } return object.entrySet().size(); diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java index a19e89e89..6be9f8af1 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java @@ -73,8 +73,7 @@ public static BufferedImage loadUrl(@Nonnull String url) throws IOException { public static BufferedImage loadResource(@Nonnull String path) throws IOException { InputStream stream = ImageUtils.class.getClassLoader().getResourceAsStream(path); - assert stream != null; - return ImageIO.read(stream); + return ImageIO.read(stream); } public static BufferedImage loadFile(@Nonnull File file) throws IOException { diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java index 4fb6cb7a4..2c4566199 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java @@ -49,7 +49,7 @@ public static Method getInheritedPrivateMethod(@Nonnull Class clazz, @Nonnull for (Class current : ClassWalker.walk(clazz)) { try { return current.getDeclaredMethod(name, parameterTypes); - } catch (Throwable ignored) { + } catch (Throwable ex) { } } @@ -61,7 +61,7 @@ public static Field getInheritedPrivateField(@Nonnull Class clazz, @Nonnull S for (Class current : ClassWalker.walk(clazz)) { try { return current.getDeclaredField(name); - } catch (Throwable ignored) { + } catch (Throwable ex) { } } @@ -77,7 +77,7 @@ public static > E getFirstEnumByNames(@Nonnull Class classO for (String name : names) { try { return Enum.valueOf(classOfEnum, name); - } catch (IllegalArgumentException | NoSuchFieldError ignored) { } + } catch (IllegalArgumentException | NoSuchFieldError ex) { } } throw new IllegalArgumentException("No enum found in " + classOfEnum.getName() + " for " + Arrays.toString(names)); } @@ -234,8 +234,7 @@ public static T getAnnotationValue(@Nonnull Annotation annotation) { public static > E getEnumByAlternateNames(@Nonnull Class classOfE, @Nonnull String input) { E[] values = invokeStaticMethodOrNull(classOfE, "values"); String[] methodNames = { "getName", "getNames", "getAlias", "getAliases", "getKey", "getKeys", "name", "toString", "ordinal", "getId", "id" }; - assert values != null; - for (E value : values) { + for (E value : values) { for (String method : methodNames) { if (check(input, invokeMethodOrNull(value, method))) return value; diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java index e92d8938e..66faae82d 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java @@ -35,7 +35,7 @@ public static void disableErrorLogging() { public static String convertMapToString(@Nonnull Map map, @Nonnull Function key, @Nonnull Function value) { StringBuilder builder = new StringBuilder(); for (Entry entry : map.entrySet()) { - if (!builder.isEmpty()) builder.append(REGEX_1); + if (builder.length() != 0) builder.append(REGEX_1); builder.append(key.apply(entry.getKey())); builder.append(REGEX_2); builder.append(value.apply(entry.getValue())); diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java index b24f8cd0b..29dbac10b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java @@ -1,12 +1,10 @@ package net.codingarea.commons.common.version; -import lombok.Getter; import net.codingarea.commons.common.logging.ILogger; import javax.annotation.Nullable; import java.util.Objects; -@Getter public class VersionInfo implements Version { protected static final ILogger logger = ILogger.forThisClass(); @@ -23,7 +21,19 @@ public VersionInfo(int major, int minor, int revision) { this.revision = revision; } - @Override + public int getMajor() { + return major; + } + + public int getMinor() { + return minor; + } + + public int getRevision() { + return revision; + } + + @Override public boolean equals(Object other) { if (this == other) return true; if (!(other instanceof Version)) return false; diff --git a/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java index 2c169866d..8c67b2b87 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java +++ b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java @@ -1,26 +1,18 @@ package net.codingarea.commons.database; -import lombok.Getter; import net.codingarea.commons.common.config.Propertyable; import javax.annotation.Nonnull; public final class DatabaseConfig { - @Getter - private final String host; - @Getter - private final String database; - @Getter - private final String authDatabase; - @Getter - private final String password; - @Getter - private final String user; - @Getter - private final String file; - @Getter - private final int port; + private final String host; + private final String database; + private final String authDatabase; + private final String password; + private final String user; + private final String file; + private final int port; private final boolean portIsSet; public DatabaseConfig(String host, String database, String password, String user, int port) { @@ -65,11 +57,39 @@ public DatabaseConfig(@Nonnull Propertyable config) { ); } - public boolean isPortSet() { + public int getPort() { + return port; + } + + public String getAuthDatabase() { + return authDatabase; + } + + public String getDatabase() { + return database; + } + + public String getHost() { + return host; + } + + public String getPassword() { + return password; + } + + public String getUser() { + return user; + } + + public boolean isPortSet() { return portIsSet; } - @Override + public String getFile() { + return file; + } + + @Override public String toString() { return "DatabaseConfig{" + "host='" + host + '\'' + diff --git a/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java index ea78c59a7..0770c8b67 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java @@ -1,6 +1,5 @@ package net.codingarea.commons.database; -import lombok.Getter; import net.codingarea.commons.common.concurrent.task.Task; import net.codingarea.commons.database.action.*; import net.codingarea.commons.database.exceptions.DatabaseException; @@ -12,7 +11,6 @@ import java.util.Collections; import java.util.List; -@Getter public class EmptyDatabase implements Database { private final boolean silent; @@ -21,7 +19,11 @@ public EmptyDatabase(boolean silent) { this.silent = silent; } - protected void exception(@Nonnull String message) { + public boolean isSilent() { + return silent; + } + + protected void exception(@Nonnull String message) { throw new UnsupportedOperationException(message); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java index 66f00bfbb..75536fe81 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java @@ -121,7 +121,7 @@ protected PreparedStatement prepare() throws SQLException, DatabaseException { command.append(" ORDER BY "); command.append(orderBy); if (order != null) - command.append(" ").append(order == Order.HIGHEST ? "DESC" : "ASC"); + command.append(" " + (order == Order.HIGHEST ? "DESC" : "ASC")); command.append(" "); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java index b0cb9da9c..2d6536855 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java @@ -8,7 +8,6 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Map; -import java.util.Objects; public final class SQLResult extends MapDocument { @@ -20,7 +19,7 @@ public SQLResult(@Nonnull Map values) { @Override public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { try { - return new GsonDocument(Objects.requireNonNull(getString(path)), this, this).readonly(); + return new GsonDocument(getString(path), this, this).readonly(); } catch (Exception ex) { return new EmptyDocument(this, null); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java index 47dae0851..d3b4cd844 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java @@ -92,7 +92,7 @@ protected PreparedStatement prepare() throws SQLException, DatabaseException { int index = 0; for (Entry entry : values.entrySet()) { if (index > 0) command.append(", "); - command.append("`").append(entry.getKey()).append("` = ?"); + command.append("`" + entry.getKey() + "` = ?"); args.add(entry.getValue()); index++; } From b19e52b5ccc057b8d3a2993ba6519e4a7c0cd591 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Tue, 26 May 2026 12:59:44 +0200 Subject: [PATCH 065/119] chore: sync development with master, resolve conflicts does not resolve issues with cloudnet impl --- mongo-connector/src/main/resources/plugin.yml | 2 +- .../net/codingarea/challenges/plugin/Challenges.java | 1 + .../settings/trigger/impl/ConsumeItemTrigger.java | 2 +- .../spigot/listener/PlayerConnectionListener.java | 8 ++++---- plugin/src/main/resources/config.yml | 12 ++++++++++++ renovate.json | 8 ++++++++ 6 files changed, 27 insertions(+), 6 deletions(-) create mode 100644 renovate.json diff --git a/mongo-connector/src/main/resources/plugin.yml b/mongo-connector/src/main/resources/plugin.yml index 94c231489..620f9d2d5 100644 --- a/mongo-connector/src/main/resources/plugin.yml +++ b/mongo-connector/src/main/resources/plugin.yml @@ -1,5 +1,5 @@ name: Challenges-MongoConnector -version: 2.3.2 +version: 2.4 api-version: 1.14 author: CodingArea authors: diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java index 1cec3de1a..2b6ce2984 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java @@ -28,6 +28,7 @@ import net.codingarea.challenges.plugin.utils.bukkit.command.ForwardingCommand; import javax.annotation.Nonnull; +import java.io.File; @Getter public final class Challenges extends BukkitModule { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java index b13f0e5d3..1311f078a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java @@ -18,7 +18,7 @@ public ConsumeItemTrigger(String name) { super(name, SubSettingsBuilder.createChooseMultipleItem(SubSettingsHelper.ITEM).fill(builder -> { for (Material material : ExperimentalUtils.getMaterials()) { if (material.isEdible()) { - builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); + builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemComponent(material).toPlainText()).build()); } } })); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index 22ef71374..67e0faa28 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -1,6 +1,8 @@ package net.codingarea.challenges.plugin.spigot.listener; -import net.codingarea.commons.common.config.Document; +import java.util.List; +import javax.annotation.Nonnull; + import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -10,6 +12,7 @@ import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -18,9 +21,6 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; -import javax.annotation.Nonnull; -import java.util.List; - public class PlayerConnectionListener implements Listener { private final boolean messages; diff --git a/plugin/src/main/resources/config.yml b/plugin/src/main/resources/config.yml index 02be209b6..b63f1ff1f 100644 --- a/plugin/src/main/resources/config.yml +++ b/plugin/src/main/resources/config.yml @@ -24,6 +24,15 @@ # We recommend regenerating the config to get access to new features / settings. config-version: "2.4" +# Currently supported by default +# - en (English) +# - de (German / Deutsch) +language: "de" + +# Makes text from the plugin appear in the 'small caps' font +# Example: ᴛʜɪs ɪs sᴍᴀʟʟ ᴄᴀᴘs +small-caps: false + timer: format: seconds: "{mm}:{ss}" @@ -69,6 +78,9 @@ design: # These can be edited in the corresponding language file join-quit-messages: true +# Send players a permission info message when they join the server when noone with the permission 'challenges.gui' has joined before +permission-info: true + # Players with the permission 'challenges.gui' will get a message if the timer is paused when they join timer-is-paused-info: true diff --git a/renovate.json b/renovate.json new file mode 100644 index 000000000..a60d92cfe --- /dev/null +++ b/renovate.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "labels": ["type: dependencies"], + "extends": ["config:recommended", ":dependencyDashboard"], + "baseBranches": ["development"], + "prHourlyLimit": 50, + "prConcurrentLimit": 10 +} From 80b78a7ad9f79c1d747fd16cee025f116adbb3b1 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Tue, 26 May 2026 18:14:40 +0200 Subject: [PATCH 066/119] chore: migrate to gradle [!!!] following issues are known and might cause build/checks to fail - will be addressed in upcoming changes: - artifact version ambiguity for gson caused by cloudnet might cause build failure due to breaking changes between versions - cloudnet depend resolution (legacy repo might be discontinued) - java version compatibility Replace Maven build with Gradle: add Gradle wrapper, top-level build.gradle.kts, settings, gradle.properties and libs.versions.toml. Add subproject build scripts for plugin and mongo-connector using the Shadow plugin, configure Java 16, resource filtering (injecting ${version}), and UTF-8 compilation. Update CI/workflow: rename GitHub Action to use Gradle (setup-gradle, ./gradlew build) and update artifact paths. Update .gitignore for Gradle outputs and keep gradle/wrapper/gradle-wrapper.jar tracked. Update plugin.yml files to use version token expansion. --- .../workflows/{maven-build.yml => build.yml} | 16 +- .gitignore | 10 +- build.gradle.kts | 38 +++ gradle.properties | 2 + gradle/libs.versions.toml | 45 ++++ gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 60756 bytes gradle/wrapper/gradle-wrapper.properties | 7 + gradlew | 234 ++++++++++++++++++ gradlew.bat | 89 +++++++ mongo-connector/build.gradle.kts | 43 ++++ mongo-connector/pom.xml | 161 ------------ mongo-connector/src/main/resources/plugin.yml | 2 +- plugin/build.gradle.kts | 41 +++ plugin/pom.xml | 198 --------------- plugin/src/main/resources/plugin.yml | 4 +- pom.xml | 23 -- settings.gradle.kts | 3 + 17 files changed, 521 insertions(+), 395 deletions(-) rename .github/workflows/{maven-build.yml => build.yml} (59%) create mode 100644 build.gradle.kts create mode 100644 gradle.properties create mode 100644 gradle/libs.versions.toml create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 mongo-connector/build.gradle.kts delete mode 100644 mongo-connector/pom.xml create mode 100644 plugin/build.gradle.kts delete mode 100644 plugin/pom.xml delete mode 100644 pom.xml create mode 100644 settings.gradle.kts diff --git a/.github/workflows/maven-build.yml b/.github/workflows/build.yml similarity index 59% rename from .github/workflows/maven-build.yml rename to .github/workflows/build.yml index 27375443d..d0f4f4dd2 100644 --- a/.github/workflows/maven-build.yml +++ b/.github/workflows/build.yml @@ -1,4 +1,4 @@ -name: Java CI with Maven +name: Java CI with Gradle on: push: @@ -8,24 +8,26 @@ on: jobs: build: - runs-on: ubuntu-latest - steps: - uses: actions/checkout@v4 + - name: Validate gradle wrapper + uses: gradle/actions/wrapper-validation@v4 - name: Set up JDK 17 uses: actions/setup-java@v4 with: java-version: 17 distribution: corretto - - name: Build with Maven + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 + - name: Build with Gradle env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: mvn -B package --file pom.xml + run: ./gradlew build - name: Capture build artifacts uses: actions/upload-artifact@v4 with: name: Artifacts path: | - plugin/target/Challenges.jar - mongo-connector/target/Challenges-MongoConnector.jar + plugin/build/libs/Challenges.jar + mongo-connector/build/libs/Challenges-MongoConnector.jar diff --git a/.gitignore b/.gitignore index db9783414..a4b9a33a4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,8 @@ # User-specific stuff .idea/ -plugin/dependency-reduced-pom.xml -mongo-connector/dependency-reduced-pom.xml +*.iml +**/dependency-reduced-pom.xml # Test Sources **/src/test @@ -10,6 +10,10 @@ mongo-connector/dependency-reduced-pom.xml # Compiled files **/out **/target +**/build *.class *.jar -*.iml +.gradle/ + +# Gradle wrapper jar must be tracked +!gradle/wrapper/gradle-wrapper.jar diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 000000000..cb6d678ae --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,38 @@ +plugins { + base + id("com.gradleup.shadow") version "8.3.5" apply false +} + +allprojects { + repositories { + mavenCentral() + maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/") + maven("https://libraries.minecraft.net/") + maven("https://jitpack.io") + // legacy cloudnet 3 repository, officially "https://repo.cloudnetservice.eu/repository/releases/" + maven("https://repo.cloudnetservice.eu/releases/") + } +} + +subprojects { + apply(plugin = "java-library") + + extensions.configure("java") { + sourceCompatibility = JavaVersion.VERSION_16 + targetCompatibility = JavaVersion.VERSION_16 + withSourcesJar() + } + + tasks.withType().configureEach { + options.encoding = "UTF-8" + } + + tasks.named("processResources") { + filteringCharset = "UTF-8" + val tokens = mapOf("version" to project.version.toString()) + filesMatching(listOf("plugin.yml", "config.yml")) { + expand(tokens) + } + from(rootProject.file("LICENSE")) + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 000000000..d668feedc --- /dev/null +++ b/gradle.properties @@ -0,0 +1,2 @@ +group=net.codingarea.challenges +version=2.4 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 000000000..bd6e0ab50 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,45 @@ +[versions] + +# minecraft +spigot = "1.21.4-R0.1-SNAPSHOT" +authlib = "1.5.21" + +# logging +slf4j = "1.7.32" + +# annotations, compile time processing +lombok = "1.18.38" +jsr305 = "3.0.2" # TODO replace with jetbrains annotations + +# database +mongodb = "3.12.14" + +# cloudnet +cloudnet3 = "3.4.5-RELEASE" +cloudnet2 = "2.1.17" + +[libraries] + +# minecraft +spigot-api = { group = "org.spigotmc", name = "spigot-api", version.ref = "spigot" } +authlib = { group = "com.mojang", name = "authlib", version.ref = "authlib" } + +# logging +slf4j-api = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" } + +# annotations, compile time processing +lombok = { group = "org.projectlombok", name = "lombok", version.ref = "lombok" } +jsr305 = { group = "com.google.code.findbugs", name = "jsr305", version.ref = "jsr305" } + +# database +mongodb-driver = { group = "org.mongodb", name = "mongodb-driver", version.ref = "mongodb" } + +# cloudnet +cloudnet3-driver = { group = "de.dytanic.cloudnet", name = "cloudnet-driver", version.ref = "cloudnet3" } +cloudnet3-bridge = { group = "de.dytanic.cloudnet", name = "cloudnet-bridge", version.ref = "cloudnet3" } +cloudnet2-bridge = { group = "de.dytanic.cloudnet", name = "cloudnet-api-bridge", version.ref = "cloudnet2" } + +[bundles] + +cloudnet = ["cloudnet3-driver", "cloudnet3-bridge", "cloudnet2-bridge"] + diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..249e5832f090a2944b7473328c07c9755baa3196 GIT binary patch literal 60756 zcmb5WV{~QRw(p$^Dz@00IL3?^hro$gg*4VI_WAaTyVM5Foj~O|-84 z$;06hMwt*rV;^8iB z1~&0XWpYJmG?Ts^K9PC62H*`G}xom%S%yq|xvG~FIfP=9*f zZoDRJBm*Y0aId=qJ?7dyb)6)JGWGwe)MHeNSzhi)Ko6J<-m@v=a%NsP537lHe0R* z`If4$aaBA#S=w!2z&m>{lpTy^Lm^mg*3?M&7HFv}7K6x*cukLIGX;bQG|QWdn{%_6 zHnwBKr84#B7Z+AnBXa16a?or^R?+>$4`}{*a_>IhbjvyTtWkHw)|ay)ahWUd-qq$~ zMbh6roVsj;_qnC-R{G+Cy6bApVOinSU-;(DxUEl!i2)1EeQ9`hrfqj(nKI7?Z>Xur zoJz-a`PxkYit1HEbv|jy%~DO^13J-ut986EEG=66S}D3!L}Efp;Bez~7tNq{QsUMm zh9~(HYg1pA*=37C0}n4g&bFbQ+?-h-W}onYeE{q;cIy%eZK9wZjSwGvT+&Cgv z?~{9p(;bY_1+k|wkt_|N!@J~aoY@|U_RGoWX<;p{Nu*D*&_phw`8jYkMNpRTWx1H* z>J-Mi_!`M468#5Aix$$u1M@rJEIOc?k^QBc?T(#=n&*5eS#u*Y)?L8Ha$9wRWdH^3D4|Ps)Y?m0q~SiKiSfEkJ!=^`lJ(%W3o|CZ zSrZL-Xxc{OrmsQD&s~zPfNJOpSZUl%V8tdG%ei}lQkM+z@-4etFPR>GOH9+Y_F<3=~SXln9Kb-o~f>2a6Xz@AS3cn^;c_>lUwlK(n>z?A>NbC z`Ud8^aQy>wy=$)w;JZzA)_*Y$Z5hU=KAG&htLw1Uh00yE!|Nu{EZkch zY9O6x7Y??>!7pUNME*d!=R#s)ghr|R#41l!c?~=3CS8&zr6*aA7n9*)*PWBV2w+&I zpW1-9fr3j{VTcls1>ua}F*bbju_Xq%^v;-W~paSqlf zolj*dt`BBjHI)H9{zrkBo=B%>8}4jeBO~kWqO!~Thi!I1H(in=n^fS%nuL=X2+s!p}HfTU#NBGiwEBF^^tKU zbhhv+0dE-sbK$>J#t-J!B$TMgN@Wh5wTtK2BG}4BGfsZOoRUS#G8Cxv|6EI*n&Xxq zt{&OxCC+BNqz$9b0WM7_PyBJEVObHFh%%`~!@MNZlo*oXDCwDcFwT~Rls!aApL<)^ zbBftGKKBRhB!{?fX@l2_y~%ygNFfF(XJzHh#?`WlSL{1lKT*gJM zs>bd^H9NCxqxn(IOky5k-wALFowQr(gw%|`0991u#9jXQh?4l|l>pd6a&rx|v=fPJ z1mutj{YzpJ_gsClbWFk(G}bSlFi-6@mwoQh-XeD*j@~huW4(8ub%^I|azA)h2t#yG z7e_V_<4jlM3D(I+qX}yEtqj)cpzN*oCdYHa!nm%0t^wHm)EmFP*|FMw!tb@&`G-u~ zK)=Sf6z+BiTAI}}i{*_Ac$ffr*Wrv$F7_0gJkjx;@)XjYSh`RjAgrCck`x!zP>Ifu z&%he4P|S)H*(9oB4uvH67^0}I-_ye_!w)u3v2+EY>eD3#8QR24<;7?*hj8k~rS)~7 zSXs5ww)T(0eHSp$hEIBnW|Iun<_i`}VE0Nc$|-R}wlSIs5pV{g_Dar(Zz<4X3`W?K z6&CAIl4U(Qk-tTcK{|zYF6QG5ArrEB!;5s?tW7 zrE3hcFY&k)+)e{+YOJ0X2uDE_hd2{|m_dC}kgEKqiE9Q^A-+>2UonB+L@v3$9?AYw zVQv?X*pK;X4Ovc6Ev5Gbg{{Eu*7{N3#0@9oMI~}KnObQE#Y{&3mM4`w%wN+xrKYgD zB-ay0Q}m{QI;iY`s1Z^NqIkjrTlf`B)B#MajZ#9u41oRBC1oM1vq0i|F59> z#StM@bHt|#`2)cpl_rWB($DNJ3Lap}QM-+A$3pe}NyP(@+i1>o^fe-oxX#Bt`mcQc zb?pD4W%#ep|3%CHAYnr*^M6Czg>~L4?l16H1OozM{P*en298b+`i4$|w$|4AHbzqB zHpYUsHZET$Z0ztC;U+0*+amF!@PI%^oUIZy{`L{%O^i{Xk}X0&nl)n~tVEpcAJSJ} zverw15zP1P-O8h9nd!&hj$zuwjg?DoxYIw{jWM zW5_pj+wFy8Tsa9g<7Qa21WaV&;ejoYflRKcz?#fSH_)@*QVlN2l4(QNk| z4aPnv&mrS&0|6NHq05XQw$J^RR9T{3SOcMKCXIR1iSf+xJ0E_Wv?jEc*I#ZPzyJN2 zUG0UOXHl+PikM*&g$U@g+KbG-RY>uaIl&DEtw_Q=FYq?etc!;hEC_}UX{eyh%dw2V zTTSlap&5>PY{6I#(6`j-9`D&I#|YPP8a;(sOzgeKDWsLa!i-$frD>zr-oid!Hf&yS z!i^cr&7tN}OOGmX2)`8k?Tn!!4=tz~3hCTq_9CdiV!NIblUDxHh(FJ$zs)B2(t5@u z-`^RA1ShrLCkg0)OhfoM;4Z{&oZmAec$qV@ zGQ(7(!CBk<5;Ar%DLJ0p0!ResC#U<+3i<|vib1?{5gCebG7$F7URKZXuX-2WgF>YJ^i zMhHDBsh9PDU8dlZ$yJKtc6JA#y!y$57%sE>4Nt+wF1lfNIWyA`=hF=9Gj%sRwi@vd z%2eVV3y&dvAgyuJ=eNJR+*080dbO_t@BFJO<@&#yqTK&+xc|FRR;p;KVk@J3$S{p` zGaMj6isho#%m)?pOG^G0mzOAw0z?!AEMsv=0T>WWcE>??WS=fII$t$(^PDPMU(P>o z_*0s^W#|x)%tx8jIgZY~A2yG;US0m2ZOQt6yJqW@XNY_>_R7(Nxb8Ged6BdYW6{prd!|zuX$@Q2o6Ona8zzYC1u!+2!Y$Jc9a;wy+pXt}o6~Bu1oF1c zp7Y|SBTNi@=I(K%A60PMjM#sfH$y*c{xUgeSpi#HB`?|`!Tb&-qJ3;vxS!TIzuTZs-&%#bAkAyw9m4PJgvey zM5?up*b}eDEY+#@tKec)-c(#QF0P?MRlD1+7%Yk*jW;)`f;0a-ZJ6CQA?E%>i2Dt7T9?s|9ZF|KP4;CNWvaVKZ+Qeut;Jith_y{v*Ny6Co6!8MZx;Wgo z=qAi%&S;8J{iyD&>3CLCQdTX*$+Rx1AwA*D_J^0>suTgBMBb=*hefV+Ars#mmr+YsI3#!F@Xc1t4F-gB@6aoyT+5O(qMz*zG<9Qq*f0w^V!03rpr*-WLH}; zfM{xSPJeu6D(%8HU%0GEa%waFHE$G?FH^kMS-&I3)ycx|iv{T6Wx}9$$D&6{%1N_8 z_CLw)_9+O4&u94##vI9b-HHm_95m)fa??q07`DniVjAy`t7;)4NpeyAY(aAk(+T_O z1om+b5K2g_B&b2DCTK<>SE$Ode1DopAi)xaJjU>**AJK3hZrnhEQ9E`2=|HHe<^tv z63e(bn#fMWuz>4erc47}!J>U58%<&N<6AOAewyzNTqi7hJc|X{782&cM zHZYclNbBwU6673=!ClmxMfkC$(CykGR@10F!zN1Se83LR&a~$Ht&>~43OX22mt7tcZUpa;9@q}KDX3O&Ugp6< zLZLfIMO5;pTee1vNyVC$FGxzK2f>0Z-6hM82zKg44nWo|n}$Zk6&;5ry3`(JFEX$q zK&KivAe${e^5ZGc3a9hOt|!UOE&OocpVryE$Y4sPcs4rJ>>Kbi2_subQ9($2VN(3o zb~tEzMsHaBmBtaHAyES+d3A(qURgiskSSwUc9CfJ@99&MKp2sooSYZu+-0t0+L*!I zYagjOlPgx|lep9tiU%ts&McF6b0VE57%E0Ho%2oi?=Ks+5%aj#au^OBwNwhec zta6QAeQI^V!dF1C)>RHAmB`HnxyqWx?td@4sd15zPd*Fc9hpDXP23kbBenBxGeD$k z;%0VBQEJ-C)&dTAw_yW@k0u?IUk*NrkJ)(XEeI z9Y>6Vel>#s_v@=@0<{4A{pl=9cQ&Iah0iD0H`q)7NeCIRz8zx;! z^OO;1+IqoQNak&pV`qKW+K0^Hqp!~gSohcyS)?^P`JNZXw@gc6{A3OLZ?@1Uc^I2v z+X!^R*HCm3{7JPq{8*Tn>5;B|X7n4QQ0Bs79uTU%nbqOJh`nX(BVj!#f;#J+WZxx4 z_yM&1Y`2XzhfqkIMO7tB3raJKQS+H5F%o83bM+hxbQ zeeJm=Dvix$2j|b4?mDacb67v-1^lTp${z=jc1=j~QD>7c*@+1?py>%Kj%Ejp7Y-!? z8iYRUlGVrQPandAaxFfks53@2EC#0)%mrnmGRn&>=$H$S8q|kE_iWko4`^vCS2aWg z#!`RHUGyOt*k?bBYu3*j3u0gB#v(3tsije zgIuNNWNtrOkx@Pzs;A9un+2LX!zw+p3_NX^Sh09HZAf>m8l@O*rXy_82aWT$Q>iyy zqO7Of)D=wcSn!0+467&!Hl))eff=$aneB?R!YykdKW@k^_uR!+Q1tR)+IJb`-6=jj zymzA>Sv4>Z&g&WWu#|~GcP7qP&m*w-S$)7Xr;(duqCTe7p8H3k5>Y-n8438+%^9~K z3r^LIT_K{i7DgEJjIocw_6d0!<;wKT`X;&vv+&msmhAAnIe!OTdybPctzcEzBy88_ zWO{6i4YT%e4^WQZB)KHCvA(0tS zHu_Bg+6Ko%a9~$EjRB90`P(2~6uI@SFibxct{H#o&y40MdiXblu@VFXbhz>Nko;7R z70Ntmm-FePqhb%9gL+7U8@(ch|JfH5Fm)5${8|`Lef>LttM_iww6LW2X61ldBmG0z zax3y)njFe>j*T{i0s8D4=L>X^j0)({R5lMGVS#7(2C9@AxL&C-lZQx~czI7Iv+{%1 z2hEG>RzX4S8x3v#9sgGAnPzptM)g&LB}@%E>fy0vGSa(&q0ch|=ncKjNrK z`jA~jObJhrJ^ri|-)J^HUyeZXz~XkBp$VhcTEcTdc#a2EUOGVX?@mYx#Vy*!qO$Jv zQ4rgOJ~M*o-_Wptam=~krnmG*p^j!JAqoQ%+YsDFW7Cc9M%YPiBOrVcD^RY>m9Pd< zu}#9M?K{+;UIO!D9qOpq9yxUquQRmQNMo0pT`@$pVt=rMvyX)ph(-CCJLvUJy71DI zBk7oc7)-%ngdj~s@76Yse3L^gV0 z2==qfp&Q~L(+%RHP0n}+xH#k(hPRx(!AdBM$JCfJ5*C=K3ts>P?@@SZ_+{U2qFZb>4kZ{Go37{# zSQc+-dq*a-Vy4?taS&{Ht|MLRiS)Sn14JOONyXqPNnpq&2y~)6wEG0oNy>qvod$FF z`9o&?&6uZjhZ4_*5qWVrEfu(>_n2Xi2{@Gz9MZ8!YmjYvIMasE9yVQL10NBrTCczq zcTY1q^PF2l!Eraguf{+PtHV3=2A?Cu&NN&a8V(y;q(^_mFc6)%Yfn&X&~Pq zU1?qCj^LF(EQB1F`8NxNjyV%fde}dEa(Hx=r7$~ts2dzDwyi6ByBAIx$NllB4%K=O z$AHz1<2bTUb>(MCVPpK(E9wlLElo(aSd(Os)^Raum`d(g9Vd_+Bf&V;l=@mM=cC>) z)9b0enb)u_7V!!E_bl>u5nf&Rl|2r=2F3rHMdb7y9E}}F82^$Rf+P8%dKnOeKh1vs zhH^P*4Ydr^$)$h@4KVzxrHyy#cKmWEa9P5DJ|- zG;!Qi35Tp7XNj60=$!S6U#!(${6hyh7d4q=pF{`0t|N^|L^d8pD{O9@tF~W;#Je*P z&ah%W!KOIN;SyAEhAeTafJ4uEL`(RtnovM+cb(O#>xQnk?dzAjG^~4$dFn^<@-Na3 z395;wBnS{t*H;Jef2eE!2}u5Ns{AHj>WYZDgQJt8v%x?9{MXqJsGP|l%OiZqQ1aB! z%E=*Ig`(!tHh>}4_z5IMpg{49UvD*Pp9!pxt_gdAW%sIf3k6CTycOT1McPl=_#0?8 zVjz8Hj*Vy9c5-krd-{BQ{6Xy|P$6LJvMuX$* zA+@I_66_ET5l2&gk9n4$1M3LN8(yEViRx&mtd#LD}AqEs?RW=xKC(OCWH;~>(X6h!uDxXIPH06xh z*`F4cVlbDP`A)-fzf>MuScYsmq&1LUMGaQ3bRm6i7OsJ|%uhTDT zlvZA1M}nz*SalJWNT|`dBm1$xlaA>CCiQ zK`xD-RuEn>-`Z?M{1%@wewf#8?F|(@1e0+T4>nmlSRrNK5f)BJ2H*$q(H>zGD0>eL zQ!tl_Wk)k*e6v^m*{~A;@6+JGeWU-q9>?+L_#UNT%G?4&BnOgvm9@o7l?ov~XL+et zbGT)|G7)KAeqb=wHSPk+J1bdg7N3$vp(ekjI1D9V$G5Cj!=R2w=3*4!z*J-r-cyeb zd(i2KmX!|Lhey!snRw z?#$Gu%S^SQEKt&kep)up#j&9}e+3=JJBS(s>MH+|=R(`8xK{mmndWo_r`-w1#SeRD&YtAJ#GiVI*TkQZ}&aq<+bU2+coU3!jCI6E+Ad_xFW*ghnZ$q zAoF*i&3n1j#?B8x;kjSJD${1jdRB;)R*)Ao!9bd|C7{;iqDo|T&>KSh6*hCD!rwv= zyK#F@2+cv3=|S1Kef(E6Niv8kyLVLX&e=U;{0x{$tDfShqkjUME>f8d(5nzSkY6@! z^-0>DM)wa&%m#UF1F?zR`8Y3X#tA!*7Q$P3lZJ%*KNlrk_uaPkxw~ zxZ1qlE;Zo;nb@!SMazSjM>;34ROOoygo%SF);LL>rRonWwR>bmSd1XD^~sGSu$Gg# zFZ`|yKU0%!v07dz^v(tY%;So(e`o{ZYTX`hm;@b0%8|H>VW`*cr8R%3n|ehw2`(9B+V72`>SY}9^8oh$En80mZK9T4abVG*to;E z1_S6bgDOW?!Oy1LwYy=w3q~KKdbNtyH#d24PFjX)KYMY93{3-mPP-H>@M-_>N~DDu zENh~reh?JBAK=TFN-SfDfT^=+{w4ea2KNWXq2Y<;?(gf(FgVp8Zp-oEjKzB%2Iqj;48GmY3h=bcdYJ}~&4tS`Q1sb=^emaW$IC$|R+r-8V- zf0$gGE(CS_n4s>oicVk)MfvVg#I>iDvf~Ov8bk}sSxluG!6#^Z_zhB&U^`eIi1@j( z^CK$z^stBHtaDDHxn+R;3u+>Lil^}fj?7eaGB z&5nl^STqcaBxI@v>%zG|j))G(rVa4aY=B@^2{TFkW~YP!8!9TG#(-nOf^^X-%m9{Z zCC?iC`G-^RcBSCuk=Z`(FaUUe?hf3{0C>>$?Vs z`2Uud9M+T&KB6o4o9kvdi^Q=Bw!asPdxbe#W-Oaa#_NP(qpyF@bVxv5D5))srkU#m zj_KA+#7sqDn*Ipf!F5Byco4HOSd!Ui$l94|IbW%Ny(s1>f4|Mv^#NfB31N~kya9!k zWCGL-$0ZQztBate^fd>R!hXY_N9ZjYp3V~4_V z#eB)Kjr8yW=+oG)BuNdZG?jaZlw+l_ma8aET(s+-x+=F-t#Qoiuu1i`^x8Sj>b^U} zs^z<()YMFP7CmjUC@M=&lA5W7t&cxTlzJAts*%PBDAPuqcV5o7HEnqjif_7xGt)F% zGx2b4w{@!tE)$p=l3&?Bf#`+!-RLOleeRk3 z7#pF|w@6_sBmn1nECqdunmG^}pr5(ZJQVvAt$6p3H(16~;vO>?sTE`Y+mq5YP&PBo zvq!7#W$Gewy`;%6o^!Dtjz~x)T}Bdk*BS#=EY=ODD&B=V6TD2z^hj1m5^d6s)D*wk zu$z~D7QuZ2b?5`p)E8e2_L38v3WE{V`bVk;6fl#o2`) z99JsWhh?$oVRn@$S#)uK&8DL8>An0&S<%V8hnGD7Z^;Y(%6;^9!7kDQ5bjR_V+~wp zfx4m3z6CWmmZ<8gDGUyg3>t8wgJ5NkkiEm^(sedCicP^&3D%}6LtIUq>mXCAt{9eF zNXL$kGcoUTf_Lhm`t;hD-SE)m=iBnxRU(NyL}f6~1uH)`K!hmYZjLI%H}AmEF5RZt z06$wn63GHnApHXZZJ}s^s)j9(BM6e*7IBK6Bq(!)d~zR#rbxK9NVIlgquoMq z=eGZ9NR!SEqP6=9UQg#@!rtbbSBUM#ynF);zKX+|!Zm}*{H z+j=d?aZ2!?@EL7C~%B?6ouCKLnO$uWn;Y6Xz zX8dSwj732u(o*U3F$F=7xwxm>E-B+SVZH;O-4XPuPkLSt_?S0)lb7EEg)Mglk0#eS z9@jl(OnH4juMxY+*r03VDfPx_IM!Lmc(5hOI;`?d37f>jPP$?9jQQIQU@i4vuG6MagEoJrQ=RD7xt@8E;c zeGV*+Pt+t$@pt!|McETOE$9k=_C!70uhwRS9X#b%ZK z%q(TIUXSS^F0`4Cx?Rk07C6wI4!UVPeI~-fxY6`YH$kABdOuiRtl73MqG|~AzZ@iL&^s?24iS;RK_pdlWkhcF z@Wv-Om(Aealfg)D^adlXh9Nvf~Uf@y;g3Y)i(YP zEXDnb1V}1pJT5ZWyw=1i+0fni9yINurD=EqH^ciOwLUGi)C%Da)tyt=zq2P7pV5-G zR7!oq28-Fgn5pW|nlu^b!S1Z#r7!Wtr{5J5PQ>pd+2P7RSD?>(U7-|Y z7ZQ5lhYIl_IF<9?T9^IPK<(Hp;l5bl5tF9>X-zG14_7PfsA>6<$~A338iYRT{a@r_ zuXBaT=`T5x3=s&3=RYx6NgG>No4?5KFBVjE(swfcivcIpPQFx5l+O;fiGsOrl5teR z_Cm+;PW}O0Dwe_(4Z@XZ)O0W-v2X><&L*<~*q3dg;bQW3g7)a#3KiQP>+qj|qo*Hk z?57>f2?f@`=Fj^nkDKeRkN2d$Z@2eNKpHo}ksj-$`QKb6n?*$^*%Fb3_Kbf1(*W9K>{L$mud2WHJ=j0^=g30Xhg8$#g^?36`p1fm;;1@0Lrx+8t`?vN0ZorM zSW?rhjCE8$C|@p^sXdx z|NOHHg+fL;HIlqyLp~SSdIF`TnSHehNCU9t89yr@)FY<~hu+X`tjg(aSVae$wDG*C zq$nY(Y494R)hD!i1|IIyP*&PD_c2FPgeY)&mX1qujB1VHPG9`yFQpLFVQ0>EKS@Bp zAfP5`C(sWGLI?AC{XEjLKR4FVNw(4+9b?kba95ukgR1H?w<8F7)G+6&(zUhIE5Ef% z=fFkL3QKA~M@h{nzjRq!Y_t!%U66#L8!(2-GgFxkD1=JRRqk=n%G(yHKn%^&$dW>; zSjAcjETMz1%205se$iH_)ZCpfg_LwvnsZQAUCS#^FExp8O4CrJb6>JquNV@qPq~3A zZ<6dOU#6|8+fcgiA#~MDmcpIEaUO02L5#T$HV0$EMD94HT_eXLZ2Zi&(! z&5E>%&|FZ`)CN10tM%tLSPD*~r#--K(H-CZqIOb99_;m|D5wdgJ<1iOJz@h2Zkq?} z%8_KXb&hf=2Wza(Wgc;3v3TN*;HTU*q2?#z&tLn_U0Nt!y>Oo>+2T)He6%XuP;fgn z-G!#h$Y2`9>Jtf}hbVrm6D70|ERzLAU>3zoWhJmjWfgM^))T+2u$~5>HF9jQDkrXR z=IzX36)V75PrFjkQ%TO+iqKGCQ-DDXbaE;C#}!-CoWQx&v*vHfyI>$HNRbpvm<`O( zlx9NBWD6_e&J%Ous4yp~s6)Ghni!I6)0W;9(9$y1wWu`$gs<$9Mcf$L*piP zPR0Av*2%ul`W;?-1_-5Zy0~}?`e@Y5A&0H!^ApyVTT}BiOm4GeFo$_oPlDEyeGBbh z1h3q&Dx~GmUS|3@4V36&$2uO8!Yp&^pD7J5&TN{?xphf*-js1fP?B|`>p_K>lh{ij zP(?H%e}AIP?_i^f&Li=FDSQ`2_NWxL+BB=nQr=$ zHojMlXNGauvvwPU>ZLq!`bX-5F4jBJ&So{kE5+ms9UEYD{66!|k~3vsP+mE}x!>%P za98bAU0!h0&ka4EoiDvBM#CP#dRNdXJcb*(%=<(g+M@<)DZ!@v1V>;54En?igcHR2 zhubQMq}VSOK)onqHfczM7YA@s=9*ow;k;8)&?J3@0JiGcP! zP#00KZ1t)GyZeRJ=f0^gc+58lc4Qh*S7RqPIC6GugG1gXe$LIQMRCo8cHf^qXgAa2 z`}t>u2Cq1CbSEpLr~E=c7~=Qkc9-vLE%(v9N*&HF`(d~(0`iukl5aQ9u4rUvc8%m) zr2GwZN4!s;{SB87lJB;veebPmqE}tSpT>+`t?<457Q9iV$th%i__Z1kOMAswFldD6 ztbOvO337S5o#ZZgN2G99_AVqPv!?Gmt3pzgD+Hp3QPQ`9qJ(g=kjvD+fUSS3upJn! zqoG7acIKEFRX~S}3|{EWT$kdz#zrDlJU(rPkxjws_iyLKU8+v|*oS_W*-guAb&Pj1 z35Z`3z<&Jb@2Mwz=KXucNYdY#SNO$tcVFr9KdKm|%^e-TXzs6M`PBper%ajkrIyUe zp$vVxVs9*>Vp4_1NC~Zg)WOCPmOxI1V34QlG4!aSFOH{QqSVq1^1)- z0P!Z?tT&E-ll(pwf0?=F=yOzik=@nh1Clxr9}Vij89z)ePDSCYAqw?lVI?v?+&*zH z)p$CScFI8rrwId~`}9YWPFu0cW1Sf@vRELs&cbntRU6QfPK-SO*mqu|u~}8AJ!Q$z znzu}50O=YbjwKCuSVBs6&CZR#0FTu)3{}qJJYX(>QPr4$RqWiwX3NT~;>cLn*_&1H zaKpIW)JVJ>b{uo2oq>oQt3y=zJjb%fU@wLqM{SyaC6x2snMx-}ivfU<1- znu1Lh;i$3Tf$Kh5Uk))G!D1UhE8pvx&nO~w^fG)BC&L!_hQk%^p`Kp@F{cz>80W&T ziOK=Sq3fdRu*V0=S53rcIfWFazI}Twj63CG(jOB;$*b`*#B9uEnBM`hDk*EwSRdwP8?5T?xGUKs=5N83XsR*)a4|ijz|c{4tIU+4j^A5C<#5 z*$c_d=5ml~%pGxw#?*q9N7aRwPux5EyqHVkdJO=5J>84!X6P>DS8PTTz>7C#FO?k#edkntG+fJk8ZMn?pmJSO@`x-QHq;7^h6GEXLXo1TCNhH z8ZDH{*NLAjo3WM`xeb=X{((uv3H(8&r8fJJg_uSs_%hOH%JDD?hu*2NvWGYD+j)&` zz#_1%O1wF^o5ryt?O0n;`lHbzp0wQ?rcbW(F1+h7_EZZ9{>rePvLAPVZ_R|n@;b$;UchU=0j<6k8G9QuQf@76oiE*4 zXOLQ&n3$NR#p4<5NJMVC*S);5x2)eRbaAM%VxWu9ohlT;pGEk7;002enCbQ>2r-us z3#bpXP9g|mE`65VrN`+3mC)M(eMj~~eOf)do<@l+fMiTR)XO}422*1SL{wyY(%oMpBgJagtiDf zz>O6(m;};>Hi=t8o{DVC@YigqS(Qh+ix3Rwa9aliH}a}IlOCW1@?%h_bRbq-W{KHF z%Vo?-j@{Xi@=~Lz5uZP27==UGE15|g^0gzD|3x)SCEXrx`*MP^FDLl%pOi~~Il;dc z^hrwp9sYeT7iZ)-ajKy@{a`kr0-5*_!XfBpXwEcFGJ;%kV$0Nx;apKrur zJN2J~CAv{Zjj%FolyurtW8RaFmpn&zKJWL>(0;;+q(%(Hx!GMW4AcfP0YJ*Vz!F4g z!ZhMyj$BdXL@MlF%KeInmPCt~9&A!;cRw)W!Hi@0DY(GD_f?jeV{=s=cJ6e}JktJw zQORnxxj3mBxfrH=x{`_^Z1ddDh}L#V7i}$njUFRVwOX?qOTKjfPMBO4y(WiU<)epb zvB9L=%jW#*SL|Nd_G?E*_h1^M-$PG6Pc_&QqF0O-FIOpa4)PAEPsyvB)GKasmBoEt z?_Q2~QCYGH+hW31x-B=@5_AN870vY#KB~3a*&{I=f);3Kv7q4Q7s)0)gVYx2#Iz9g(F2;=+Iy4 z6KI^8GJ6D@%tpS^8boU}zpi=+(5GfIR)35PzrbuXeL1Y1N%JK7PG|^2k3qIqHfX;G zQ}~JZ-UWx|60P5?d1e;AHx!_;#PG%d=^X(AR%i`l0jSpYOpXoKFW~7ip7|xvN;2^? zsYC9fanpO7rO=V7+KXqVc;Q5z%Bj})xHVrgoR04sA2 zl~DAwv=!(()DvH*=lyhIlU^hBkA0$e*7&fJpB0|oB7)rqGK#5##2T`@_I^|O2x4GO z;xh6ROcV<9>?e0)MI(y++$-ksV;G;Xe`lh76T#Htuia+(UrIXrf9?

L(tZ$0BqX1>24?V$S+&kLZ`AodQ4_)P#Q3*4xg8}lMV-FLwC*cN$< zt65Rf%7z41u^i=P*qO8>JqXPrinQFapR7qHAtp~&RZ85$>ob|Js;GS^y;S{XnGiBc zGa4IGvDl?x%gY`vNhv8wgZnP#UYI-w*^4YCZnxkF85@ldepk$&$#3EAhrJY0U)lR{F6sM3SONV^+$;Zx8BD&Eku3K zKNLZyBni3)pGzU0;n(X@1fX8wYGKYMpLmCu{N5-}epPDxClPFK#A@02WM3!myN%bkF z|GJ4GZ}3sL{3{qXemy+#Uk{4>Kf8v11;f8I&c76+B&AQ8udd<8gU7+BeWC`akUU~U zgXoxie>MS@rBoyY8O8Tc&8id!w+_ooxcr!1?#rc$-|SBBtH6S?)1e#P#S?jFZ8u-Bs&k`yLqW|{j+%c#A4AQ>+tj$Y z^CZajspu$F%73E68Lw5q7IVREED9r1Ijsg#@DzH>wKseye>hjsk^{n0g?3+gs@7`i zHx+-!sjLx^fS;fY!ERBU+Q zVJ!e0hJH%P)z!y%1^ZyG0>PN@5W~SV%f>}c?$H8r;Sy-ui>aruVTY=bHe}$e zi&Q4&XK!qT7-XjCrDaufT@>ieQ&4G(SShUob0Q>Gznep9fR783jGuUynAqc6$pYX; z7*O@@JW>O6lKIk0G00xsm|=*UVTQBB`u1f=6wGAj%nHK_;Aqmfa!eAykDmi-@u%6~ z;*c!pS1@V8r@IX9j&rW&d*}wpNs96O2Ute>%yt{yv>k!6zfT6pru{F1M3P z2WN1JDYqoTB#(`kE{H676QOoX`cnqHl1Yaru)>8Ky~VU{)r#{&s86Vz5X)v15ULHA zAZDb{99+s~qI6;-dQ5DBjHJP@GYTwn;Dv&9kE<0R!d z8tf1oq$kO`_sV(NHOSbMwr=To4r^X$`sBW4$gWUov|WY?xccQJN}1DOL|GEaD_!@& z15p?Pj+>7d`@LvNIu9*^hPN)pwcv|akvYYq)ks%`G>!+!pW{-iXPZsRp8 z35LR;DhseQKWYSD`%gO&k$Dj6_6q#vjWA}rZcWtQr=Xn*)kJ9kacA=esi*I<)1>w^ zO_+E>QvjP)qiSZg9M|GNeLtO2D7xT6vsj`88sd!94j^AqxFLi}@w9!Y*?nwWARE0P znuI_7A-saQ+%?MFA$gttMV-NAR^#tjl_e{R$N8t2NbOlX373>e7Ox=l=;y#;M7asp zRCz*CLnrm$esvSb5{T<$6CjY zmZ(i{Rs_<#pWW>(HPaaYj`%YqBra=Ey3R21O7vUbzOkJJO?V`4-D*u4$Me0Bx$K(lYo`JO}gnC zx`V}a7m-hLU9Xvb@K2ymioF)vj12<*^oAqRuG_4u%(ah?+go%$kOpfb`T96P+L$4> zQ#S+sA%VbH&mD1k5Ak7^^dZoC>`1L%i>ZXmooA!%GI)b+$D&ziKrb)a=-ds9xk#~& z7)3iem6I|r5+ZrTRe_W861x8JpD`DDIYZNm{$baw+$)X^Jtjnl0xlBgdnNY}x%5za zkQ8E6T<^$sKBPtL4(1zi_Rd(tVth*3Xs!ulflX+70?gb&jRTnI8l+*Aj9{|d%qLZ+ z>~V9Z;)`8-lds*Zgs~z1?Fg?Po7|FDl(Ce<*c^2=lFQ~ahwh6rqSjtM5+$GT>3WZW zj;u~w9xwAhOc<kF}~`CJ68 z?(S5vNJa;kriPlim33{N5`C{9?NWhzsna_~^|K2k4xz1`xcui*LXL-1#Y}Hi9`Oo!zQ>x-kgAX4LrPz63uZ+?uG*84@PKq-KgQlMNRwz=6Yes) zY}>YN+qP}nwr$(CZQFjUOI=-6J$2^XGvC~EZ+vrqWaOXB$k?%Suf5k=4>AveC1aJ! ziaW4IS%F$_Babi)kA8Y&u4F7E%99OPtm=vzw$$ zEz#9rvn`Iot_z-r3MtV>k)YvErZ<^Oa${`2>MYYODSr6?QZu+be-~MBjwPGdMvGd!b!elsdi4% z`37W*8+OGulab8YM?`KjJ8e+jM(tqLKSS@=jimq3)Ea2EB%88L8CaM+aG7;27b?5` z4zuUWBr)f)k2o&xg{iZ$IQkJ+SK>lpq4GEacu~eOW4yNFLU!Kgc{w4&D$4ecm0f}~ zTTzquRW@`f0}|IILl`!1P+;69g^upiPA6F{)U8)muWHzexRenBU$E^9X-uIY2%&1w z_=#5*(nmxJ9zF%styBwivi)?#KMG96-H@hD-H_&EZiRNsfk7mjBq{L%!E;Sqn!mVX*}kXhwH6eh;b42eD!*~upVG@ z#smUqz$ICm!Y8wY53gJeS|Iuard0=;k5i5Z_hSIs6tr)R4n*r*rE`>38Pw&lkv{_r!jNN=;#?WbMj|l>cU(9trCq; z%nN~r^y7!kH^GPOf3R}?dDhO=v^3BeP5hF|%4GNQYBSwz;x({21i4OQY->1G=KFyu z&6d`f2tT9Yl_Z8YACZaJ#v#-(gcyeqXMhYGXb=t>)M@fFa8tHp2x;ODX=Ap@a5I=U z0G80^$N0G4=U(>W%mrrThl0DjyQ-_I>+1Tdd_AuB3qpYAqY54upwa3}owa|x5iQ^1 zEf|iTZxKNGRpI>34EwkIQ2zHDEZ=(J@lRaOH>F|2Z%V_t56Km$PUYu^xA5#5Uj4I4RGqHD56xT%H{+P8Ag>e_3pN$4m8n>i%OyJFPNWaEnJ4McUZPa1QmOh?t8~n& z&RulPCors8wUaqMHECG=IhB(-tU2XvHP6#NrLVyKG%Ee*mQ5Ps%wW?mcnriTVRc4J`2YVM>$ixSF2Xi+Wn(RUZnV?mJ?GRdw%lhZ+t&3s7g!~g{%m&i<6 z5{ib-<==DYG93I(yhyv4jp*y3#*WNuDUf6`vTM%c&hiayf(%=x@4$kJ!W4MtYcE#1 zHM?3xw63;L%x3drtd?jot!8u3qeqctceX3m;tWetK+>~q7Be$h>n6riK(5@ujLgRS zvOym)k+VAtyV^mF)$29Y`nw&ijdg~jYpkx%*^ z8dz`C*g=I?;clyi5|!27e2AuSa$&%UyR(J3W!A=ZgHF9OuKA34I-1U~pyD!KuRkjA zbkN!?MfQOeN>DUPBxoy5IX}@vw`EEB->q!)8fRl_mqUVuRu|C@KD-;yl=yKc=ZT0% zB$fMwcC|HE*0f8+PVlWHi>M`zfsA(NQFET?LrM^pPcw`cK+Mo0%8*x8@65=CS_^$cG{GZQ#xv($7J z??R$P)nPLodI;P!IC3eEYEHh7TV@opr#*)6A-;EU2XuogHvC;;k1aI8asq7ovoP!* z?x%UoPrZjj<&&aWpsbr>J$Er-7!E(BmOyEv!-mbGQGeJm-U2J>74>o5x`1l;)+P&~ z>}f^=Rx(ZQ2bm+YE0u=ZYrAV@apyt=v1wb?R@`i_g64YyAwcOUl=C!i>=Lzb$`tjv zOO-P#A+)t-JbbotGMT}arNhJmmGl-lyUpMn=2UacVZxmiG!s!6H39@~&uVokS zG=5qWhfW-WOI9g4!R$n7!|ViL!|v3G?GN6HR0Pt_L5*>D#FEj5wM1DScz4Jv@Sxnl zB@MPPmdI{(2D?;*wd>3#tjAirmUnQoZrVv`xM3hARuJksF(Q)wd4P$88fGYOT1p6U z`AHSN!`St}}UMBT9o7i|G`r$ zrB=s$qV3d6$W9@?L!pl0lf%)xs%1ko^=QY$ty-57=55PvP(^6E7cc zGJ*>m2=;fOj?F~yBf@K@9qwX0hA803Xw+b0m}+#a(>RyR8}*Y<4b+kpp|OS+!whP( zH`v{%s>jsQI9rd$*vm)EkwOm#W_-rLTHcZRek)>AtF+~<(did)*oR1|&~1|e36d-d zgtm5cv1O0oqgWC%Et@P4Vhm}Ndl(Y#C^MD03g#PH-TFy+7!Osv1z^UWS9@%JhswEq~6kSr2DITo59+; ze=ZC}i2Q?CJ~Iyu?vn|=9iKV>4j8KbxhE4&!@SQ^dVa-gK@YfS9xT(0kpW*EDjYUkoj! zE49{7H&E}k%5(>sM4uGY)Q*&3>{aitqdNnRJkbOmD5Mp5rv-hxzOn80QsG=HJ_atI-EaP69cacR)Uvh{G5dTpYG7d zbtmRMq@Sexey)||UpnZ?;g_KMZq4IDCy5}@u!5&B^-=6yyY{}e4Hh3ee!ZWtL*s?G zxG(A!<9o!CL+q?u_utltPMk+hn?N2@?}xU0KlYg?Jco{Yf@|mSGC<(Zj^yHCvhmyx z?OxOYoxbptDK()tsJ42VzXdINAMWL$0Gcw?G(g8TMB)Khw_|v9`_ql#pRd2i*?CZl z7k1b!jQB=9-V@h%;Cnl7EKi;Y^&NhU0mWEcj8B|3L30Ku#-9389Q+(Yet0r$F=+3p z6AKOMAIi|OHyzlHZtOm73}|ntKtFaXF2Fy|M!gOh^L4^62kGUoWS1i{9gsds_GWBc zLw|TaLP64z3z9?=R2|T6Xh2W4_F*$cq>MtXMOy&=IPIJ`;!Tw?PqvI2b*U1)25^<2 zU_ZPoxg_V0tngA0J+mm?3;OYw{i2Zb4x}NedZug!>EoN3DC{1i)Z{Z4m*(y{ov2%- zk(w>+scOO}MN!exSc`TN)!B=NUX`zThWO~M*ohqq;J2hx9h9}|s#?@eR!=F{QTrq~ zTcY|>azkCe$|Q0XFUdpFT=lTcyW##i;-e{}ORB4D?t@SfqGo_cS z->?^rh$<&n9DL!CF+h?LMZRi)qju!meugvxX*&jfD!^1XB3?E?HnwHP8$;uX{Rvp# zh|)hM>XDv$ZGg=$1{+_bA~u-vXqlw6NH=nkpyWE0u}LQjF-3NhATL@9rRxMnpO%f7 z)EhZf{PF|mKIMFxnC?*78(}{Y)}iztV12}_OXffJ;ta!fcFIVjdchyHxH=t%ci`Xd zX2AUB?%?poD6Zv*&BA!6c5S#|xn~DK01#XvjT!w!;&`lDXSJT4_j$}!qSPrb37vc{ z9^NfC%QvPu@vlxaZ;mIbn-VHA6miwi8qJ~V;pTZkKqqOii<1Cs}0i?uUIss;hM4dKq^1O35y?Yp=l4i zf{M!@QHH~rJ&X~8uATV><23zZUbs-J^3}$IvV_ANLS08>k`Td7aU_S1sLsfi*C-m1 z-e#S%UGs4E!;CeBT@9}aaI)qR-6NU@kvS#0r`g&UWg?fC7|b^_HyCE!8}nyh^~o@< zpm7PDFs9yxp+byMS(JWm$NeL?DNrMCNE!I^ko-*csB+dsf4GAq{=6sfyf4wb>?v1v zmb`F*bN1KUx-`ra1+TJ37bXNP%`-Fd`vVQFTwWpX@;s(%nDQa#oWhgk#mYlY*!d>( zE&!|ySF!mIyfING+#%RDY3IBH_fW$}6~1%!G`suHub1kP@&DoAd5~7J55;5_noPI6eLf{t;@9Kf<{aO0`1WNKd?<)C-|?C?)3s z>wEq@8=I$Wc~Mt$o;g++5qR+(6wt9GI~pyrDJ%c?gPZe)owvy^J2S=+M^ z&WhIE`g;;J^xQLVeCtf7b%Dg#Z2gq9hp_%g)-%_`y*zb; zn9`f`mUPN-Ts&fFo(aNTsXPA|J!TJ{0hZp0^;MYHLOcD=r_~~^ymS8KLCSeU3;^QzJNqS z5{5rEAv#l(X?bvwxpU;2%pQftF`YFgrD1jt2^~Mt^~G>T*}A$yZc@(k9orlCGv&|1 zWWvVgiJsCAtamuAYT~nzs?TQFt<1LSEx!@e0~@yd6$b5!Zm(FpBl;(Cn>2vF?k zOm#TTjFwd2D-CyA!mqR^?#Uwm{NBemP>(pHmM}9;;8`c&+_o3#E5m)JzfwN?(f-a4 zyd%xZc^oQx3XT?vcCqCX&Qrk~nu;fxs@JUoyVoi5fqpi&bUhQ2y!Ok2pzsFR(M(|U zw3E+kH_zmTRQ9dUMZWRE%Zakiwc+lgv7Z%|YO9YxAy`y28`Aw;WU6HXBgU7fl@dnt z-fFBV)}H-gqP!1;V@Je$WcbYre|dRdp{xt!7sL3Eoa%IA`5CAA%;Wq8PktwPdULo! z8!sB}Qt8#jH9Sh}QiUtEPZ6H0b*7qEKGJ%ITZ|vH)5Q^2m<7o3#Z>AKc%z7_u`rXA zqrCy{-{8;9>dfllLu$^M5L z-hXs))h*qz%~ActwkIA(qOVBZl2v4lwbM>9l70Y`+T*elINFqt#>OaVWoja8RMsep z6Or3f=oBnA3vDbn*+HNZP?8LsH2MY)x%c13@(XfuGR}R?Nu<|07{$+Lc3$Uv^I!MQ z>6qWgd-=aG2Y^24g4{Bw9ueOR)(9h`scImD=86dD+MnSN4$6 z^U*o_mE-6Rk~Dp!ANp#5RE9n*LG(Vg`1)g6!(XtDzsov$Dvz|Gv1WU68J$CkshQhS zCrc|cdkW~UK}5NeaWj^F4MSgFM+@fJd{|LLM)}_O<{rj z+?*Lm?owq?IzC%U%9EBga~h-cJbIu=#C}XuWN>OLrc%M@Gu~kFEYUi4EC6l#PR2JS zQUkGKrrS#6H7}2l0F@S11DP`@pih0WRkRJl#F;u{c&ZC{^$Z+_*lB)r)-bPgRFE;* zl)@hK4`tEP=P=il02x7-C7p%l=B`vkYjw?YhdJU9!P!jcmY$OtC^12w?vy3<<=tlY zUwHJ_0lgWN9vf>1%WACBD{UT)1qHQSE2%z|JHvP{#INr13jM}oYv_5#xsnv9`)UAO zuwgyV4YZ;O)eSc3(mka6=aRohi!HH@I#xq7kng?Acdg7S4vDJb6cI5fw?2z%3yR+| zU5v@Hm}vy;${cBp&@D=HQ9j7NcFaOYL zj-wV=eYF{|XTkFNM2uz&T8uH~;)^Zo!=KP)EVyH6s9l1~4m}N%XzPpduPg|h-&lL` zAXspR0YMOKd2yO)eMFFJ4?sQ&!`dF&!|niH*!^*Ml##o0M(0*uK9&yzekFi$+mP9s z>W9d%Jb)PtVi&-Ha!o~Iyh@KRuKpQ@)I~L*d`{O8!kRObjO7=n+Gp36fe!66neh+7 zW*l^0tTKjLLzr`x4`_8&on?mjW-PzheTNox8Hg7Nt@*SbE-%kP2hWYmHu#Fn@Q^J(SsPUz*|EgOoZ6byg3ew88UGdZ>9B2Tq=jF72ZaR=4u%1A6Vm{O#?@dD!(#tmR;eP(Fu z{$0O%=Vmua7=Gjr8nY%>ul?w=FJ76O2js&17W_iq2*tb!i{pt#`qZB#im9Rl>?t?0c zicIC}et_4d+CpVPx)i4~$u6N-QX3H77ez z?ZdvXifFk|*F8~L(W$OWM~r`pSk5}#F?j_5u$Obu9lDWIknO^AGu+Blk7!9Sb;NjS zncZA?qtASdNtzQ>z7N871IsPAk^CC?iIL}+{K|F@BuG2>qQ;_RUYV#>hHO(HUPpk@ z(bn~4|F_jiZi}Sad;_7`#4}EmD<1EiIxa48QjUuR?rC}^HRocq`OQPM@aHVKP9E#q zy%6bmHygCpIddPjE}q_DPC`VH_2m;Eey&ZH)E6xGeStOK7H)#+9y!%-Hm|QF6w#A( zIC0Yw%9j$s-#odxG~C*^MZ?M<+&WJ+@?B_QPUyTg9DJGtQN#NIC&-XddRsf3n^AL6 zT@P|H;PvN;ZpL0iv$bRb7|J{0o!Hq+S>_NrH4@coZtBJu#g8#CbR7|#?6uxi8d+$g z87apN>EciJZ`%Zv2**_uiET9Vk{pny&My;+WfGDw4EVL#B!Wiw&M|A8f1A@ z(yFQS6jfbH{b8Z-S7D2?Ixl`j0{+ZnpT=;KzVMLW{B$`N?Gw^Fl0H6lT61%T2AU**!sX0u?|I(yoy&Xveg7XBL&+>n6jd1##6d>TxE*Vj=8lWiG$4=u{1UbAa5QD>5_ z;Te^42v7K6Mmu4IWT6Rnm>oxrl~b<~^e3vbj-GCdHLIB_>59}Ya+~OF68NiH=?}2o zP(X7EN=quQn&)fK>M&kqF|<_*H`}c zk=+x)GU>{Af#vx&s?`UKUsz})g^Pc&?Ka@t5$n$bqf6{r1>#mWx6Ep>9|A}VmWRnowVo`OyCr^fHsf# zQjQ3Ttp7y#iQY8l`zEUW)(@gGQdt(~rkxlkefskT(t%@i8=|p1Y9Dc5bc+z#n$s13 zGJk|V0+&Ekh(F};PJzQKKo+FG@KV8a<$gmNSD;7rd_nRdc%?9)p!|B-@P~kxQG}~B zi|{0}@}zKC(rlFUYp*dO1RuvPC^DQOkX4<+EwvBAC{IZQdYxoq1Za!MW7%p7gGr=j zzWnAq%)^O2$eItftC#TTSArUyL$U54-O7e|)4_7%Q^2tZ^0-d&3J1}qCzR4dWX!)4 zzIEKjgnYgMus^>6uw4Jm8ga6>GBtMjpNRJ6CP~W=37~||gMo_p@GA@#-3)+cVYnU> zE5=Y4kzl+EbEh%dhQokB{gqNDqx%5*qBusWV%!iprn$S!;oN_6E3?0+umADVs4ako z?P+t?m?};gev9JXQ#Q&KBpzkHPde_CGu-y z<{}RRAx=xlv#mVi+Ibrgx~ujW$h{?zPfhz)Kp7kmYS&_|97b&H&1;J-mzrBWAvY} zh8-I8hl_RK2+nnf&}!W0P+>5?#?7>npshe<1~&l_xqKd0_>dl_^RMRq@-Myz&|TKZBj1=Q()) zF{dBjv5)h=&Z)Aevx}+i|7=R9rG^Di!sa)sZCl&ctX4&LScQ-kMncgO(9o6W6)yd< z@Rk!vkja*X_N3H=BavGoR0@u0<}m-7|2v!0+2h~S2Q&a=lTH91OJsvms2MT~ zY=c@LO5i`mLpBd(vh|)I&^A3TQLtr>w=zoyzTd=^f@TPu&+*2MtqE$Avf>l>}V|3-8Fp2hzo3y<)hr_|NO(&oSD z!vEjTWBxbKTiShVl-U{n*B3#)3a8$`{~Pk}J@elZ=>Pqp|MQ}jrGv7KrNcjW%TN_< zZz8kG{#}XoeWf7qY?D)L)8?Q-b@Na&>i=)(@uNo zr;cH98T3$Iau8Hn*@vXi{A@YehxDE2zX~o+RY`)6-X{8~hMpc#C`|8y> zU8Mnv5A0dNCf{Ims*|l-^ z(MRp{qoGohB34|ggDI*p!Aw|MFyJ|v+<+E3brfrI)|+l3W~CQLPbnF@G0)P~Ly!1TJLp}xh8uW`Q+RB-v`MRYZ9Gam3cM%{ zb4Cb*f)0deR~wtNb*8w-LlIF>kc7DAv>T0D(a3@l`k4TFnrO+g9XH7;nYOHxjc4lq zMmaW6qpgAgy)MckYMhl?>sq;-1E)-1llUneeA!ya9KM$)DaNGu57Z5aE>=VST$#vb zFo=uRHr$0M{-ha>h(D_boS4zId;3B|Tpqo|?B?Z@I?G(?&Iei+-{9L_A9=h=Qfn-U z1wIUnQe9!z%_j$F_{rf&`ZFSott09gY~qrf@g3O=Y>vzAnXCyL!@(BqWa)Zqt!#_k zfZHuwS52|&&)aK;CHq9V-t9qt0au{$#6c*R#e5n3rje0hic7c7m{kW$p(_`wB=Gw7 z4k`1Hi;Mc@yA7dp@r~?@rfw)TkjAW++|pkfOG}0N|2guek}j8Zen(!+@7?qt_7ndX zB=BG6WJ31#F3#Vk3=aQr8T)3`{=p9nBHlKzE0I@v`{vJ}h8pd6vby&VgFhzH|q;=aonunAXL6G2y(X^CtAhWr*jI zGjpY@raZDQkg*aMq}Ni6cRF z{oWv}5`nhSAv>usX}m^GHt`f(t8@zHc?K|y5Zi=4G*UG1Sza{$Dpj%X8 zzEXaKT5N6F5j4J|w#qlZP!zS7BT)9b+!ZSJdToqJts1c!)fwih4d31vfb{}W)EgcA zH2pZ^8_k$9+WD2n`6q5XbOy8>3pcYH9 z07eUB+p}YD@AH!}p!iKv><2QF-Y^&xx^PAc1F13A{nUeCDg&{hnix#FiO!fe(^&%Qcux!h znu*S!s$&nnkeotYsDthh1dq(iQrE|#f_=xVgfiiL&-5eAcC-> z5L0l|DVEM$#ulf{bj+Y~7iD)j<~O8CYM8GW)dQGq)!mck)FqoL^X zwNdZb3->hFrbHFm?hLvut-*uK?zXn3q1z|UX{RZ;-WiLoOjnle!xs+W0-8D)kjU#R z+S|A^HkRg$Ij%N4v~k`jyHffKaC~=wg=9)V5h=|kLQ@;^W!o2^K+xG&2n`XCd>OY5Ydi= zgHH=lgy++erK8&+YeTl7VNyVm9-GfONlSlVb3)V9NW5tT!cJ8d7X)!b-$fb!s76{t z@d=Vg-5K_sqHA@Zx-L_}wVnc@L@GL9_K~Zl(h5@AR#FAiKad8~KeWCo@mgXIQ#~u{ zgYFwNz}2b6Vu@CP0XoqJ+dm8px(5W5-Jpis97F`+KM)TuP*X8H@zwiVKDKGVp59pI zifNHZr|B+PG|7|Y<*tqap0CvG7tbR1R>jn70t1X`XJixiMVcHf%Ez*=xm1(CrTSDt z0cle!+{8*Ja&EOZ4@$qhBuKQ$U95Q%rc7tg$VRhk?3=pE&n+T3upZg^ZJc9~c2es% zh7>+|mrmA-p&v}|OtxqmHIBgUxL~^0+cpfkSK2mhh+4b=^F1Xgd2)}U*Yp+H?ls#z zrLxWg_hm}AfK2XYWr!rzW4g;+^^&bW%LmbtRai9f3PjU${r@n`JThy-cphbcwn)rq9{A$Ht`lmYKxOacy z6v2R(?gHhD5@&kB-Eg?4!hAoD7~(h>(R!s1c1Hx#s9vGPePUR|of32bS`J5U5w{F) z>0<^ktO2UHg<0{oxkdOQ;}coZDQph8p6ruj*_?uqURCMTac;>T#v+l1Tc~%^k-Vd@ zkc5y35jVNc49vZpZx;gG$h{%yslDI%Lqga1&&;mN{Ush1c7p>7e-(zp}6E7f-XmJb4nhk zb8zS+{IVbL$QVF8pf8}~kQ|dHJAEATmmnrb_wLG}-yHe>W|A&Y|;muy-d^t^<&)g5SJfaTH@P1%euONny=mxo+C z4N&w#biWY41r8k~468tvuYVh&XN&d#%QtIf9;iVXfWY)#j=l`&B~lqDT@28+Y!0E+MkfC}}H*#(WKKdJJq=O$vNYCb(ZG@p{fJgu;h z21oHQ(14?LeT>n5)s;uD@5&ohU!@wX8w*lB6i@GEH0pM>YTG+RAIWZD;4#F1&F%Jp zXZUml2sH0!lYJT?&sA!qwez6cXzJEd(1ZC~kT5kZSp7(@=H2$Azb_*W&6aA|9iwCL zdX7Q=42;@dspHDwYE?miGX#L^3xD&%BI&fN9^;`v4OjQXPBaBmOF1;#C)8XA(WFlH zycro;DS2?(G&6wkr6rqC>rqDv3nfGw3hmN_9Al>TgvmGsL8_hXx09};l9Ow@)F5@y z#VH5WigLDwZE4nh^7&@g{1FV^UZ%_LJ-s<{HN*2R$OPg@R~Z`c-ET*2}XB@9xvAjrK&hS=f|R8Gr9 zr|0TGOsI7RD+4+2{ZiwdVD@2zmg~g@^D--YL;6UYGSM8i$NbQr4!c7T9rg!8;TM0E zT#@?&S=t>GQm)*ua|?TLT2ktj#`|R<_*FAkOu2Pz$wEc%-=Y9V*$&dg+wIei3b*O8 z2|m$!jJG!J!ZGbbIa!(Af~oSyZV+~M1qGvelMzPNE_%5?c2>;MeeG2^N?JDKjFYCy z7SbPWH-$cWF9~fX%9~v99L!G(wi!PFp>rB!9xj7=Cv|F+7CsGNwY0Q_J%FID%C^CBZQfJ9K(HK%k31j~e#&?hQ zNuD6gRkVckU)v+53-fc} z7ZCzYN-5RG4H7;>>Hg?LU9&5_aua?A0)0dpew1#MMlu)LHe(M;OHjHIUl7|%%)YPo z0cBk;AOY00%Fe6heoN*$(b<)Cd#^8Iu;-2v@>cE-OB$icUF9EEoaC&q8z9}jMTT2I z8`9;jT%z0;dy4!8U;GW{i`)3!c6&oWY`J3669C!tM<5nQFFrFRglU8f)5Op$GtR-3 zn!+SPCw|04sv?%YZ(a7#L?vsdr7ss@WKAw&A*}-1S|9~cL%uA+E~>N6QklFE>8W|% zyX-qAUGTY1hQ-+um`2|&ji0cY*(qN!zp{YpDO-r>jPk*yuVSay<)cUt`t@&FPF_&$ zcHwu1(SQ`I-l8~vYyUxm@D1UEdFJ$f5Sw^HPH7b!9 zzYT3gKMF((N(v0#4f_jPfVZ=ApN^jQJe-X$`A?X+vWjLn_%31KXE*}5_}d8 zw_B1+a#6T1?>M{ronLbHIlEsMf93muJ7AH5h%;i99<~JX^;EAgEB1uHralD*!aJ@F zV2ruuFe9i2Q1C?^^kmVy921eb=tLDD43@-AgL^rQ3IO9%+vi_&R2^dpr}x{bCVPej z7G0-0o64uyWNtr*loIvslyo0%)KSDDKjfThe0hcqs)(C-MH1>bNGBDRTW~scy_{w} zp^aq8Qb!h9Lwielq%C1b8=?Z=&U)ST&PHbS)8Xzjh2DF?d{iAv)Eh)wsUnf>UtXN( zL7=$%YrZ#|^c{MYmhn!zV#t*(jdmYdCpwqpZ{v&L8KIuKn`@IIZfp!uo}c;7J57N` zAxyZ-uA4=Gzl~Ovycz%MW9ZL7N+nRo&1cfNn9(1H5eM;V_4Z_qVann7F>5f>%{rf= zPBZFaV@_Sobl?Fy&KXyzFDV*FIdhS5`Uc~S^Gjo)aiTHgn#<0C=9o-a-}@}xDor;D zZyZ|fvf;+=3MZd>SR1F^F`RJEZo+|MdyJYQAEauKu%WDol~ayrGU3zzbHKsnHKZ*z zFiwUkL@DZ>!*x05ql&EBq@_Vqv83&?@~q5?lVmffQZ+V-=qL+!u4Xs2Z2zdCQ3U7B&QR9_Iggy} z(om{Y9eU;IPe`+p1ifLx-XWh?wI)xU9ik+m#g&pGdB5Bi<`PR*?92lE0+TkRuXI)z z5LP!N2+tTc%cB6B1F-!fj#}>S!vnpgVU~3!*U1ej^)vjUH4s-bd^%B=ItQqDCGbrEzNQi(dJ`J}-U=2{7-d zK8k^Rlq2N#0G?9&1?HSle2vlkj^KWSBYTwx`2?9TU_DX#J+f+qLiZCqY1TXHFxXZqYMuD@RU$TgcnCC{_(vwZ-*uX)~go#%PK z@}2Km_5aQ~(<3cXeJN6|F8X_1@L%@xTzs}$_*E|a^_URF_qcF;Pfhoe?FTFwvjm1o z8onf@OY@jC2tVcMaZS;|T!Ks(wOgPpRzRnFS-^RZ4E!9dsnj9sFt609a|jJbb1Dt@ z<=Gal2jDEupxUSwWu6zp<<&RnAA;d&4gKVG0iu6g(DsST(4)z6R)zDpfaQ}v{5ARt zyhwvMtF%b-YazR5XLz+oh=mn;y-Mf2a8>7?2v8qX;19y?b>Z5laGHvzH;Nu9S`B8} zI)qN$GbXIQ1VL3lnof^6TS~rvPVg4V?Dl2Bb*K2z4E{5vy<(@@K_cN@U>R!>aUIRnb zL*)=787*cs#zb31zBC49x$`=fkQbMAef)L2$dR{)6BAz!t5U_B#1zZG`^neKSS22oJ#5B=gl%U=WeqL9REF2g zZnfCb0?quf?Ztj$VXvDSWoK`0L=Zxem2q}!XWLoT-kYMOx)!7fcgT35uC~0pySEme z`{wGWTkGr7>+Kb^n;W?BZH6ZP(9tQX%-7zF>vc2}LuWDI(9kh1G#7B99r4x6;_-V+k&c{nPUrR zAXJGRiMe~aup{0qzmLNjS_BC4cB#sXjckx{%_c&^xy{M61xEb>KW_AG5VFXUOjAG4 z^>Qlm9A#1N{4snY=(AmWzatb!ngqiqPbBZ7>Uhb3)dTkSGcL#&SH>iMO-IJBPua`u zo)LWZ>=NZLr758j{%(|uQuZ)pXq_4c!!>s|aDM9#`~1bzK3J1^^D#<2bNCccH7~-X}Ggi!pIIF>uFx%aPARGQsnC8ZQc8lrQ5o~smqOg>Ti^GNme94*w z)JZy{_{#$jxGQ&`M z!OMvZMHR>8*^>eS%o*6hJwn!l8VOOjZQJvh)@tnHVW&*GYPuxqXw}%M!(f-SQf`=L z5;=5w2;%82VMH6Xi&-K3W)o&K^+vJCepWZ-rW%+Dc6X3(){z$@4zjYxQ|}8UIojeC zYZpQ1dU{fy=oTr<4VX?$q)LP}IUmpiez^O&N3E_qPpchGTi5ZM6-2ScWlQq%V&R2Euz zO|Q0Hx>lY1Q1cW5xHv5!0OGU~PVEqSuy#fD72d#O`N!C;o=m+YioGu-wH2k6!t<~K zSr`E=W9)!g==~x9VV~-8{4ZN9{~-A9zJpRe%NGg$+MDuI-dH|b@BD)~>pPCGUNNzY zMDg||0@XGQgw`YCt5C&A{_+J}mvV9Wg{6V%2n#YSRN{AP#PY?1FF1#|vO_%e+#`|2*~wGAJaeRX6=IzFNeWhz6gJc8+(03Ph4y6ELAm=AkN7TOgMUEw*N{= z_)EIDQx5q22oUR+_b*tazu9+pX|n1c*IB-}{DqIj z-?E|ks{o3AGRNb;+iKcHkZvYJvFsW&83RAPs1Oh@IWy%l#5x2oUP6ZCtv+b|q>jsf zZ_9XO;V!>n`UxH1LvH8)L4?8raIvasEhkpQoJ`%!5rBs!0Tu(s_D{`4opB;57)pkX z4$A^8CsD3U5*!|bHIEqsn~{q+Ddj$ME@Gq4JXtgVz&7l{Ok!@?EA{B3P~NAqb9)4? zkQo30A^EbHfQ@87G5&EQTd`frrwL)&Yw?%-W@uy^Gn23%j?Y!Iea2xw<-f;esq zf%w5WN@E1}zyXtYv}}`U^B>W`>XPmdLj%4{P298|SisrE;7HvXX;A}Ffi8B#3Lr;1 zHt6zVb`8{#+e$*k?w8|O{Uh|&AG}|DG1PFo1i?Y*cQm$ZwtGcVgMwtBUDa{~L1KT-{jET4w60>{KZ27vXrHJ;fW{6| z=|Y4!&UX020wU1>1iRgB@Q#m~1^Z^9CG1LqDhYBrnx%IEdIty z!46iOoKlKs)c}newDG)rWUikD%j`)p z_w9Ph&e40=(2eBy;T!}*1p1f1SAUDP9iWy^u^Ubdj21Kn{46;GR+hwLO=4D11@c~V zI8x&(D({K~Df2E)Nx_yQvYfh4;MbMJ@Z}=Dt3_>iim~QZ*hZIlEs0mEb z_54+&*?wMD`2#vsQRN3KvoT>hWofI_Vf(^C1ff-Ike@h@saEf7g}<9T`W;HAne-Nd z>RR+&SP35w)xKn8^U$7))PsM!jKwYZ*RzEcG-OlTrX3}9a{q%#Un5E5W{{hp>w~;` zGky+3(vJvQyGwBo`tCpmo0mo((?nM8vf9aXrrY1Ve}~TuVkB(zeds^jEfI}xGBCM2 zL1|#tycSaWCurP+0MiActG3LCas@_@tao@(R1ANlwB$4K53egNE_;!&(%@Qo$>h`^1S_!hN6 z)vZtG$8fN!|BXBJ=SI>e(LAU(y(i*PHvgQ2llulxS8>qsimv7yL}0q_E5WiAz7)(f zC(ahFvG8&HN9+6^jGyLHM~$)7auppeWh_^zKk&C_MQ~8;N??OlyH~azgz5fe^>~7F zl3HnPN3z-kN)I$4@`CLCMQx3sG~V8hPS^}XDXZrQA>}mQPw%7&!sd(Pp^P=tgp-s^ zjl}1-KRPNWXgV_K^HkP__SR`S-|OF0bR-N5>I%ODj&1JUeAQ3$9i;B~$S6}*^tK?= z**%aCiH7y?xdY?{LgVP}S0HOh%0%LI$wRx;$T|~Y8R)Vdwa}kGWv8?SJVm^>r6+%I z#lj1aR94{@MP;t-scEYQWc#xFA30^}?|BeX*W#9OL;Q9#WqaaM546j5j29((^_8Nu z4uq}ESLr~r*O7E7$D{!k9W>`!SLoyA53i9QwRB{!pHe8um|aDE`Cg0O*{jmor)^t)3`>V>SWN-2VJcFmj^1?~tT=JrP`fVh*t zXHarp=8HEcR#vFe+1a%XXuK+)oFs`GDD}#Z+TJ}Ri`FvKO@ek2ayn}yaOi%(8p%2$ zpEu)v0Jym@f}U|-;}CbR=9{#<^z28PzkkTNvyKvJDZe+^VS2bES3N@Jq!-*}{oQlz z@8bgC_KnDnT4}d#&Cpr!%Yb?E!brx0!eVOw~;lLwUoz#Np%d$o%9scc3&zPm`%G((Le|6o1 zM(VhOw)!f84zG^)tZ1?Egv)d8cdNi+T${=5kV+j;Wf%2{3g@FHp^Gf*qO0q!u$=m9 zCaY`4mRqJ;FTH5`a$affE5dJrk~k`HTP_7nGTY@B9o9vvnbytaID;^b=Tzp7Q#DmD zC(XEN)Ktn39z5|G!wsVNnHi) z%^q94!lL|hF`IijA^9NR0F$@h7k5R^ljOW(;Td9grRN0Mb)l_l7##{2nPQ@?;VjXv zaLZG}yuf$r$<79rVPpXg?6iiieX|r#&`p#Con2i%S8*8F}(E) zI5E6c3tG*<;m~6>!&H!GJ6zEuhH7mkAzovdhLy;)q z{H2*8I^Pb}xC4s^6Y}6bJvMu=8>g&I)7!N!5QG$xseeU#CC?ZM-TbjsHwHgDGrsD= z{%f;@Sod+Ch66Ko2WF~;Ty)v>&x^aovCbCbD7>qF*!?BXmOV3(s|nxsb*Lx_2lpB7 zokUnzrk;P=T-&kUHO}td+Zdj!3n&NR?K~cRU zAXU!DCp?51{J4w^`cV#ye}(`SQhGQkkMu}O3M*BWt4UsC^jCFUy;wTINYmhD$AT;4 z?Xd{HaJjP`raZ39qAm;%beDbrLpbRf(mkKbANan7XsL>_pE2oo^$TgdidjRP!5-`% zv0d!|iKN$c0(T|L0C~XD0aS8t{*&#LnhE;1Kb<9&=c2B+9JeLvJr*AyyRh%@jHej=AetOMSlz^=!kxX>>B{2B1uIrQyfd8KjJ+DBy!h)~*(!|&L4^Q_07SQ~E zcemVP`{9CwFvPFu7pyVGCLhH?LhEVb2{7U+Z_>o25#+3<|8%1T^5dh}*4(kfJGry} zm%r#hU+__Z;;*4fMrX=Bkc@7|v^*B;HAl0((IBPPii%X9+u3DDF6%bI&6?Eu$8&aWVqHIM7mK6?Uvq$1|(-T|)IV<>e?!(rY zqkmO1MRaLeTR=)io(0GVtQT@s6rN%C6;nS3@eu;P#ry4q;^O@1ZKCJyp_Jo)Ty^QW z+vweTx_DLm{P-XSBj~Sl<%_b^$=}odJ!S2wAcxenmzFGX1t&Qp8Vxz2VT`uQsQYtdn&_0xVivIcxZ_hnrRtwq4cZSj1c-SG9 z7vHBCA=fd0O1<4*=lu$6pn~_pVKyL@ztw1swbZi0B?spLo56ZKu5;7ZeUml1Ws1?u zqMf1p{5myAzeX$lAi{jIUqo1g4!zWLMm9cfWcnw`k6*BR^?$2(&yW?>w;G$EmTA@a z6?y#K$C~ZT8+v{87n5Dm&H6Pb_EQ@V0IWmG9cG=O;(;5aMWWrIPzz4Q`mhK;qQp~a z+BbQrEQ+w{SeiuG-~Po5f=^EvlouB@_|4xQXH@A~KgpFHrwu%dwuCR)=B&C(y6J4J zvoGk9;lLs9%iA-IJGU#RgnZZR+@{5lYl8(e1h6&>Vc_mvg0d@);X zji4T|n#lB!>pfL|8tQYkw?U2bD`W{na&;*|znjmalA&f;*U++_aBYerq;&C8Kw7mI z7tsG*?7*5j&dU)Lje;^{D_h`%(dK|pB*A*1(Jj)w^mZ9HB|vGLkF1GEFhu&rH=r=8 zMxO42e{Si6$m+Zj`_mXb&w5Q(i|Yxyg?juUrY}78uo@~3v84|8dfgbPd0iQJRdMj< zncCNGdMEcsxu#o#B5+XD{tsg*;j-eF8`mp~K8O1J!Z0+>0=7O=4M}E?)H)ENE;P*F z$Ox?ril_^p0g7xhDUf(q652l|562VFlC8^r8?lQv;TMvn+*8I}&+hIQYh2 z1}uQQaag&!-+DZ@|C+C$bN6W;S-Z@)d1|en+XGvjbOxCa-qAF*LA=6s(Jg+g;82f$ z(Vb)8I)AH@cdjGFAR5Rqd0wiNCu!xtqWbcTx&5kslzTb^7A78~Xzw1($UV6S^VWiP zFd{Rimd-0CZC_Bu(WxBFW7+k{cOW7DxBBkJdJ;VsJ4Z@lERQr%3eVv&$%)b%<~ zCl^Y4NgO}js@u{|o~KTgH}>!* z_iDNqX2(As7T0xivMH|3SC1ivm8Q}6Ffcd7owUKN5lHAtzMM4<0v+ykUT!QiowO;`@%JGv+K$bBx@*S7C8GJVqQ_K>12}M`f_Ys=S zKFh}HM9#6Izb$Y{wYzItTy+l5U2oL%boCJn?R3?jP@n$zSIwlmyGq30Cw4QBO|14` zW5c);AN*J3&eMFAk$SR~2k|&+&Bc$e>s%c{`?d~85S-UWjA>DS5+;UKZ}5oVa5O(N zqqc@>)nee)+4MUjH?FGv%hm2{IlIF-QX}ym-7ok4Z9{V+ZHVZQl$A*x!(q%<2~iVv znUa+BX35&lCb#9VE-~Y^W_f;Xhl%vgjwdjzMy$FsSIj&ok}L+X`4>J=9BkN&nu^E*gbhj3(+D>C4E z@Fwq_=N)^bKFSHTzZk?-gNU$@l}r}dwGyh_fNi=9b|n}J>&;G!lzilbWF4B}BBq4f zYIOl?b)PSh#XTPp4IS5ZR_2C!E)Z`zH0OW%4;&~z7UAyA-X|sh9@~>cQW^COA9hV4 zXcA6qUo9P{bW1_2`eo6%hgbN%(G-F1xTvq!sc?4wN6Q4`e9Hku zFwvlAcRY?6h^Fj$R8zCNEDq8`=uZB8D-xn)tA<^bFFy}4$vA}Xq0jAsv1&5!h!yRA zU()KLJya5MQ`q&LKdH#fwq&(bNFS{sKlEh_{N%{XCGO+po#(+WCLmKW6&5iOHny>g z3*VFN?mx!16V5{zyuMWDVP8U*|BGT$(%IO|)?EF|OI*sq&RovH!N%=>i_c?K*A>>k zyg1+~++zY4Q)J;VWN0axhoIKx;l&G$gvj(#go^pZskEVj8^}is3Jw26LzYYVos0HX zRPvmK$dVxM8(Tc?pHFe0Z3uq){{#OK3i-ra#@+;*=ui8)y6hsRv z4Fxx1c1+fr!VI{L3DFMwXKrfl#Q8hfP@ajgEau&QMCxd{g#!T^;ATXW)nUg&$-n25 zruy3V!!;{?OTobo|0GAxe`Acn3GV@W=&n;~&9 zQM>NWW~R@OYORkJAo+eq1!4vzmf9K%plR4(tB@TR&FSbDoRgJ8qVcH#;7lQub*nq&?Z>7WM=oeEVjkaG zT#f)=o!M2DO5hLR+op>t0CixJCIeXH*+z{-XS|%jx)y(j&}Wo|3!l7{o)HU3m7LYyhv*xF&tq z%IN7N;D4raue&&hm0xM=`qv`+TK@;_xAcGKuK(2|75~ar2Yw)geNLSmVxV@x89bQu zpViVKKnlkwjS&&c|-X6`~xdnh}Ps)Hs z4VbUL^{XNLf7_|Oi>tA%?SG5zax}esF*FH3d(JH^Gvr7Rp*n=t7frH!U;!y1gJB^i zY_M$KL_}mW&XKaDEi9K-wZR|q*L32&m+2n_8lq$xRznJ7p8}V>w+d@?uB!eS3#u<} zIaqi!b!w}a2;_BfUUhGMy#4dPx>)_>yZ`ai?Rk`}d0>~ce-PfY-b?Csd(28yX22L% zI7XI>OjIHYTk_@Xk;Gu^F52^Gn6E1&+?4MxDS2G_#PQ&yXPXP^<-p|2nLTb@AAQEY zI*UQ9Pmm{Kat}wuazpjSyXCdnrD&|C1c5DIb1TnzF}f4KIV6D)CJ!?&l&{T)e4U%3HTSYqsQ zo@zWB1o}ceQSV)<4G<)jM|@@YpL+XHuWsr5AYh^Q{K=wSV99D~4RRU52FufmMBMmd z_H}L#qe(}|I9ZyPRD6kT>Ivj&2Y?qVZq<4bG_co_DP`sE*_Xw8D;+7QR$Uq(rr+u> z8bHUWbV19i#)@@G4bCco@Xb<8u~wVDz9S`#k@ciJtlu@uP1U0X?yov8v9U3VOig2t zL9?n$P3=1U_Emi$#slR>N5wH-=J&T=EdUHA}_Z zZIl3nvMP*AZS9{cDqFanrA~S5BqxtNm9tlu;^`)3X&V4tMAkJ4gEIPl= zoV!Gyx0N{3DpD@)pv^iS*dl2FwANu;1;%EDl}JQ7MbxLMAp>)UwNwe{=V}O-5C*>F zu?Ny+F64jZn<+fKjF01}8h5H_3pey|;%bI;SFg$w8;IC<8l|3#Lz2;mNNik6sVTG3 z+Su^rIE#40C4a-587$U~%KedEEw1%r6wdvoMwpmlXH$xPnNQN#f%Z7|p)nC>WsuO= z4zyqapLS<8(UJ~Qi9d|dQijb_xhA2)v>la)<1md5s^R1N&PiuA$^k|A<+2C?OiHbj z>Bn$~t)>Y(Zb`8hW7q9xQ=s>Rv81V+UiuZJc<23HplI88isqRCId89fb`Kt|CxVIg znWcwprwXnotO>3s&Oypkte^9yJjlUVVxSe%_xlzmje|mYOVPH^vjA=?6xd0vaj0Oz zwJ4OJNiFdnHJX3rw&inskjryukl`*fRQ#SMod5J|KroJRsVXa5_$q7whSQ{gOi*s0 z1LeCy|JBWRsDPn7jCb4s(p|JZiZ8+*ExC@Vj)MF|*Vp{B(ziccSn`G1Br9bV(v!C2 z6#?eqpJBc9o@lJ#^p-`-=`4i&wFe>2)nlPK1p9yPFzJCzBQbpkcR>={YtamIw)3nt z(QEF;+)4`>8^_LU)_Q3 zC5_7lgi_6y>U%m)m@}Ku4C}=l^J=<<7c;99ec3p{aR+v=diuJR7uZi%aQv$oP?dn?@6Yu_+*^>T0ptf(oobdL;6)N-I!TO`zg^Xbv3#L0I~sn@WGk-^SmPh5>W+LB<+1PU}AKa?FCWF|qMNELOgdxR{ zbqE7@jVe+FklzdcD$!(A$&}}H*HQFTJ+AOrJYnhh}Yvta(B zQ_bW4Rr;R~&6PAKwgLWXS{Bnln(vUI+~g#kl{r+_zbngT`Y3`^Qf=!PxN4IYX#iW4 zucW7@LLJA9Zh3(rj~&SyN_pjO8H&)|(v%!BnMWySBJV=eSkB3YSTCyIeJ{i;(oc%_hk{$_l;v>nWSB)oVeg+blh=HB5JSlG_r7@P z3q;aFoZjD_qS@zygYqCn=;Zxjo!?NK!%J$ z52lOP`8G3feEj+HTp@Tnn9X~nG=;tS+z}u{mQX_J0kxtr)O30YD%oo)L@wy`jpQYM z@M>Me=95k1p*FW~rHiV1CIfVc{K8r|#Kt(ApkXKsDG$_>76UGNhHExFCw#Ky9*B-z zNq2ga*xax!HMf_|Vp-86r{;~YgQKqu7%szk8$hpvi_2I`OVbG1doP(`gn}=W<8%Gn z%81#&WjkH4GV;4u43EtSW>K_Ta3Zj!XF?;SO3V#q=<=>Tc^@?A`i;&`-cYj|;^ zEo#Jl5zSr~_V-4}y8pnufXLa80vZY4z2ko7fj>DR)#z=wWuS1$$W!L?(y}YC+yQ|G z@L&`2upy3f>~*IquAjkVNU>}c10(fq#HdbK$~Q3l6|=@-eBbo>B9(6xV`*)sae58*f zym~RRVx;xoCG3`JV`xo z!lFw)=t2Hy)e!IFs?0~7osWk(d%^wxq&>_XD4+U#y&-VF%4z?XH^i4w`TxpF{`XhZ z%G}iEzf!T(l>g;W9<~K+)$g!{UvhW{E0Lis(S^%I8OF&%kr!gJ&fMOpM=&=Aj@wuL zBX?*6i51Qb$uhkwkFYkaD_UDE+)rh1c;(&Y=B$3)J&iJfQSx!1NGgPtK!$c9OtJuu zX(pV$bfuJpRR|K(dp@^j}i&HeJOh@|7lWo8^$*o~Xqo z5Sb+!EtJ&e@6F+h&+_1ETbg7LfP5GZjvIUIN3ibCOldAv z)>YdO|NH$x7AC8dr=<2ekiY1%fN*r~e5h6Yaw<{XIErujKV~tiyrvV_DV0AzEknC- zR^xKM3i<1UkvqBj3C{wDvytOd+YtDSGu!gEMg+!&|8BQrT*|p)(dwQLEy+ zMtMzij3zo40)CA!BKZF~yWg?#lWhqD3@qR)gh~D{uZaJO;{OWV8XZ_)J@r3=)T|kt zUS1pXr6-`!Z}w2QR7nP%d?ecf90;K_7C3d!UZ`N(TZoWNN^Q~RjVhQG{Y<%E1PpV^4 z-m-K+$A~-+VDABs^Q@U*)YvhY4Znn2^w>732H?NRK(5QSS$V@D7yz2BVX4)f5A04~$WbxGOam22>t&uD)JB8-~yiQW6ik;FGblY_I>SvB_z2?PS z*Qm&qbKI{H1V@YGWzpx`!v)WeLT02};JJo*#f$a*FH?IIad-^(;9XC#YTWN6;Z6+S zm4O1KH=#V@FJw7Pha0!9Vb%ZIM$)a`VRMoiN&C|$YA3~ZC*8ayZRY^fyuP6$n%2IU z$#XceYZeqLTXw(m$_z|33I$B4k~NZO>pP6)H_}R{E$i%USGy{l{-jOE;%CloYPEU+ zRFxOn4;7lIOh!7abb23YKD+_-?O z0FP9otcAh+oSj;=f#$&*ExUHpd&e#bSF%#8*&ItcL2H$Sa)?pt0Xtf+t)z$_u^wZi z44oE}r4kIZGy3!Mc8q$B&6JqtnHZ>Znn!Zh@6rgIu|yU+zG8q`q9%B18|T|oN3zMq z`l&D;U!OL~%>vo&q0>Y==~zLiCZk4v%s_7!9DxQ~id1LLE93gf*gg&2$|hB#j8;?3 z5v4S;oM6rT{Y;I+#FdmNw z){d%tNM<<#GN%n9ox7B=3#;u7unZ~tLB_vRZ52a&2=IM)2VkXm=L+Iqq~uk#Dug|x z>S84e+A7EiOY5lj*!q?6HDkNh~0g;0Jy(al!ZHHDtur9T$y-~)94HelX1NHjXWIM7UAe}$?jiz z9?P4`I0JM=G5K{3_%2jPLC^_Mlw?-kYYgb7`qGa3@dn|^1fRMwiyM@Ch z;CB&o7&&?c5e>h`IM;Wnha0QKnEp=$hA8TJgR-07N~U5(>9vJzeoFsSRBkDq=x(YgEMpb=l4TDD`2 zwVJpWGTA_u7}?ecW7s6%rUs&NXD3+n;jB86`X?8(l3MBo6)PdakI6V6a}22{)8ilT zM~T*mU}__xSy|6XSrJ^%lDAR3Lft%+yxC|ZUvSO_nqMX!_ul3;R#*{~4DA=h$bP)%8Yv9X zyp><|e8=_ttI}ZAwOd#dlnSjck#6%273{E$kJuCGu=I@O)&6ID{nWF5@gLb16sj|&Sb~+du4e4O_%_o`Ix4NRrAsyr1_}MuP94s>de8cH-OUkVPk3+K z&jW)It9QiU-ti~AuJkL`XMca8Oh4$SyJ=`-5WU<{cIh+XVH#e4d&zive_UHC!pN>W z3TB;Mn5i)9Qn)#6@lo4QpI3jFYc0~+jS)4AFz8fVC;lD^+idw^S~Qhq>Tg(!3$yLD zzktzoFrU@6s4wwCMz}edpF5i5Q1IMmEJQHzp(LAt)pgN3&O!&d?3W@6U4)I^2V{;- z6A(?zd93hS*uQmnh4T)nHnE{wVhh(=MMD(h(P4+^p83Om6t<*cUW>l(qJzr%5vp@K zN27ka(L{JX=1~e2^)F^i=TYj&;<7jyUUR2Bek^A8+3Up*&Xwc{)1nRR5CT8vG>ExV zHnF3UqXJOAno_?bnhCX-&kwI~Ti8t4`n0%Up>!U`ZvK^w2+0Cs-b9%w%4`$+To|k= zKtgc&l}P`*8IS>8DOe?EB84^kx4BQp3<7P{Pq}&p%xF_81pg!l2|u=&I{AuUgmF5n zJQCTLv}%}xbFGYtKfbba{CBo)lWW%Z>i(_NvLhoQZ*5-@2l&x>e+I~0Nld3UI9tdL zRzu8}i;X!h8LHVvN?C+|M81e>Jr38%&*9LYQec9Ax>?NN+9(_>XSRv&6hlCYB`>Qm z1&ygi{Y()OU4@D_jd_-7vDILR{>o|7-k)Sjdxkjgvi{@S>6GqiF|o`*Otr;P)kLHN zZkpts;0zw_6;?f(@4S1FN=m!4^mv~W+lJA`&7RH%2$)49z0A+8@0BCHtj|yH--AEL z0tW6G%X-+J+5a{5*WKaM0QDznf;V?L5&uQw+yegDNDP`hA;0XPYc6e0;Xv6|i|^F2WB)Z$LR|HR4 zTQsRAby9(^Z@yATyOgcfQw7cKyr^3Tz7lc7+JEwwzA7)|2x+PtEb>nD(tpxJQm)Kn zW9K_*r!L%~N*vS8<5T=iv|o!zTe9k_2jC_j*7ik^M_ zaf%k{WX{-;0*`t`G!&`eW;gChVXnJ-Rn)To8vW-?>>a%QU1v`ZC=U)f8iA@%JG0mZ zDqH;~mgBnrCP~1II<=V9;EBL)J+xzCoiRBaeH&J6rL!{4zIY8tZka?_FBeQeNO3q6 zyG_alW54Ba&wQf{&F1v-r1R6ID)PTsqjIBc+5MHkcW5Fnvi~{-FjKe)t1bl}Y;z@< z=!%zvpRua>>t_x}^}z0<7MI!H2v6|XAyR9!t50q-A)xk0nflgF4*OQlCGK==4S|wc zRMsSscNhRzHMBU8TdcHN!q^I}x0iXJ%uehac|Zs_B$p@CnF)HeXPpB_Za}F{<@6-4 zl%kml@}kHQ(ypD8FsPJ2=14xXJE|b20RUIgs!2|R3>LUMGF6X*B_I|$`Qg=;zm7C z{mEDy9dTmPbued7mlO@phdmAmJ7p@GR1bjCkMw6*G7#4+`k>fk1czdJUB!e@Q(~6# zwo%@p@V5RL0ABU2LH7Asq^quDUho@H>eTZH9f*no9fY0T zD_-9px3e}A!>>kv5wk91%C9R1J_Nh!*&Kk$J3KNxC}c_@zlgpJZ+5L)Nw|^p=2ue}CJtm;uj*Iqr)K})kA$xtNUEvX;4!Px*^&9T_`IN{D z{6~QY=Nau6EzpvufB^hflc#XIsSq0Y9(nf$d~6ZwK}fal92)fr%T3=q{0mP-EyP_G z)UR5h@IX}3Qll2b0oCAcBF>b*@Etu*aTLPU<%C>KoOrk=x?pN!#f_Og-w+;xbFgjQ zXp`et%lDBBh~OcFnMKMUoox0YwBNy`N0q~bSPh@+enQ=4RUw1) zpovN`QoV>vZ#5LvC;cl|6jPr}O5tu!Ipoyib8iXqy}TeJ;4+_7r<1kV0v5?Kv>fYp zg>9L`;XwXa&W7-jf|9~uP2iyF5`5AJ`Q~p4eBU$MCC00`rcSF>`&0fbd^_eqR+}mK z4n*PMMa&FOcc)vTUR zlDUAn-mh`ahi_`f`=39JYTNVjsTa_Y3b1GOIi)6dY)D}xeshB0T8Eov5%UhWd1)u}kjEQ|LDo{tqKKrYIfVz~@dp!! zMOnah@vp)%_-jDTUG09l+;{CkDCH|Q{NqX*uHa1YxFShy*1+;J`gywKaz|2Q{lG8x zP?KBur`}r`!WLKXY_K;C8$EWG>jY3UIh{+BLv0=2)KH%P}6xE2kg)%(-uA6lC?u8}{K(#P*c zE9C8t*u%j2r_{;Rpe1A{9nNXU;b_N0vNgyK!EZVut~}+R2rcbsHilqsOviYh-pYX= zHw@53nlmwYI5W5KP>&`dBZe0Jn?nAdC^HY1wlR6$u^PbpB#AS&5L6zqrXN&7*N2Q` z+Rae1EwS)H=aVSIkr8Ek^1jy2iS2o7mqm~Mr&g5=jjt7VxwglQ^`h#Mx+x2v|9ZAwE$i_9918MjJxTMr?n!bZ6n$}y11u8I9COTU`Z$Fi z!AeAQLMw^gp_{+0QTEJrhL424pVDp%wpku~XRlD3iv{vQ!lAf!_jyqd_h}+Tr1XG| z`*FT*NbPqvHCUsYAkFnM`@l4u_QH&bszpUK#M~XLJt{%?00GXY?u_{gj3Hvs!=N(I z(=AuWPijyoU!r?aFTsa8pLB&cx}$*%;K$e*XqF{~*rA-qn)h^!(-;e}O#B$|S~c+U zN4vyOK0vmtx$5K!?g*+J@G1NmlEI=pyZXZ69tAv=@`t%ag_Hk{LP~OH9iE)I= zaJ69b4kuCkV0V zo(M0#>phpQ_)@j;h%m{-a*LGi(72TP)ws2w*@4|C-3+;=5DmC4s7Lp95%n%@Ko zfdr3-a7m*dys9iIci$A=4NPJ`HfJ;hujLgU)ZRuJI`n;Pw|yksu!#LQnJ#dJysgNb z@@qwR^wrk(jbq4H?d!lNyy72~Dnn87KxsgQ!)|*m(DRM+eC$wh7KnS-mho3|KE)7h zK3k;qZ;K1Lj6uEXLYUYi)1FN}F@-xJ z@@3Hb84sl|j{4$3J}aTY@cbX@pzB_qM~APljrjju6P0tY{C@ zpUCOz_NFmALMv1*blCcwUD3?U6tYs+N%cmJ98D%3)%)Xu^uvzF zS5O!sc#X6?EwsYkvPo6A%O8&y8sCCQH<%f2togVwW&{M;PR!a(ZT_A+jVAbf{@5kL zB@Z(hb$3U{T_}SKA_CoQVU-;j>2J=L#lZ~aQCFg-d<9rzs$_gO&d5N6eFSc z1ml8)P*FSi+k@!^M9nDWR5e@ATD8oxtDu=36Iv2!;dZzidIS(PCtEuXAtlBb1;H%Z zwnC^Ek*D)EX4#Q>R$$WA2sxC_t(!!6Tr?C#@{3}n{<^o;9id1RA&-Pig1e-2B1XpG zliNjgmd3c&%A}s>qf{_j#!Z`fu0xIwm4L0)OF=u(OEmp;bLCIaZX$&J_^Z%4Sq4GZ zPn6sV_#+6pJmDN_lx@1;Zw6Md_p0w9h6mHtzpuIEwNn>OnuRSC2=>fP^Hqgc)xu^4 z<3!s`cORHJh#?!nKI`Et7{3C27+EuH)Gw1f)aoP|B3y?fuVfvpYYmmukx0ya-)TQX zR{ggy5cNf4X|g)nl#jC9p>7|09_S7>1D2GTRBUTW zAkQ=JMRogZqG#v;^=11O6@rPPwvJkr{bW-Qg8`q8GoD#K`&Y+S#%&B>SGRL>;ZunM@49!}Uy zN|bBCJ%sO;@3wl0>0gbl3L@1^O60ONObz8ZI7nder>(udj-jt`;yj^nTQ$L9`OU9W zX4alF#$|GiR47%x@s&LV>2Sz2R6?;2R~5k6V>)nz!o_*1Y!$p>BC5&?hJg_MiE6UBy>RkVZj`9UWbRkN-Hk!S`=BS3t3uyX6)7SF#)71*}`~Ogz z1rap5H6~dhBJ83;q-Y<5V35C2&F^JI-it(=5D#v!fAi9p#UwV~2tZQI+W(Dv?1t9? zfh*xpxxO{-(VGB>!Q&0%^YW_F!@aZS#ucP|YaD#>wd1Fv&Z*SR&mc;asi}1G) z_H>`!akh-Zxq9#io(7%;a$)w+{QH)Y$?UK1Dt^4)up!Szcxnu}kn$0afcfJL#IL+S z5gF_Y30j;{lNrG6m~$Ay?)*V9fZuU@3=kd40=LhazjFrau>(Y>SJNtOz>8x_X-BlA zIpl{i>OarVGj1v(4?^1`R}aQB&WCRQzS~;7R{tDZG=HhgrW@B`W|#cdyj%YBky)P= zpxuOZkW>S6%q7U{VsB#G(^FMsH5QuGXhb(sY+!-R8Bmv6Sx3WzSW<1MPPN1!&PurYky(@`bP9tz z52}LH9Q?+FF5jR6-;|+GVdRA!qtd;}*-h&iIw3Tq3qF9sDIb1FFxGbo&fbG5n8$3F zyY&PWL{ys^dTO}oZ#@sIX^BKW*bon=;te9j5k+T%wJ zNJtoN1~YVj4~YRrlZl)b&kJqp+Z`DqT!la$x&&IxgOQw#yZd-nBP3!7FijBXD|IsU8Zl^ zc6?MKpJQ+7ka|tZQLfchD$PD|;K(9FiLE|eUZX#EZxhG!S-63C$jWX1Yd!6-Yxi-u zjULIr|0-Q%D9jz}IF~S%>0(jOqZ(Ln<$9PxiySr&2Oic7vb<8q=46)Ln%Z|<*z5&> z3f~Zw@m;vR(bESB<=Jqkxn(=#hQw42l(7)h`vMQQTttz9XW6^|^8EK7qhju4r_c*b zJIi`)MB$w@9epwdIfnEBR+?~);yd6C(LeMC& zn&&N*?-g&BBJcV;8&UoZi4Lmxcj16ojlxR~zMrf=O_^i1wGb9X-0@6_rpjPYemIin zmJb+;lHe;Yp=8G)Q(L1bzH*}I>}uAqhj4;g)PlvD9_e_ScR{Ipq|$8NvAvLD8MYr}xl=bU~)f%B3E>r3Bu9_t|ThF3C5~BdOve zEbk^r&r#PT&?^V1cb{72yEWH}TXEE}w>t!cY~rA+hNOTK8FAtIEoszp!qqptS&;r$ zaYV-NX96-h$6aR@1xz6_E0^N49mU)-v#bwtGJm)ibygzJ8!7|WIrcb`$XH~^!a#s& z{Db-0IOTFq#9!^j!n_F}#Z_nX{YzBK8XLPVmc&X`fT7!@$U-@2KM9soGbmOSAmqV z{nr$L^MBo_u^Joyf0E^=eo{Rt0{{e$IFA(#*kP@SQd6lWT2-#>` zP1)7_@IO!9lk>Zt?#CU?cuhiLF&)+XEM9B)cS(gvQT!X3`wL*{fArTS;Ak`J<84du zALKPz4}3nlG8Fo^MH0L|oK2-4xIY!~Oux~1sw!+It)&D3p;+N8AgqKI`ld6v71wy8I!eP0o~=RVcFQR2Gr(eP_JbSytoQ$Yt}l*4r@A8Me94y z8cTDWhqlq^qoAhbOzGBXv^Wa4vUz$(7B!mX`T=x_ueKRRDfg&Uc-e1+z4x$jyW_Pm zp?U;-R#xt^Z8Ev~`m`iL4*c#65Nn)q#=Y0l1AuD&+{|8-Gsij3LUZXpM0Bx0u7WWm zH|%yE@-#XEph2}-$-thl+S;__ciBxSSzHveP%~v}5I%u!z_l_KoW{KRx2=eB33umE zIYFtu^5=wGU`Jab8#}cnYry@9p5UE#U|VVvx_4l49JQ;jQdp(uw=$^A$EA$LM%vmE zvdEOaIcp5qX8wX{mYf0;#51~imYYPn4=k&#DsKTxo{_Mg*;S495?OBY?#gv=edYC* z^O@-sd-qa+U24xvcbL0@C7_6o!$`)sVr-jSJE4XQUQ$?L7}2(}Eixqv;L8AdJAVqc zq}RPgpnDb@E_;?6K58r3h4-!4rT4Ab#rLHLX?eMOfluJk=3i1@Gt1i#iA=O`M0@x! z(HtJP9BMHXEzuD93m|B&woj0g6T?f#^)>J>|I4C5?Gam>n9!8CT%~aT;=oco5d6U8 zMXl(=W;$ND_8+DD*?|5bJ!;8ebESXMUKBAf7YBwNVJibGaJ*(2G`F%wx)grqVPjudiaq^Kl&g$8A2 zWMxMr@_$c}d+;_B`#kUX-t|4VKH&_f^^EP0&=DPLW)H)UzBG%%Tra*5 z%$kyZe3I&S#gfie^z5)!twG={3Cuh)FdeA!Kj<-9** zvT*5%Tb`|QbE!iW-XcOuy39>D3oe6x{>&<#E$o8Ac|j)wq#kQzz|ATd=Z0K!p2$QE zPu?jL8Lb^y3_CQE{*}sTDe!2!dtlFjq&YLY@2#4>XS`}v#PLrpvc4*@q^O{mmnr5D zmyJq~t?8>FWU5vZdE(%4cuZuao0GNjp3~Dt*SLaxI#g_u>hu@k&9Ho*#CZP~lFJHj z(e!SYlLigyc?&5-YxlE{uuk$9b&l6d`uIlpg_z15dPo*iU&|Khx2*A5Fp;8iK_bdP z?T6|^7@lcx2j0T@x>X7|kuuBSB7<^zeY~R~4McconTxA2flHC0_jFxmSTv-~?zVT| zG_|yDqa9lkF*B6_{j=T>=M8r<0s;@z#h)3BQ4NLl@`Xr__o7;~M&dL3J8fP&zLfDfy z);ckcTev{@OUlZ`bCo(-3? z1u1xD`PKgSg?RqeVVsF<1SLF;XYA@Bsa&cY!I48ZJn1V<3d!?s=St?TLo zC0cNr`qD*M#s6f~X>SCNVkva^9A2ZP>CoJ9bvgXe_c}WdX-)pHM5m7O zrHt#g$F0AO+nGA;7dSJ?)|Mo~cf{z2L)Rz!`fpi73Zv)H=a5K)*$5sf_IZypi($P5 zsPwUc4~P-J1@^3C6-r9{V-u0Z&Sl7vNfmuMY4yy*cL>_)BmQF!8Om9Dej%cHxbIzA zhtV0d{=%cr?;bpBPjt@4w=#<>k5ee=TiWAXM2~tUGfm z$s&!Dm0R^V$}fOR*B^kGaipi~rx~A2cS0;t&khV1a4u38*XRUP~f za!rZMtay8bsLt6yFYl@>-y^31(*P!L^^s@mslZy(SMsv9bVoX`O#yBgEcjCmGpyc* zeH$Dw6vB5P*;jor+JOX@;6K#+xc)Z9B8M=x2a@Wx-{snPGpRmOC$zpsqW*JCh@M2Y z#K+M(>=#d^>Of9C`))h<=Bsy)6zaMJ&x-t%&+UcpLjV`jo4R2025 zXaG8EA!0lQa)|dx-@{O)qP6`$rhCkoQqZ`^SW8g-kOwrwsK8 z3ms*AIcyj}-1x&A&vSq{r=QMyp3CHdWH35!sad#!Sm>^|-|afB+Q;|Iq@LFgqIp#Z zD1%H+3I?6RGnk&IFo|u+E0dCxXz4yI^1i!QTu7uvIEH>i3rR{srcST`LIRwdV1P;W z+%AN1NIf@xxvVLiSX`8ILA8MzNqE&7>%jMzGt9wm78bo9<;h*W84i29^w!>V>{N+S zd`5Zmz^G;f=icvoOZfK5#1ctx*~UwD=ab4DGQXehQ!XYnak*dee%YN$_ZPL%KZuz$ zD;$PpT;HM^$KwtQm@7uvT`i6>Hae1CoRVM2)NL<2-k2PiX=eAx+-6j#JI?M}(tuBW zkF%jjLR)O`gI2fcPBxF^HeI|DWwQWHVR!;;{BXXHskxh8F@BMDn`oEi-NHt;CLymW z=KSv5)3dyzec0T5B*`g-MQ<;gz=nIWKUi9ko<|4I(-E0k$QncH>E4l z**1w&#={&zv4Tvhgz#c29`m|;lU-jmaXFMC11 z*dlXDMEOG>VoLMc>!rApwOu2prKSi*!w%`yzGmS+k(zm*CsLK*wv{S_0WX^8A-rKy zbk^Gf_92^7iB_uUF)EE+ET4d|X|>d&mdN?x@vxKAQk`O+r4Qdu>XGy(a(19g;=jU} zFX{O*_NG>!$@jh!U369Lnc+D~qch3uT+_Amyi}*k#LAAwh}k8IPK5a-WZ81ufD>l> z$4cF}GSz>ce`3FAic}6W4Z7m9KGO?(eWqi@L|5Hq0@L|&2flN1PVl}XgQ2q*_n2s3 zt5KtowNkTYB5b;SVuoXA@i5irXO)A&%7?V`1@HGCB&)Wgk+l|^XXChq;u(nyPB}b3 zY>m5jkxpZgi)zfbgv&ec4Zqdvm+D<?Im*mXweS9H+V>)zF#Zp3)bhl$PbISY{5=_z!8&*Jv~NYtI-g!>fDs zmvL5O^U%!^VaKA9gvKw|5?-jk>~%CVGvctKmP$kpnpfN{D8@X*Aazi$txfa%vd-|E z>kYmV66W!lNekJPom29LdZ%(I+ZLZYTXzTg*to~m?7vp%{V<~>H+2}PQ?PPAq`36R z<%wR8v6UkS>Wt#hzGk#44W<%9S=nBfB);6clKwnxY}T*w21Qc3_?IJ@4gYzC7s;WP zVQNI(M=S=JT#xsZy7G`cR(BP9*je0bfeN8JN5~zY(DDs0t{LpHOIbN);?T-69Pf3R zSNe*&p2%AwXHL>__g+xd4Hlc_vu<25H?(`nafS%)3UPP7_4;gk-9ckt8SJRTv5v0M z_Hww`qPudL?ajIR&X*;$y-`<)6dxx1U~5eGS13CB!lX;3w7n&lDDiArbAhSycd}+b zya_3p@A`$kQy;|NJZ~s44Hqo7Hwt}X86NK=(ey>lgWTtGL6k@Gy;PbO!M%1~Wcn2k zUFP|*5d>t-X*RU8g%>|(wwj*~#l4z^Aatf^DWd1Wj#Q*AY0D^V@sC`M zjJc6qXu0I7Y*2;;gGu!plAFzG=J;1%eIOdn zQA>J&e05UN*7I5@yRhK|lbBSfJ+5Uq;!&HV@xfPZrgD}kE*1DSq^=%{o%|LChhl#0 zlMb<^a6ixzpd{kNZr|3jTGeEzuo}-eLT-)Q$#b{!vKx8Tg}swCni>{#%vDY$Ww$84 zew3c9BBovqb}_&BRo#^!G(1Eg((BScRZ}C)Oz?y`T5wOrv);)b^4XR8 zhJo7+<^7)qB>I;46!GySzdneZ>n_E1oWZY;kf94#)s)kWjuJN1c+wbVoNQcmnv}{> zN0pF+Sl3E}UQ$}slSZeLJrwT>Sr}#V(dVaezCQl2|4LN`7L7v&siYR|r7M(*JYfR$ zst3=YaDw$FSc{g}KHO&QiKxuhEzF{f%RJLKe3p*7=oo`WNP)M(9X1zIQPP0XHhY3c znrP{$4#Ol$A0s|4S7Gx2L23dv*Gv2o;h((XVn+9+$qvm}s%zi6nI-_s6?mG! zj{DV;qesJb&owKeEK?=J>UcAlYckA7Sl+I&IN=yasrZOkejir*kE@SN`fk<8Fgx*$ zy&fE6?}G)d_N`){P~U@1jRVA|2*69)KSe_}!~?+`Yb{Y=O~_+@!j<&oVQQMnhoIRU zA0CyF1OFfkK44n*JD~!2!SCPM;PRSk%1XL=0&rz00wxPs&-_eapJy#$h!eqY%nS0{ z!aGg58JIJPF3_ci%n)QSVpa2H`vIe$RD43;#IRfDV&Ibit z+?>HW4{2wOfC6Fw)}4x}i1maDxcE1qi@BS*qcxD2gE@h3#4cgU*D-&3z7D|tVZWt= z-Cy2+*Cm@P4GN_TPUtaVyVesbVDazF@)j8VJ4>XZv!f%}&eO1SvIgr}4`A*3#vat< z_MoByL(qW6L7SFZ#|Gc1fFN)L2PxY+{B8tJp+pxRyz*87)vXR}*=&ahXjBlQKguuf zX6x<<6fQulE^C*KH8~W%ptpaC0l?b=_{~*U4?5Vt;dgM4t_{&UZ1C2j?b>b+5}{IF_CUyvz-@QZPMlJ)r_tS$9kH%RPv#2_nMb zRLj5;chJ72*U`Z@Dqt4$@_+k$%|8m(HqLG!qT4P^DdfvGf&){gKnGCX#H0!;W=AGP zbA&Z`-__a)VTS}kKFjWGk z%|>yE?t*EJ!qeQ%dPk$;xIQ+P0;()PCBDgjJm6Buj{f^awNoVx+9<|lg3%-$G(*f) zll6oOkN|yamn1uyl2*N-lnqRI1cvs_JxLTeahEK=THV$Sz*gQhKNb*p0fNoda#-&F zB-qJgW^g}!TtM|0bS2QZekW7_tKu%GcJ!4?lObt0z_$mZ4rbQ0o=^curCs3bJK6sq z9fu-aW-l#>z~ca(B;4yv;2RZ?tGYAU)^)Kz{L|4oPj zdOf_?de|#yS)p2v8-N||+XL=O*%3+y)oI(HbM)Ds?q8~HPzIP(vs*G`iddbWq}! z(2!VjP&{Z1w+%eUq^ '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# 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*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 \ + "$@" + +# 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" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 000000000..107acd32c --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@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=. +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%" == "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%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/mongo-connector/build.gradle.kts b/mongo-connector/build.gradle.kts new file mode 100644 index 000000000..ea795fbde --- /dev/null +++ b/mongo-connector/build.gradle.kts @@ -0,0 +1,43 @@ +plugins { + `java-library` + id("com.gradleup.shadow") +} + +dependencies { + implementation(libs.slf4j.api) + implementation(libs.mongodb.driver) + implementation(libs.jsr305) + + compileOnly(libs.spigot.api) + compileOnly(libs.lombok) + + implementation(project(":plugin")) + + annotationProcessor(libs.lombok) +} + +tasks { + jar { + archiveClassifier = "plain" + } + + shadowJar { + archiveBaseName = "Challenges-MongoConnector" + archiveClassifier = "" + archiveVersion = "" + + dependencies { + include(dependency("org.mongodb:mongodb-driver")) + include(dependency("org.mongodb:mongodb-driver-core")) + include(dependency("org.mongodb:bson")) + } + } + + build { + dependsOn(shadowJar) + } +} + + + + diff --git a/mongo-connector/pom.xml b/mongo-connector/pom.xml deleted file mode 100644 index 0fcaef25e..000000000 --- a/mongo-connector/pom.xml +++ /dev/null @@ -1,161 +0,0 @@ - - - 4.0.0 - - - net.codingarea.challenges - root - 2.4 - - - mongo-connector - - - 8 - 8 - UTF-8 - - - - - - - org.slf4j - slf4j-api - 1.7.32 - - - - org.spigotmc - spigot-api - ${spigot.version} - provided - - - - org.mongodb - mongodb-driver - 3.12.14 - - - - com.google.code.findbugs - jsr305 - 3.0.2 - - - - net.codingarea.challenges - plugin - ${project.version} - - - - - - - - spigot-repo - https://hub.spigotmc.org/nexus/content/repositories/snapshots/ - - - - - jitpack.io - https://jitpack.io - - - - - - - Challenges-MongoConnector - src/main/java - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.14.0 - - 1.8 - 1.8 - - - - - - org.apache.maven.plugins - maven-source-plugin - 3.3.1 - - - attach-sources - - jar - - - - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.6.0 - - - package - - shade - - - - - com.github.anweisen.Utility:database-mongodb - org.mongodb:mongodb-driver - org.mongodb:mongodb-driver-core - org.mongodb:bson - - - - - - - - - - org.apache.maven.plugins - maven-resources-plugin - 3.3.1 - - - copy-license - generate-sources - - copy-resources - - - ${basedir}/target/classes - - - ${user.dir} - - LICENSE - - - - - - - - - - - - - diff --git a/mongo-connector/src/main/resources/plugin.yml b/mongo-connector/src/main/resources/plugin.yml index 620f9d2d5..0b4173ff6 100644 --- a/mongo-connector/src/main/resources/plugin.yml +++ b/mongo-connector/src/main/resources/plugin.yml @@ -1,5 +1,5 @@ name: Challenges-MongoConnector -version: 2.4 +version: ${version} api-version: 1.14 author: CodingArea authors: diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts new file mode 100644 index 000000000..ac018eaf1 --- /dev/null +++ b/plugin/build.gradle.kts @@ -0,0 +1,41 @@ +plugins { + `java-library` + id("com.gradleup.shadow") +} + +dependencies { + implementation(libs.slf4j.api) + implementation(libs.jsr305) + + compileOnly(libs.spigot.api) + compileOnly(libs.authlib) + + compileOnly(libs.lombok) + + compileOnly(libs.cloudnet3.driver) + compileOnly(libs.cloudnet3.bridge) + compileOnly(libs.cloudnet2.bridge) + + annotationProcessor(libs.lombok) +} + +tasks { + jar { + archiveClassifier = "plain" + } + + shadowJar { + archiveBaseName = "Challenges" + archiveClassifier = "" + archiveVersion = "" + + dependencies { + // TODO adopted from maven shade configuration, check necessity + include(dependency("net.kyori:adventure-api")) + } + } + + build { + dependsOn(shadowJar) + } +} diff --git a/plugin/pom.xml b/plugin/pom.xml deleted file mode 100644 index edfeaadca..000000000 --- a/plugin/pom.xml +++ /dev/null @@ -1,198 +0,0 @@ - - - 4.0.0 - - - net.codingarea.challenges - root - 2.4 - - - plugin - - - 8 - 8 - UTF-8 - - - - - - - org.slf4j - slf4j-api - 1.7.32 - - - - - org.spigotmc - spigot-api - ${spigot.version} - provided - - - com.mojang - authlib - 1.5.21 - provided - - - - - de.dytanic.cloudnet - cloudnet-driver - 3.4.5-RELEASE - provided - - - de.dytanic.cloudnet - cloudnet-bridge - 3.4.5-RELEASE - provided - - - de.dytanic.cloudnet - cloudnet-api-bridge - 2.1.17 - provided - - - - - org.projectlombok - lombok - 1.18.38 - provided - - - com.google.code.findbugs - jsr305 - 3.0.2 - - - - - - - - - spigot-repo - https://hub.spigotmc.org/nexus/content/repositories/snapshots/ - - - minecraft-repo - https://libraries.minecraft.net/ - - - - - releases - https://repo.cloudnetservice.eu/repository/releases/ - - - cloudnet - https://cloudnetservice.eu/repositories/ - - - - - - - Challenges - src/main/java - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.14.0 - - 16 - 16 - utf-8 - - - org.projectlombok - lombok - 1.18.38 - - - - - - - - org.apache.maven.plugins - maven-source-plugin - 3.3.1 - - - attach-sources - - jar - - - - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.6.0 - - - package - - shade - - - - - net.kyori:adventure-api - - - - - - - - - - - org.apache.maven.plugins - maven-resources-plugin - 3.3.1 - - - copy-license - generate-sources - - copy-resources - - - ${basedir}/target/classes - - - ${user.dir} - - LICENSE - - - - - - - - - - - - - diff --git a/plugin/src/main/resources/plugin.yml b/plugin/src/main/resources/plugin.yml index c331983af..70cb24ec3 100644 --- a/plugin/src/main/resources/plugin.yml +++ b/plugin/src/main/resources/plugin.yml @@ -1,5 +1,5 @@ name: Challenges -version: 2.3.3 +version: ${version} author: CodingArea authors: - anweisen @@ -231,4 +231,4 @@ commands: permission: "challenges.setlanguage" aliases: - "setlang" - - "language" \ No newline at end of file + - "language" diff --git a/pom.xml b/pom.xml deleted file mode 100644 index 810fb27fb..000000000 --- a/pom.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - 4.0.0 - - net.codingarea.challenges - root - 2.4 - pom - root - https://github.com/anweisen/Challenges - - - plugin - mongo-connector - - - - 1.21.4-R0.1-SNAPSHOT - - - diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 000000000..531a13a12 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,3 @@ +rootProject.name = "Challenges" + +include("plugin", "mongo-connector") From 76d95edca3b5e58d33f5a91517072ce3febfab52 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Tue, 26 May 2026 18:23:49 +0200 Subject: [PATCH 067/119] ci: enhance build workflow - concurrency check - file permissions - remove redundant wrapper validation (newer gradle action) --- .github/workflows/build.yml | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d0f4f4dd2..0551ebff7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -6,24 +6,37 @@ on: pull_request: branches: [ master, development ] +# Cancel any in-progress runs for the same branch/PR +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + jobs: build: runs-on: ubuntu-latest + steps: - - uses: actions/checkout@v4 - - name: Validate gradle wrapper - uses: gradle/actions/wrapper-validation@v4 + - name: Checkout code + uses: actions/checkout@v4 + - name: Set up JDK 17 uses: actions/setup-java@v4 with: - java-version: 17 - distribution: corretto + java-version: '17' + distribution: 'corretto' + - name: Setup Gradle - uses: gradle/actions/setup-gradle@v3 + uses: gradle/actions/setup-gradle@v6 + + # Fallback Fix: Explicitly ensures executable permissions if Git drops them + - name: Make Gradlew Executable + run: chmod +x gradlew + - name: Build with Gradle env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: ./gradlew build + - name: Capture build artifacts uses: actions/upload-artifact@v4 with: From a4c485c6e74933792a9bbafe8f7361c89e21f7e7 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Tue, 26 May 2026 20:11:18 +0200 Subject: [PATCH 068/119] chore: gson depend - explicit compileOnly gson version (use bundled mojang gson) - necessary due to ambiguity created by multiple gson versions bundled by depends - consider bundling via relocate --- gradle/libs.versions.toml | 9 ++++++--- plugin/build.gradle.kts | 4 ++++ .../challenges/plugin/content/loader/LanguageLoader.java | 4 ++-- .../challenges/plugin/utils/item/ItemBuilder.java | 2 +- .../common/config/document/gson/PairTypeAdapter.java | 2 +- .../net/codingarea/commons/common/misc/GsonUtils.java | 2 +- 6 files changed, 15 insertions(+), 8 deletions(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index bd6e0ab50..447342029 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -4,8 +4,9 @@ spigot = "1.21.4-R0.1-SNAPSHOT" authlib = "1.5.21" -# logging +# utilities slf4j = "1.7.32" +gson = "2.13.2" # annotations, compile time processing lombok = "1.18.38" @@ -18,14 +19,16 @@ mongodb = "3.12.14" cloudnet3 = "3.4.5-RELEASE" cloudnet2 = "2.1.17" + [libraries] # minecraft spigot-api = { group = "org.spigotmc", name = "spigot-api", version.ref = "spigot" } authlib = { group = "com.mojang", name = "authlib", version.ref = "authlib" } -# logging +# utilities slf4j-api = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" } +gson = { group = "com.google.code.gson", name = "gson", version.ref = "gson" } # annotations, compile time processing lombok = { group = "org.projectlombok", name = "lombok", version.ref = "lombok" } @@ -39,7 +42,7 @@ cloudnet3-driver = { group = "de.dytanic.cloudnet", name = "cloudnet-driver", ve cloudnet3-bridge = { group = "de.dytanic.cloudnet", name = "cloudnet-bridge", version.ref = "cloudnet3" } cloudnet2-bridge = { group = "de.dytanic.cloudnet", name = "cloudnet-api-bridge", version.ref = "cloudnet2" } + [bundles] cloudnet = ["cloudnet3-driver", "cloudnet3-bridge", "cloudnet2-bridge"] - diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index ac018eaf1..00c6e2ece 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -12,6 +12,10 @@ dependencies { compileOnly(libs.lombok) + // gson is already bundled by mojang, accessing it saves on artifact size but might cause compatibilty issues + // consider bundling relocated impl if version compatibility becomes unmanageable + compileOnly(libs.gson) + compileOnly(libs.cloudnet3.driver) compileOnly(libs.cloudnet3.bridge) compileOnly(libs.cloudnet2.bridge) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index fc34aca48..c1e14f933 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -134,7 +134,7 @@ private void init() { private void download() { try { - JsonArray languages = JsonParser.parseString(IOUtils.toString(getGitHubUrl("language/languages.json"))).getAsJsonArray(); + JsonArray languages = JsonParser.parseString(IOUtils.toString(getGitHubUrl("language/languages.json"))).getAsJsonArray(); // TODO fix(deps) version ambiguity Logger.debug("Fetched languages {}", languages); for (JsonElement element : languages) { try { @@ -182,7 +182,7 @@ private void readLanguage(@Nonnull File file) { } int messages = 0; - JsonObject read = JsonParser.parseReader(FileUtils.newBufferedReader(file)).getAsJsonObject(); + JsonObject read = JsonParser.parseReader(FileUtils.newBufferedReader(file)).getAsJsonObject(); // TODO fix(deps) version ambiguity for (Entry entry : read.entrySet()) { Message message = Message.forName(entry.getKey()); JsonElement element = entry.getValue(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index b457a897e..17ebf2d92 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -316,7 +316,7 @@ public ItemBuilder.SkullBuilder setBase64Texture(@NonNull String base64Texture) String textureUrlJson = new String(Base64.getDecoder().decode(base64Texture), StandardCharsets.UTF_8); - String textureUrl = JsonParser.parseString(textureUrlJson) + String textureUrl = JsonParser.parseString(textureUrlJson) // TODO fix(deps) version ambiguity .getAsJsonObject() .get("textures").getAsJsonObject() .get("SKIN").getAsJsonObject() diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java index 6b4b393d0..f8f9c2a91 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java @@ -17,7 +17,7 @@ public class PairTypeAdapter implements GsonTypeAdapter { @Override public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Pair object) throws IOException { Object[] values = object.values(); - JsonArray array = new JsonArray(values.length); + JsonArray array = new JsonArray(values.length); // TODO fix(deps) version ambiguity for (Object value : values) { array.add(gson.toJsonTree(value)); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java index ce3988f94..4f7d07eee 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java @@ -118,7 +118,7 @@ public static void setDocumentProperties(@Nonnull Gson gson, @Nonnull JsonObject public static int getSize(@Nonnull JsonObject object) { try { return object.size(); - } catch (NoSuchMethodError ex) { + } catch (NoSuchMethodError ignored) { } return object.entrySet().size(); From 9fcb8881b94cd4aaaa8999dc5c0b9450b660dc98 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Tue, 26 May 2026 20:15:16 +0200 Subject: [PATCH 069/119] refactor: replace deprecated SecurityManager - necessary because SecurityManager was marked for removal in java17, removes all calls to it --- .../common/collection/NamedThreadFactory.java | 5 ++-- .../collection/PublicSecurityManager.java | 12 ---------- .../commons/common/misc/ReflectionUtils.java | 23 ++++++++----------- 3 files changed, 12 insertions(+), 28 deletions(-) delete mode 100644 plugin/src/main/java/net/codingarea/commons/common/collection/PublicSecurityManager.java diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java index 624f2508f..53e228f6a 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java @@ -15,9 +15,8 @@ public class NamedThreadFactory implements ThreadFactory { protected final AtomicInteger threadNumber = new AtomicInteger(1); public NamedThreadFactory(@Nonnull IntFunction nameFunction) { - SecurityManager securityManager = System.getSecurityManager(); - this.group = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup(); - this.nameFunction = nameFunction; + this.group = Thread.currentThread().getThreadGroup(); + this.nameFunction = nameFunction; } public NamedThreadFactory(@Nonnull String prefix) { diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/PublicSecurityManager.java b/plugin/src/main/java/net/codingarea/commons/common/collection/PublicSecurityManager.java deleted file mode 100644 index b561b6bf8..000000000 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/PublicSecurityManager.java +++ /dev/null @@ -1,12 +0,0 @@ -package net.codingarea.commons.common.collection; - -import javax.annotation.Nonnull; - -public class PublicSecurityManager extends SecurityManager { - - @Nonnull - public Class[] getPublicClassContext() { - return getClassContext(); - } - -} diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java index 2c4566199..35a744ed7 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java @@ -106,19 +106,16 @@ public static Iterable iterableArray(@Nonnull Object array) { return ArrayWalker.walk(array); } - @CheckReturnValue - public static Class getCaller(int index) { - try { - return new PublicSecurityManager().getPublicClassContext()[index + 2]; - } catch (Exception ex) { - throw new WrappedException(ex); - } - } - - @CheckReturnValue - public static Class getCaller() { - return getCaller(2); - } + @CheckReturnValue + public static Class getCaller() { + return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE) + .walk(stream -> stream + .skip(2) // skip frame 0 (getCaller) and frame 1 (the intermediate method) + .findFirst() + .map(StackWalker.StackFrame::getDeclaringClass) + .orElseThrow(() -> new IllegalStateException("Stack not deep enough to find caller")) + ); + } @Nonnull public static String getCallerName() { From 9289b2d8648f7cc47c393c172306c875c709cfca Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Tue, 26 May 2026 20:20:03 +0200 Subject: [PATCH 070/119] fix: security manager import oops --- .../java/net/codingarea/commons/common/misc/ReflectionUtils.java | 1 - 1 file changed, 1 deletion(-) diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java index 35a744ed7..c4d997ff9 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java @@ -2,7 +2,6 @@ import net.codingarea.commons.common.collection.ArrayWalker; import net.codingarea.commons.common.collection.ClassWalker; -import net.codingarea.commons.common.collection.PublicSecurityManager; import net.codingarea.commons.common.collection.WrappedException; import javax.annotation.CheckReturnValue; From f9add22cc9b11443a2996058d31cbc0aa408ab91 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Tue, 26 May 2026 23:44:32 +0200 Subject: [PATCH 071/119] style: indent, optimize imports - include .editorconfig --- .editorconfig | 18 + mongo-connector/src/main/resources/plugin.yml | 2 +- .../challenges/plugin/Challenges.java | 5 +- .../challenges/custom/CustomChallenge.java | 2 +- .../custom/settings/CustomSettingsLoader.java | 4 +- .../settings/action/ChallengeAction.java | 2 +- .../settings/action/IChallengeAction.java | 2 +- .../action/impl/BoostEntityInAirAction.java | 2 +- .../action/impl/ChangeWorldBorderAction.java | 2 +- .../action/impl/HealEntityAction.java | 2 +- .../action/impl/PlaceStructureAction.java | 4 +- .../action/impl/SpawnEntityAction.java | 2 +- .../action/impl/SwapRandomMobAction.java | 2 +- .../settings/sub/SubSettingsBuilder.java | 2 +- .../custom/settings/sub/ValueSetting.java | 2 +- .../sub/builder/ValueSubSettingsBuilder.java | 2 +- .../settings/sub/impl/BooleanSetting.java | 2 +- .../settings/sub/impl/ModifierSetting.java | 2 +- .../trigger/impl/EntityDamageTrigger.java | 4 +- .../challenge/DamageTeleportChallenge.java | 2 +- .../challenge/ZeroHeartsChallenge.java | 4 +- .../damage/BlockPlaceDamageChallenge.java | 2 +- .../damage/DeathOnFallChallenge.java | 2 +- .../damage/DelayDamageChallenge.java | 2 +- .../challenge/damage/FreezeChallenge.java | 2 +- .../challenge/damage/JumpDamageChallenge.java | 2 +- .../damage/WaterAllergyChallenge.java | 2 +- .../effect/BlockEffectChallenge.java | 6 +- .../effect/ChunkRandomEffectChallenge.java | 6 +- .../effect/EntityRandomEffectChallenge.java | 2 +- .../PermanentEffectOnDamageChallenge.java | 8 +- .../effect/RandomPotionEffectChallenge.java | 4 +- .../entities/AllMobsToDeathPoint.java | 2 +- .../entities/BlockMobsChallenge.java | 2 +- .../entities/HydraPlusChallenge.java | 2 +- .../entities/InvisibleMobsChallenge.java | 2 +- .../entities/MobSightDamageChallenge.java | 2 +- .../entities/MobTransformationChallenge.java | 2 +- .../entities/MobsRespawnInEndChallenge.java | 6 +- .../entities/NewEntityOnJumpChallenge.java | 2 +- .../entities/StoneSightChallenge.java | 4 +- .../extraworld/JumpAndRunChallenge.java | 4 +- .../challenge/force/ForceBiomeChallenge.java | 4 +- .../challenge/force/ForceBlockChallenge.java | 4 +- .../challenge/force/ForceHeightChallenge.java | 4 +- .../challenge/force/ForceItemChallenge.java | 6 +- .../challenge/force/ForceMobChallenge.java | 2 +- .../inventory/MissingItemsChallenge.java | 12 +- .../MovementItemRemovingChallenge.java | 2 +- .../inventory/NoDupedItemsChallenge.java | 4 +- .../inventory/PermanentItemChallenge.java | 4 +- .../inventory/PickupItemLaunchChallenge.java | 2 +- .../inventory/UncraftItemsChallenge.java | 4 +- .../miscellaneous/EnderGamesChallenge.java | 4 +- .../miscellaneous/FoodLaunchChallenge.java | 2 +- .../miscellaneous/InvertHealthChallenge.java | 4 +- .../miscellaneous/LowDropRateChallenge.java | 2 +- .../NoSharedAdvancementsChallenge.java | 6 +- .../movement/AlwaysRunningChallenge.java | 4 +- .../movement/DontStopRunningChallenge.java | 2 +- .../movement/FiveHundredBlocksChallenge.java | 4 +- .../movement/HungerPerBlockChallenge.java | 2 +- .../challenge/movement/MoveMouseDamage.java | 2 +- .../challenge/movement/OnlyDirtChallenge.java | 2 +- .../challenge/movement/OnlyDownChallenge.java | 2 +- .../movement/TrafficLightChallenge.java | 4 +- .../challenge/quiz/QuizChallenge.java | 12 +- .../randomizer/BlockRandomizerChallenge.java | 4 +- .../EntityLootRandomizerChallenge.java | 2 +- .../randomizer/HotBarRandomizerChallenge.java | 4 +- .../randomizer/MobRandomizerChallenge.java | 4 +- .../randomizer/RandomChallengeChallenge.java | 2 +- .../randomizer/RandomEventChallenge.java | 6 +- .../randomizer/RandomItemChallenge.java | 2 +- .../RandomItemDroppingChallenge.java | 2 +- .../RandomItemRemovingChallenge.java | 2 +- .../RandomItemSwappingChallenge.java | 2 +- .../RandomTeleportOnHitChallenge.java | 2 +- .../randomizer/RandomizedHPChallenge.java | 2 +- .../challenge/time/MaxBiomeTimeChallenge.java | 2 +- .../time/MaxHeightTimeChallenge.java | 2 +- .../world/AllBlocksDisappearChallenge.java | 6 +- .../challenge/world/AnvilRainChallenge.java | 2 +- .../challenge/world/BedrockWallChallenge.java | 2 +- .../world/BlockFlyInAirChallenge.java | 2 +- .../BlocksDisappearAfterTimeChallenge.java | 2 +- .../world/ChunkDeconstructionChallenge.java | 2 +- .../world/ChunkDeletionChallenge.java | 2 +- .../challenge/world/IceFloorChallenge.java | 4 +- .../challenge/world/LevelBorderChallenge.java | 8 +- .../challenge/world/LoopChallenge.java | 8 +- .../world/RepeatInChunkChallenge.java | 10 +- .../challenge/world/SnakeChallenge.java | 2 +- .../challenge/world/SurfaceHoleChallenge.java | 2 +- .../challenge/world/TsunamiChallenge.java | 6 +- .../goal/AllAdvancementGoal.java | 2 +- .../goal/CollectAllItemsGoal.java | 10 +- .../goal/CollectHorseAmorGoal.java | 4 +- .../goal/CollectIceBlocksGoal.java | 2 +- .../goal/CollectMostDeathsGoal.java | 4 +- .../goal/CollectMostExpGoal.java | 2 +- .../goal/CollectMostItemsGoal.java | 2 +- .../goal/CollectSwordsGoal.java | 4 +- .../implementation/goal/CollectWoodGoal.java | 4 +- .../goal/CollectWorkstationsGoal.java | 4 +- .../implementation/goal/EatCakeGoal.java | 2 +- .../implementation/goal/EatMostGoal.java | 2 +- .../implementation/goal/FindElytraGoal.java | 2 +- .../implementation/goal/FinishRaidGoal.java | 4 +- .../goal/FirstOneToDieGoal.java | 2 +- .../goal/GetFullHealthGoal.java | 4 +- .../goal/KillAllBossesGoal.java | 2 +- .../goal/KillAllBossesNewGoal.java | 4 +- .../implementation/goal/KillAllMobsGoal.java | 2 +- .../goal/KillAllMonsterGoal.java | 4 +- .../goal/KillElderGuardianGoal.java | 4 +- .../goal/KillEnderDragonGoal.java | 2 +- .../goal/KillIronGolemGoal.java | 4 +- .../goal/KillSnowGolemGoal.java | 4 +- .../implementation/goal/KillWardenGoal.java | 6 +- .../implementation/goal/KillWitherGoal.java | 2 +- .../goal/LastManStandingGoal.java | 2 +- .../implementation/goal/MaxHeightGoal.java | 2 +- .../implementation/goal/MinHeightGoal.java | 4 +- .../implementation/goal/MostEmeraldsGoal.java | 2 +- .../implementation/goal/MostOresGoal.java | 4 +- .../implementation/goal/RaceGoal.java | 6 +- .../forcebattle/ExtremeForceBattleGoal.java | 6 +- .../ForceAdvancementBattleGoal.java | 6 +- .../forcebattle/ForceBiomeBattleGoal.java | 2 +- .../forcebattle/ForceBlockBattleGoal.java | 4 +- .../forcebattle/ForceDamageBattleGoal.java | 2 +- .../forcebattle/ForceHeightBattleGoal.java | 4 +- .../goal/forcebattle/ForceItemBattleGoal.java | 4 +- .../goal/forcebattle/ForceMobBattleGoal.java | 4 +- .../forcebattle/ForcePositionBattleGoal.java | 2 +- .../forcebattle/targets/PositionTarget.java | 4 +- .../setting/BackpackSetting.java | 4 +- .../setting/BastionSpawnSetting.java | 4 +- .../setting/CutCleanSetting.java | 6 +- .../setting/DamageDisplaySetting.java | 2 +- .../setting/DeathPositionSetting.java | 2 +- .../setting/DifficultySetting.java | 2 +- .../setting/EnderChestCommandSetting.java | 2 +- .../setting/FortressSpawnSetting.java | 2 +- .../setting/HealthDisplaySetting.java | 2 +- .../setting/ImmediateRespawnSetting.java | 2 +- .../setting/MaxHealthSetting.java | 10 +- .../setting/NoOffhandSetting.java | 2 +- .../implementation/setting/OldPvPSetting.java | 4 +- .../setting/PositionSetting.java | 4 +- .../setting/RespawnSetting.java | 2 +- .../setting/SlotLimitSetting.java | 2 +- .../implementation/setting/SoupSetting.java | 2 +- .../setting/SplitHealthSetting.java | 2 +- .../implementation/setting/TimberSetting.java | 4 +- .../setting/TopCommandSetting.java | 2 +- .../setting/TotemSaveDeathSetting.java | 2 +- .../challenges/type/EmptyChallenge.java | 4 +- .../plugin/challenges/type/IChallenge.java | 2 +- .../plugin/challenges/type/IGoal.java | 2 +- .../type/abstraction/AbstractChallenge.java | 6 +- .../abstraction/AbstractForceChallenge.java | 4 +- .../type/abstraction/CollectionGoal.java | 4 +- .../CompletableForceChallenge.java | 2 +- .../abstraction/EndingForceChallenge.java | 2 +- .../abstraction/ForceBattleDisplayGoal.java | 2 +- .../type/abstraction/ForceBattleGoal.java | 6 +- .../type/abstraction/ItemCollectionGoal.java | 2 +- .../type/abstraction/KillMobsGoal.java | 2 +- .../challenges/type/abstraction/MenuGoal.java | 2 +- .../type/abstraction/MenuSetting.java | 10 +- .../challenges/type/abstraction/Modifier.java | 2 +- .../abstraction/ModifierCollectionGoal.java | 2 +- .../abstraction/NetherPortalSpawnSetting.java | 2 +- .../type/abstraction/PointsGoal.java | 2 +- .../type/abstraction/RandomizerSetting.java | 4 +- .../challenges/type/abstraction/Setting.java | 4 +- .../type/abstraction/SettingGoal.java | 2 +- .../type/abstraction/SettingModifier.java | 4 +- .../SettingModifierCollectionGoal.java | 4 +- .../type/abstraction/SettingModifierGoal.java | 2 +- .../type/abstraction/TimedChallenge.java | 4 +- .../abstraction/WorldDependentChallenge.java | 2 +- .../type/helper/ChallengeConfigHelper.java | 2 +- .../type/helper/ChallengeHelper.java | 4 +- .../challenges/type/helper/GoalHelper.java | 2 +- .../type/helper/SubSettingsHelper.java | 6 +- .../plugin/content/ItemDescription.java | 2 +- .../challenges/plugin/content/Message.java | 2 +- .../plugin/content/impl/MessageImpl.java | 4 +- .../plugin/content/loader/LanguageLoader.java | 6 +- .../plugin/content/loader/LoaderRegistry.java | 2 +- .../plugin/content/loader/PrefixLoader.java | 2 +- .../plugin/content/loader/UpdateLoader.java | 2 +- .../management/blocks/BlockDropManager.java | 2 +- .../management/bstats/MetricsLoader.java | 6 +- .../challenges/ChallengeLoader.java | 2 +- .../challenges/ChallengeManager.java | 12 +- .../challenges/CustomChallengesLoader.java | 2 +- .../challenges/ModuleChallengeLoader.java | 6 +- .../management/cloud/CloudSupportManager.java | 6 +- .../management/database/DatabaseManager.java | 4 +- .../management/files/ConfigManager.java | 2 +- .../inventory/PlayerInventoryManager.java | 10 +- .../plugin/management/menu/MenuManager.java | 10 +- .../generator/ChallengeMenuGenerator.java | 10 +- .../menu/generator/ChooseItemGenerator.java | 6 +- .../ChooseMultipleItemGenerator.java | 6 +- .../menu/generator/MenuGenerator.java | 4 +- .../generator/MultiPageMenuGenerator.java | 2 +- .../menu/generator/ValueMenuGenerator.java | 6 +- .../categorised/CategorisedMenuGenerator.java | 4 +- .../implementation/SettingsMenuGenerator.java | 2 +- .../implementation/TimerMenuGenerator.java | 6 +- .../custom/InfoMenuGenerator.java | 8 +- .../custom/MainCustomMenuGenerator.java | 4 +- .../custom/MaterialMenuGenerator.java | 2 +- .../menu/position/GeneratorMenuPosition.java | 2 +- .../management/scheduler/ScheduleManager.java | 4 +- .../scheduler/timer/ChallengeTimer.java | 6 +- .../management/server/GameWorldStorage.java | 2 +- .../server/GeneratorWorldPortalManager.java | 2 +- .../management/server/ServerManager.java | 10 +- .../management/server/TitleManager.java | 2 +- .../management/server/WorldManager.java | 8 +- .../server/scoreboard/ChallengeBossBar.java | 4 +- .../scoreboard/ChallengeScoreboard.java | 4 +- .../plugin/management/stats/StatsManager.java | 4 +- .../plugin/management/team/TeamProvider.java | 1 - .../spigot/command/DatabaseCommand.java | 4 +- .../spigot/command/GamestateCommand.java | 2 +- .../plugin/spigot/command/HealCommand.java | 2 +- .../plugin/spigot/command/InvseeCommand.java | 4 +- .../spigot/command/LeaderboardCommand.java | 8 +- .../plugin/spigot/command/ResetCommand.java | 4 +- .../plugin/spigot/command/ResultCommand.java | 2 +- .../plugin/spigot/command/SearchCommand.java | 4 +- .../plugin/spigot/command/StatsCommand.java | 6 +- .../plugin/spigot/command/TimeCommand.java | 2 +- .../plugin/spigot/command/TimerCommand.java | 4 +- .../plugin/spigot/command/VillageCommand.java | 2 +- .../spigot/listener/BlockDropListener.java | 4 +- .../plugin/spigot/listener/CheatListener.java | 2 +- .../spigot/listener/CustomEventListener.java | 2 +- .../listener/PlayerConnectionListener.java | 6 +- .../utils/bukkit/command/PlayerCommand.java | 2 +- .../utils/bukkit/command/SenderCommand.java | 2 +- .../utils/bukkit/misc/BukkitStringUtils.java | 20 +- .../plugin/utils/bukkit/nms/NMSProvider.java | 2 +- .../plugin/utils/item/ItemBuilder.java | 2 +- .../plugin/utils/misc/DatabaseHelper.java | 2 +- .../plugin/utils/misc/InventoryUtils.java | 8 +- .../plugin/utils/misc/MapUtils.java | 2 +- .../utils/misc/MinecraftNameWrapper.java | 2 +- .../plugin/utils/misc/StatsHelper.java | 2 +- .../commons/bukkit/core/BukkitModule.java | 665 +++++----- .../bukkit/core/RequirementsChecker.java | 142 +-- .../bukkit/core/SimpleConfigManager.java | 57 +- .../utils/animation/AnimatedInventory.java | 299 ++--- .../utils/animation/AnimationFrame.java | 140 +-- .../bukkit/utils/animation/SoundSample.java | 196 +-- .../utils/bstats/JsonObjectBuilder.java | 392 +++--- .../commons/bukkit/utils/bstats/Metrics.java | 578 ++++----- .../utils/bstats/chart/AdvancedBarChart.java | 68 +- .../utils/bstats/chart/AdvancedPie.java | 68 +- .../utils/bstats/chart/CustomChart.java | 54 +- .../utils/bstats/chart/DrilldownPie.java | 76 +- .../utils/bstats/chart/MultiLineChart.java | 68 +- .../utils/bstats/chart/SimpleBarChart.java | 48 +- .../bukkit/utils/bstats/chart/SimplePie.java | 40 +- .../utils/bstats/chart/SingleLineChart.java | 40 +- .../bukkit/utils/item/BannerPattern.java | 100 +- .../bukkit/utils/item/ItemBuilder.java | 798 ++++++------ .../commons/bukkit/utils/item/ItemUtils.java | 190 +-- .../commons/bukkit/utils/logging/Logger.java | 41 +- .../bukkit/utils/menu/MenuClickInfo.java | 100 +- .../bukkit/utils/menu/MenuPosition.java | 39 +- .../bukkit/utils/menu/MenuPositionHolder.java | 10 +- .../utils/menu/MenuPositionListener.java | 38 +- .../menu/positions/EmptyMenuPosition.java | 8 +- .../menu/positions/SlottedMenuPosition.java | 68 +- .../utils/misc/BukkitReflectionUtils.java | 290 ++--- .../bukkit/utils/misc/GameProfileUtils.java | 145 +-- .../bukkit/utils/misc/MinecraftVersion.java | 206 ++-- .../bukkit/utils/wrapper/ActionListener.java | 86 +- .../bukkit/utils/wrapper/MaterialWrapper.java | 19 +- .../utils/wrapper/SimpleEventExecutor.java | 30 +- .../common/annotations/AlsoKnownAs.java | 4 +- .../common/annotations/DeprecatedSince.java | 4 +- .../common/annotations/ReplaceWith.java | 4 +- .../commons/common/annotations/Since.java | 4 +- .../common/collection/ArrayWalker.java | 91 +- .../common/collection/ClassWalker.java | 88 +- .../commons/common/collection/Colors.java | 50 +- .../common/collection/FontBuilder.java | 160 +-- .../commons/common/collection/IOUtils.java | 55 +- .../commons/common/collection/IRandom.java | 204 ++-- .../common/collection/NamedThreadFactory.java | 42 +- .../common/collection/NumberFormatter.java | 690 +++++------ .../common/collection/RandomWrapper.java | 276 ++--- .../common/collection/RomanNumerals.java | 77 +- .../common/collection/RunnableTimerTask.java | 16 +- .../collection/SeededRandomWrapper.java | 48 +- .../common/collection/SingletonRandom.java | 8 +- .../collection/StringBuilderPrintWriter.java | 26 +- .../collection/StringBuilderWriter.java | 108 +- .../commons/common/collection/Triple.java | 10 +- .../commons/common/collection/Tuple.java | 10 +- .../common/collection/WrappedException.java | 98 +- .../commons/common/collection/pair/Pair.java | 30 +- .../common/collection/pair/Quadro.java | 250 ++-- .../common/collection/pair/Triple.java | 212 ++-- .../commons/common/collection/pair/Tuple.java | 180 +-- .../cache/CleanAndWriteDatabaseCache.java | 185 +-- .../concurrent/cache/CleanWriteableCache.java | 103 +- .../concurrent/cache/CoolDownCache.java | 130 +- .../concurrent/cache/DatabaseCache.java | 7 +- .../common/concurrent/cache/ICache.java | 27 +- .../concurrent/cache/WriteableCache.java | 6 +- .../concurrent/task/CompletableTask.java | 310 ++--- .../common/concurrent/task/CompletedTask.java | 194 +-- .../commons/common/concurrent/task/Task.java | 410 +++---- .../common/concurrent/task/TaskListener.java | 12 +- .../commons/common/config/Config.java | 157 ++- .../commons/common/config/Document.java | 630 +++++----- .../commons/common/config/FileDocument.java | 303 +++-- .../commons/common/config/Json.java | 70 +- .../commons/common/config/PropertyHelper.java | 59 +- .../commons/common/config/Propertyable.java | 226 ++-- .../config/document/AbstractConfig.java | 514 ++++---- .../config/document/AbstractDocument.java | 282 ++--- .../common/config/document/EmptyDocument.java | 986 +++++++-------- .../common/config/document/GsonDocument.java | 958 +++++++-------- .../common/config/document/MapDocument.java | 530 ++++---- .../config/document/PropertiesDocument.java | 516 ++++---- .../common/config/document/YamlDocument.java | 652 +++++----- ...kkitReflectionSerializableTypeAdapter.java | 58 +- .../document/gson/ClassTypeAdapter.java | 28 +- .../document/gson/ColorTypeAdapter.java | 20 +- .../document/gson/DocumentTypeAdapter.java | 58 +- .../config/document/gson/GsonTypeAdapter.java | 88 +- .../config/document/gson/PairTypeAdapter.java | 42 +- .../readonly/ReadOnlyDocumentWrapper.java | 24 +- .../document/wrapper/FileDocumentWrapper.java | 96 +- .../document/wrapper/WrappedDocument.java | 970 +++++++-------- .../exceptions/ConfigReadOnlyException.java | 6 +- .../commons/common/debug/TimingsHelper.java | 73 +- .../common/discord/DiscordWebhook.java | 956 +++++++-------- .../function/ExceptionallyBiConsumer.java | 18 +- .../function/ExceptionallyBiFunction.java | 18 +- .../function/ExceptionallyConsumer.java | 18 +- .../function/ExceptionallyDoubleFunction.java | 18 +- .../function/ExceptionallyFunction.java | 28 +- .../function/ExceptionallyIntFunction.java | 18 +- .../function/ExceptionallyLongFunction.java | 18 +- .../function/ExceptionallyRunnable.java | 28 +- .../function/ExceptionallySupplier.java | 26 +- .../ExceptionallyToDoubleFunction.java | 18 +- .../function/ExceptionallyToIntFunction.java | 18 +- .../function/ExceptionallyToLongFunction.java | 18 +- .../commons/common/logging/ILogger.java | 511 ++++---- .../common/logging/ILoggerFactory.java | 6 +- .../commons/common/logging/LogLevel.java | 126 +- .../common/logging/LogOutputStream.java | 28 +- .../common/logging/LoggingApiUser.java | 56 +- .../common/logging/WrappedILogger.java | 294 ++--- .../logging/handler/HandledAsyncLogger.java | 16 +- .../common/logging/handler/HandledLogger.java | 90 +- .../logging/handler/HandledSyncLogger.java | 14 +- .../common/logging/handler/LogEntry.java | 76 +- .../common/logging/handler/LogHandler.java | 4 +- .../logging/internal/BukkitLoggerWrapper.java | 20 +- .../logging/internal/FallbackLogger.java | 92 +- .../logging/internal/JavaLoggerWrapper.java | 770 ++++++------ .../common/logging/internal/SimpleLogger.java | 704 +++++------ .../logging/internal/Slf4jILoggerWrapper.java | 322 ++--- .../logging/internal/Slf4jLoggerWrapper.java | 708 +++++------ .../factory/ConstantLoggerFactory.java | 32 +- .../factory/DefaultLoggerFactory.java | 38 +- .../internal/factory/Slf4jLoggerFactory.java | 20 +- .../common/logging/lib/JavaILogger.java | 12 +- .../common/logging/lib/Slf4jILogger.java | 40 +- .../BukkitReflectionSerializationUtils.java | 176 +-- .../commons/common/misc/FileUtils.java | 1071 +++++++++-------- .../commons/common/misc/GsonUtils.java | 221 ++-- .../commons/common/misc/ImageUtils.java | 177 ++- .../commons/common/misc/MathHelper.java | 11 +- .../commons/common/misc/PropertiesUtils.java | 13 +- .../commons/common/misc/ReflectionUtils.java | 436 ++++--- .../common/misc/SimpleCollectionUtils.java | 257 ++-- .../commons/common/misc/StringUtils.java | 337 +++--- .../commons/common/version/Version.java | 182 +-- .../common/version/VersionComparator.java | 8 +- .../commons/common/version/VersionInfo.java | 137 ++- .../codingarea/commons/database/Database.java | 185 ++- .../commons/database/DatabaseConfig.java | 192 +-- .../commons/database/EmptyDatabase.java | 546 ++++----- .../codingarea/commons/database/Order.java | 4 +- .../commons/database/SQLColumn.java | 288 +++-- .../database/SimpleDatabaseTypeResolver.java | 54 +- .../commons/database/SpecificDatabase.java | 82 +- .../abstraction/AbstractDatabase.java | 170 +-- .../abstraction/DefaultExecutedQuery.java | 218 ++-- .../abstraction/DefaultSpecificDatabase.java | 156 +-- .../database/access/CachedDatabaseAccess.java | 134 +-- .../database/access/DatabaseAccess.java | 28 +- .../database/access/DatabaseAccessConfig.java | 48 +- .../database/access/DirectDatabaseAccess.java | 94 +- .../database/action/DatabaseAction.java | 75 +- .../database/action/DatabaseCountEntries.java | 8 +- .../database/action/DatabaseDeletion.java | 36 +- .../database/action/DatabaseInsertion.java | 12 +- .../action/DatabaseInsertionOrUpdate.java | 42 +- .../database/action/DatabaseListTables.java | 6 +- .../database/action/DatabaseQuery.java | 64 +- .../database/action/DatabaseUpdate.java | 42 +- .../database/action/ExecutedQuery.java | 98 +- .../action/hierarchy/OrderedAction.java | 4 +- .../database/action/hierarchy/SetAction.java | 4 +- .../action/hierarchy/WhereAction.java | 30 +- .../DatabaseAlreadyConnectedException.java | 6 +- .../DatabaseConnectionClosedException.java | 6 +- .../exceptions/DatabaseException.java | 25 +- .../DatabaseUnsupportedFeatureException.java | 10 +- .../exceptions/UnsignedDatabaseException.java | 17 +- .../sql/abstraction/AbstractSQLDatabase.java | 218 ++-- .../database/sql/abstraction/SQLHelper.java | 40 +- .../abstraction/count/SQLCountEntries.java | 80 +- .../sql/abstraction/deletion/SQLDeletion.java | 180 +-- .../abstraction/insertion/SQLInsertion.java | 138 +-- .../insertorupdate/SQLInsertionOrUpdate.java | 116 +- .../sql/abstraction/query/SQLQuery.java | 302 ++--- .../sql/abstraction/query/SQLResult.java | 32 +- .../sql/abstraction/update/SQLUpdate.java | 240 ++-- .../sql/abstraction/where/ObjectWhere.java | 68 +- .../sql/abstraction/where/SQLWhere.java | 8 +- .../where/StringIgnoreCaseWhere.java | 64 +- .../database/sql/mysql/MySQLDatabase.java | 46 +- .../sql/mysql/list/MySQLListTables.java | 44 +- .../database/sql/sqlite/SQLiteDatabase.java | 72 +- .../sql/sqlite/list/SQLiteListTables.java | 44 +- 442 files changed, 15094 insertions(+), 14993 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..775e81932 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,18 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file +root = true + +# All files +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 2 +max_line_length = 120 + +# Markdown files +[*.md] +trim_trailing_whitespace = false diff --git a/mongo-connector/src/main/resources/plugin.yml b/mongo-connector/src/main/resources/plugin.yml index 0b4173ff6..a31f0c1c7 100644 --- a/mongo-connector/src/main/resources/plugin.yml +++ b/mongo-connector/src/main/resources/plugin.yml @@ -8,4 +8,4 @@ main: net.codingarea.challenges.mongoconnector.MongoConnector depend: - Challenges description: | - Provides the needed depedencies to the ChallengesPlugin to conntent to a MongoDB database + Provides the needed dependencies to the ChallengesPlugin to connect to a MongoDB database diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java index 2b6ce2984..4ffa641df 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java @@ -1,8 +1,6 @@ package net.codingarea.challenges.plugin; import lombok.Getter; -import net.codingarea.commons.bukkit.core.BukkitModule; -import net.codingarea.commons.common.version.Version; import net.codingarea.challenges.plugin.challenges.custom.settings.CustomSettingsLoader; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.content.loader.LoaderRegistry; @@ -26,9 +24,10 @@ import net.codingarea.challenges.plugin.spigot.command.*; import net.codingarea.challenges.plugin.spigot.listener.*; import net.codingarea.challenges.plugin.utils.bukkit.command.ForwardingCommand; +import net.codingarea.commons.bukkit.core.BukkitModule; +import net.codingarea.commons.common.version.Version; import javax.annotation.Nonnull; -import java.io.File; @Getter public final class Challenges extends BukkitModule { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index e8a2e9237..99f35dacf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -2,7 +2,6 @@ import lombok.Getter; import lombok.ToString; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; @@ -12,6 +11,7 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.InfoMenuGenerator; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java index 1cc84980d..e2ec9446a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java @@ -1,14 +1,14 @@ package net.codingarea.challenges.plugin.challenges.custom.settings; import lombok.Getter; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.*; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.impl.*; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Bukkit; import javax.annotation.Nullable; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java index d808902a1..3a29e4797 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action; -import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.collection.IRandom; import org.bukkit.inventory.ItemStack; import java.util.LinkedHashMap; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java index 22194c0dd..d8dce1044 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/IChallengeAction.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action; -import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; +import net.codingarea.commons.common.collection.IRandom; import java.util.Map; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java index 20915daf0..150f374be 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.util.Vector; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java index bb6e2ecf7..4c3ada6e8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.WorldBorder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java index 76de8e406..d41647df9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java @@ -2,10 +2,10 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Entity; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java index f370a9651..68d127520 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.challenges.custom.settings.FallbackNames; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.collection.IRandom; import org.bukkit.*; import org.bukkit.entity.Entity; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java index f51cddf9d..0e8acac10 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; +import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Entity; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java index 1c967aab1..cdaba090a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; -import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import net.codingarea.challenges.plugin.challenges.custom.settings.action.IEntityTargetAction; import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.RandomTeleportOnHitChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; +import net.codingarea.commons.common.collection.IRandom; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Entity; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java index 76dbdf823..4c1946bc2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub; import lombok.Getter; -import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.*; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.impl.MessageManager; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; +import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.entity.Player; import org.bukkit.event.player.AsyncPlayerChatEvent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java index 2ba7ab835..e6fab4a2a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub; import lombok.Getter; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; public abstract class ValueSetting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java index 5ed694708..34bd817de 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java @@ -2,7 +2,6 @@ import com.google.common.collect.Lists; import lombok.Getter; -import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl.BooleanSetting; @@ -13,6 +12,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.SubSettingValueMenuGenerator; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.entity.Player; import java.util.LinkedHashMap; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java index 48623e544..249c1f8ef 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; public class BooleanSetting extends ValueSetting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java index 93269312d..6165ac9d5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import java.util.function.Function; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java index a0ca61a73..80d8ff77c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.trigger.impl; -import net.codingarea.commons.bukkit.utils.item.ItemBuilder.PotionBuilder; -import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java index 01256bb88..fdaedc626 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index 3a394f7c5..4aed4f536 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.implementation.setting.MaxHealthSetting; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; @@ -8,9 +7,10 @@ import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java index b1688facf..1bfef2206 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.block.BlockPlaceEvent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java index 1fe1e8ac6..963f0126c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java index 24614d601..a85704c62 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java index 5c5e8222f..0d93ac66d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java index 67f64d91f..375f55d66 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -11,6 +10,7 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.LeatherArmorBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java index 39056f367..ea80f79be 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java index 9857ad5a2..1e278c99a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.collection.IRandom; -import net.codingarea.commons.common.collection.SeededRandomWrapper; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -14,6 +11,9 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.collection.SeededRandomWrapper; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java index 30b0a6d39..d7ebb1bc5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.collection.IRandom; -import net.codingarea.commons.common.collection.SeededRandomWrapper; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -11,6 +8,9 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.collection.SeededRandomWrapper; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java index b140744a9..2251648dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java index 5b7ebeaa8..ae02128f1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java @@ -1,9 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.collection.pair.Tuple; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -16,6 +12,10 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.TriConsumer; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Tuple; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index 5b15d051e..ce4f1bae5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -9,6 +7,8 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java index f7ed9e957..5a7361d9e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDeathByPlayerEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.*; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java index 01cb2af32..f8cf8656d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomMobAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java index e82b06d22..399cd242e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.HydraChallenge; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java index 0d9df9a5a..75131b7bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -10,6 +9,7 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.World; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java index 064c9b2c5..beb3f0121 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java index e87867380..85207883c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDamageByPlayerEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.EnderDragon; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java index b11f85864..76ae0acce 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -11,6 +8,9 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDeathByPlayerEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java index 08491be15..8f855b4fb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomMobAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -9,6 +8,7 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.LeatherArmorBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java index f91b95b93..85df80778 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java index bfa6fc65d..805956ebc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.extraworld; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.WorldDependentChallenge; @@ -20,6 +18,8 @@ import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java index 26a31ea9b..0c71dd962 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -14,6 +12,8 @@ import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.Registry; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java index 85ae08737..a77dfaac2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.codingarea.commons.bukkit.utils.item.ItemUtils; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -15,6 +13,8 @@ import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java index fd61eda4b..94b15fe80 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -13,6 +11,8 @@ import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java index 261f26e45..60bcf0cd2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.codingarea.commons.bukkit.utils.item.ItemUtils; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -18,6 +15,9 @@ import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.boss.BarColor; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java index 47074dea0..6648251b3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.force; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -13,6 +12,7 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.Utils; +import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java index 8e7ad6ab9..858bdb9a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java @@ -1,11 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.item.ItemUtils; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -18,6 +12,12 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Tuple; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ClickEvent.Action; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java index 3a9dbd54e..b62474076 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -10,6 +9,7 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java index fe6b3f63c..b7161917e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.collection.pair.Triple; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -13,6 +11,8 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Triple; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java index 6b86b70af..1c4a905f5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java index 486f05d40..e67b49fac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -9,6 +8,7 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java index 7c3ddab89..ec0702a0e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 899c446cc..b1b4413f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java index d43893978..759248d1b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java index 5c22246d4..203e34b53 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -9,6 +7,8 @@ import net.codingarea.challenges.plugin.management.challenges.annotations.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java index 5cf2c4414..3d162e60c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -9,6 +8,7 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java index 188c7dbb5..e05f5f2ad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.advancement.Advancement; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java index 5f2beb3a0..2c30ec4cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.util.Vector; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java index c56645114..4be9cb7ab 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -9,6 +8,7 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java index 25ec885dc..4fc5a6a4a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -12,6 +10,8 @@ import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java index 8b1b57f9b..40713305b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java index bc8eb2b81..1abfdcb3b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -11,6 +10,7 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java index 779262f1c..b332c98e2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -10,6 +9,7 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java index fb7817f69..39c551b80 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -9,6 +8,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java index 7b3a20314..c783eeed8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -11,6 +9,8 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index 90b44a7e9..3427176da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -1,10 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.quiz; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.collection.IRandom; -import net.codingarea.commons.common.config.Document; -import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.implementation.challenge.quiz.QuizChallenge.IQuestion.Question; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; @@ -15,11 +10,16 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.TriFunction; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; import org.bukkit.boss.BarColor; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java index ae3433268..ad6e77487 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.codingarea.commons.bukkit.utils.item.ItemUtils; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; import net.codingarea.challenges.plugin.content.Message; @@ -10,6 +8,8 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.Material; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java index 659d6be31..df0d4f0ad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; import net.codingarea.challenges.plugin.content.Message; @@ -12,6 +11,7 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; import net.codingarea.challenges.plugin.utils.misc.Utils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 32c31c8f6..4005ed489 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -12,6 +10,8 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java index aff8383d1..6384de216 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; @@ -12,6 +10,8 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java index 16f8537a3..b62eb3380 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; @@ -13,6 +12,7 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java index f378b2c0c..69eab970a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -11,6 +8,9 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java index 55820aaee..521532871 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomItemAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java index b7e3a964e..3fad92fd6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java index cf96f92f3..3e23a4503 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java index 33ded8246..079e2261d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java index cdc626c77..87e30ab43 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDamageByPlayerEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java index b1686d8a2..c475ceca6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java @@ -6,9 +6,9 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java index fcd1ae478..f384b6fa6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.time; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.block.Biome; import org.bukkit.boss.BarColor; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java index 515636263..31fad03db 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.time; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.boss.BarColor; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java index 116e3760e..1052de3c1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeConfigHelper; @@ -12,6 +9,9 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java index 9ea5570da..cdd70b0be 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -10,6 +9,7 @@ import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; import net.codingarea.challenges.plugin.management.stats.Statistic.Display; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.entity.*; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java index 00369062f..805ef6538 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java index 61a77a830..16233d54c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java index f86204b47..f3576ab03 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java index 2e1c5c8a3..155bed1ef 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -9,6 +8,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.*; import org.bukkit.block.Block; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java index b17959b79..089e818d1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.collection.pair.Tuple; import org.bukkit.*; import org.bukkit.World.Environment; import org.bukkit.block.Block; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java index b3c46958b..02e222ae8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java index e615d4b96..d6ee2489a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java @@ -1,9 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.config.Document; -import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; @@ -18,6 +14,10 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.NMSProvider; import net.codingarea.challenges.plugin.utils.bukkit.nms.type.PacketBorder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import org.bukkit.*; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index 000dea1ee..5c8e95f0c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -13,9 +10,12 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java index a0b2dc226..426e596fb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java @@ -1,11 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import com.google.common.collect.Lists; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.collection.pair.Triple; -import net.codingarea.commons.common.config.Document; -import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -13,6 +8,11 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.pair.Triple; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index 28ae22550..a1147e49a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -9,6 +8,7 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java index 92e6e160c..9c72132df 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java index 127b856eb..7611270ac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -11,6 +8,9 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java index ee0c8ee49..ad6b21b80 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.advancement.Advancement; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index 303b56631..9337fceff 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -1,11 +1,6 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import lombok.Getter; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.item.ItemUtils; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.collection.SeededRandomWrapper; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; @@ -17,6 +12,11 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.SeededRandomWrapper; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.command.CommandSender; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java index ff3a3e747..51d16ad5c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java index 1631103ae..d1841ba32 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java index e2e7cbffe..3f95511a3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.CollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.entity.EntityDamageEvent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java index 2e710b704..acaca9793 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java index 1e28b334f..79a48eca9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.CollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.item.ItemUtils; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java index c371f63f5..e607eb32a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java index d0c36d32b..462b7d395 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -13,6 +11,8 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java index 8027dc78b..539e927a7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java index 2fa73fcf7..81de60ac2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java index e84756f69..14b2a0bb5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java index 00a768f51..a304a9a1f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.FindItemGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java index 394272035..970cf6ff4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; @@ -9,6 +7,8 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.Raid.RaidStatus; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java index bd79ebbed..cb582ec83 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index aa3ed1570..eb81fb0f1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -8,8 +7,9 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java index 170fb80ac..2b6640616 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java index 376d625c3..4e20f659b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java index 0b97d4274..b6fb7bb9e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java index eed2c9d87..5cedfaa6e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.bukkit.entity.Monster; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java index 4a1cb5ac5..311a93954 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java index 3aa197d2f..e7a6a4238 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Material; import org.bukkit.World.Environment; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java index f84395c18..56ce69182 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java index 6fd97c7be..606e9d077 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.Sound; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java index e98c71fbf..41d975a97 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java index 551b46b8f..c16fdc86c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java index 0834bea22..4a686f4fb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java index 16a7bb90f..f87686d2d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.FirstPlayerAtHeightGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.World.Environment; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java index e27fb4c3a..0af817a88 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.FirstPlayerAtHeightGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.World.Environment; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java index b4405e994..74c28a5f1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java index d63c7a93f..4a359c706 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java index ed4f63bf3..0e0916922 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.collection.IRandom; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierGoal; @@ -18,6 +15,9 @@ import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.config.Document; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java index 7e8908424..722351c55 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.*; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; @@ -14,6 +11,9 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.NamespacedKey; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java index bd9a823b7..cf4e3b33c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.AdvancementTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.NamespacedKey; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java index 783e07722..6ad34836d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.BiomeTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.Registry; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java index b2764d8ae..3a03236ea 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.BlockTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.content.Message; @@ -9,6 +7,8 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java index 9f5519808..949179a96 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.DamageTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java index 399dbb267..a20a8c3a4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.HeightTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java index 826021f01..d0bbaec8c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ItemTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.content.Message; @@ -9,6 +7,8 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java index 3325a2396..8c6cc344f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.codingarea.commons.common.annotations.Since; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.MobTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; +import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java index 5e9a2c85e..96ec11574 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.PositionTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java index 524057bd7..43b898f20 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; +import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; +import net.codingarea.challenges.plugin.content.Message; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.commons.common.config.Document; -import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.Message; import org.bukkit.Location; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java index 3b02b1a14..3835b6613 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; @@ -15,6 +13,8 @@ import net.codingarea.challenges.plugin.utils.bukkit.container.BukkitSerialization; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java index 3c062bb33..1fcf74c13 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.NetherPortalSpawnSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.StructureType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java index c30223490..a56afac9c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.item.ItemUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -14,6 +11,9 @@ import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.Utils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java index 303ddf53a..f16116bdd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -10,6 +9,7 @@ import net.codingarea.challenges.plugin.management.stats.Statistic.Display; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java index f0e163278..d1eca389f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java index f6368a423..80ebdf9d4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -12,6 +11,7 @@ import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import net.codingarea.commons.common.config.Document; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.TranslatableComponent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java index 551859310..9f8a5b96b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java index f4abafbc2..5fa357f75 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.NetherPortalSpawnSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.StructureType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java index e1134eb6c..33e30529e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java index 088db39dc..c5553bb88 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.GameRule; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index 68ca3bde3..116c77d08 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -1,16 +1,16 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.bukkit.utils.wrapper.MaterialWrapper; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.config.Document; -import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; +import net.codingarea.commons.bukkit.utils.wrapper.MaterialWrapper; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java index 23be5b36a..79fd3de5c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java index 054dd292d..43b96aaa3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java index c1b1ce733..04770c37a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; @@ -15,6 +13,8 @@ import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; import net.codingarea.challenges.plugin.utils.misc.Utils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import org.bukkit.*; import org.bukkit.Particle.DustOptions; import org.bukkit.World.Environment; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java index 4be83995e..3fbd01b29 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; @@ -10,6 +9,7 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java index 6b3f76e71..56c86ecdb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.content.Message; @@ -10,6 +9,7 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java index 3881c0cc2..0c4e9861a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index da91a8eef..95cf0c17b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -4,9 +4,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java index c4bc864bf..df36636db 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.bukkit.utils.item.ItemUtils; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -10,6 +8,8 @@ import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java index 627bd099e..d53d47855 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java index 74bd86114..1d0c39ec4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java index 4ef7440cc..8b3be4c54 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.type; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java index 506d29f1c..6ef245016 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.type; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.challenges.ChallengeManager; import net.codingarea.challenges.plugin.management.challenges.entities.GamestateSaveable; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; +import net.codingarea.commons.common.config.Document; import org.bukkit.inventory.ItemStack; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java index 6f597140d..d2cc2ab81 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.challenges.type; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.challenges.ChallengeManager; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.entity.Player; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java index 35838577d..f9008203f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java @@ -2,9 +2,6 @@ import lombok.Getter; import lombok.Setter; -import net.codingarea.commons.common.annotations.DeprecatedSince; -import net.codingarea.commons.common.collection.IRandom; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; @@ -14,6 +11,9 @@ import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeScoreboard; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.annotations.DeprecatedSince; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java index 102977b53..fd1dd34ec 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import lombok.Setter; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java index 2ad3bacf4..b41c1eaed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java index 0c2ef8b48..09e28abda 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.entity.Player; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java index 4c29f8444..53543adbe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Bukkit; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java index b92624eed..139d16b87 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ForceTarget; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; +import net.codingarea.commons.common.config.Document; import org.bukkit.World; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java index 0ff8f60b3..4fa3c78f2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.config.Document; -import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ForceTarget; import net.codingarea.challenges.plugin.content.Message; @@ -16,6 +13,9 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.document.GsonDocument; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java index aeec44b76..b4cb0fcae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java index 5b10af2c1..667eb7ba6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; +import net.codingarea.commons.common.config.Document; import org.bukkit.boss.BarColor; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java index 11da3d1d0..abe1efc1e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java index b2d8270ff..96eff4212 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java @@ -1,11 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import lombok.Getter; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import net.codingarea.commons.bukkit.utils.menu.positions.EmptyMenuPosition; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; @@ -15,6 +10,11 @@ import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.positions.EmptyMenuPosition; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java index e6676859a..97dd509a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java index c656d0ff7..ddced796e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; +import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java index 5fc09751b..ccf50eede 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.commons.common.config.Document; import org.bukkit.*; import org.bukkit.World.Environment; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java index 58a57c890..122f82ffd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; +import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.config.Document; -import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import org.bukkit.entity.Player; import javax.annotation.CheckReturnValue; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java index 29a6f6e87..5ba7d94c8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.collection.SeededRandomWrapper; import net.codingarea.commons.common.config.Document; -import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java index 3539e476a..6ee50fc3e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java index 92721607a..43f9bea9f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import javax.annotation.Nonnull; import javax.annotation.Nullable; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java index 7d407578f..123453845 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import org.bukkit.inventory.ItemStack; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java index 75f07e057..8945fef12 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import org.bukkit.inventory.ItemStack; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java index aab2ddca6..ceea748b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import javax.annotation.Nonnull; import javax.annotation.Nullable; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java index a4255303a..b1c6931c6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import lombok.Setter; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java index 6e57cc5c5..293b72f9f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.server.WorldManager.WorldSettings; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.GameMode; import org.bukkit.World; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java index cc59d1b49..4c992555a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.helper; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.commons.common.config.Document; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index 7cfd70ce4..f5d4c9b7c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -1,8 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.helper; import lombok.Getter; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; @@ -16,6 +14,8 @@ import net.codingarea.challenges.plugin.management.menu.generator.ChallengeMenuGenerator; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java index 1051d797c..01db8cb5f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.challenges.type.helper; -import net.codingarea.commons.common.collection.NumberFormatter; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeScoreboard.ScoreboardInstance; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.common.collection.NumberFormatter; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java index f4dfa9226..ebd859b38 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.challenges.type.helper; -import net.codingarea.commons.bukkit.utils.item.ItemBuilder.PotionBuilder; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.ChooseItemSubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.ChooseMultipleItemSubSettingBuilder; @@ -12,6 +9,9 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.StructureUtils; +import net.codingarea.commons.bukkit.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Material; import org.bukkit.StructureType; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java index 9ea299e7f..69cdcba2e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.content; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.misc.ColorConversions; +import net.codingarea.commons.common.config.Document; import org.bukkit.ChatColor; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java index a7266d1a8..cef0c1b7e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.content; +import net.codingarea.challenges.plugin.content.impl.MessageManager; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.collection.IRandom; -import net.codingarea.challenges.plugin.content.impl.MessageManager; import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java index bbef01e1d..77acaf2ee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.content.impl; -import net.codingarea.commons.common.collection.IRandom; -import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.ItemDescription; import net.codingarea.challenges.plugin.content.Message; @@ -9,6 +7,8 @@ import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.misc.FontUtils; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.misc.StringUtils; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index c1e14f933..86404acea 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -5,15 +5,15 @@ import com.google.gson.JsonObject; import com.google.gson.JsonParser; import lombok.Getter; +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.collection.IOUtils; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.FileDocument; import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.commons.common.misc.GsonUtils; -import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; import javax.annotation.Nonnull; import java.io.File; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java index 05a44760a..c6a63dd50 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.content.loader; -import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; +import net.codingarea.commons.bukkit.utils.logging.Logger; import javax.annotation.Nonnull; import java.util.*; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java index 0cf9321b8..cd8d446a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.content.loader; +import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.config.FileDocument; import net.codingarea.commons.common.misc.FileUtils; -import net.codingarea.challenges.plugin.content.Prefix; import java.io.File; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java index 129814eb0..f39f9e6d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/UpdateLoader.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.content.loader; import lombok.Getter; +import net.codingarea.challenges.plugin.Challenges; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.collection.IOUtils; import net.codingarea.commons.common.version.Version; -import net.codingarea.challenges.plugin.Challenges; import org.bukkit.configuration.file.YamlConfiguration; import java.net.URL; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java index 6d9734968..626a1ef2f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.management.blocks; -import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.challenges.implementation.setting.CutCleanSetting; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting.SubSetting; +import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.inventory.ItemStack; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java index 92bd18d14..b4156cb93 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.management.bstats; +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.loader.LanguageLoader; +import net.codingarea.challenges.plugin.utils.misc.MemoryConverter; import net.codingarea.commons.bukkit.utils.bstats.Metrics; import net.codingarea.commons.bukkit.utils.bstats.chart.AdvancedPie; import net.codingarea.commons.bukkit.utils.bstats.chart.SimplePie; import net.codingarea.commons.bukkit.utils.bstats.chart.SingleLineChart; import net.codingarea.commons.common.misc.StringUtils; -import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.loader.LanguageLoader; -import net.codingarea.challenges.plugin.utils.misc.MemoryConverter; import java.util.HashMap; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java index cf5b7a59a..4848e8820 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.management.challenges; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.implementation.challenge.damage.*; import net.codingarea.challenges.plugin.challenges.implementation.challenge.effect.*; @@ -20,6 +19,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.setting.*; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; import net.codingarea.challenges.plugin.utils.misc.ArmorUtils; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Material; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java index da5245eac..40943b7cd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java @@ -1,17 +1,17 @@ package net.codingarea.challenges.plugin.management.challenges; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.common.config.Document; -import net.codingarea.commons.common.config.FileDocument; -import net.codingarea.commons.common.config.document.GsonDocument; -import net.codingarea.commons.common.config.document.wrapper.FileDocumentWrapper; -import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.management.challenges.entities.GamestateSaveable; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.wrapper.FileDocumentWrapper; +import net.codingarea.commons.database.exceptions.DatabaseException; import org.bukkit.entity.Player; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java index 4696a756d..6fd7fc5e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java @@ -1,7 +1,6 @@ package net.codingarea.challenges.plugin.management.challenges; import lombok.Getter; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; @@ -12,6 +11,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.ChallengeMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; import net.codingarea.challenges.plugin.utils.misc.MapUtils; +import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java index 28950d530..e8eede5ca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java @@ -1,14 +1,14 @@ package net.codingarea.challenges.plugin.management.challenges; -import net.codingarea.commons.bukkit.core.BukkitModule; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.implementation.damage.DamageRuleSetting; import net.codingarea.challenges.plugin.challenges.implementation.material.BlockMaterialSetting; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.core.BukkitModule; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Material; import org.bukkit.command.CommandExecutor; import org.bukkit.event.HandlerList; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java index ff36638d7..165675448 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java @@ -1,15 +1,15 @@ package net.codingarea.challenges.plugin.management.cloud; import lombok.Getter; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.common.collection.WrappedException; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.cloud.support.CloudNet2Support; import net.codingarea.challenges.plugin.management.cloud.support.CloudNet3Support; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.WrappedException; +import net.codingarea.commons.common.config.Document; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java index 1ff4612f6..dfd72cf9a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java @@ -1,6 +1,8 @@ package net.codingarea.challenges.plugin.management.database; import lombok.Getter; +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.commons.common.config.Document; @@ -9,8 +11,6 @@ import net.codingarea.commons.database.SQLColumn; import net.codingarea.commons.database.action.ExecutedQuery; import net.codingarea.commons.database.exceptions.DatabaseException; -import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; import net.codingarea.commons.database.sql.mysql.MySQLDatabase; import net.codingarea.commons.database.sql.sqlite.SQLiteDatabase; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java index 73ad01456..7aeb96bb1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.management.files; import lombok.Getter; +import net.codingarea.challenges.plugin.Challenges; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.FileDocument; import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.commons.common.config.document.YamlDocument; import net.codingarea.commons.common.misc.FileUtils; -import net.codingarea.challenges.plugin.Challenges; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java index e2c86f35f..a78e40c6d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java @@ -1,11 +1,6 @@ package net.codingarea.challenges.plugin.management.inventory; import lombok.Getter; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.common.collection.pair.Triple; -import net.codingarea.commons.common.config.Document; -import net.codingarea.commons.common.config.FileDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -14,6 +9,11 @@ import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.SkullBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.pair.Triple; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java index f4f63b65e..91f7eb945 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java @@ -1,11 +1,6 @@ package net.codingarea.challenges.plugin.management.menu; import lombok.Getter; -import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; -import net.codingarea.commons.bukkit.utils.animation.AnimationFrame; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; @@ -15,6 +10,11 @@ import net.codingarea.challenges.plugin.management.menu.generator.ChallengeMenuGenerator; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.AnimationFrame; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.entity.Player; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java index 6996e9588..2cf752df1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java @@ -1,11 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator; import com.google.common.collect.ImmutableList; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import net.codingarea.commons.common.version.Version; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.content.Message; @@ -13,6 +8,11 @@ import net.codingarea.challenges.plugin.management.menu.position.GeneratorMenuPosition; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.common.version.Version; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java index b268c8558..ba4774fd3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.MainCustomMenuGenerator; import net.codingarea.challenges.plugin.management.menu.position.GeneratorMenuPosition; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java index 8efcc07f5..10eb68260 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -12,6 +9,9 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java index 5fadbe3f4..05d16d340 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java @@ -2,10 +2,10 @@ import lombok.Getter; import lombok.Setter; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.position.GeneratorMenuPosition; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java index e0a398b3a..eb7ec54d1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils.InventorySetter; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.Bukkit; import org.bukkit.inventory.Inventory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java index 42bcb88e1..3322ba088 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java @@ -1,9 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator; import lombok.Getter; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; @@ -11,6 +8,9 @@ import net.codingarea.challenges.plugin.management.menu.position.GeneratorMenuPosition; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java index 865652da3..ad02f7280 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.management.menu.generator.categorised; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.content.Message; @@ -10,6 +8,8 @@ import net.codingarea.challenges.plugin.management.menu.generator.implementation.SettingsMenuGenerator; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.ChatColor; import org.bukkit.inventory.Inventory; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java index 02585fecf..a3f7f8db4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.management.menu.generator.ChallengeMenuGenerator; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java index 194f6e778..8935cf143 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -17,6 +14,9 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java index 0700ff5bc..06d2a8dc8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java @@ -2,10 +2,6 @@ import lombok.Getter; import lombok.ToString; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; @@ -24,6 +20,10 @@ import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils.InventorySetter; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.common.collection.IRandom; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java index 2f5417ac5..3136d7f20 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.type.IChallenge; @@ -12,6 +10,8 @@ import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import org.bukkit.Material; import org.bukkit.inventory.Inventory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java index ff40c7b97..86fb6663c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; import net.codingarea.challenges.plugin.management.menu.generator.ChooseItemGenerator; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.MapUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java index 694b9463f..613cd9766 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.menu.position; import lombok.Getter; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; @Getter public abstract class GeneratorMenuPosition implements MenuPosition { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java index 9c3c5e88b..678697934 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.management.scheduler; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.common.misc.ReflectionUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.misc.ReflectionUtils; import javax.annotation.Nonnull; import java.lang.reflect.Method; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java index 44d2789c0..216893860 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java @@ -1,9 +1,6 @@ package net.codingarea.challenges.plugin.management.scheduler.timer; import lombok.Getter; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.config.Document; -import net.codingarea.commons.common.config.FileDocument; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; @@ -17,6 +14,9 @@ import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.*; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java index fa4c045dc..be78dc4e6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.management.server; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.challenges.entities.GamestateSaveable; import net.codingarea.challenges.plugin.spigot.generator.VoidMapGenerator; +import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.World.Environment; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java index 6d192f443..82ed3d7de 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.server; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.challenges.entities.GamestateSaveable; +import net.codingarea.commons.common.config.Document; import org.bukkit.Location; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java index a94da3f0d..dcf2c78a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java @@ -1,16 +1,16 @@ package net.codingarea.challenges.plugin.management.server; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.config.Document; -import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java index e27a364d9..c096a0ce1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.management.server; import lombok.Getter; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.commons.common.config.Document; import org.bukkit.entity.Player; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java index 2d7435838..326e085dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java @@ -2,15 +2,15 @@ import lombok.Getter; import lombok.Setter; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.common.config.Document; -import net.codingarea.commons.common.config.FileDocument; -import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.bukkit.container.PlayerData; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.config.FileDocument; +import net.codingarea.commons.common.misc.FileUtils; import org.bukkit.*; import org.bukkit.World.Environment; import org.bukkit.command.CommandSender; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java index a1f7d0ba8..f2d44b052 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.management.server.scoreboard; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.bukkit.nms.NMSUtils; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java index d61318aee..def523111 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java @@ -2,10 +2,10 @@ import lombok.Getter; import lombok.ToString; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.scoreboard.DisplaySlot; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java index 6a83e2f97..08269d1da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.management.stats; import lombok.Getter; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.scheduler.policy.ChallengeStatusPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.spigot.listener.StatsListener; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.database.exceptions.DatabaseException; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java index a633ec0d7..f3f6db16f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/team/TeamProvider.java @@ -2,7 +2,6 @@ import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; import java.util.LinkedList; import java.util.List; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java index 987cc8bd7..0d53c4ad7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.spigot.command; import com.google.common.collect.Lists; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java index ae464b130..bb775a5e3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.commons.common.config.FileDocument; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; +import net.codingarea.commons.common.config.FileDocument; import org.bukkit.command.CommandSender; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java index 314ba6555..43fc75a07 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java @@ -4,8 +4,8 @@ import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; +import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import org.bukkit.attribute.AttributeInstance; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java index e32682f0e..a8d7e6ee5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import net.codingarea.commons.bukkit.utils.menu.positions.SlottedMenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -10,6 +8,8 @@ import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.positions.SlottedMenuPosition; import org.bukkit.Bukkit; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java index 605a0a634..a31279eb6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java @@ -1,9 +1,5 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import net.codingarea.commons.bukkit.utils.menu.positions.SlottedMenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -16,6 +12,10 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder.SkullBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.StatsHelper; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.bukkit.utils.menu.positions.SlottedMenuPosition; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java index e463a4d51..89bfc3611 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java @@ -1,8 +1,6 @@ package net.codingarea.challenges.plugin.spigot.command; import com.google.common.collect.Lists; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -10,6 +8,8 @@ import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; import org.bukkit.command.CommandSender; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java index c5f7ef062..975ef57f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; @@ -8,6 +7,7 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java index 1997de2b3..b913d9029 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.commons.bukkit.utils.item.ItemUtils; -import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -10,6 +8,8 @@ import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.Utils; +import net.codingarea.commons.bukkit.utils.item.ItemUtils; +import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Material; import org.bukkit.command.CommandSender; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java index d14ea9e61..f81c8c976 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -16,6 +13,9 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder.SkullBuilder; import net.codingarea.challenges.plugin.utils.misc.StatsHelper; import net.codingarea.challenges.plugin.utils.misc.Utils; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.Bukkit; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java index de37a99cc..332134945 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.commons.common.collection.NumberFormatter; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; +import net.codingarea.commons.common.collection.NumberFormatter; import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java index c1a6a2e8f..391c875e8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java @@ -1,7 +1,5 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.misc.StringUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -10,6 +8,8 @@ import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java index 41b8f4d89..fd5f10b74 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.StructureType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java index 8457776c8..7b52cb48d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.spigot.listener; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java index 00de88ed9..f78290b11 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.spigot.listener; -import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java index 82dfe55ef..2ef1f4e40 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.listener; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.spigot.events.*; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.Bukkit; import org.bukkit.Statistic; import org.bukkit.entity.Entity; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index 67e0faa28..b3b2081d0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -1,8 +1,5 @@ package net.codingarea.challenges.plugin.spigot.listener; -import java.util.List; -import javax.annotation.Nonnull; - import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; @@ -21,6 +18,9 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; +import javax.annotation.Nonnull; +import java.util.List; + public class PlayerConnectionListener implements Listener { private final boolean messages; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java index 650a3e5f7..7fff7578e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.utils.bukkit.command; -import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java index 776df6c8c..6675f0632 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.utils.bukkit.command; -import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java index c5f73691e..db71db9c7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.utils.bukkit.misc; +import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.commons.common.collection.WrappedException; import net.codingarea.commons.common.logging.ILogger; -import net.codingarea.challenges.plugin.content.Prefix; import net.md_5.bungee.api.chat.*; import org.bukkit.*; import org.bukkit.advancement.Advancement; @@ -90,8 +90,8 @@ public static List format(@Nonnull String sequence, @Nonnull Obje BaseComponent replacement = current instanceof BaseComponent ? (BaseComponent) current : current instanceof Supplier ? new TextComponent(String.valueOf(((Supplier) current).get())) : - current instanceof Callable ? new TextComponent(String.valueOf(((Callable) current).call())) : - new TextComponent(String.valueOf(current)); + current instanceof Callable ? new TextComponent(String.valueOf(((Callable) current).call())) : + new TextComponent(String.valueOf(current)); if (replacement instanceof TextComponent) { currentText.setText(currentText.getText() + ((TextComponent) replacement).getText()); @@ -163,13 +163,13 @@ public static Object[] replaceArguments(Object[] args, boolean toStrings) { arg = arg instanceof Material ? getItemComponent((Material) arg) : arg instanceof EntityType ? getEntityName((EntityType) arg) : - arg instanceof PotionEffectType ? getPotionEffectName((PotionEffectType) arg) : - arg instanceof Biome ? getBiomeName((Biome) arg) : - arg instanceof GameMode ? getGameModeName((GameMode) arg) : - arg instanceof Advancement ? getAdvancementComponent((Advancement) arg) : - arg instanceof LootTable ? getEntityName((LootTable) arg) : - arg instanceof Difficulty ? getDifficultyName((Difficulty) arg) : - arg; + arg instanceof PotionEffectType ? getPotionEffectName((PotionEffectType) arg) : + arg instanceof Biome ? getBiomeName((Biome) arg) : + arg instanceof GameMode ? getGameModeName((GameMode) arg) : + arg instanceof Advancement ? getAdvancementComponent((Advancement) arg) : + arg instanceof LootTable ? getEntityName((LootTable) arg) : + arg instanceof Difficulty ? getDifficultyName((Difficulty) arg) : + arg; if (toStrings) { if (arg instanceof BaseComponent) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java index 4b941e688..671fe1ead 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/nms/NMSProvider.java @@ -1,7 +1,6 @@ package net.codingarea.challenges.plugin.utils.bukkit.nms; import lombok.Getter; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_13.*; import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_17.BorderPacketFactory_1_17; @@ -10,6 +9,7 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_18.PacketBorder_1_18; import net.codingarea.challenges.plugin.utils.bukkit.nms.implementations.v1_18.PlayerConnection_1_18; import net.codingarea.challenges.plugin.utils.bukkit.nms.type.*; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.World; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index 17ebf2d92..fc5804288 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -2,9 +2,9 @@ import com.google.gson.JsonParser; import lombok.NonNull; -import net.codingarea.commons.bukkit.utils.item.BannerPattern; import net.codingarea.challenges.plugin.content.ItemDescription; import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.commons.bukkit.utils.item.BannerPattern; import org.bukkit.*; import org.bukkit.block.banner.Pattern; import org.bukkit.block.banner.PatternType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java index 348a43631..3c6ae809e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java @@ -3,9 +3,9 @@ import com.mojang.authlib.GameProfile; import com.mojang.authlib.properties.Property; import com.mojang.authlib.properties.PropertyMap; +import net.codingarea.challenges.plugin.Challenges; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.bukkit.utils.misc.GameProfileUtils; -import net.codingarea.challenges.plugin.Challenges; import org.bukkit.Bukkit; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java index 56c365fd0..b39fd976f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.codingarea.commons.bukkit.utils.animation.AnimationFrame; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.common.collection.IRandom; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.AnimationFrame; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.common.collection.IRandom; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World.Environment; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java index cf6e7c1f6..31ec8de85 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MapUtils.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.codingarea.commons.common.config.Document; import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.commons.common.config.Document; import java.util.*; import java.util.Map.Entry; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java index 023f90fa7..d161f2419 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.codingarea.commons.common.misc.ReflectionUtils; import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; +import net.codingarea.commons.common.misc.ReflectionUtils; import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.enchantments.Enchantment; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java index 18fe9135a..cf9ccd5e2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.stats.Statistic; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; import org.bukkit.Material; import javax.annotation.Nonnull; diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java index c90eea42b..beaa0c21b 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java @@ -42,334 +42,341 @@ public abstract class BukkitModule extends JavaPlugin { - private static volatile BukkitModule firstInstance; - private static boolean setFirstInstance = true; - private static boolean wasShutdown; - - private final Map commands = new HashMap<>(); - private final List listeners = new ArrayList<>(); - private final SimpleConfigManager configManager = new SimpleConfigManager(this); - - private JavaILogger logger; - private ExecutorService executorService; - private Document config, pluginConfig; - private Version version; - private boolean devMode; - private boolean firstInstall; - private boolean isReloaded; - private boolean isLoaded; - - private boolean requirementsMet = true; - - @Override - public final void onLoad() { - isLoaded = true; - - if (!requirementsMet || !(requirementsMet = new RequirementsChecker(this).checkBoolean(getPluginDocument().getDocument("require")))) - return; - - if (setFirstInstance || firstInstance == null) { - setFirstInstance(this); - } - - ILogger.setConstantFactory(this.getILogger()); - trySaveDefaultConfig(); - if (wasShutdown) isReloaded = true; - if (firstInstall = !getDataFolder().exists()) { - getILogger().info("Detected first install!"); - } - if (devMode = getConfigDocument().getBoolean("dev-mode") || getConfigDocument().getBoolean("dev-mode.enabled")) { - getILogger().setLevel(Level.ALL); - getILogger().debug("Devmode is enabled: Showing debug messages. This can be disabled in the plugin.yml ('dev-mode')"); - } else { - getILogger().setLevel(Level.INFO); - } - - injectInstance(); - - try { - handleLoad(); - } catch (Exception ex) { - throw new WrappedException(ex); - } - } - - @Override - public final void onEnable() { - if (!requirementsMet) return; - - commands.forEach((name, executor) -> registerCommand0(executor, name)); - listeners.forEach(this::registerListener); - - - try { - handleEnable(); - } catch (Exception ex) { - throw new WrappedException(ex); - } - } - - @Override - public final void onDisable() { - Throwable error = null; - try { - handleDisable(); - } catch (Throwable ex) { - error = ex; - } - - setFirstInstance = true; - wasShutdown = true; - isLoaded = false; - commands.clear(); - listeners.clear(); - - if (executorService != null) - executorService.shutdown(); - - for (Player player : Bukkit.getOnlinePlayers()) { - InventoryView view = player.getOpenInventory(); - Inventory inventory = view.getTopInventory(); - if (inventory.getHolder() == MenuPosition.HOLDER) - view.close(); - } - - if (error != null) - throw new WrappedException(error); - } - - protected void handleLoad() throws Exception {} - protected void handleEnable() throws Exception {} - protected void handleDisable() throws Exception {} - - public boolean isDevMode() { - return devMode; - } - - public final boolean isFirstInstall() { - return firstInstall; - } - - public final boolean isReloaded() { - return isReloaded; - } - - public final boolean isLoaded() { - return isLoaded; - } - - public final boolean isFirstInstance() { - return firstInstance == this; - } - - @Nonnull - public JavaILogger getILogger() { - return logger != null ? logger : (logger = new BukkitLoggerWrapper(super.getLogger())); - } - - @Nonnull - public Document getConfigDocument() { - checkLoaded(); - return config != null ? config : (config = new YamlDocument(super.getConfig())); - } - - @Override - public void reloadConfig() { - config = null; - super.reloadConfig(); - } - - /** - * @return the plugin configuration (plugin.yml) as document - */ - @Nonnull - public Document getPluginDocument() { - return pluginConfig != null ? pluginConfig : - (pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(getResource("plugin.yml"), Charsets.UTF_8)))); - } - - @Nonnull - public FileDocument getConfig(@Nonnull String filename) { - return configManager.getDocument(filename); - } - - @Nonnull - public Version getVersion() { - return version != null ? version : (version = Version.parse(getDescription().getVersion())); - } - - @Nonnull - @Deprecated - @DeprecatedSince("1.3.0") - @ReplaceWith("MinecraftVersion.current()") - public MinecraftVersion getServerVersion() { - return MinecraftVersion.current(); - } - - @Nonnull - @Deprecated - @DeprecatedSince("1.3.0") - @ReplaceWith("MinecraftVersion.currentExact()") - public Version getServerVersionExact() { - return MinecraftVersion.currentExact(); - } - - @Nonnull - @Override - @Deprecated - @ReplaceWith("getConfigDocument()") - public FileConfiguration getConfig() { - return super.getConfig(); - } - - @Override - @Deprecated - public void saveConfig() { - super.saveConfig(); - } - - public void setRequirementsFailed() { - this.requirementsMet = false; - } - - public final void registerListenerCommand(@Nonnull T listenerAndExecutor, @Nonnull String... names) { - registerCommand(listenerAndExecutor, names); - registerListener(listenerAndExecutor); - } - - public final void registerCommand(@Nonnull CommandExecutor executor, @Nonnull String... names) { - for (String name : names) { - if (isEnabled()) { - registerCommand0(executor, name); - } else { - commands.put(name, executor); - } - } - } - - private void registerCommand0(@Nonnull CommandExecutor executor, @Nonnull String name) { - PluginCommand command = getCommand(name); - if (command == null) { - getILogger().warn("Tried to register invalid command '{}'", name); - } else { - command.setExecutor(executor); - } - } - - public final void registerListener(@Nonnull Listener... listeners) { - if (isEnabled()) { - for (Listener listener : listeners) { - registerListener0(listener); - } - } else { - this.listeners.addAll(Arrays.asList(listeners)); - } - } - - private void registerListener0(@Nonnull Listener listener) { - if (listener instanceof ActionListener) { - ActionListener actionListener = (ActionListener) listener; - getServer().getPluginManager().registerEvent( - actionListener.getClassOfEvent(), actionListener, actionListener.getPriority(), - new SimpleEventExecutor(actionListener.getClassOfEvent(), actionListener.getListener()), this, actionListener.isIgnoreCancelled() - ); - } else { - getServer().getPluginManager().registerEvents(listener, this); - } - } - - public final void on(@Nonnull Class classOfEvent, @Nonnull Consumer action) { - on(classOfEvent, EventPriority.NORMAL, action); - } - - public final void on(@Nonnull Class classOfEvent, @Nonnull EventPriority priority, @Nonnull Consumer action) { - on(classOfEvent, priority, false, action); - } - - public final void on(@Nonnull Class classOfEvent, @Nonnull EventPriority priority, boolean ignoreCancelled, @Nonnull Consumer action) { - registerListener(new ActionListener<>(classOfEvent, action, priority, ignoreCancelled)); - } - - public final void disablePlugin() { - getServer().getPluginManager().disablePlugin(this); - } - - @Nonnull - public final File getDataFile(@Nonnull String filename) { - return new File(getDataFolder(), filename); - } - - @Nonnull - public final File getDataFile(@Nonnull String subfolder, @Nonnull String filename) { - return new File(getDataFile(subfolder), filename); - } - - @Nonnull - public ExecutorService getExecutor() { - return executorService != null ? executorService : (executorService = Executors.newCachedThreadPool(new NamedThreadFactory(threadId -> String.format("%s-Task-%s", this.getName(), threadId)))); - } - - public void runAsync(@Nonnull Runnable task) { - getExecutor().submit(task); - } - - public final void checkLoaded() { - if (!isLoaded()) - throw new IllegalStateException("Plugin (" + getName() + ") is not loaded yet"); - } - - public final void checkEnabled() { - if (!isEnabled()) - throw new IllegalStateException("Plugin (" + getName() + ") is not enabled yet"); - } - - private void registerAsFirstInstance() { - getILogger().info(getName() + " was loaded as the first BukkitModule"); - registerListener( - new MenuPositionListener() - ); - getILogger().info("Detected server version {} -> {}", getServerVersionExact(), getServerVersion()); - } - - private void trySaveDefaultConfig() { - try { - saveDefaultConfig(); - } catch (IllegalArgumentException ex) { - // No default config exists - } - } - - private void injectInstance() { - try { - Field instanceField = this.getClass().getDeclaredField("instance"); - instanceField.setAccessible(true); - instanceField.set(null, this); - } catch (Throwable ex) { - } - } - - @Nonnull - public static BukkitModule getFirstInstance() { - if (firstInstance == null) { - JavaPlugin provider = JavaPlugin.getProvidingPlugin(BukkitModule.class); - if (!(provider instanceof BukkitModule)) throw new IllegalStateException("No BukkitModule was initialized yet & BukkitModule class was not loaded by a BukkitModule"); - firstInstance = (BukkitModule) provider; - } - - return firstInstance; - } - - private static synchronized void setFirstInstance(@Nonnull BukkitModule module) { - setFirstInstance = false; - firstInstance = module; - module.registerAsFirstInstance(); - } - - @Nonnull - public static BukkitModule getProvidingModule(@Nonnull Class clazz) { - JavaPlugin provider = JavaPlugin.getProvidingPlugin(clazz); - if (!(provider instanceof BukkitModule)) throw new IllegalStateException(clazz.getName() + " is not provided by a BukkitModule"); - return (BukkitModule) provider; - } + private static volatile BukkitModule firstInstance; + private static boolean setFirstInstance = true; + private static boolean wasShutdown; + + private final Map commands = new HashMap<>(); + private final List listeners = new ArrayList<>(); + private final SimpleConfigManager configManager = new SimpleConfigManager(this); + + private JavaILogger logger; + private ExecutorService executorService; + private Document config, pluginConfig; + private Version version; + private boolean devMode; + private boolean firstInstall; + private boolean isReloaded; + private boolean isLoaded; + + private boolean requirementsMet = true; + + @Override + public final void onLoad() { + isLoaded = true; + + if (!requirementsMet || !(requirementsMet = new RequirementsChecker(this).checkBoolean(getPluginDocument().getDocument("require")))) + return; + + if (setFirstInstance || firstInstance == null) { + setFirstInstance(this); + } + + ILogger.setConstantFactory(this.getILogger()); + trySaveDefaultConfig(); + if (wasShutdown) isReloaded = true; + if (firstInstall = !getDataFolder().exists()) { + getILogger().info("Detected first install!"); + } + if (devMode = getConfigDocument().getBoolean("dev-mode") || getConfigDocument().getBoolean("dev-mode.enabled")) { + getILogger().setLevel(Level.ALL); + getILogger().debug("Devmode is enabled: Showing debug messages. This can be disabled in the plugin.yml ('dev-mode')"); + } else { + getILogger().setLevel(Level.INFO); + } + + injectInstance(); + + try { + handleLoad(); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Override + public final void onEnable() { + if (!requirementsMet) return; + + commands.forEach((name, executor) -> registerCommand0(executor, name)); + listeners.forEach(this::registerListener); + + + try { + handleEnable(); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Override + public final void onDisable() { + Throwable error = null; + try { + handleDisable(); + } catch (Throwable ex) { + error = ex; + } + + setFirstInstance = true; + wasShutdown = true; + isLoaded = false; + commands.clear(); + listeners.clear(); + + if (executorService != null) + executorService.shutdown(); + + for (Player player : Bukkit.getOnlinePlayers()) { + InventoryView view = player.getOpenInventory(); + Inventory inventory = view.getTopInventory(); + if (inventory.getHolder() == MenuPosition.HOLDER) + view.close(); + } + + if (error != null) + throw new WrappedException(error); + } + + protected void handleLoad() throws Exception { + } + + protected void handleEnable() throws Exception { + } + + protected void handleDisable() throws Exception { + } + + public boolean isDevMode() { + return devMode; + } + + public final boolean isFirstInstall() { + return firstInstall; + } + + public final boolean isReloaded() { + return isReloaded; + } + + public final boolean isLoaded() { + return isLoaded; + } + + public final boolean isFirstInstance() { + return firstInstance == this; + } + + @Nonnull + public JavaILogger getILogger() { + return logger != null ? logger : (logger = new BukkitLoggerWrapper(super.getLogger())); + } + + @Nonnull + public Document getConfigDocument() { + checkLoaded(); + return config != null ? config : (config = new YamlDocument(super.getConfig())); + } + + @Override + public void reloadConfig() { + config = null; + super.reloadConfig(); + } + + /** + * @return the plugin configuration (plugin.yml) as document + */ + @Nonnull + public Document getPluginDocument() { + return pluginConfig != null ? pluginConfig : + (pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(getResource("plugin.yml"), Charsets.UTF_8)))); + } + + @Nonnull + public FileDocument getConfig(@Nonnull String filename) { + return configManager.getDocument(filename); + } + + @Nonnull + public Version getVersion() { + return version != null ? version : (version = Version.parse(getDescription().getVersion())); + } + + @Nonnull + @Deprecated + @DeprecatedSince("1.3.0") + @ReplaceWith("MinecraftVersion.current()") + public MinecraftVersion getServerVersion() { + return MinecraftVersion.current(); + } + + @Nonnull + @Deprecated + @DeprecatedSince("1.3.0") + @ReplaceWith("MinecraftVersion.currentExact()") + public Version getServerVersionExact() { + return MinecraftVersion.currentExact(); + } + + @Nonnull + @Override + @Deprecated + @ReplaceWith("getConfigDocument()") + public FileConfiguration getConfig() { + return super.getConfig(); + } + + @Override + @Deprecated + public void saveConfig() { + super.saveConfig(); + } + + public void setRequirementsFailed() { + this.requirementsMet = false; + } + + public final void registerListenerCommand(@Nonnull T listenerAndExecutor, @Nonnull String... names) { + registerCommand(listenerAndExecutor, names); + registerListener(listenerAndExecutor); + } + + public final void registerCommand(@Nonnull CommandExecutor executor, @Nonnull String... names) { + for (String name : names) { + if (isEnabled()) { + registerCommand0(executor, name); + } else { + commands.put(name, executor); + } + } + } + + private void registerCommand0(@Nonnull CommandExecutor executor, @Nonnull String name) { + PluginCommand command = getCommand(name); + if (command == null) { + getILogger().warn("Tried to register invalid command '{}'", name); + } else { + command.setExecutor(executor); + } + } + + public final void registerListener(@Nonnull Listener... listeners) { + if (isEnabled()) { + for (Listener listener : listeners) { + registerListener0(listener); + } + } else { + this.listeners.addAll(Arrays.asList(listeners)); + } + } + + private void registerListener0(@Nonnull Listener listener) { + if (listener instanceof ActionListener) { + ActionListener actionListener = (ActionListener) listener; + getServer().getPluginManager().registerEvent( + actionListener.getClassOfEvent(), actionListener, actionListener.getPriority(), + new SimpleEventExecutor(actionListener.getClassOfEvent(), actionListener.getListener()), this, actionListener.isIgnoreCancelled() + ); + } else { + getServer().getPluginManager().registerEvents(listener, this); + } + } + + public final void on(@Nonnull Class classOfEvent, @Nonnull Consumer action) { + on(classOfEvent, EventPriority.NORMAL, action); + } + + public final void on(@Nonnull Class classOfEvent, @Nonnull EventPriority priority, @Nonnull Consumer action) { + on(classOfEvent, priority, false, action); + } + + public final void on(@Nonnull Class classOfEvent, @Nonnull EventPriority priority, boolean ignoreCancelled, @Nonnull Consumer action) { + registerListener(new ActionListener<>(classOfEvent, action, priority, ignoreCancelled)); + } + + public final void disablePlugin() { + getServer().getPluginManager().disablePlugin(this); + } + + @Nonnull + public final File getDataFile(@Nonnull String filename) { + return new File(getDataFolder(), filename); + } + + @Nonnull + public final File getDataFile(@Nonnull String subfolder, @Nonnull String filename) { + return new File(getDataFile(subfolder), filename); + } + + @Nonnull + public ExecutorService getExecutor() { + return executorService != null ? executorService : (executorService = Executors.newCachedThreadPool(new NamedThreadFactory(threadId -> String.format("%s-Task-%s", this.getName(), threadId)))); + } + + public void runAsync(@Nonnull Runnable task) { + getExecutor().submit(task); + } + + public final void checkLoaded() { + if (!isLoaded()) + throw new IllegalStateException("Plugin (" + getName() + ") is not loaded yet"); + } + + public final void checkEnabled() { + if (!isEnabled()) + throw new IllegalStateException("Plugin (" + getName() + ") is not enabled yet"); + } + + private void registerAsFirstInstance() { + getILogger().info(getName() + " was loaded as the first BukkitModule"); + registerListener( + new MenuPositionListener() + ); + getILogger().info("Detected server version {} -> {}", getServerVersionExact(), getServerVersion()); + } + + private void trySaveDefaultConfig() { + try { + saveDefaultConfig(); + } catch (IllegalArgumentException ex) { + // No default config exists + } + } + + private void injectInstance() { + try { + Field instanceField = this.getClass().getDeclaredField("instance"); + instanceField.setAccessible(true); + instanceField.set(null, this); + } catch (Throwable ex) { + } + } + + @Nonnull + public static BukkitModule getFirstInstance() { + if (firstInstance == null) { + JavaPlugin provider = JavaPlugin.getProvidingPlugin(BukkitModule.class); + if (!(provider instanceof BukkitModule)) + throw new IllegalStateException("No BukkitModule was initialized yet & BukkitModule class was not loaded by a BukkitModule"); + firstInstance = (BukkitModule) provider; + } + + return firstInstance; + } + + private static synchronized void setFirstInstance(@Nonnull BukkitModule module) { + setFirstInstance = false; + firstInstance = module; + module.registerAsFirstInstance(); + } + + @Nonnull + public static BukkitModule getProvidingModule(@Nonnull Class clazz) { + JavaPlugin provider = JavaPlugin.getProvidingPlugin(clazz); + if (!(provider instanceof BukkitModule)) + throw new IllegalStateException(clazz.getName() + " is not provided by a BukkitModule"); + return (BukkitModule) provider; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java index 87cae1721..0097459d8 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java @@ -9,86 +9,86 @@ public final class RequirementsChecker { - private final BukkitModule module; + private final BukkitModule module; - public RequirementsChecker(@Nonnull BukkitModule module) { - this.module = module; - } + public RequirementsChecker(@Nonnull BukkitModule module) { + this.module = module; + } - public void checkExceptionally(@Nonnull Document requirements) throws IllegalStateException { - if (requirements.getBoolean("spigot")) requireSpigot(); - if (requirements.getBoolean("paper")) requirePaper(); - if (requirements.contains("version")) requireVersion(requirements.getVersion("version")); - } + public void checkExceptionally(@Nonnull Document requirements) throws IllegalStateException { + if (requirements.getBoolean("spigot")) requireSpigot(); + if (requirements.getBoolean("paper")) requirePaper(); + if (requirements.contains("version")) requireVersion(requirements.getVersion("version")); + } - public boolean checkBoolean(@Nonnull Document requirements) { - try { - checkExceptionally(requirements); - return true; - } catch (IllegalStateException ex) { - return false; - } - } + public boolean checkBoolean(@Nonnull Document requirements) { + try { + checkExceptionally(requirements); + return true; + } catch (IllegalStateException ex) { + return false; + } + } - private void requireSpigot() { - try { - Bukkit.spigot(); - } catch (Throwable ex) { - log(""); - log("============================== {} ==============================", module.getName()); - log(""); - log("Your server does not run an instance of Spigot (Your server: {}", Bukkit.getVersion()); - log("Please use an instance of Spigot or Paper to be able to use this plugin!"); - log(""); - log("Paper Download: https://papermc.io/downloads"); - log("Spigot Download: https://getbukkit.org/download/spigot"); - log(""); - log("============================== {} ==============================", module.getName()); - log(""); + private void requireSpigot() { + try { + Bukkit.spigot(); + } catch (Throwable ex) { + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + log("Your server does not run an instance of Spigot (Your server: {}", Bukkit.getVersion()); + log("Please use an instance of Spigot or Paper to be able to use this plugin!"); + log(""); + log("Paper Download: https://papermc.io/downloads"); + log("Spigot Download: https://getbukkit.org/download/spigot"); + log(""); + log("============================== {} ==============================", module.getName()); + log(""); - throw new IllegalStateException(); - } - } + throw new IllegalStateException(); + } + } - private void requirePaper() { - try { - Class.forName("com.destroystokyo.paper.VersionHistoryManager"); - } catch (Throwable ex) { - log(""); - log("============================== {} ==============================", module.getName()); - log(""); - log("Your server does not run an instance of PaperMC (Your server: {}", Bukkit.getVersion()); - log("Please use an instance of Paper to be able to use this plugin!"); - log(""); - log("Paper Download: https://papermc.io/downloads"); - log(""); - log("============================== {} ==============================", module.getName()); - log(""); + private void requirePaper() { + try { + Class.forName("com.destroystokyo.paper.VersionHistoryManager"); + } catch (Throwable ex) { + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + log("Your server does not run an instance of PaperMC (Your server: {}", Bukkit.getVersion()); + log("Please use an instance of Paper to be able to use this plugin!"); + log(""); + log("Paper Download: https://papermc.io/downloads"); + log(""); + log("============================== {} ==============================", module.getName()); + log(""); - throw new IllegalStateException(); - } - } + throw new IllegalStateException(); + } + } - private void requireVersion(@Nonnull Version required) { - if (MinecraftVersion.currentExact().isOlderThan(required)) { - log(""); - log("============================== {} ==============================", module.getName()); - log(""); - log("This plugin requires the server version {} (You have: {})", required.format(), MinecraftVersion.currentExact().format()); - log("Please use this version (or an newer version) to be able to use this plugin!"); - log(""); - log("Paper Download: https://papermc.io/downloads"); - log("Spigot Download: https://getbukkit.org/download/spigot"); - log(""); - log("============================== {} ==============================", module.getName()); - log(""); + private void requireVersion(@Nonnull Version required) { + if (MinecraftVersion.currentExact().isOlderThan(required)) { + log(""); + log("============================== {} ==============================", module.getName()); + log(""); + log("This plugin requires the server version {} (You have: {})", required.format(), MinecraftVersion.currentExact().format()); + log("Please use this version (or an newer version) to be able to use this plugin!"); + log(""); + log("Paper Download: https://papermc.io/downloads"); + log("Spigot Download: https://getbukkit.org/download/spigot"); + log(""); + log("============================== {} ==============================", module.getName()); + log(""); - throw new IllegalStateException(); - } - } + throw new IllegalStateException(); + } + } - private void log(@Nonnull String line, @Nonnull Object... args) { - module.getILogger().error(line, args); - } + private void log(@Nonnull String line, @Nonnull Object... args) { + module.getILogger().error(line, args); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java index a4570ad3f..65fd437b1 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java @@ -13,32 +13,35 @@ public class SimpleConfigManager { - protected final Map configs = new HashMap<>(); - protected final BukkitModule module; - - public SimpleConfigManager(@Nonnull BukkitModule module) { - this.module = module; - } - - @Nonnull - public FileDocument getDocument(@Nonnull String filename) { - if (!filename.contains(".")) filename += ".json"; - return getDocument(module.getDataFile(filename)); - } - - public synchronized FileDocument getDocument(@Nonnull File file) { - String extension = FileUtils.getFileExtension(file); - return configs.computeIfAbsent(file.getName(), key -> FileDocument.readFile(resolveType(extension), file)); - } - - @Nonnull - public static Class resolveType(@Nonnull String extension) { - switch (extension.toLowerCase()) { - case "json": return GsonDocument.class; - case "yml": - case "yaml": return YamlDocument.class; - default: throw new IllegalArgumentException("Unknown document file extension '" + extension + "'"); - } - } + protected final Map configs = new HashMap<>(); + protected final BukkitModule module; + + public SimpleConfigManager(@Nonnull BukkitModule module) { + this.module = module; + } + + @Nonnull + public FileDocument getDocument(@Nonnull String filename) { + if (!filename.contains(".")) filename += ".json"; + return getDocument(module.getDataFile(filename)); + } + + public synchronized FileDocument getDocument(@Nonnull File file) { + String extension = FileUtils.getFileExtension(file); + return configs.computeIfAbsent(file.getName(), key -> FileDocument.readFile(resolveType(extension), file)); + } + + @Nonnull + public static Class resolveType(@Nonnull String extension) { + switch (extension.toLowerCase()) { + case "json": + return GsonDocument.class; + case "yml": + case "yaml": + return YamlDocument.class; + default: + throw new IllegalArgumentException("Unknown document file extension '" + extension + "'"); + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java index 3bd67d790..0ebd04e9f 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java @@ -15,154 +15,155 @@ public class AnimatedInventory { - private final List frames = new ArrayList<>(); - private final InventoryHolder holder; - private final int size; - private final String title; - private SoundSample frameSound = SoundSample.CLICK, endSound = SoundSample.OPEN; - private int frameDelay = 1; - - public AnimatedInventory(@Nonnull String title, int size) { - this(title, size, null); - } - - public AnimatedInventory(@Nonnull String title, int size, @Nullable InventoryHolder holder) { - this.title = title; - this.size = size; - this.holder = holder; - } - - public void open(@Nonnull Player player) { - open(player, BukkitModule.getFirstInstance()); - } - - public void open(@Nonnull Player player, @Nonnull JavaPlugin plugin) { - if (!Bukkit.isPrimaryThread()) { - Bukkit.getScheduler().runTask(plugin, () -> open(player, plugin)); - return; - } - - Inventory inventory = createInventory(); - applyFrame(inventory, 0, player); - player.openInventory(inventory); - - AtomicInteger index = new AtomicInteger(1); - Bukkit.getScheduler().runTaskTimer(plugin, task -> { - - boolean opened = inventory.getViewers().contains(player); - if (index.get() >= frames.size() || !opened) { - task.cancel(); - return; - } - - applyFrame(inventory, index.get(), player); - - index.incrementAndGet(); - - }, frameDelay, frameDelay); - - } - - public void openNotAnimated(@Nonnull Player player, boolean playSound) { - openNotAnimated(player, playSound, BukkitModule.getFirstInstance()); - } - - public void openNotAnimated(@Nonnull Player player, boolean playSound, @Nonnull JavaPlugin plugin) { - if (!Bukkit.isPrimaryThread()) { - Bukkit.getScheduler().runTask(plugin, () -> openNotAnimated(player, playSound, plugin)); - return; - } - - Inventory inventory = createInventory(); - - if (!frames.isEmpty()) { - AnimationFrame frame = getLastFrame(); - inventory.setContents(frame.getContent()); - } - - player.openInventory(inventory); - - if (playSound && endSound != null) endSound.play(player); - - } - - private void applyFrame(@Nonnull Inventory inventory, int index, @Nonnull Player viewer) { - AnimationFrame frame = frames.get(index); - inventory.setContents(frame.getContent()); - - if (index == frames.size() - 1 && endSound != null) endSound.play(viewer); - else if (frameSound != null && frame.shouldPlaySound()) frameSound.play(viewer); - } - - @Nonnull - public AnimatedInventory addFrame(@Nonnull AnimationFrame frame) { - if (size != frame.getSize()) throw new IllegalArgumentException("AnimationFrame must have the same size (Expected " + size + "; Got " + frame.getSize() + ")"); - frames.add(frame); - return this; - } - - @Nonnull - public AnimationFrame createAndAdd() { - AnimationFrame frame = new AnimationFrame(size); - addFrame(frame); - return frame; - } - - @Nonnull - public AnimationFrame getFrame(int index) { - return frames.get(index); - } - - @Nonnull - public AnimationFrame getOrCreateFrame(int index) { - while (frames.size() <= index) { - cloneLastAndAdd(); - } - return getFrame(index); - } - - @Nonnull - public AnimationFrame cloneAndAdd(int index) { - AnimationFrame frame = getFrame(index).clone(); - addFrame(frame); - return frame; - } - - @Nonnull - public AnimationFrame getLastFrame() { - if (frames.isEmpty()) throw new IllegalStateException("Frames are empty"); - return getFrame(frames.size() - 1); - } - - @Nonnull - public AnimationFrame cloneLastAndAdd() { - AnimationFrame frame = getLastFrame().clone(); - addFrame(frame); - return frame; - } - - @Nonnull - public AnimatedInventory setEndSound(@Nullable SoundSample endSound) { - this.endSound = endSound; - return this; - } - - @Nonnull - public AnimatedInventory setFrameSound(@Nullable SoundSample frameSound) { - this.frameSound = frameSound; - return this; - } - - @Nonnull - public AnimatedInventory setFrameDelay(int delay) { - if (delay < 1) throw new IllegalArgumentException("Delay cannot be smaller than 1"); - this.frameDelay = delay; - return this; - } - - @Nonnull - private Inventory createInventory() { - return Bukkit.createInventory(holder, size, title); - } + private final List frames = new ArrayList<>(); + private final InventoryHolder holder; + private final int size; + private final String title; + private SoundSample frameSound = SoundSample.CLICK, endSound = SoundSample.OPEN; + private int frameDelay = 1; + + public AnimatedInventory(@Nonnull String title, int size) { + this(title, size, null); + } + + public AnimatedInventory(@Nonnull String title, int size, @Nullable InventoryHolder holder) { + this.title = title; + this.size = size; + this.holder = holder; + } + + public void open(@Nonnull Player player) { + open(player, BukkitModule.getFirstInstance()); + } + + public void open(@Nonnull Player player, @Nonnull JavaPlugin plugin) { + if (!Bukkit.isPrimaryThread()) { + Bukkit.getScheduler().runTask(plugin, () -> open(player, plugin)); + return; + } + + Inventory inventory = createInventory(); + applyFrame(inventory, 0, player); + player.openInventory(inventory); + + AtomicInteger index = new AtomicInteger(1); + Bukkit.getScheduler().runTaskTimer(plugin, task -> { + + boolean opened = inventory.getViewers().contains(player); + if (index.get() >= frames.size() || !opened) { + task.cancel(); + return; + } + + applyFrame(inventory, index.get(), player); + + index.incrementAndGet(); + + }, frameDelay, frameDelay); + + } + + public void openNotAnimated(@Nonnull Player player, boolean playSound) { + openNotAnimated(player, playSound, BukkitModule.getFirstInstance()); + } + + public void openNotAnimated(@Nonnull Player player, boolean playSound, @Nonnull JavaPlugin plugin) { + if (!Bukkit.isPrimaryThread()) { + Bukkit.getScheduler().runTask(plugin, () -> openNotAnimated(player, playSound, plugin)); + return; + } + + Inventory inventory = createInventory(); + + if (!frames.isEmpty()) { + AnimationFrame frame = getLastFrame(); + inventory.setContents(frame.getContent()); + } + + player.openInventory(inventory); + + if (playSound && endSound != null) endSound.play(player); + + } + + private void applyFrame(@Nonnull Inventory inventory, int index, @Nonnull Player viewer) { + AnimationFrame frame = frames.get(index); + inventory.setContents(frame.getContent()); + + if (index == frames.size() - 1 && endSound != null) endSound.play(viewer); + else if (frameSound != null && frame.shouldPlaySound()) frameSound.play(viewer); + } + + @Nonnull + public AnimatedInventory addFrame(@Nonnull AnimationFrame frame) { + if (size != frame.getSize()) + throw new IllegalArgumentException("AnimationFrame must have the same size (Expected " + size + "; Got " + frame.getSize() + ")"); + frames.add(frame); + return this; + } + + @Nonnull + public AnimationFrame createAndAdd() { + AnimationFrame frame = new AnimationFrame(size); + addFrame(frame); + return frame; + } + + @Nonnull + public AnimationFrame getFrame(int index) { + return frames.get(index); + } + + @Nonnull + public AnimationFrame getOrCreateFrame(int index) { + while (frames.size() <= index) { + cloneLastAndAdd(); + } + return getFrame(index); + } + + @Nonnull + public AnimationFrame cloneAndAdd(int index) { + AnimationFrame frame = getFrame(index).clone(); + addFrame(frame); + return frame; + } + + @Nonnull + public AnimationFrame getLastFrame() { + if (frames.isEmpty()) throw new IllegalStateException("Frames are empty"); + return getFrame(frames.size() - 1); + } + + @Nonnull + public AnimationFrame cloneLastAndAdd() { + AnimationFrame frame = getLastFrame().clone(); + addFrame(frame); + return frame; + } + + @Nonnull + public AnimatedInventory setEndSound(@Nullable SoundSample endSound) { + this.endSound = endSound; + return this; + } + + @Nonnull + public AnimatedInventory setFrameSound(@Nullable SoundSample frameSound) { + this.frameSound = frameSound; + return this; + } + + @Nonnull + public AnimatedInventory setFrameDelay(int delay) { + if (delay < 1) throw new IllegalArgumentException("Delay cannot be smaller than 1"); + this.frameDelay = delay; + return this; + } + + @Nonnull + private Inventory createInventory() { + return Bukkit.createInventory(holder, size, title); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java index 130785522..02e9b8a04 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java @@ -10,75 +10,75 @@ public class AnimationFrame implements Cloneable { - private final ItemStack[] content; - private boolean sound = true; - - public AnimationFrame(@Nonnull ItemStack[] content) { - this.content = Arrays.copyOf(content, content.length); - } - - public AnimationFrame(int size) { - this.content = new ItemStack[size]; - } - - @Nonnull - public AnimationFrame fill(@Nonnull ItemStack item) { - Arrays.fill(content, item); - return this; - } - - @Nonnull - public AnimationFrame setAccent(int... slots) { - for (int slot : slots) { - content[slot] = ItemBuilder.FILL_ITEM_2; - } - return this; - } - - @Nonnull - public AnimationFrame setItem(int slot, @Nonnull ItemBuilder item) { - return setItem(slot, item.build()); - } - - @Nonnull - public AnimationFrame setItem(int slot, @Nonnull ItemStack item) { - content[slot] = item; - return this; - } - - @Nonnull - public AnimationFrame setSound(boolean play) { - this.sound = play; - return this; - } - - @Nullable - public ItemStack getItem(int slot) { - return content[slot]; - } - - @Nullable - public Material getItemType(int slot) { - return getItem(slot) == null ? Material.AIR : getItem(slot).getType(); - } - - @Nonnull - public ItemStack[] getContent() { - return content; - } - - public boolean shouldPlaySound() { - return sound; - } - - public int getSize() { - return content.length; - } - - @Nonnull - @Override - public AnimationFrame clone() { - return new AnimationFrame(content); - } + private final ItemStack[] content; + private boolean sound = true; + + public AnimationFrame(@Nonnull ItemStack[] content) { + this.content = Arrays.copyOf(content, content.length); + } + + public AnimationFrame(int size) { + this.content = new ItemStack[size]; + } + + @Nonnull + public AnimationFrame fill(@Nonnull ItemStack item) { + Arrays.fill(content, item); + return this; + } + + @Nonnull + public AnimationFrame setAccent(int... slots) { + for (int slot : slots) { + content[slot] = ItemBuilder.FILL_ITEM_2; + } + return this; + } + + @Nonnull + public AnimationFrame setItem(int slot, @Nonnull ItemBuilder item) { + return setItem(slot, item.build()); + } + + @Nonnull + public AnimationFrame setItem(int slot, @Nonnull ItemStack item) { + content[slot] = item; + return this; + } + + @Nonnull + public AnimationFrame setSound(boolean play) { + this.sound = play; + return this; + } + + @Nullable + public ItemStack getItem(int slot) { + return content[slot]; + } + + @Nullable + public Material getItemType(int slot) { + return getItem(slot) == null ? Material.AIR : getItem(slot).getType(); + } + + @Nonnull + public ItemStack[] getContent() { + return content; + } + + public boolean shouldPlaySound() { + return sound; + } + + public int getSize() { + return content.length; + } + + @Nonnull + @Override + public AnimationFrame clone() { + return new AnimationFrame(content); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java index 8991960e0..665fa6461 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java @@ -11,103 +11,103 @@ public final class SoundSample { - public static final SoundSample - CLICK = new SoundSample().addSound(Sound.BLOCK_WOODEN_BUTTON_CLICK_ON, 0.5f), - BASS_OFF = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BASS, 0.5F), - BASS_ON = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_PLING, 0.5F), - PLING = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BELL, 1), - KLING = new SoundSample().addSound(Sound.ENTITY_PLAYER_LEVELUP, 0.6F, 2), - LEVEL_UP = new SoundSample().addSound(Sound.ENTITY_PLAYER_LEVELUP, 0.6F, 1.1f), - PLOP = new SoundSample().addSound(Sound.ENTITY_CHICKEN_EGG, 1, 2), - LOW_PLOP = new SoundSample().addSound(Sound.ENTITY_CHICKEN_EGG, 1, 1.3f), - DEATH = new SoundSample().addSound(Sound.ENTITY_BAT_DEATH, 0.7F), - TELEPORT = new SoundSample().addSound(Sound.ITEM_CHORUS_FRUIT_TELEPORT, 0.9F), - OPEN = new SoundSample().addSound(KLING).addSound(PLOP), - EAT = new SoundSample().addSound(Sound.ENTITY_PLAYER_BURP, 1), - BLAST = new SoundSample().addSound(Sound.ENTITY_FIREWORK_ROCKET_LARGE_BLAST, 1), - BREAK = new SoundSample().addSound(Sound.ENTITY_WITHER_BREAK_BLOCK, 0.7f), - WIN = new SoundSample().addSound(Sound.UI_TOAST_CHALLENGE_COMPLETE, 1), - DRAGON_BREATH = new SoundSample().addSound(Sound.ENTITY_ENDER_DRAGON_GROWL, 0.5F); - - public static void playStatusSound(@Nonnull Player player, boolean enabled) { - (enabled ? BASS_ON : BASS_OFF).play(player); - } - - private static final class SoundFrame { - - private final float pitch, volume; - private final Sound sound; - - public SoundFrame(@Nonnull Sound sound, float volume, float pitch) { - this.volume = volume; - this.pitch = pitch; - this.sound = sound; - } - - public SoundFrame(@Nonnull Sound sound, float volume) { - this(sound, volume, 1); - } - - public void play(@Nonnull Player player, @Nonnull Location location) { - player.playSound(location, sound, volume, pitch); - } - - public float getPitch() { - return pitch; - } - - public float getVolume() { - return volume; - } - - @Nonnull - public Sound getSound() { - return sound; - } - - } - - private final List frames = new ArrayList<>(); - - @Nonnull - public SoundSample addSound(@Nonnull Sound sound, float volume, float pitch) { - frames.add(new SoundFrame(sound, volume, pitch)); - return this; - } - - @Nonnull - public SoundSample addSound(@Nonnull Sound sound, float volume) { - frames.add(new SoundFrame(sound, volume)); - return this; - } - - @Nonnull - public SoundSample addSound(@Nonnull SoundSample sound) { - frames.addAll(sound.frames); - return this; - } - - public void play(@Nonnull Player player) { - play(player, player.getLocation()); - } - - public void play(@Nonnull Player player, @Nonnull Location location) { - for (SoundFrame frame : frames) { - frame.play(player, location); - } - } - - public void playIfPlayer(@Nonnull Object target) { - if (target instanceof Player) - play((Player) target); - } - - public void broadcast() { - Bukkit.getOnlinePlayers().forEach(this::play); - } - - public void broadcast(@Nonnull Location location) { - Bukkit.getOnlinePlayers().forEach(player -> play(player, location)); - } + public static final SoundSample + CLICK = new SoundSample().addSound(Sound.BLOCK_WOODEN_BUTTON_CLICK_ON, 0.5f), + BASS_OFF = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BASS, 0.5F), + BASS_ON = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_PLING, 0.5F), + PLING = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BELL, 1), + KLING = new SoundSample().addSound(Sound.ENTITY_PLAYER_LEVELUP, 0.6F, 2), + LEVEL_UP = new SoundSample().addSound(Sound.ENTITY_PLAYER_LEVELUP, 0.6F, 1.1f), + PLOP = new SoundSample().addSound(Sound.ENTITY_CHICKEN_EGG, 1, 2), + LOW_PLOP = new SoundSample().addSound(Sound.ENTITY_CHICKEN_EGG, 1, 1.3f), + DEATH = new SoundSample().addSound(Sound.ENTITY_BAT_DEATH, 0.7F), + TELEPORT = new SoundSample().addSound(Sound.ITEM_CHORUS_FRUIT_TELEPORT, 0.9F), + OPEN = new SoundSample().addSound(KLING).addSound(PLOP), + EAT = new SoundSample().addSound(Sound.ENTITY_PLAYER_BURP, 1), + BLAST = new SoundSample().addSound(Sound.ENTITY_FIREWORK_ROCKET_LARGE_BLAST, 1), + BREAK = new SoundSample().addSound(Sound.ENTITY_WITHER_BREAK_BLOCK, 0.7f), + WIN = new SoundSample().addSound(Sound.UI_TOAST_CHALLENGE_COMPLETE, 1), + DRAGON_BREATH = new SoundSample().addSound(Sound.ENTITY_ENDER_DRAGON_GROWL, 0.5F); + + public static void playStatusSound(@Nonnull Player player, boolean enabled) { + (enabled ? BASS_ON : BASS_OFF).play(player); + } + + private static final class SoundFrame { + + private final float pitch, volume; + private final Sound sound; + + public SoundFrame(@Nonnull Sound sound, float volume, float pitch) { + this.volume = volume; + this.pitch = pitch; + this.sound = sound; + } + + public SoundFrame(@Nonnull Sound sound, float volume) { + this(sound, volume, 1); + } + + public void play(@Nonnull Player player, @Nonnull Location location) { + player.playSound(location, sound, volume, pitch); + } + + public float getPitch() { + return pitch; + } + + public float getVolume() { + return volume; + } + + @Nonnull + public Sound getSound() { + return sound; + } + + } + + private final List frames = new ArrayList<>(); + + @Nonnull + public SoundSample addSound(@Nonnull Sound sound, float volume, float pitch) { + frames.add(new SoundFrame(sound, volume, pitch)); + return this; + } + + @Nonnull + public SoundSample addSound(@Nonnull Sound sound, float volume) { + frames.add(new SoundFrame(sound, volume)); + return this; + } + + @Nonnull + public SoundSample addSound(@Nonnull SoundSample sound) { + frames.addAll(sound.frames); + return this; + } + + public void play(@Nonnull Player player) { + play(player, player.getLocation()); + } + + public void play(@Nonnull Player player, @Nonnull Location location) { + for (SoundFrame frame : frames) { + frame.play(player, location); + } + } + + public void playIfPlayer(@Nonnull Object target) { + if (target instanceof Player) + play((Player) target); + } + + public void broadcast() { + Bukkit.getOnlinePlayers().forEach(this::play); + } + + public void broadcast(@Nonnull Location location) { + Bukkit.getOnlinePlayers().forEach(player -> play(player, location)); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java index 172e2e4ff..1ed8d4b71 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/JsonObjectBuilder.java @@ -11,200 +11,200 @@ */ public class JsonObjectBuilder { - private StringBuilder builder = new StringBuilder(); - - private boolean hasAtLeastOneField = false; - - public JsonObjectBuilder() { - builder.append("{"); - } - - /** - * Appends a null field to the JSON. - * - * @param key The key of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendNull(String key) { - appendFieldUnescaped(key, "null"); - return this; - } - - /** - * Appends a string field to the JSON. - * - * @param key The key of the field. - * @param value The value of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, String value) { - if (value == null) { - throw new IllegalArgumentException("JSON value must not be null"); - } - appendFieldUnescaped(key, "\"" + escape(value) + "\""); - return this; - } - - /** - * Appends an integer field to the JSON. - * - * @param key The key of the field. - * @param value The value of the field. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, int value) { - appendFieldUnescaped(key, String.valueOf(value)); - return this; - } - - /** - * Appends an object to the JSON. - * - * @param key The key of the field. - * @param object The object. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, JsonObject object) { - if (object == null) { - throw new IllegalArgumentException("JSON object must not be null"); - } - appendFieldUnescaped(key, object.toString()); - return this; - } - - /** - * Appends a string array to the JSON. - * - * @param key The key of the field. - * @param values The string array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, String[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = - Arrays.stream(values) - .map(value -> "\"" + escape(value) + "\"") - .collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends an integer array to the JSON. - * - * @param key The key of the field. - * @param values The integer array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, int[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = - Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends an object array to the JSON. - * - * @param key The key of the field. - * @param values The integer array. - * @return A reference to this object. - */ - public JsonObjectBuilder appendField(String key, JsonObject[] values) { - if (values == null) { - throw new IllegalArgumentException("JSON values must not be null"); - } - String escapedValues = - Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); - appendFieldUnescaped(key, "[" + escapedValues + "]"); - return this; - } - - /** - * Appends a field to the object. - * - * @param key The key of the field. - * @param escapedValue The escaped value of the field. - */ - private void appendFieldUnescaped(String key, String escapedValue) { - if (builder == null) { - throw new IllegalStateException("JSON has already been built"); - } - if (key == null) { - throw new IllegalArgumentException("JSON key must not be null"); - } - if (hasAtLeastOneField) { - builder.append(","); - } - builder.append("\"").append(escape(key)).append("\":").append(escapedValue); - hasAtLeastOneField = true; - } - - /** - * Builds the JSON string and invalidates this builder. - * - * @return The built JSON string. - */ - public JsonObject build() { - if (builder == null) { - throw new IllegalStateException("JSON has already been built"); - } - JsonObject object = new JsonObject(builder.append("}").toString()); - builder = null; - return object; - } - - /** - * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. - * - *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. - * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). - * - * @param value The value to escape. - * @return The escaped value. - */ - private static String escape(String value) { - final StringBuilder builder = new StringBuilder(); - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - if (c == '"') { - builder.append("\\\""); - } else if (c == '\\') { - builder.append("\\\\"); - } else if (c <= '\u000F') { - builder.append("\\u000").append(Integer.toHexString(c)); - } else if (c <= '\u001F') { - builder.append("\\u00").append(Integer.toHexString(c)); - } else { - builder.append(c); - } - } - return builder.toString(); - } - - /** - * A super simple representation of a JSON object. - * - *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not - * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, - * JsonObject)}. - */ - public static class JsonObject { - - private final String value; - - private JsonObject(String value) { - this.value = value; - } - - @Override - public String toString() { - return value; - } - } + private StringBuilder builder = new StringBuilder(); + + private boolean hasAtLeastOneField = false; + + public JsonObjectBuilder() { + builder.append("{"); + } + + /** + * Appends a null field to the JSON. + * + * @param key The key of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendNull(String key) { + appendFieldUnescaped(key, "null"); + return this; + } + + /** + * Appends a string field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String value) { + if (value == null) { + throw new IllegalArgumentException("JSON value must not be null"); + } + appendFieldUnescaped(key, "\"" + escape(value) + "\""); + return this; + } + + /** + * Appends an integer field to the JSON. + * + * @param key The key of the field. + * @param value The value of the field. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int value) { + appendFieldUnescaped(key, String.valueOf(value)); + return this; + } + + /** + * Appends an object to the JSON. + * + * @param key The key of the field. + * @param object The object. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject object) { + if (object == null) { + throw new IllegalArgumentException("JSON object must not be null"); + } + appendFieldUnescaped(key, object.toString()); + return this; + } + + /** + * Appends a string array to the JSON. + * + * @param key The key of the field. + * @param values The string array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, String[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values) + .map(value -> "\"" + escape(value) + "\"") + .collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an integer array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, int[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends an object array to the JSON. + * + * @param key The key of the field. + * @param values The integer array. + * @return A reference to this object. + */ + public JsonObjectBuilder appendField(String key, JsonObject[] values) { + if (values == null) { + throw new IllegalArgumentException("JSON values must not be null"); + } + String escapedValues = + Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(",")); + appendFieldUnescaped(key, "[" + escapedValues + "]"); + return this; + } + + /** + * Appends a field to the object. + * + * @param key The key of the field. + * @param escapedValue The escaped value of the field. + */ + private void appendFieldUnescaped(String key, String escapedValue) { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + if (key == null) { + throw new IllegalArgumentException("JSON key must not be null"); + } + if (hasAtLeastOneField) { + builder.append(","); + } + builder.append("\"").append(escape(key)).append("\":").append(escapedValue); + hasAtLeastOneField = true; + } + + /** + * Builds the JSON string and invalidates this builder. + * + * @return The built JSON string. + */ + public JsonObject build() { + if (builder == null) { + throw new IllegalStateException("JSON has already been built"); + } + JsonObject object = new JsonObject(builder.append("}").toString()); + builder = null; + return object; + } + + /** + * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt. + * + *

This method escapes only the necessary characters '"', '\'. and '\u0000' - '\u001F'. + * Compact escapes are not used (e.g., '\n' is escaped as "\u000a" and not as "\n"). + * + * @param value The value to escape. + * @return The escaped value. + */ + private static String escape(String value) { + final StringBuilder builder = new StringBuilder(); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c == '"') { + builder.append("\\\""); + } else if (c == '\\') { + builder.append("\\\\"); + } else if (c <= '\u000F') { + builder.append("\\u000").append(Integer.toHexString(c)); + } else if (c <= '\u001F') { + builder.append("\\u00").append(Integer.toHexString(c)); + } else { + builder.append(c); + } + } + return builder.toString(); + } + + /** + * A super simple representation of a JSON object. + * + *

This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not + * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String, + * JsonObject)}. + */ + public static class JsonObject { + + private final String value; + + private JsonObject(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/Metrics.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/Metrics.java index 60574d3fc..691fc52b6 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/Metrics.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/Metrics.java @@ -24,310 +24,314 @@ public class Metrics { - private final Plugin plugin; - private final MetricsBase metricsBase; + private final Plugin plugin; + private final MetricsBase metricsBase; - /** - * Creates a new Metrics instance. - * - * @param plugin Your plugin instance. - * @param serviceId The id of the service. It can be found at What is my plugin id? - */ - public Metrics(JavaPlugin plugin, int serviceId) { - this.plugin = plugin; + /** + * Creates a new Metrics instance. + * + * @param plugin Your plugin instance. + * @param serviceId The id of the service. It can be found at What is my plugin id? + */ + public Metrics(JavaPlugin plugin, int serviceId) { + this.plugin = plugin; - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - if (!config.isSet("serverUuid")) { - config.addDefault("enabled", true); - config.addDefault("serverUuid", UUID.randomUUID().toString()); - config.addDefault("logFailedRequests", false); - config.addDefault("logSentData", false); - config.addDefault("logResponseStatusText", false); - // Inform the server owners about bStats - config - .options() - .header( - "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" - + "many people use their plugin and their total player count. It's recommended to keep bStats\n" - + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" - + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" - + "anonymous.") - .copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { - } - } + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + if (!config.isSet("serverUuid")) { + config.addDefault("enabled", true); + config.addDefault("serverUuid", UUID.randomUUID().toString()); + config.addDefault("logFailedRequests", false); + config.addDefault("logSentData", false); + config.addDefault("logResponseStatusText", false); + // Inform the server owners about bStats + config + .options() + .header( + "bStats (https://bStats.org) collects some basic information for plugin authors, like how\n" + + "many people use their plugin and their total player count. It's recommended to keep bStats\n" + + "enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n" + + "performance penalty associated with having metrics enabled, and data sent to bStats is fully\n" + + "anonymous.") + .copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } - String serverUUID = config.getString("serverUuid"); - boolean logErrors = config.getBoolean("logFailedRequests", false); - boolean logSentData = config.getBoolean("logSentData", false); - boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); - metricsBase = - new MetricsBase( - "bukkit", - serverUUID, - serviceId, - true, - this::appendPlatformData, - this::appendServiceData, - submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), - plugin::isEnabled, - (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), - (message) -> this.plugin.getLogger().log(Level.INFO, message), - logErrors, - logSentData, - logResponseStatusText); - } + String serverUUID = config.getString("serverUuid"); + boolean logErrors = config.getBoolean("logFailedRequests", false); + boolean logSentData = config.getBoolean("logSentData", false); + boolean logResponseStatusText = config.getBoolean("logResponseStatusText", false); + metricsBase = + new MetricsBase( + "bukkit", + serverUUID, + serviceId, + true, + this::appendPlatformData, + this::appendServiceData, + submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask), + plugin::isEnabled, + (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error), + (message) -> this.plugin.getLogger().log(Level.INFO, message), + logErrors, + logSentData, + logResponseStatusText); + } - /** - * Adds a custom chart. - * - * @param chart The chart to add. - */ - public void addCustomChart(CustomChart chart) { - metricsBase.addCustomChart(chart); - } + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + metricsBase.addCustomChart(chart); + } - private void appendPlatformData(JsonObjectBuilder builder) { - builder.appendField("playerAmount", getPlayerAmount()); - builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0); - builder.appendField("bukkitVersion", Bukkit.getVersion()); - builder.appendField("bukkitName", Bukkit.getName()); - builder.appendField("javaVersion", System.getProperty("java.version")); - builder.appendField("osName", System.getProperty("os.name")); - builder.appendField("osArch", System.getProperty("os.arch")); - builder.appendField("osVersion", System.getProperty("os.version")); - builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()); - } + private void appendPlatformData(JsonObjectBuilder builder) { + builder.appendField("playerAmount", getPlayerAmount()); + builder.appendField("onlineMode", Bukkit.getOnlineMode() ? 1 : 0); + builder.appendField("bukkitVersion", Bukkit.getVersion()); + builder.appendField("bukkitName", Bukkit.getName()); + builder.appendField("javaVersion", System.getProperty("java.version")); + builder.appendField("osName", System.getProperty("os.name")); + builder.appendField("osArch", System.getProperty("os.arch")); + builder.appendField("osVersion", System.getProperty("os.version")); + builder.appendField("coreCount", Runtime.getRuntime().availableProcessors()); + } - private void appendServiceData(JsonObjectBuilder builder) { - builder.appendField("pluginVersion", plugin.getDescription().getVersion()); - } + private void appendServiceData(JsonObjectBuilder builder) { + builder.appendField("pluginVersion", plugin.getDescription().getVersion()); + } - private int getPlayerAmount() { - try { - // Around MC 1.8 the return type was changed from an array to a collection, - // This fixes java.lang.NoSuchMethodError: - // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; - Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); - return onlinePlayersMethod.getReturnType().equals(Collection.class) - ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() - : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch (Exception e) { - // Just use the new method if the reflection failed - return Bukkit.getOnlinePlayers().size(); - } - } + private int getPlayerAmount() { + try { + // Around MC 1.8 the return type was changed from an array to a collection, + // This fixes java.lang.NoSuchMethodError: + // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + return onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + // Just use the new method if the reflection failed + return Bukkit.getOnlinePlayers().size(); + } + } - public static class MetricsBase { + public static class MetricsBase { - /** The version of the Metrics class. */ - public static final String METRICS_VERSION = "2.2.1"; + /** + * The version of the Metrics class. + */ + public static final String METRICS_VERSION = "2.2.1"; - private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, task -> new Thread(task, "bStats-Metrics")); - private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; + private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, task -> new Thread(task, "bStats-Metrics")); + private static final String REPORT_URL = "https://bStats.org/api/v2/data/%s"; - private final String platform; - private final String serverUuid; - private final int serviceId; - private final Consumer appendPlatformDataConsumer; - private final Consumer appendServiceDataConsumer; - private final Consumer submitTaskConsumer; - private final Supplier checkServiceEnabledSupplier; - private final BiConsumer errorLogger; - private final Consumer infoLogger; - private final boolean logErrors; - private final boolean logSentData; - private final boolean logResponseStatusText; - private final Set customCharts = new HashSet<>(); - private final boolean enabled; + private final String platform; + private final String serverUuid; + private final int serviceId; + private final Consumer appendPlatformDataConsumer; + private final Consumer appendServiceDataConsumer; + private final Consumer submitTaskConsumer; + private final Supplier checkServiceEnabledSupplier; + private final BiConsumer errorLogger; + private final Consumer infoLogger; + private final boolean logErrors; + private final boolean logSentData; + private final boolean logResponseStatusText; + private final Set customCharts = new HashSet<>(); + private final boolean enabled; - /** - * Creates a new MetricsBase class instance. - * - * @param platform The platform of the service. - * @param serviceId The id of the service. - * @param serverUuid The server uuid. - * @param enabled Whether or not data sending is enabled. - * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and - * appends all platform-specific data. - * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and - * appends all service-specific data. - * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be - * used to delegate the data collection to a another thread to prevent errors caused by - * concurrency. Can be {@code null}. - * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled. - * @param errorLogger A consumer that accepts log message and an error. - * @param infoLogger A consumer that accepts info log messages. - * @param logErrors Whether or not errors should be logged. - * @param logSentData Whether or not the sent data should be logged. - * @param logResponseStatusText Whether or not the response status text should be logged. - */ - public MetricsBase( - String platform, - String serverUuid, - int serviceId, - boolean enabled, - Consumer appendPlatformDataConsumer, - Consumer appendServiceDataConsumer, - Consumer submitTaskConsumer, - Supplier checkServiceEnabledSupplier, - BiConsumer errorLogger, - Consumer infoLogger, - boolean logErrors, - boolean logSentData, - boolean logResponseStatusText) { - this.platform = platform; - this.serverUuid = serverUuid; - this.serviceId = serviceId; - this.enabled = enabled; - this.appendPlatformDataConsumer = appendPlatformDataConsumer; - this.appendServiceDataConsumer = appendServiceDataConsumer; - this.submitTaskConsumer = submitTaskConsumer; - this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; - this.errorLogger = errorLogger; - this.infoLogger = infoLogger; - this.logErrors = logErrors; - this.logSentData = logSentData; - this.logResponseStatusText = logResponseStatusText; - checkRelocation(); - if (enabled) { - startSubmitting(); - } - } + /** + * Creates a new MetricsBase class instance. + * + * @param platform The platform of the service. + * @param serviceId The id of the service. + * @param serverUuid The server uuid. + * @param enabled Whether or not data sending is enabled. + * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all platform-specific data. + * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and + * appends all service-specific data. + * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be + * used to delegate the data collection to a another thread to prevent errors caused by + * concurrency. Can be {@code null}. + * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled. + * @param errorLogger A consumer that accepts log message and an error. + * @param infoLogger A consumer that accepts info log messages. + * @param logErrors Whether or not errors should be logged. + * @param logSentData Whether or not the sent data should be logged. + * @param logResponseStatusText Whether or not the response status text should be logged. + */ + public MetricsBase( + String platform, + String serverUuid, + int serviceId, + boolean enabled, + Consumer appendPlatformDataConsumer, + Consumer appendServiceDataConsumer, + Consumer submitTaskConsumer, + Supplier checkServiceEnabledSupplier, + BiConsumer errorLogger, + Consumer infoLogger, + boolean logErrors, + boolean logSentData, + boolean logResponseStatusText) { + this.platform = platform; + this.serverUuid = serverUuid; + this.serviceId = serviceId; + this.enabled = enabled; + this.appendPlatformDataConsumer = appendPlatformDataConsumer; + this.appendServiceDataConsumer = appendServiceDataConsumer; + this.submitTaskConsumer = submitTaskConsumer; + this.checkServiceEnabledSupplier = checkServiceEnabledSupplier; + this.errorLogger = errorLogger; + this.infoLogger = infoLogger; + this.logErrors = logErrors; + this.logSentData = logSentData; + this.logResponseStatusText = logResponseStatusText; + checkRelocation(); + if (enabled) { + startSubmitting(); + } + } - public void addCustomChart(CustomChart chart) { - this.customCharts.add(chart); - } + public void addCustomChart(CustomChart chart) { + this.customCharts.add(chart); + } - private void startSubmitting() { - final Runnable submitTask = - () -> { - if (!enabled || !checkServiceEnabledSupplier.get()) { - // Submitting data or service is disabled - scheduler.shutdown(); - return; - } - if (submitTaskConsumer != null) { - submitTaskConsumer.accept(this::submitData); - } else { - this.submitData(); - } - }; - // Many servers tend to restart at a fixed time at xx:00 which causes an uneven distribution - // of requests on the - // bStats backend. To circumvent this problem, we introduce some randomness into the initial - // and second delay. - // WARNING: You must not modify and part of this Metrics class, including the submit delay or - // frequency! - // WARNING: Modifying this code will get your plugin banned on bStats. Just don't do it! - long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); - long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); - scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); - scheduler.scheduleAtFixedRate( - submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); - } + private void startSubmitting() { + final Runnable submitTask = + () -> { + if (!enabled || !checkServiceEnabledSupplier.get()) { + // Submitting data or service is disabled + scheduler.shutdown(); + return; + } + if (submitTaskConsumer != null) { + submitTaskConsumer.accept(this::submitData); + } else { + this.submitData(); + } + }; + // Many servers tend to restart at a fixed time at xx:00 which causes an uneven distribution + // of requests on the + // bStats backend. To circumvent this problem, we introduce some randomness into the initial + // and second delay. + // WARNING: You must not modify and part of this Metrics class, including the submit delay or + // frequency! + // WARNING: Modifying this code will get your plugin banned on bStats. Just don't do it! + long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3)); + long secondDelay = (long) (1000 * 60 * (Math.random() * 30)); + scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS); + scheduler.scheduleAtFixedRate( + submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS); + } - private void submitData() { - final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); - appendPlatformDataConsumer.accept(baseJsonBuilder); - final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); - appendServiceDataConsumer.accept(serviceJsonBuilder); - JsonObjectBuilder.JsonObject[] chartData = - customCharts.stream() - .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) - .filter(Objects::nonNull) - .toArray(JsonObjectBuilder.JsonObject[]::new); - serviceJsonBuilder.appendField("id", serviceId); - serviceJsonBuilder.appendField("customCharts", chartData); - baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); - baseJsonBuilder.appendField("serverUUID", serverUuid); - baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); - JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); - scheduler.execute( - () -> { - try { - sendData(data); - } catch (Exception e) { - if (logErrors) { - errorLogger.accept("Could not submit bStats metrics data", e); - } - } - }); - } + private void submitData() { + final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder(); + appendPlatformDataConsumer.accept(baseJsonBuilder); + final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder(); + appendServiceDataConsumer.accept(serviceJsonBuilder); + JsonObjectBuilder.JsonObject[] chartData = + customCharts.stream() + .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors)) + .filter(Objects::nonNull) + .toArray(JsonObjectBuilder.JsonObject[]::new); + serviceJsonBuilder.appendField("id", serviceId); + serviceJsonBuilder.appendField("customCharts", chartData); + baseJsonBuilder.appendField("service", serviceJsonBuilder.build()); + baseJsonBuilder.appendField("serverUUID", serverUuid); + baseJsonBuilder.appendField("metricsVersion", METRICS_VERSION); + JsonObjectBuilder.JsonObject data = baseJsonBuilder.build(); + scheduler.execute( + () -> { + try { + sendData(data); + } catch (Exception e) { + if (logErrors) { + errorLogger.accept("Could not submit bStats metrics data", e); + } + } + }); + } - private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { - if (logSentData) { - infoLogger.accept("Sent bStats metrics data: " + data.toString()); - } - String url = String.format(REPORT_URL, platform); - HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); - connection.setRequestProperty("User-Agent", "Metrics-Service/1"); - connection.setDoOutput(true); - try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { - outputStream.write(compressedData); - } - StringBuilder builder = new StringBuilder(); - try (BufferedReader bufferedReader = - new BufferedReader(new InputStreamReader(connection.getInputStream()))) { - String line; - while ((line = bufferedReader.readLine()) != null) { - builder.append(line); - } - } - if (logResponseStatusText) { - infoLogger.accept("Sent data to bStats and received response: " + builder); - } - } + private void sendData(JsonObjectBuilder.JsonObject data) throws Exception { + if (logSentData) { + infoLogger.accept("Sent bStats metrics data: " + data.toString()); + } + String url = String.format(REPORT_URL, platform); + HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setRequestProperty("User-Agent", "Metrics-Service/1"); + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } + StringBuilder builder = new StringBuilder(); + try (BufferedReader bufferedReader = + new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } + if (logResponseStatusText) { + infoLogger.accept("Sent data to bStats and received response: " + builder); + } + } - /** Checks that the class was properly relocated. */ - private void checkRelocation() { - // You can use the property to disable the check in your test environment - if (System.getProperty("bstats.relocatecheck") == null - || !System.getProperty("bstats.relocatecheck").equals("false")) { - // Maven's Relocate is clever and changes strings, too. So we have to use this little - // "trick" ... :D - final String defaultPackage = - new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'}); - final String examplePackage = - new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); - // We want to make sure no one just copy & pastes the example and uses the wrong package - // names - if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) - || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { - throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); - } - } - } + /** + * Checks that the class was properly relocated. + */ + private void checkRelocation() { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null + || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little + // "trick" ... :D + final String defaultPackage = + new String(new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'}); + final String examplePackage = + new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure no one just copy & pastes the example and uses the wrong package + // names + if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage) + || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } - /** - * Gzips the given string. - * - * @param str The string to gzip. - * @return The gzipped string. - */ - private static byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { - gzip.write(str.getBytes(StandardCharsets.UTF_8)); - } - return outputStream.toByteArray(); - } - } + /** + * Gzips the given string. + * + * @param str The string to gzip. + * @return The gzipped string. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedBarChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedBarChart.java index 48063d475..046438d0d 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedBarChart.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedBarChart.java @@ -8,40 +8,40 @@ public class AdvancedBarChart extends CustomChart { - private final Callable> callable; + private final Callable> callable; - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } - @Override - protected JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue().length == 0) { - // Skip this invalid - continue; - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedPie.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedPie.java index afdba71ee..39ce27835 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedPie.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/AdvancedPie.java @@ -8,40 +8,40 @@ public class AdvancedPie extends CustomChart { - private final Callable> callable; + private final Callable> callable; - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public AdvancedPie(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } - @Override - protected JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - // Skip this invalid - continue; - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/CustomChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/CustomChart.java index 3897be5c7..37e5c1188 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/CustomChart.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/CustomChart.java @@ -7,34 +7,34 @@ public abstract class CustomChart { - private final String chartId; + private final String chartId; - protected CustomChart(String chartId) { - if (chartId == null) { - throw new IllegalArgumentException("chartId must not be null"); - } - this.chartId = chartId; - } + protected CustomChart(String chartId) { + if (chartId == null) { + throw new IllegalArgumentException("chartId must not be null"); + } + this.chartId = chartId; + } - public JsonObject getRequestJsonObject( - BiConsumer errorLogger, boolean logErrors) { - JsonObjectBuilder builder = new JsonObjectBuilder(); - builder.appendField("chartId", chartId); - try { - JsonObject data = getChartData(); - if (data == null) { - // If the data is null we don't send the chart. - return null; - } - builder.appendField("data", data); - } catch (Throwable t) { - if (logErrors) { - errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); - } - return null; - } - return builder.build(); - } + public JsonObject getRequestJsonObject( + BiConsumer errorLogger, boolean logErrors) { + JsonObjectBuilder builder = new JsonObjectBuilder(); + builder.appendField("chartId", chartId); + try { + JsonObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + builder.appendField("data", data); + } catch (Throwable t) { + if (logErrors) { + errorLogger.accept("Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return builder.build(); + } - protected abstract JsonObject getChartData() throws Exception; + protected abstract JsonObject getChartData() throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/DrilldownPie.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/DrilldownPie.java index d0cb2ff19..739cda561 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/DrilldownPie.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/DrilldownPie.java @@ -8,44 +8,44 @@ public class DrilldownPie extends CustomChart { - private final Callable>> callable; + private final Callable>> callable; - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public DrilldownPie(String chartId, Callable>> callable) { - super(chartId); - this.callable = callable; - } + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } - @Override - public JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map> map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean reallyAllSkipped = true; - for (Map.Entry> entryValues : map.entrySet()) { - JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); - boolean allSkipped = true; - for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { - valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); - allSkipped = false; - } - if (!allSkipped) { - reallyAllSkipped = false; - valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); - } - } - if (reallyAllSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } + @Override + public JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JsonObjectBuilder valueBuilder = new JsonObjectBuilder(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build()); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/MultiLineChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/MultiLineChart.java index 0d62864af..15a394c53 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/MultiLineChart.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/MultiLineChart.java @@ -8,40 +8,40 @@ public class MultiLineChart extends CustomChart { - private final Callable> callable; + private final Callable> callable; - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public MultiLineChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } - @Override - protected JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - boolean allSkipped = true; - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() == 0) { - // Skip this invalid - continue; - } - allSkipped = false; - valuesBuilder.appendField(entry.getKey(), entry.getValue()); - } - if (allSkipped) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + // Skip this invalid + continue; + } + allSkipped = false; + valuesBuilder.appendField(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimpleBarChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimpleBarChart.java index aa7d49220..03de31d97 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimpleBarChart.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimpleBarChart.java @@ -8,30 +8,30 @@ public class SimpleBarChart extends CustomChart { - private final Callable> callable; + private final Callable> callable; - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimpleBarChart(String chartId, Callable> callable) { - super(chartId); - this.callable = callable; - } + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } - @Override - protected JsonObject getChartData() throws Exception { - JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); - Map map = callable.call(); - if (map == null || map.isEmpty()) { - // Null = skip the chart - return null; - } - for (Map.Entry entry : map.entrySet()) { - valuesBuilder.appendField(entry.getKey(), new int[]{entry.getValue()}); - } - return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); - } + @Override + protected JsonObject getChartData() throws Exception { + JsonObjectBuilder valuesBuilder = new JsonObjectBuilder(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + valuesBuilder.appendField(entry.getKey(), new int[]{entry.getValue()}); + } + return new JsonObjectBuilder().appendField("values", valuesBuilder.build()).build(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimplePie.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimplePie.java index e42f4a5c7..b1f5f48eb 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimplePie.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SimplePie.java @@ -7,26 +7,26 @@ public class SimplePie extends CustomChart { - private final Callable callable; + private final Callable callable; - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SimplePie(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } - @Override - protected JsonObject getChartData() throws Exception { - String value = callable.call(); - if (value == null || value.isEmpty()) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("value", value).build(); - } + @Override + protected JsonObject getChartData() throws Exception { + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SingleLineChart.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SingleLineChart.java index 8e4d91259..8275423e2 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SingleLineChart.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/bstats/chart/SingleLineChart.java @@ -7,26 +7,26 @@ public class SingleLineChart extends CustomChart { - private final Callable callable; + private final Callable callable; - /** - * Class constructor. - * - * @param chartId The id of the chart. - * @param callable The callable which is used to request the chart data. - */ - public SingleLineChart(String chartId, Callable callable) { - super(chartId); - this.callable = callable; - } + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } - @Override - protected JsonObject getChartData() throws Exception { - int value = callable.call(); - if (value == 0) { - // Null = skip the chart - return null; - } - return new JsonObjectBuilder().appendField("value", value).build(); - } + @Override + protected JsonObject getChartData() throws Exception { + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + return new JsonObjectBuilder().appendField("value", value).build(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java index 4901ae38d..0e5bba154 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java @@ -6,59 +6,59 @@ public enum BannerPattern { - BASE_DEXTER_CANTON(PatternType.SQUARE_BOTTOM_LEFT), - BASE_SINISTER_CANTON(PatternType.SQUARE_BOTTOM_RIGHT), - CHIEF_DEXTER_CANTON(PatternType.SQUARE_TOP_LEFT), - CHIEF_SINISTER_CANTON(PatternType.SQUARE_TOP_RIGHT), - BASE(PatternType.STRIPE_BOTTOM), - CHIEF(PatternType.STRIPE_TOP), - PALE_DEXTER(PatternType.STRIPE_LEFT), - PALE_SINISTER(PatternType.STRIPE_RIGHT), - PALE(PatternType.STRIPE_CENTER), - FESS(PatternType.STRIPE_MIDDLE), - BEND(PatternType.STRIPE_DOWNRIGHT), - BEND_SINISTER(PatternType.STRIPE_DOWNLEFT), - PALY(PatternType.SMALL_STRIPES), - SALTIRE(PatternType.CROSS), - CROSS(PatternType.STRAIGHT_CROSS), - CHEVRON(PatternType.TRIANGLE_BOTTOM), - INVERTED_CHEVRON(PatternType.TRIANGLE_TOP), - BASE_INDENTED(PatternType.TRIANGLES_BOTTOM), - CHIEF_INDENTED(PatternType.TRIANGLES_TOP), - PER_BEND_SINISTER(PatternType.DIAGONAL_LEFT), - PER_BEND_SINISTER_INVERTED(PatternType.DIAGONAL_RIGHT), - PER_BEND_INVERTED(PatternType.DIAGONAL_UP_LEFT), - PER_BEND(PatternType.DIAGONAL_UP_RIGHT), - ROUNDEL(PatternType.CIRCLE), - LOZENGE(PatternType.STRIPE_MIDDLE), - PER_PALE(PatternType.HALF_VERTICAL), - PER_FESS(PatternType.HALF_HORIZONTAL), - PER_PALE_INVERTED(PatternType.HALF_VERTICAL_RIGHT), - PER_FESS_INVERTED(PatternType.HALF_HORIZONTAL_BOTTOM), - BORDURE(PatternType.BORDER), - BORDURE_INDENTED(PatternType.CURLY_BORDER), - GRADIENT(PatternType.GRADIENT), - BASE_GRADIENT(PatternType.GRADIENT_UP), - FIELD_MASONED(PatternType.BRICKS), - CREEPER_CHARGE(PatternType.CREEPER), - SKULL_CHARGE(PatternType.SKULL), - FLOWER_CHARGE(PatternType.FLOWER), - MOJANG(PatternType.MOJANG); + BASE_DEXTER_CANTON(PatternType.SQUARE_BOTTOM_LEFT), + BASE_SINISTER_CANTON(PatternType.SQUARE_BOTTOM_RIGHT), + CHIEF_DEXTER_CANTON(PatternType.SQUARE_TOP_LEFT), + CHIEF_SINISTER_CANTON(PatternType.SQUARE_TOP_RIGHT), + BASE(PatternType.STRIPE_BOTTOM), + CHIEF(PatternType.STRIPE_TOP), + PALE_DEXTER(PatternType.STRIPE_LEFT), + PALE_SINISTER(PatternType.STRIPE_RIGHT), + PALE(PatternType.STRIPE_CENTER), + FESS(PatternType.STRIPE_MIDDLE), + BEND(PatternType.STRIPE_DOWNRIGHT), + BEND_SINISTER(PatternType.STRIPE_DOWNLEFT), + PALY(PatternType.SMALL_STRIPES), + SALTIRE(PatternType.CROSS), + CROSS(PatternType.STRAIGHT_CROSS), + CHEVRON(PatternType.TRIANGLE_BOTTOM), + INVERTED_CHEVRON(PatternType.TRIANGLE_TOP), + BASE_INDENTED(PatternType.TRIANGLES_BOTTOM), + CHIEF_INDENTED(PatternType.TRIANGLES_TOP), + PER_BEND_SINISTER(PatternType.DIAGONAL_LEFT), + PER_BEND_SINISTER_INVERTED(PatternType.DIAGONAL_RIGHT), + PER_BEND_INVERTED(PatternType.DIAGONAL_UP_LEFT), + PER_BEND(PatternType.DIAGONAL_UP_RIGHT), + ROUNDEL(PatternType.CIRCLE), + LOZENGE(PatternType.STRIPE_MIDDLE), + PER_PALE(PatternType.HALF_VERTICAL), + PER_FESS(PatternType.HALF_HORIZONTAL), + PER_PALE_INVERTED(PatternType.HALF_VERTICAL_RIGHT), + PER_FESS_INVERTED(PatternType.HALF_HORIZONTAL_BOTTOM), + BORDURE(PatternType.BORDER), + BORDURE_INDENTED(PatternType.CURLY_BORDER), + GRADIENT(PatternType.GRADIENT), + BASE_GRADIENT(PatternType.GRADIENT_UP), + FIELD_MASONED(PatternType.BRICKS), + CREEPER_CHARGE(PatternType.CREEPER), + SKULL_CHARGE(PatternType.SKULL), + FLOWER_CHARGE(PatternType.FLOWER), + MOJANG(PatternType.MOJANG); - private final PatternType patternType; + private final PatternType patternType; - BannerPattern(@Nonnull PatternType patternType) { - this.patternType = patternType; - } + BannerPattern(@Nonnull PatternType patternType) { + this.patternType = patternType; + } - @Nonnull - public PatternType getPatternType() { - return patternType; - } + @Nonnull + public PatternType getPatternType() { + return patternType; + } - @Nonnull - public String getIdentifier() { - return patternType.getKeyOrThrow().getKey(); - } + @Nonnull + public String getIdentifier() { + return patternType.getKeyOrThrow().getKey(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java index 339bbaba2..527a3971b 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java @@ -21,404 +21,404 @@ public class ItemBuilder { - public static final ItemStack FILL_ITEM = new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE).setName("§0").build(), - FILL_ITEM_2 = new ItemBuilder(Material.BLACK_STAINED_GLASS_PANE).setName("§0").build(), - BLOCKED_ITEM = new ItemBuilder(Material.BARRIER, "§cBlocked").build(), - AIR = new ItemStack(Material.AIR); - - protected ItemStack item; - protected ItemMeta meta; - - public ItemBuilder(@Nonnull ItemStack item) { - this(item, item.getItemMeta()); - } - - public ItemBuilder(@Nonnull ItemStack item, @Nullable ItemMeta meta) { - this.item = item; - this.meta = meta; - } - - public ItemBuilder(@Nonnull Material material) { - this(new ItemStack(material)); - } - - public ItemBuilder(@Nonnull Material material, @Nonnull String name) { - this(material); - setName(name); - } - - public ItemBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { - this(material); - setName(name); - setLore(lore); - } - - public ItemBuilder(@Nonnull Material material, @Nonnull String name, int amount) { - this(material); - setName(name); - setAmount(amount); - } - - @Nonnull - public ItemMeta getMeta() { - return getCastedMeta(); - } - - @Nonnull - @SuppressWarnings("unchecked") - public final M getCastedMeta() { - return (M) (meta == null ? meta = item.getItemMeta() : meta); - } - - @Nonnull - public ItemBuilder setLore(@Nonnull List lore) { - getMeta().setLore(lore); - return this; - } - - @Nonnull - public ItemBuilder setLore(@Nonnull String... lore) { - return setLore(Arrays.asList(lore)); - } - - @Nonnull - public ItemBuilder appendLore(@Nonnull String... lore) { - return appendLore(Arrays.asList(lore)); - } - - @Nonnull - public ItemBuilder appendLore(@Nonnull Collection lore) { - List newLore = getMeta().getLore(); - if (newLore == null) newLore = new ArrayList<>(); - newLore.addAll(lore); - setLore(newLore); - return this; - } - - @Nonnull - public ItemBuilder lore(@Nonnull String... lore) { - return setLore(lore); - } - - @Nonnull - public ItemBuilder setName(@Nullable String name) { - getMeta().setDisplayName(name); - return this; - } - - @Nonnull - public ItemBuilder setName(@Nullable Object name) { - return setName(name == null ? null : name.toString()); - } - - @Nonnull - public ItemBuilder setName(@Nonnull String... content) { - if (content.length > 0) setName(content[0]); - if (content.length > 1) setLore(Arrays.copyOfRange(content, 1, content.length)); - return this; - } - - @Nonnull - public ItemBuilder appendName(@Nullable Object sequence) { - String name = getMeta().getDisplayName(); - return setName(name + sequence); - } - - @Nonnull - public ItemBuilder name(@Nullable Object name) { - return setName(name); - } - - @Nonnull - public ItemBuilder name(@Nonnull String... content) { - return setName(content); - } - - @Nonnull - public ItemBuilder addEnchantment(@Nonnull Enchantment enchantment, int level) { - getMeta().addEnchant(enchantment, level, true); - return this; - } - - @Nonnull - public ItemBuilder enchant(@Nonnull Enchantment enchantment, int level) { - return addEnchantment(enchantment, level); - } - - @Nonnull - public ItemBuilder addFlag(@Nonnull ItemFlag... flags) { - getMeta().addItemFlags(flags); - return this; - } - - @Nonnull - public ItemBuilder flag(@Nonnull ItemFlag... flags) { - return addFlag(flags); - } - - @Nonnull - public ItemBuilder removeFlag(@Nonnull ItemFlag... flags) { - getMeta().removeItemFlags(flags); - return this; - } - - @Nonnull - public ItemBuilder hideAttributes() { - return addFlag(ItemFlag.values()); - } - - @Nonnull - public ItemBuilder showAttributes() { - return removeFlag(ItemFlag.values()); - } - - @Nonnull - public ItemBuilder setUnbreakable(boolean unbreakable) { - getMeta().setUnbreakable(unbreakable); - return this; - } - - @Nonnull - public ItemBuilder unbreakable() { - return setUnbreakable(true); - } - - @Nonnull - public ItemBuilder breakable() { - return setUnbreakable(false); - } - - @Nonnull - public ItemBuilder setAmount(int amount) { - item.setAmount(Math.min(Math.max(amount, 0), 64)); - return this; - } - - @Nonnull - public ItemBuilder amount(int amount) { - return setAmount(amount); - } - - @Nonnull - public ItemBuilder setDamage(int damage) { - this.getCastedMeta().setDamage(damage); - return this; - } - - @Nonnull - public ItemBuilder damage(int damage) { - return setDamage(damage); - } - - @Nonnull - public ItemBuilder setType(@Nonnull Material material) { - item.setType(material); - meta = item.getItemMeta(); - return this; - } - - @Nonnull - public String getName() { - return getMeta().getDisplayName(); - } - - @Nonnull - public List getLore() { - List lore = getMeta().getLore(); - return lore == null ? new ArrayList<>() : lore; - } - - @Nonnull - public Material getType() { - return item.getType(); - } - - public int getAmount() { - return item.getAmount(); - } - - public int getDamage() { - return this.getCastedMeta().getDamage(); - } - - @Nonnull - public ItemStack build() { - item.setItemMeta(getMeta()); // Call to getter to prevent null value - return item; - } - - @Nonnull - public ItemStack toItem() { - return build(); - } - - @Override - public ItemBuilder clone() { - return new ItemBuilder(item.clone(), getMeta().clone()); - } - - public static class BannerBuilder extends ItemBuilder { - - public BannerBuilder(@Nonnull Material material) { - super(material); - } - - public BannerBuilder(@Nonnull Material material, @Nonnull String name) { - super(material, name); - } - - public BannerBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { - super(material, name, lore); - } - - public BannerBuilder(@Nonnull Material material, @Nonnull String name, int amount) { - super(material, name, amount); - } - - public BannerBuilder(@Nonnull ItemStack item) { - super(item); - } - - @Nonnull - public BannerBuilder addPattern(@Nonnull BannerPattern pattern, @Nonnull DyeColor color) { - return addPattern(pattern.getPatternType(), color); - } - - @Nonnull - public BannerBuilder addPattern(@Nonnull PatternType pattern, @Nonnull DyeColor color) { - getMeta().addPattern(new Pattern(color, pattern)); - return this; - } - - @Nonnull - @Override - public BannerMeta getMeta() { - return getCastedMeta(); - } - - } - - public static class SkullBuilder extends ItemBuilder { - - public SkullBuilder() { - super(Material.PLAYER_HEAD); - } - - public SkullBuilder(@Nonnull String owner) { - super(Material.PLAYER_HEAD); - setOwner(owner); - } - - public SkullBuilder(@Nonnull String owner, @Nonnull String name, @Nonnull String... lore) { - super(Material.PLAYER_HEAD, name, lore); - setOwner(owner); - } - - public SkullBuilder setOwner(@Nonnull String owner) { - getMeta().setOwner(owner); - return this; - } - - @Nonnull - @Override - public SkullMeta getMeta() { - return getCastedMeta(); - } - - } - - public static class PotionBuilder extends ItemBuilder { - - @Nonnull - @CheckReturnValue - public static ItemBuilder createWaterBottle() { - return new PotionBuilder(Material.POTION).setColor(Color.BLUE).hideAttributes(); - } - - public PotionBuilder(@Nonnull Material material) { - super(material); - } - - public PotionBuilder(@Nonnull Material material, @Nonnull String name) { - super(material, name); - } - - public PotionBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { - super(material, name, lore); - } - - public PotionBuilder(@Nonnull Material material, @Nonnull String name, int amount) { - super(material, name, amount); - } - - public PotionBuilder(@Nonnull ItemStack item) { - super(item); - } - - @Nonnull - public PotionBuilder addEffect(@Nonnull PotionEffect effect) { - getMeta().addCustomEffect(effect, true); - return this; - } - - @Nonnull - public PotionBuilder setColor(@Nonnull Color color) { - getMeta().setColor(color); - return this; - } - - @Nonnull - public PotionBuilder color(@Nonnull Color color) { - return setColor(color); - } - - @Nonnull - @Override - public PotionMeta getMeta() { - return getCastedMeta(); - } - - } - - public static class LeatherArmorBuilder extends ItemBuilder { - - public LeatherArmorBuilder(@Nonnull Material material) { - super(material); - } - - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name) { - super(material, name); - } - - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { - super(material, name, lore); - } - - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, int amount) { - super(material, name, amount); - } - - public LeatherArmorBuilder(@Nonnull ItemStack item) { - super(item); - } - - @Nonnull - public LeatherArmorBuilder setColor(@Nonnull Color color) { - getMeta().setColor(color); - return this; - } - - @Nonnull - public LeatherArmorBuilder color(@Nonnull Color color) { - return setColor(color); - } - - @Nonnull - @Override - public LeatherArmorMeta getMeta() { - return getCastedMeta(); - } - - } + public static final ItemStack FILL_ITEM = new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE).setName("§0").build(), + FILL_ITEM_2 = new ItemBuilder(Material.BLACK_STAINED_GLASS_PANE).setName("§0").build(), + BLOCKED_ITEM = new ItemBuilder(Material.BARRIER, "§cBlocked").build(), + AIR = new ItemStack(Material.AIR); + + protected ItemStack item; + protected ItemMeta meta; + + public ItemBuilder(@Nonnull ItemStack item) { + this(item, item.getItemMeta()); + } + + public ItemBuilder(@Nonnull ItemStack item, @Nullable ItemMeta meta) { + this.item = item; + this.meta = meta; + } + + public ItemBuilder(@Nonnull Material material) { + this(new ItemStack(material)); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name) { + this(material); + setName(name); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + this(material); + setName(name); + setLore(lore); + } + + public ItemBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + this(material); + setName(name); + setAmount(amount); + } + + @Nonnull + public ItemMeta getMeta() { + return getCastedMeta(); + } + + @Nonnull + @SuppressWarnings("unchecked") + public final M getCastedMeta() { + return (M) (meta == null ? meta = item.getItemMeta() : meta); + } + + @Nonnull + public ItemBuilder setLore(@Nonnull List lore) { + getMeta().setLore(lore); + return this; + } + + @Nonnull + public ItemBuilder setLore(@Nonnull String... lore) { + return setLore(Arrays.asList(lore)); + } + + @Nonnull + public ItemBuilder appendLore(@Nonnull String... lore) { + return appendLore(Arrays.asList(lore)); + } + + @Nonnull + public ItemBuilder appendLore(@Nonnull Collection lore) { + List newLore = getMeta().getLore(); + if (newLore == null) newLore = new ArrayList<>(); + newLore.addAll(lore); + setLore(newLore); + return this; + } + + @Nonnull + public ItemBuilder lore(@Nonnull String... lore) { + return setLore(lore); + } + + @Nonnull + public ItemBuilder setName(@Nullable String name) { + getMeta().setDisplayName(name); + return this; + } + + @Nonnull + public ItemBuilder setName(@Nullable Object name) { + return setName(name == null ? null : name.toString()); + } + + @Nonnull + public ItemBuilder setName(@Nonnull String... content) { + if (content.length > 0) setName(content[0]); + if (content.length > 1) setLore(Arrays.copyOfRange(content, 1, content.length)); + return this; + } + + @Nonnull + public ItemBuilder appendName(@Nullable Object sequence) { + String name = getMeta().getDisplayName(); + return setName(name + sequence); + } + + @Nonnull + public ItemBuilder name(@Nullable Object name) { + return setName(name); + } + + @Nonnull + public ItemBuilder name(@Nonnull String... content) { + return setName(content); + } + + @Nonnull + public ItemBuilder addEnchantment(@Nonnull Enchantment enchantment, int level) { + getMeta().addEnchant(enchantment, level, true); + return this; + } + + @Nonnull + public ItemBuilder enchant(@Nonnull Enchantment enchantment, int level) { + return addEnchantment(enchantment, level); + } + + @Nonnull + public ItemBuilder addFlag(@Nonnull ItemFlag... flags) { + getMeta().addItemFlags(flags); + return this; + } + + @Nonnull + public ItemBuilder flag(@Nonnull ItemFlag... flags) { + return addFlag(flags); + } + + @Nonnull + public ItemBuilder removeFlag(@Nonnull ItemFlag... flags) { + getMeta().removeItemFlags(flags); + return this; + } + + @Nonnull + public ItemBuilder hideAttributes() { + return addFlag(ItemFlag.values()); + } + + @Nonnull + public ItemBuilder showAttributes() { + return removeFlag(ItemFlag.values()); + } + + @Nonnull + public ItemBuilder setUnbreakable(boolean unbreakable) { + getMeta().setUnbreakable(unbreakable); + return this; + } + + @Nonnull + public ItemBuilder unbreakable() { + return setUnbreakable(true); + } + + @Nonnull + public ItemBuilder breakable() { + return setUnbreakable(false); + } + + @Nonnull + public ItemBuilder setAmount(int amount) { + item.setAmount(Math.min(Math.max(amount, 0), 64)); + return this; + } + + @Nonnull + public ItemBuilder amount(int amount) { + return setAmount(amount); + } + + @Nonnull + public ItemBuilder setDamage(int damage) { + this.getCastedMeta().setDamage(damage); + return this; + } + + @Nonnull + public ItemBuilder damage(int damage) { + return setDamage(damage); + } + + @Nonnull + public ItemBuilder setType(@Nonnull Material material) { + item.setType(material); + meta = item.getItemMeta(); + return this; + } + + @Nonnull + public String getName() { + return getMeta().getDisplayName(); + } + + @Nonnull + public List getLore() { + List lore = getMeta().getLore(); + return lore == null ? new ArrayList<>() : lore; + } + + @Nonnull + public Material getType() { + return item.getType(); + } + + public int getAmount() { + return item.getAmount(); + } + + public int getDamage() { + return this.getCastedMeta().getDamage(); + } + + @Nonnull + public ItemStack build() { + item.setItemMeta(getMeta()); // Call to getter to prevent null value + return item; + } + + @Nonnull + public ItemStack toItem() { + return build(); + } + + @Override + public ItemBuilder clone() { + return new ItemBuilder(item.clone(), getMeta().clone()); + } + + public static class BannerBuilder extends ItemBuilder { + + public BannerBuilder(@Nonnull Material material) { + super(material); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public BannerBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public BannerBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public BannerBuilder addPattern(@Nonnull BannerPattern pattern, @Nonnull DyeColor color) { + return addPattern(pattern.getPatternType(), color); + } + + @Nonnull + public BannerBuilder addPattern(@Nonnull PatternType pattern, @Nonnull DyeColor color) { + getMeta().addPattern(new Pattern(color, pattern)); + return this; + } + + @Nonnull + @Override + public BannerMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class SkullBuilder extends ItemBuilder { + + public SkullBuilder() { + super(Material.PLAYER_HEAD); + } + + public SkullBuilder(@Nonnull String owner) { + super(Material.PLAYER_HEAD); + setOwner(owner); + } + + public SkullBuilder(@Nonnull String owner, @Nonnull String name, @Nonnull String... lore) { + super(Material.PLAYER_HEAD, name, lore); + setOwner(owner); + } + + public SkullBuilder setOwner(@Nonnull String owner) { + getMeta().setOwner(owner); + return this; + } + + @Nonnull + @Override + public SkullMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class PotionBuilder extends ItemBuilder { + + @Nonnull + @CheckReturnValue + public static ItemBuilder createWaterBottle() { + return new PotionBuilder(Material.POTION).setColor(Color.BLUE).hideAttributes(); + } + + public PotionBuilder(@Nonnull Material material) { + super(material); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public PotionBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public PotionBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public PotionBuilder addEffect(@Nonnull PotionEffect effect) { + getMeta().addCustomEffect(effect, true); + return this; + } + + @Nonnull + public PotionBuilder setColor(@Nonnull Color color) { + getMeta().setColor(color); + return this; + } + + @Nonnull + public PotionBuilder color(@Nonnull Color color) { + return setColor(color); + } + + @Nonnull + @Override + public PotionMeta getMeta() { + return getCastedMeta(); + } + + } + + public static class LeatherArmorBuilder extends ItemBuilder { + + public LeatherArmorBuilder(@Nonnull Material material) { + super(material); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name) { + super(material, name); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + super(material, name, lore); + } + + public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + super(material, name, amount); + } + + public LeatherArmorBuilder(@Nonnull ItemStack item) { + super(item); + } + + @Nonnull + public LeatherArmorBuilder setColor(@Nonnull Color color) { + getMeta().setColor(color); + return this; + } + + @Nonnull + public LeatherArmorBuilder color(@Nonnull Color color) { + return setColor(color); + } + + @Nonnull + @Override + public LeatherArmorMeta getMeta() { + return getCastedMeta(); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java index e967429a8..31e95a13b 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java @@ -11,107 +11,107 @@ public class ItemUtils { - @Nonnull - public static Material convertFoodToCookedFood(@Nonnull Material material) { - try { - return Material.valueOf("COOKED_" + material.name()); - } catch (Exception ex) { - return material; // No cooked material is available - } - } + @Nonnull + public static Material convertFoodToCookedFood(@Nonnull Material material) { + try { + return Material.valueOf("COOKED_" + material.name()); + } catch (Exception ex) { + return material; // No cooked material is available + } + } - public static boolean isObtainableInSurvival(@Nonnull Material material) { - String name = material.name(); - if (BukkitReflectionUtils.isAir(material)) return false; - if (name.endsWith("_SPAWN_EGG")) return false; - if (name.startsWith("INFESTED_")) return false; - if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable - switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist - case "CHAIN_COMMAND_BLOCK": - case "REPEATING_COMMAND_BLOCK": - case "COMMAND_BLOCK": - case "COMMAND_BLOCK_MINECART": - case "JIGSAW": - case "STRUCTURE_BLOCK": - case "STRUCTURE_VOID": - case "BARRIER": - case "BEDROCK": - case "KNOWLEDGE_BOOK": - case "DEBUG_STICK": - case "END_PORTAL_FRAME": - case "END_PORTAL": - case "NETHER_PORTAL": - case "END_GATEWAY": - case "LAVA": - case "WATER": - case "LARGE_FERN": - case "TALL_GRASS": - case "TALL_SEAGRASS": - case "PATH_BLOCK": - case "CHORUS_PLANT": - case "PETRIFIED_OAK_SLAB": - case "FARMLAND": - case "PLAYER_HEAD": - case "GLOBE_BANNER_PATTERN": - case "SPAWNER": - case "AMETHYST_CLUSTER": - case "BUDDING_AMETHYST": - case "POWDER_SNOW": - case "LIGHT": - case "BUNDLE": - case "REINFORCED_DEEPSLATE": - case "FROGSPAWN": - return false; - } + public static boolean isObtainableInSurvival(@Nonnull Material material) { + String name = material.name(); + if (BukkitReflectionUtils.isAir(material)) return false; + if (name.endsWith("_SPAWN_EGG")) return false; + if (name.startsWith("INFESTED_")) return false; + if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable + switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist + case "CHAIN_COMMAND_BLOCK": + case "REPEATING_COMMAND_BLOCK": + case "COMMAND_BLOCK": + case "COMMAND_BLOCK_MINECART": + case "JIGSAW": + case "STRUCTURE_BLOCK": + case "STRUCTURE_VOID": + case "BARRIER": + case "BEDROCK": + case "KNOWLEDGE_BOOK": + case "DEBUG_STICK": + case "END_PORTAL_FRAME": + case "END_PORTAL": + case "NETHER_PORTAL": + case "END_GATEWAY": + case "LAVA": + case "WATER": + case "LARGE_FERN": + case "TALL_GRASS": + case "TALL_SEAGRASS": + case "PATH_BLOCK": + case "CHORUS_PLANT": + case "PETRIFIED_OAK_SLAB": + case "FARMLAND": + case "PLAYER_HEAD": + case "GLOBE_BANNER_PATTERN": + case "SPAWNER": + case "AMETHYST_CLUSTER": + case "BUDDING_AMETHYST": + case "POWDER_SNOW": + case "LIGHT": + case "BUNDLE": + case "REINFORCED_DEEPSLATE": + case "FROGSPAWN": + return false; + } - if (MinecraftVersion.current().isOlderThan(MinecraftVersion.V1_19)) { - return !name.equals("SCULK_SENSOR"); - } + if (MinecraftVersion.current().isOlderThan(MinecraftVersion.V1_19)) { + return !name.equals("SCULK_SENSOR"); + } - return true; - } + return true; + } - public static boolean blockIsAvailableInSurvival(@Nonnull Material material) { - if (!material.isBlock()) return false; - String name = material.name(); - if (BukkitReflectionUtils.isAir(material)) return false; - if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable - switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist - case "CHAIN_COMMAND_BLOCK": - case "REPEATING_COMMAND_BLOCK": - case "COMMAND_BLOCK": - case "COMMAND_BLOCK_MINECART": - case "JIGSAW": - case "STRUCTURE_BLOCK": - case "STRUCTURE_VOID": - case "BARRIER": - case "KNOWLEDGE_BOOK": - case "DEBUG_STICK": - case "END_PORTAL": - case "NETHER_PORTAL": - case "END_GATEWAY": - case "PETRIFIED_OAK_SLAB": - case "PLAYER_HEAD": - case "GLOBE_BANNER_PATTERN": - case "LIGHT": - case "BUNDLE": - return false; - } + public static boolean blockIsAvailableInSurvival(@Nonnull Material material) { + if (!material.isBlock()) return false; + String name = material.name(); + if (BukkitReflectionUtils.isAir(material)) return false; + if (name.startsWith("LEGACY_")) return false; // Legacy items should not be obtainable + switch (name) { // Use name instead of enum its self, to prevent NoSuchFieldErrors in older versions where this specific enum does not exist + case "CHAIN_COMMAND_BLOCK": + case "REPEATING_COMMAND_BLOCK": + case "COMMAND_BLOCK": + case "COMMAND_BLOCK_MINECART": + case "JIGSAW": + case "STRUCTURE_BLOCK": + case "STRUCTURE_VOID": + case "BARRIER": + case "KNOWLEDGE_BOOK": + case "DEBUG_STICK": + case "END_PORTAL": + case "NETHER_PORTAL": + case "END_GATEWAY": + case "PETRIFIED_OAK_SLAB": + case "PLAYER_HEAD": + case "GLOBE_BANNER_PATTERN": + case "LIGHT": + case "BUNDLE": + return false; + } - return true; - } + return true; + } - public static void damageItem(@Nonnull ItemStack item) { - damageItem(item, 1); - } + public static void damageItem(@Nonnull ItemStack item) { + damageItem(item, 1); + } - public static void damageItem(@Nonnull ItemStack item, int amount) { - ItemMeta meta = item.getItemMeta(); - if (meta == null) return; - if (!(meta instanceof Damageable)) return; - Damageable damageable = (Damageable) meta; - damageable.setDamage(damageable.getDamage() + amount); - item.setItemMeta(meta); - } + public static void damageItem(@Nonnull ItemStack item, int amount) { + ItemMeta meta = item.getItemMeta(); + if (meta == null) return; + if (!(meta instanceof Damageable)) return; + Damageable damageable = (Damageable) meta; + damageable.setDamage(damageable.getDamage() + amount); + item.setItemMeta(meta); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java index ac6f766f5..29c385e2c 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java @@ -9,31 +9,32 @@ public final class Logger { - private Logger() {} + private Logger() { + } - @Nonnull - public static ILogger getInstance() { - return BukkitModule.getProvidingModule(ReflectionUtils.getCaller()).getILogger(); - } + @Nonnull + public static ILogger getInstance() { + return BukkitModule.getProvidingModule(ReflectionUtils.getCaller()).getILogger(); + } - public static void error(@Nullable Object message, @Nonnull Object... args) { - getInstance().error(message, args); - } + public static void error(@Nullable Object message, @Nonnull Object... args) { + getInstance().error(message, args); + } - public static void warn(@Nullable Object message, @Nonnull Object... args) { - getInstance().warn(message, args); - } + public static void warn(@Nullable Object message, @Nonnull Object... args) { + getInstance().warn(message, args); + } - public static void info(@Nullable Object message, @Nonnull Object... args) { - getInstance().info(message, args); - } + public static void info(@Nullable Object message, @Nonnull Object... args) { + getInstance().info(message, args); + } - public static void debug(@Nullable Object message, @Nonnull Object... args) { - getInstance().debug(message, args); - } + public static void debug(@Nullable Object message, @Nonnull Object... args) { + getInstance().debug(message, args); + } - public static void trace(@Nullable Object message, @Nonnull Object... args) { - getInstance().trace(message, args); - } + public static void trace(@Nullable Object message, @Nonnull Object... args) { + getInstance().trace(message, args); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java index 5753ad174..91dc239b1 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java @@ -11,65 +11,65 @@ public class MenuClickInfo { - protected final Player player; - protected final Inventory inventory; - protected final boolean shiftClick; - protected final boolean rightClick; - protected final int slot; + protected final Player player; + protected final Inventory inventory; + protected final boolean shiftClick; + protected final boolean rightClick; + protected final int slot; - public MenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boolean shiftClick, boolean rightClick, @Nonnegative int slot) { - this.player = player; - this.inventory = inventory; - this.shiftClick = shiftClick; - this.rightClick = rightClick; - this.slot = slot; - } + public MenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boolean shiftClick, boolean rightClick, @Nonnegative int slot) { + this.player = player; + this.inventory = inventory; + this.shiftClick = shiftClick; + this.rightClick = rightClick; + this.slot = slot; + } - @Nonnull - public Player getPlayer() { - return player; - } + @Nonnull + public Player getPlayer() { + return player; + } - @Nonnull - public Inventory getInventory() { - return inventory; - } + @Nonnull + public Inventory getInventory() { + return inventory; + } - public boolean isRightClick() { - return rightClick; - } + public boolean isRightClick() { + return rightClick; + } - public boolean isLeftClick() { - return !rightClick; - } + public boolean isLeftClick() { + return !rightClick; + } - public boolean isShiftClick() { - return shiftClick; - } + public boolean isShiftClick() { + return shiftClick; + } - public int getSlot() { - return slot; - } + public int getSlot() { + return slot; + } - @Nullable - public ItemStack getClickedItem() { - return inventory.getItem(slot); - } + @Nullable + public ItemStack getClickedItem() { + return inventory.getItem(slot); + } - @Nonnull - public Material getClickedMaterial() { - return getClickedItem() == null ? Material.AIR : getClickedItem().getType(); - } + @Nonnull + public Material getClickedMaterial() { + return getClickedItem() == null ? Material.AIR : getClickedItem().getType(); + } - @Override - public String toString() { - return "MenuClickInfo{" + - "player=" + player + - ", inventory=" + inventory + - ", shiftClick=" + shiftClick + - ", rightClick=" + rightClick + - ", slot=" + slot + - '}'; - } + @Override + public String toString() { + return "MenuClickInfo{" + + "player=" + player + + ", inventory=" + inventory + + ", shiftClick=" + shiftClick + + ", rightClick=" + rightClick + + ", slot=" + slot + + '}'; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java index 527cc844f..9df01539e 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java @@ -12,33 +12,34 @@ @FunctionalInterface public interface MenuPosition { - final class Holder { + final class Holder { - private Holder() {} + private Holder() { + } - private static final Map positions = new ConcurrentHashMap<>(); + private static final Map positions = new ConcurrentHashMap<>(); - } + } - InventoryHolder HOLDER = new MenuPositionHolder(); + InventoryHolder HOLDER = new MenuPositionHolder(); - static void set(@Nonnull Player player, @Nullable MenuPosition position) { - Holder.positions.put(player, position); - } + static void set(@Nonnull Player player, @Nullable MenuPosition position) { + Holder.positions.put(player, position); + } - static void remove(@Nonnull Player player) { - Holder.positions.remove(player); - } + static void remove(@Nonnull Player player) { + Holder.positions.remove(player); + } - @Nullable - static MenuPosition get(@Nonnull Player player) { - return Holder.positions.get(player); - } + @Nullable + static MenuPosition get(@Nonnull Player player) { + return Holder.positions.get(player); + } - static void setEmpty(@Nonnull Player player) { - set(player, new EmptyMenuPosition()); - } + static void setEmpty(@Nonnull Player player) { + set(player, new EmptyMenuPosition()); + } - void handleClick(@Nonnull MenuClickInfo info); + void handleClick(@Nonnull MenuClickInfo info); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java index 669b1367f..283f7b3c4 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java @@ -7,10 +7,10 @@ class MenuPositionHolder implements InventoryHolder { - @Nonnull - @Override - public Inventory getInventory() { - return null; - } + @Nonnull + @Override + public Inventory getInventory() { + return null; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java index 8addddaca..69a025729 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java @@ -13,35 +13,35 @@ public final class MenuPositionListener implements Listener { - @EventHandler(priority = EventPriority.LOW) - public void onClick(@Nonnull InventoryClickEvent event) { + @EventHandler(priority = EventPriority.LOW) + public void onClick(@Nonnull InventoryClickEvent event) { - HumanEntity human = event.getWhoClicked(); - if (!(human instanceof Player)) return; - Player player = (Player) human; + HumanEntity human = event.getWhoClicked(); + if (!(human instanceof Player)) return; + Player player = (Player) human; - Inventory inventory = event.getClickedInventory(); - if (inventory == null) return; + Inventory inventory = event.getClickedInventory(); + if (inventory == null) return; - if (inventory == CompatibilityUtils.getTopInventory(event)) { + if (inventory == CompatibilityUtils.getTopInventory(event)) { - if (inventory.getHolder() != MenuPosition.HOLDER) return; // No menu inventory + if (inventory.getHolder() != MenuPosition.HOLDER) return; // No menu inventory - MenuPosition position = MenuPosition.get(player); - if (position == null) return; // Currently in no menu + MenuPosition position = MenuPosition.get(player); + if (position == null) return; // Currently in no menu - event.setCancelled(true); - position.handleClick(new MenuClickInfo(player, inventory, event.isShiftClick(), event.isRightClick(), event.getSlot())); + event.setCancelled(true); + position.handleClick(new MenuClickInfo(player, inventory, event.isShiftClick(), event.isRightClick(), event.getSlot())); - } else if (event.isShiftClick()) { // Player inventory was clicked + } else if (event.isShiftClick()) { // Player inventory was clicked - Inventory topInventory = event.getInventory(); - if (topInventory.getHolder() != MenuPosition.HOLDER) return; // No menu inventory + Inventory topInventory = event.getInventory(); + if (topInventory.getHolder() != MenuPosition.HOLDER) return; // No menu inventory - event.setCancelled(true); + event.setCancelled(true); - } + } - } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java index dfe653abf..badfbf48a 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java @@ -8,9 +8,9 @@ public class EmptyMenuPosition implements MenuPosition { - @Override - public void handleClick(@Nonnull MenuClickInfo info) { - SoundSample.CLICK.play(info.getPlayer()); - } + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + SoundSample.CLICK.play(info.getPlayer()); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java index 8ea854148..5b7755881 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java @@ -12,39 +12,39 @@ public class SlottedMenuPosition implements MenuPosition { - protected final Map> actions = new HashMap<>(); - protected boolean emptySound = true; - - @Override - public void handleClick(@Nonnull MenuClickInfo info) { - Consumer action = actions.get(info.getSlot()); - if (action == null) { - if (emptySound) SoundSample.CLICK.play(info.getPlayer()); - return; - } - - action.accept(info); - } - - @Nonnull - public SlottedMenuPosition setAction(int slot, @Nonnull Consumer action) { - actions.put(slot, action); - return this; - } - - @Nonnull - public SlottedMenuPosition setPlayerAction(int slot, @Nonnull Consumer action) { - return setAction(slot, info -> action.accept(info.getPlayer())); - } - - @Nonnull - public SlottedMenuPosition setAction(int slot, @Nonnull Runnable action) { - return setAction(slot, info -> action.run()); - } - - public SlottedMenuPosition setEmptySound(boolean playSound) { - this.emptySound = playSound; - return this; - } + protected final Map> actions = new HashMap<>(); + protected boolean emptySound = true; + + @Override + public void handleClick(@Nonnull MenuClickInfo info) { + Consumer action = actions.get(info.getSlot()); + if (action == null) { + if (emptySound) SoundSample.CLICK.play(info.getPlayer()); + return; + } + + action.accept(info); + } + + @Nonnull + public SlottedMenuPosition setAction(int slot, @Nonnull Consumer action) { + actions.put(slot, action); + return this; + } + + @Nonnull + public SlottedMenuPosition setPlayerAction(int slot, @Nonnull Consumer action) { + return setAction(slot, info -> action.accept(info.getPlayer())); + } + + @Nonnull + public SlottedMenuPosition setAction(int slot, @Nonnull Runnable action) { + return setAction(slot, info -> action.run()); + } + + public SlottedMenuPosition setEmptySound(boolean playSound) { + this.emptySound = playSound; + return this; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java index 36284f5e3..7fad422f7 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java @@ -21,150 +21,150 @@ */ public final class BukkitReflectionUtils { - private static final ILogger logger = ILogger.forThisClass(); - - private BukkitReflectionUtils() { - } - - public static double getAbsorptionAmount(@Nonnull Player player) { - Class classOfPlayer = player.getClass(); - - try { - return player.getAbsorptionAmount(); - } catch (Throwable ignored) { - } - - try { - Method getHandleMethod = classOfPlayer.getMethod("getHandle"); - getHandleMethod.setAccessible(true); - - Object handle = getHandleMethod.invoke(player); - Class classOfHandle = handle.getClass(); - - Method getAbsorptionMethod = classOfHandle.getMethod("getAbsorptionHearts"); - getAbsorptionMethod.setAccessible(true); - return (double) (float) getAbsorptionMethod.invoke(handle); - } catch (Throwable ignored) { - } - - logger.warn("Could not get absorption amount for player of class {}", classOfPlayer.getName()); - return 0; - } - - public static boolean isAir(@Nonnull Material material) { - try { - return material.isAir(); - } catch (Throwable ignored) { - } - - switch (material.name()) { - case "AIR": - case "VOID_AIR": - case "CAVE_AIR": - case "LEGACY_AIR": - return true; - default: - return false; - } - } - - public static int getMinHeight(@Nonnull World world) { - try { - return world.getMinHeight(); - } catch (Throwable ignored) { - } - - return 0; - } - - /** - * @return if the entity is in water, {@code false} otherwise or if not implemented - * @deprecated not implemented in all forks of bukkit - */ - @Deprecated - public static boolean isInWater(@Nonnull Entity entity) { - try { - return entity.isInWater(); - } catch (Throwable ignored) { - } - - return false; - } - - private static final Pattern VALID_KEY = Pattern.compile("[a-z0-9/._-]+"); - - /** - * Get a NamespacedKey from the supplied string. - * - * The default namespace will be Minecraft's (i.e. - * {@link NamespacedKey#minecraft(String)}). - * - * @param key the key to convert to a NamespacedKey - * @return the created NamespacedKey. null if invalid - * @see #fromString(String, Plugin) - */ - @Nullable - public static NamespacedKey fromString(@Nonnull String key) { - return fromString(key, null); - } - - /** - * Does not exists in versions prior to 1.14 - * - * Get a NamespacedKey from the supplied string with a default namespace if - * a namespace is not defined. This is a utility method meant to fetch a - * NamespacedKey from user input. Please note that casing does matter and - * any instance of uppercase characters will be considered invalid. The - * input contract is as follows: - *

-	 * fromString("foo", plugin) -{@literal >} "plugin:foo"
-	 * fromString("foo:bar", plugin) -{@literal >} "foo:bar"
-	 * fromString(":foo", null) -{@literal >} "minecraft:foo"
-	 * fromString("foo", null) -{@literal >} "minecraft:foo"
-	 * fromString("Foo", plugin) -{@literal >} null
-	 * fromString(":Foo", plugin) -{@literal >} null
-	 * fromString("foo:bar:bazz", plugin) -{@literal >} null
-	 * fromString("", plugin) -{@literal >} null
-	 * 
- * - * @param string the string to convert to a NamespacedKey - * @param defaultNamespace the default namespace to use if none was - * supplied. If null, the {@code minecraft} namespace - * ({@link NamespacedKey#minecraft(String)}) will be used - * @return the created NamespacedKey. null if invalid key - * @see #fromString(String) - */ - @Nullable - public static NamespacedKey fromString(@Nonnull String string, @Nullable Plugin defaultNamespace) { - Preconditions.checkArgument(string != null && !string.isEmpty(), "Input string must not be empty or null"); - - String[] components = string.split(":", 3); - if (components.length > 2) { - return null; - } - - String key = (components.length == 2) ? components[1] : ""; - if (components.length == 1) { - String value = components[0]; - if (value.isEmpty() || !VALID_KEY.matcher(value).matches()) { - return null; - } - - return (defaultNamespace != null) ? new NamespacedKey(defaultNamespace, value) : NamespacedKey.minecraft(value); - } else if (components.length == 2 && !VALID_KEY.matcher(key).matches()) { - return null; - } - - String namespace = components[0]; - if (namespace.isEmpty()) { - return (defaultNamespace != null) ? new NamespacedKey(defaultNamespace, key) : NamespacedKey.minecraft(key); - } - - if (!VALID_KEY.matcher(namespace).matches()) { - return null; - } - - return new NamespacedKey(namespace, key); - } + private static final ILogger logger = ILogger.forThisClass(); + + private BukkitReflectionUtils() { + } + + public static double getAbsorptionAmount(@Nonnull Player player) { + Class classOfPlayer = player.getClass(); + + try { + return player.getAbsorptionAmount(); + } catch (Throwable ignored) { + } + + try { + Method getHandleMethod = classOfPlayer.getMethod("getHandle"); + getHandleMethod.setAccessible(true); + + Object handle = getHandleMethod.invoke(player); + Class classOfHandle = handle.getClass(); + + Method getAbsorptionMethod = classOfHandle.getMethod("getAbsorptionHearts"); + getAbsorptionMethod.setAccessible(true); + return (double) (float) getAbsorptionMethod.invoke(handle); + } catch (Throwable ignored) { + } + + logger.warn("Could not get absorption amount for player of class {}", classOfPlayer.getName()); + return 0; + } + + public static boolean isAir(@Nonnull Material material) { + try { + return material.isAir(); + } catch (Throwable ignored) { + } + + switch (material.name()) { + case "AIR": + case "VOID_AIR": + case "CAVE_AIR": + case "LEGACY_AIR": + return true; + default: + return false; + } + } + + public static int getMinHeight(@Nonnull World world) { + try { + return world.getMinHeight(); + } catch (Throwable ignored) { + } + + return 0; + } + + /** + * @return if the entity is in water, {@code false} otherwise or if not implemented + * @deprecated not implemented in all forks of bukkit + */ + @Deprecated + public static boolean isInWater(@Nonnull Entity entity) { + try { + return entity.isInWater(); + } catch (Throwable ignored) { + } + + return false; + } + + private static final Pattern VALID_KEY = Pattern.compile("[a-z0-9/._-]+"); + + /** + * Get a NamespacedKey from the supplied string. + *

+ * The default namespace will be Minecraft's (i.e. + * {@link NamespacedKey#minecraft(String)}). + * + * @param key the key to convert to a NamespacedKey + * @return the created NamespacedKey. null if invalid + * @see #fromString(String, Plugin) + */ + @Nullable + public static NamespacedKey fromString(@Nonnull String key) { + return fromString(key, null); + } + + /** + * Does not exists in versions prior to 1.14 + *

+ * Get a NamespacedKey from the supplied string with a default namespace if + * a namespace is not defined. This is a utility method meant to fetch a + * NamespacedKey from user input. Please note that casing does matter and + * any instance of uppercase characters will be considered invalid. The + * input contract is as follows: + *

+   * fromString("foo", plugin) -{@literal >} "plugin:foo"
+   * fromString("foo:bar", plugin) -{@literal >} "foo:bar"
+   * fromString(":foo", null) -{@literal >} "minecraft:foo"
+   * fromString("foo", null) -{@literal >} "minecraft:foo"
+   * fromString("Foo", plugin) -{@literal >} null
+   * fromString(":Foo", plugin) -{@literal >} null
+   * fromString("foo:bar:bazz", plugin) -{@literal >} null
+   * fromString("", plugin) -{@literal >} null
+   * 
+ * + * @param string the string to convert to a NamespacedKey + * @param defaultNamespace the default namespace to use if none was + * supplied. If null, the {@code minecraft} namespace + * ({@link NamespacedKey#minecraft(String)}) will be used + * @return the created NamespacedKey. null if invalid key + * @see #fromString(String) + */ + @Nullable + public static NamespacedKey fromString(@Nonnull String string, @Nullable Plugin defaultNamespace) { + Preconditions.checkArgument(string != null && !string.isEmpty(), "Input string must not be empty or null"); + + String[] components = string.split(":", 3); + if (components.length > 2) { + return null; + } + + String key = (components.length == 2) ? components[1] : ""; + if (components.length == 1) { + String value = components[0]; + if (value.isEmpty() || !VALID_KEY.matcher(value).matches()) { + return null; + } + + return (defaultNamespace != null) ? new NamespacedKey(defaultNamespace, value) : NamespacedKey.minecraft(value); + } else if (components.length == 2 && !VALID_KEY.matcher(key).matches()) { + return null; + } + + String namespace = components[0]; + if (namespace.isEmpty()) { + return (defaultNamespace != null) ? new NamespacedKey(defaultNamespace, key) : NamespacedKey.minecraft(key); + } + + if (!VALID_KEY.matcher(namespace).matches()) { + return null; + } + + return new NamespacedKey(namespace, key); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java index 44d8d380f..b847c02d3 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java @@ -15,77 +15,78 @@ public final class GameProfileUtils { - private static final ILogger logger = ILogger.forThisClass(); - - private GameProfileUtils() {} - - @Nonnull - public static GameProfile getGameProfile(@Nonnull Player player) { - try { - - Class classOfPlayer = player.getClass(); - - Method getProfileMethod = classOfPlayer.getMethod("getProfile"); - getProfileMethod.setAccessible(true); - return (GameProfile) getProfileMethod.invoke(player); - - } catch (Exception ex) { - throw new WrappedException(ex); - } - } - - public static void applyTextures(@Nonnull SkullMeta meta, @Nullable UUID uuid, @Nullable String name, @Nullable String texture) { - applyTextures(meta, uuid, name, texture, null); - } - - public static void applyTextures(@Nonnull SkullMeta meta, @Nullable UUID uuid, @Nullable String name, @Nullable String texture, @Nullable String signature) { - if (texture == null || texture.isEmpty()) return; - - GameProfile profile = new GameProfile(uuid == null ? UUID.randomUUID() : uuid, name); - profile.getProperties().put("textures", new Property("textures", texture, signature)); - - Class classOfMeta = meta.getClass(); - try { - Method setProfileMethod = classOfMeta.getDeclaredMethod("setProfile", GameProfile.class); - setProfileMethod.setAccessible(true); - setProfileMethod.invoke(meta, profile); - return; - } catch (Exception ignored) { - } - - try { - Field field = classOfMeta.getDeclaredField("profile"); - field.setAccessible(true); - field.set(meta, profile); - - // This field is not implemented in every version - try { - field = classOfMeta.getDeclaredField("serializedProfile"); - field.setAccessible(true); - field.set(meta, profile); - } catch (Exception ignored) { - } - - return; - } catch (Exception ignored) { - } - - logger.warn("Unable to apply textures to item"); - - } - - @Nonnull - public static GameProfile getTextures(@Nonnull SkullMeta meta) { - - Class classOfMeta = meta.getClass(); - try { - Field field = classOfMeta.getDeclaredField("profile"); - field.setAccessible(true); - return (GameProfile) field.get(meta); - } catch (Exception ex) { - throw new WrappedException(ex); - } - - } + private static final ILogger logger = ILogger.forThisClass(); + + private GameProfileUtils() { + } + + @Nonnull + public static GameProfile getGameProfile(@Nonnull Player player) { + try { + + Class classOfPlayer = player.getClass(); + + Method getProfileMethod = classOfPlayer.getMethod("getProfile"); + getProfileMethod.setAccessible(true); + return (GameProfile) getProfileMethod.invoke(player); + + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + public static void applyTextures(@Nonnull SkullMeta meta, @Nullable UUID uuid, @Nullable String name, @Nullable String texture) { + applyTextures(meta, uuid, name, texture, null); + } + + public static void applyTextures(@Nonnull SkullMeta meta, @Nullable UUID uuid, @Nullable String name, @Nullable String texture, @Nullable String signature) { + if (texture == null || texture.isEmpty()) return; + + GameProfile profile = new GameProfile(uuid == null ? UUID.randomUUID() : uuid, name); + profile.getProperties().put("textures", new Property("textures", texture, signature)); + + Class classOfMeta = meta.getClass(); + try { + Method setProfileMethod = classOfMeta.getDeclaredMethod("setProfile", GameProfile.class); + setProfileMethod.setAccessible(true); + setProfileMethod.invoke(meta, profile); + return; + } catch (Exception ignored) { + } + + try { + Field field = classOfMeta.getDeclaredField("profile"); + field.setAccessible(true); + field.set(meta, profile); + + // This field is not implemented in every version + try { + field = classOfMeta.getDeclaredField("serializedProfile"); + field.setAccessible(true); + field.set(meta, profile); + } catch (Exception ignored) { + } + + return; + } catch (Exception ignored) { + } + + logger.warn("Unable to apply textures to item"); + + } + + @Nonnull + public static GameProfile getTextures(@Nonnull SkullMeta meta) { + + Class classOfMeta = meta.getClass(); + try { + Field field = classOfMeta.getDeclaredField("profile"); + field.setAccessible(true); + return (GameProfile) field.get(meta); + } catch (Exception ex) { + throw new WrappedException(ex); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java index 16e369a67..a131416f3 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java @@ -8,108 +8,108 @@ public enum MinecraftVersion implements Version { - V1_0, // 1.0 - V1_1, // 1.1 - V1_2_1, // 1.2.1 - V1_3_1, // 1.3.1 - V1_4_2, // 1.4.2 - V1_5, // 1.5 - V1_6, // 1.6 - V1_7, // 1.7 - V1_7_2, // 1.7.2 - V1_8, // 1.8 - V1_9, // 1.9 - V1_10, // 1.10 - V1_11, // 1.11 - V1_12, // 1.12 - V1_13, // 1.13 - V1_14, // 1.14 - V1_15, // 1.15 - V1_16, // 1.16 - V1_16_5, // 1.16.5 - V1_17, // 1.17 - V1_18, // 1.18 - V1_19, // 1.19 - V1_20, // 1.20 - V1_20_1, // 1.20.1 - V1_20_2, // 1.20.2 - V1_20_3, // 1.20.3 - V1_20_4, // 1.20.4 - V1_20_5, // 1.20.5 - V1_21, // 1.21 - V1_21_1, // 1.21.1 - V1_21_2, // 1.21.2 - V1_21_3, // 1.21.3 - V1_21_4, // 1.21.4 - V1_21_5 // 1.21.5 - ; - - private final int major, minor, revision; - - MinecraftVersion() { - - String name = this.name().substring(1); - String[] version = name.split("_"); - - if (version.length != 2 && version.length != 3) - throw new IllegalArgumentException("Name '" + name() + "' does not match pattern: V{major}_{minor}_[revision]"); - - major = Integer.parseInt(version[0]); - minor = Integer.parseInt(version[1]); - revision = version.length > 2 ? Integer.parseInt(version[2]) : 0; - - } - - @Override - public int getMajor() { - return major; - } - - @Override - public int getMinor() { - return minor; - } - - @Override - public int getRevision() { - return revision; - } - - @Override - public String toString() { - return this.format(); - } - - @Nonnull - @CheckReturnValue - public static Version parseExact(@Nonnull String bukkitVersion) { - bukkitVersion = bukkitVersion.substring(0, bukkitVersion.indexOf("-")); - return Version.parse(bukkitVersion); - } - - @Nonnull - @CheckReturnValue - public static MinecraftVersion findNearest(@Nonnull Version realVersion) { - return Version.findNearest(realVersion, values()); - } - - private static Version currentExact; - private static MinecraftVersion current; - - @Nonnull - @CheckReturnValue - public static Version currentExact() { - if (currentExact == null) - currentExact = parseExact(Bukkit.getBukkitVersion()); - return currentExact; - } - - @Nonnull - @CheckReturnValue - public static MinecraftVersion current() { - if (current == null) - current = findNearest(currentExact()); - return current; - } + V1_0, // 1.0 + V1_1, // 1.1 + V1_2_1, // 1.2.1 + V1_3_1, // 1.3.1 + V1_4_2, // 1.4.2 + V1_5, // 1.5 + V1_6, // 1.6 + V1_7, // 1.7 + V1_7_2, // 1.7.2 + V1_8, // 1.8 + V1_9, // 1.9 + V1_10, // 1.10 + V1_11, // 1.11 + V1_12, // 1.12 + V1_13, // 1.13 + V1_14, // 1.14 + V1_15, // 1.15 + V1_16, // 1.16 + V1_16_5, // 1.16.5 + V1_17, // 1.17 + V1_18, // 1.18 + V1_19, // 1.19 + V1_20, // 1.20 + V1_20_1, // 1.20.1 + V1_20_2, // 1.20.2 + V1_20_3, // 1.20.3 + V1_20_4, // 1.20.4 + V1_20_5, // 1.20.5 + V1_21, // 1.21 + V1_21_1, // 1.21.1 + V1_21_2, // 1.21.2 + V1_21_3, // 1.21.3 + V1_21_4, // 1.21.4 + V1_21_5 // 1.21.5 + ; + + private final int major, minor, revision; + + MinecraftVersion() { + + String name = this.name().substring(1); + String[] version = name.split("_"); + + if (version.length != 2 && version.length != 3) + throw new IllegalArgumentException("Name '" + name() + "' does not match pattern: V{major}_{minor}_[revision]"); + + major = Integer.parseInt(version[0]); + minor = Integer.parseInt(version[1]); + revision = version.length > 2 ? Integer.parseInt(version[2]) : 0; + + } + + @Override + public int getMajor() { + return major; + } + + @Override + public int getMinor() { + return minor; + } + + @Override + public int getRevision() { + return revision; + } + + @Override + public String toString() { + return this.format(); + } + + @Nonnull + @CheckReturnValue + public static Version parseExact(@Nonnull String bukkitVersion) { + bukkitVersion = bukkitVersion.substring(0, bukkitVersion.indexOf("-")); + return Version.parse(bukkitVersion); + } + + @Nonnull + @CheckReturnValue + public static MinecraftVersion findNearest(@Nonnull Version realVersion) { + return Version.findNearest(realVersion, values()); + } + + private static Version currentExact; + private static MinecraftVersion current; + + @Nonnull + @CheckReturnValue + public static Version currentExact() { + if (currentExact == null) + currentExact = parseExact(Bukkit.getBukkitVersion()); + return currentExact; + } + + @Nonnull + @CheckReturnValue + public static MinecraftVersion current() { + if (current == null) + current = findNearest(currentExact()); + return current; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java index 8faa0993b..7b15596df 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java @@ -10,48 +10,48 @@ public final class ActionListener implements Listener { - private final Class classOfEvent; - private final Consumer listener; - private final EventPriority priority; - private final boolean ignoreCancelled; - - public ActionListener(@Nonnull Class classOfEvent, @Nonnull Consumer listener, @Nonnull EventPriority priority, boolean ignoreCancelled) { - this.classOfEvent = classOfEvent; - this.listener = listener; - this.priority = priority; - this.ignoreCancelled = ignoreCancelled; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ActionListener that = (ActionListener) o; - return listener.equals(that.listener); - } - - @Override - public int hashCode() { - return Objects.hash(listener); - } - - @Nonnull - public Consumer getListener() { - return listener; - } - - @Nonnull - public EventPriority getPriority() { - return priority; - } - - @Nonnull - public Class getClassOfEvent() { - return classOfEvent; - } - - public boolean isIgnoreCancelled() { - return ignoreCancelled; - } + private final Class classOfEvent; + private final Consumer listener; + private final EventPriority priority; + private final boolean ignoreCancelled; + + public ActionListener(@Nonnull Class classOfEvent, @Nonnull Consumer listener, @Nonnull EventPriority priority, boolean ignoreCancelled) { + this.classOfEvent = classOfEvent; + this.listener = listener; + this.priority = priority; + this.ignoreCancelled = ignoreCancelled; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ActionListener that = (ActionListener) o; + return listener.equals(that.listener); + } + + @Override + public int hashCode() { + return Objects.hash(listener); + } + + @Nonnull + public Consumer getListener() { + return listener; + } + + @Nonnull + public EventPriority getPriority() { + return priority; + } + + @Nonnull + public Class getClassOfEvent() { + return classOfEvent; + } + + public boolean isIgnoreCancelled() { + return ignoreCancelled; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java index d073dd81f..394e5c037 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java @@ -12,16 +12,17 @@ */ public final class MaterialWrapper { - private MaterialWrapper() {} + private MaterialWrapper() { + } - public static final Material GREEN_DYE = getMaterialByNames("CACTUS_GREEN", "GREEN_DYE"); - public static final Material RED_DYE = getMaterialByNames("ROSE_RED", "RED_DYE"); - public static final Material YELLOW_DYE = getMaterialByNames("DANDELION_YELLOW", "YELLOW_DYE"); - public static final Material SIGN = getMaterialByNames("SIGN", "OAK_SIGN"); + public static final Material GREEN_DYE = getMaterialByNames("CACTUS_GREEN", "GREEN_DYE"); + public static final Material RED_DYE = getMaterialByNames("ROSE_RED", "RED_DYE"); + public static final Material YELLOW_DYE = getMaterialByNames("DANDELION_YELLOW", "YELLOW_DYE"); + public static final Material SIGN = getMaterialByNames("SIGN", "OAK_SIGN"); - @Nonnull - private static Material getMaterialByNames(@Nonnull String... names) { - return ReflectionUtils.getFirstEnumByNames(Material.class, names); - } + @Nonnull + private static Material getMaterialByNames(@Nonnull String... names) { + return ReflectionUtils.getFirstEnumByNames(Material.class, names); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java index 2b3055417..67e433db0 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java @@ -10,22 +10,22 @@ public class SimpleEventExecutor implements EventExecutor { - private final Class classOfEvent; - private final Consumer action; + private final Class classOfEvent; + private final Consumer action; - public SimpleEventExecutor(@Nonnull Class classOfEvent, @Nonnull Consumer action) { - this.classOfEvent = classOfEvent; - this.action = action; - } + public SimpleEventExecutor(@Nonnull Class classOfEvent, @Nonnull Consumer action) { + this.classOfEvent = classOfEvent; + this.action = action; + } - @Override - public void execute(@Nonnull Listener listener, @Nonnull Event event) throws EventException { - if (!classOfEvent.isAssignableFrom(event.getClass())) return; - try { - action.accept(event); - } catch (Throwable ex) { - throw new EventException(ex); - } - } + @Override + public void execute(@Nonnull Listener listener, @Nonnull Event event) throws EventException { + if (!classOfEvent.isAssignableFrom(event.getClass())) return; + try { + action.accept(event); + } catch (Throwable ex) { + throw new EventException(ex); + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java index 685852b83..586f5eaec 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java @@ -11,7 +11,7 @@ @Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) public @interface AlsoKnownAs { - @Nonnull - String[] value(); + @Nonnull + String[] value(); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java index 72fb1e113..4d7ad3555 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java @@ -11,7 +11,7 @@ @Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE}) public @interface DeprecatedSince { - @Nonnull - String value(); + @Nonnull + String value(); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java index 469355d3b..4ddc70147 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java @@ -11,7 +11,7 @@ @Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE}) public @interface ReplaceWith { - @Nonnull - String value(); + @Nonnull + String value(); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java index 0f27a0c69..eed4e34d0 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java @@ -8,7 +8,7 @@ @Retention(RetentionPolicy.RUNTIME) public @interface Since { - @Nonnull - String value(); + @Nonnull + String value(); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java b/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java index 23ba208f9..e4e54e98d 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java @@ -8,49 +8,50 @@ public class ArrayWalker implements Iterable { - protected final Object array; - protected final int length; - - protected ArrayWalker(@Nonnull Object array) { - if (!array.getClass().isArray()) throw new IllegalArgumentException(array.getClass().getName() + " is not an array"); - this.array = array; - this.length = Array.getLength(array); - } - - public static ArrayWalker walk(@Nonnull Object array) { - return new ArrayWalker<>(array); - } - - public static ArrayWalker walk(@Nonnull T... array) { - return new ArrayWalker<>(array); - } - - @Override - public Iterator iterator() { - return new Iterator() { - - private int cursor = 0; - - @Override - public boolean hasNext() { - return cursor < length; - } - - @Override - @SuppressWarnings("unchecked") - public T next() { - if (!hasNext()) throw new NoSuchElementException(); - return (T) Array.get(array, cursor++); - } - - }; - } - - @Override - @SuppressWarnings("unchecked") - public void forEach(Consumer action) { - for (int i = 0; i < length; i++) { - action.accept((T) Array.get(array, i)); - } - } + protected final Object array; + protected final int length; + + protected ArrayWalker(@Nonnull Object array) { + if (!array.getClass().isArray()) + throw new IllegalArgumentException(array.getClass().getName() + " is not an array"); + this.array = array; + this.length = Array.getLength(array); + } + + public static ArrayWalker walk(@Nonnull Object array) { + return new ArrayWalker<>(array); + } + + public static ArrayWalker walk(@Nonnull T... array) { + return new ArrayWalker<>(array); + } + + @Override + public Iterator iterator() { + return new Iterator() { + + private int cursor = 0; + + @Override + public boolean hasNext() { + return cursor < length; + } + + @Override + @SuppressWarnings("unchecked") + public T next() { + if (!hasNext()) throw new NoSuchElementException(); + return (T) Array.get(array, cursor++); + } + + }; + } + + @Override + @SuppressWarnings("unchecked") + public void forEach(Consumer action) { + for (int i = 0; i < length; i++) { + action.accept((T) Array.get(array, i)); + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java index d71f0df71..5ecf33fcf 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java @@ -8,58 +8,58 @@ */ public class ClassWalker implements Iterable> { - protected final Class clazz; - protected final Class end; + protected final Class clazz; + protected final Class end; - protected ClassWalker(@Nonnull Class clazz) { - this(clazz, Object.class); - } + protected ClassWalker(@Nonnull Class clazz) { + this(clazz, Object.class); + } - protected ClassWalker(@Nonnull Class clazz, @Nonnull Class end) { - this.clazz = clazz; - this.end = end; - } + protected ClassWalker(@Nonnull Class clazz, @Nonnull Class end) { + this.clazz = clazz; + this.end = end; + } - public static ClassWalker range(@Nonnull Class start, @Nonnull Class end) { - return new ClassWalker(start, end); - } + public static ClassWalker range(@Nonnull Class start, @Nonnull Class end) { + return new ClassWalker(start, end); + } - public static ClassWalker walk(@Nonnull Class start) { - return new ClassWalker(start); - } + public static ClassWalker walk(@Nonnull Class start) { + return new ClassWalker(start); + } - @Nonnull - @Override - public Iterator> iterator() { - return new Iterator>() { + @Nonnull + @Override + public Iterator> iterator() { + return new Iterator>() { - private final Set> done = new HashSet<>(); - private final Deque> work = new LinkedList<>(); + private final Set> done = new HashSet<>(); + private final Deque> work = new LinkedList<>(); - { - work.addLast(clazz); - done.add(end); - } + { + work.addLast(clazz); + done.add(end); + } - @Override - public boolean hasNext() { - return !work.isEmpty(); - } + @Override + public boolean hasNext() { + return !work.isEmpty(); + } - @Override - public Class next() { - Class current = work.removeFirst(); - done.add(current); - for (Class parent : current.getInterfaces()) { - if (!done.contains(parent)) - work.addLast(parent); - } + @Override + public Class next() { + Class current = work.removeFirst(); + done.add(current); + for (Class parent : current.getInterfaces()) { + if (!done.contains(parent)) + work.addLast(parent); + } - Class parent = current.getSuperclass(); - if (parent != null && !done.contains(parent)) - work.addLast(parent); - return current; - } - }; - } + Class parent = current.getSuperclass(); + if (parent != null && !done.contains(parent)) + work.addLast(parent); + return current; + } + }; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java b/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java index dc7950c10..592b996e9 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java @@ -8,31 +8,31 @@ public final class Colors { - private Colors() {} - - public static final Color - ONLINE = decode("#40AC7B"), - DO_NOT_DISTURB = decode("#E84444"), - IDLE = decode("#F09F19"), - OFFLINE = decode("#747F8D"), - STREAMING = decode("#573591"), - - EMBED = decode("#2F3136"), - NO_RANK = decode("#CCD8DE"), - - LIGHT_BLACK = decode("#1c1c1c") - ; - - @Nonnull - @CheckReturnValue - public static String asHex(@Nonnull Color color) { - String red = Integer.toHexString(color.getRed()); - String green = Integer.toHexString(color.getGreen()); - String blue = Integer.toHexString(color.getBlue()); - return "#" + (red.length() == 1 ? "0" + red : red) + - (green.length() == 1 ? "0" + green : green) + - (blue.length() == 1 ? "0" + blue : blue); - } + private Colors() { + } + + public static final Color + ONLINE = decode("#40AC7B"), + DO_NOT_DISTURB = decode("#E84444"), + IDLE = decode("#F09F19"), + OFFLINE = decode("#747F8D"), + STREAMING = decode("#573591"), + + EMBED = decode("#2F3136"), + NO_RANK = decode("#CCD8DE"), + + LIGHT_BLACK = decode("#1c1c1c"); + + @Nonnull + @CheckReturnValue + public static String asHex(@Nonnull Color color) { + String red = Integer.toHexString(color.getRed()); + String green = Integer.toHexString(color.getGreen()); + String blue = Integer.toHexString(color.getBlue()); + return "#" + (red.length() == 1 ? "0" + red : red) + + (green.length() == 1 ? "0" + green : green) + + (blue.length() == 1 ? "0" + blue : blue); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java b/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java index 4625c3347..34f1fd43f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java @@ -9,85 +9,85 @@ public class FontBuilder { - private Font font; - - public FontBuilder(@Nonnull File file) throws IOException, FontFormatException { - this(file, Font.TRUETYPE_FONT); - } - - public FontBuilder(@Nonnull File file, int type) throws IOException, FontFormatException { - this.font = Font.createFont(type, file); - } - - public FontBuilder(@Nonnull String resource) throws IOException, FontFormatException { - this(resource, Font.TRUETYPE_FONT); - } - - public FontBuilder(@Nonnull String resource, int type) throws IOException, FontFormatException { - this.font = Font.createFont(type, Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(resource))); - } - - @Nonnull - @CheckReturnValue - public FontBuilder bold() { - return style(Font.BOLD); - } - - @Nonnull - @CheckReturnValue - public FontBuilder italic() { - return style(Font.ITALIC); - } - - @Nonnull - @CheckReturnValue - public FontBuilder style(int style) { - font = font.deriveFont(style); - return this; - } - - @Nonnull - @CheckReturnValue - public FontBuilder size(float size) { - font = font.deriveFont(size); - return this; - } - - @Nonnull - @CheckReturnValue - public FontBuilder derive(int style, float size) { - font = font.deriveFont(style, size); - return this; - } - - @Nonnull - public Font build() { - registerFont(font); - return font; - } - - public static void registerFont(@Nonnull Font font) { - GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(font); - } - - @Nonnull - @CheckReturnValue - public static FontBuilder fromFile(@Nonnull String filename) { - try { - return new FontBuilder(new File(filename)); - } catch (Exception ex) { - throw new WrappedException(ex); - } - } - - @Nonnull - @CheckReturnValue - public static FontBuilder fromResource(@Nonnull String resource) { - try { - return new FontBuilder(resource); - } catch (Exception ex) { - throw new WrappedException(ex); - } - } + private Font font; + + public FontBuilder(@Nonnull File file) throws IOException, FontFormatException { + this(file, Font.TRUETYPE_FONT); + } + + public FontBuilder(@Nonnull File file, int type) throws IOException, FontFormatException { + this.font = Font.createFont(type, file); + } + + public FontBuilder(@Nonnull String resource) throws IOException, FontFormatException { + this(resource, Font.TRUETYPE_FONT); + } + + public FontBuilder(@Nonnull String resource, int type) throws IOException, FontFormatException { + this.font = Font.createFont(type, Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(resource))); + } + + @Nonnull + @CheckReturnValue + public FontBuilder bold() { + return style(Font.BOLD); + } + + @Nonnull + @CheckReturnValue + public FontBuilder italic() { + return style(Font.ITALIC); + } + + @Nonnull + @CheckReturnValue + public FontBuilder style(int style) { + font = font.deriveFont(style); + return this; + } + + @Nonnull + @CheckReturnValue + public FontBuilder size(float size) { + font = font.deriveFont(size); + return this; + } + + @Nonnull + @CheckReturnValue + public FontBuilder derive(int style, float size) { + font = font.deriveFont(style, size); + return this; + } + + @Nonnull + public Font build() { + registerFont(font); + return font; + } + + public static void registerFont(@Nonnull Font font) { + GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(font); + } + + @Nonnull + @CheckReturnValue + public static FontBuilder fromFile(@Nonnull String filename) { + try { + return new FontBuilder(new File(filename)); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + public static FontBuilder fromResource(@Nonnull String resource) { + try { + return new FontBuilder(resource); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java b/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java index 54c8675fe..04b094c8f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java @@ -12,32 +12,33 @@ public final class IOUtils { - private IOUtils() {} - - public static String toString(@Nonnull String url) throws IOException { - return toString(new URL(url)); - } - - public static String toString(@Nonnull URL url) throws IOException { - InputStream input = url.openStream(); - String string = toString(input); - input.close(); - return string; - } - - public static String toString(@Nonnull InputStream input) throws IOException { - StringBuilder builder = new StringBuilder(); - BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); - reader.lines().forEach(builder::append); - return builder.toString(); - } - - @Nonnull - @CheckReturnValue - public static HttpURLConnection createConnection(@Nonnull String url) throws IOException { - HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); - connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); - return connection; - } + private IOUtils() { + } + + public static String toString(@Nonnull String url) throws IOException { + return toString(new URL(url)); + } + + public static String toString(@Nonnull URL url) throws IOException { + InputStream input = url.openStream(); + String string = toString(input); + input.close(); + return string; + } + + public static String toString(@Nonnull InputStream input) throws IOException { + StringBuilder builder = new StringBuilder(); + BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); + reader.lines().forEach(builder::append); + return builder.toString(); + } + + @Nonnull + @CheckReturnValue + public static HttpURLConnection createConnection(@Nonnull String url) throws IOException { + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); + return connection; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java b/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java index cfd4a96bc..2ef4a2c3f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java @@ -12,141 +12,141 @@ public interface IRandom { - @Nonnull - @CheckReturnValue - static IRandom create() { - return new SeededRandomWrapper(); - } + @Nonnull + @CheckReturnValue + static IRandom create() { + return new SeededRandomWrapper(); + } - @Nonnull - @CheckReturnValue - static IRandom create(long seed) { - return new SeededRandomWrapper(seed); - } + @Nonnull + @CheckReturnValue + static IRandom create(long seed) { + return new SeededRandomWrapper(seed); + } - @Nonnull - @CheckReturnValue - static IRandom wrap(@Nonnull Random random) { - return new RandomWrapper(random); - } + @Nonnull + @CheckReturnValue + static IRandom wrap(@Nonnull Random random) { + return new RandomWrapper(random); + } - @Nonnull - @CheckReturnValue - static IRandom threadLocal() { - return wrap(ThreadLocalRandom.current()); - } + @Nonnull + @CheckReturnValue + static IRandom threadLocal() { + return wrap(ThreadLocalRandom.current()); + } - @Nonnull - @CheckReturnValue - static IRandom secure() { - return wrap(new SecureRandom()); - } + @Nonnull + @CheckReturnValue + static IRandom secure() { + return wrap(new SecureRandom()); + } - @Nonnull - @CheckReturnValue - static IRandom singleton() { - return SingletonRandom.INSTANCE; - } + @Nonnull + @CheckReturnValue + static IRandom singleton() { + return SingletonRandom.INSTANCE; + } - long getSeed(); + long getSeed(); - void setSeed(long seed); + void setSeed(long seed); - void nextBytes(@Nonnull byte[] bytes); + void nextBytes(@Nonnull byte[] bytes); - boolean nextBoolean(); + boolean nextBoolean(); - int nextInt(); + int nextInt(); - int nextInt(int bound); + int nextInt(int bound); - @Nonnull - @CheckReturnValue - IntStream ints(); + @Nonnull + @CheckReturnValue + IntStream ints(); - @Nonnull - @CheckReturnValue - IntStream ints(@Nonnegative long streamSize); + @Nonnull + @CheckReturnValue + IntStream ints(@Nonnegative long streamSize); - @Nonnull - @CheckReturnValue - IntStream ints(int randomNumberOrigin, int randomNumberBound); + @Nonnull + @CheckReturnValue + IntStream ints(int randomNumberOrigin, int randomNumberBound); - @Nonnull - @CheckReturnValue - IntStream ints(@Nonnegative long streamSize, int randomNumberOrigin, int randomNumberBound); + @Nonnull + @CheckReturnValue + IntStream ints(@Nonnegative long streamSize, int randomNumberOrigin, int randomNumberBound); - @Nonnull - @CheckReturnValue - LongStream longs(); + @Nonnull + @CheckReturnValue + LongStream longs(); - long nextLong(); + long nextLong(); - @Nonnull - @CheckReturnValue - LongStream longs(@Nonnegative long streamSize); + @Nonnull + @CheckReturnValue + LongStream longs(@Nonnegative long streamSize); - @Nonnull - @CheckReturnValue - LongStream longs(long randomNumberOrigin, long randomNumberBound); + @Nonnull + @CheckReturnValue + LongStream longs(long randomNumberOrigin, long randomNumberBound); - @Nonnull - @CheckReturnValue - LongStream longs(@Nonnegative long streamSize, long randomNumberOrigin, long randomNumberBound); + @Nonnull + @CheckReturnValue + LongStream longs(@Nonnegative long streamSize, long randomNumberOrigin, long randomNumberBound); - double nextDouble(); + double nextDouble(); - double nextGaussian(); + double nextGaussian(); - @Nonnull - @CheckReturnValue - DoubleStream doubles(); + @Nonnull + @CheckReturnValue + DoubleStream doubles(); - @Nonnull - @CheckReturnValue - DoubleStream doubles(@Nonnegative long streamSize); + @Nonnull + @CheckReturnValue + DoubleStream doubles(@Nonnegative long streamSize); - @Nonnull - @CheckReturnValue - DoubleStream doubles(double randomNumberOrigin, double randomNumberBound); + @Nonnull + @CheckReturnValue + DoubleStream doubles(double randomNumberOrigin, double randomNumberBound); - @Nonnull - @CheckReturnValue - DoubleStream doubles(@Nonnegative long streamSize, double randomNumberOrigin, double randomNumberBound); + @Nonnull + @CheckReturnValue + DoubleStream doubles(@Nonnegative long streamSize, double randomNumberOrigin, double randomNumberBound); - float nextFloat(); + float nextFloat(); - default T choose(@Nonnull T... array) { - return array[nextInt(array.length)]; - } + default T choose(@Nonnull T... array) { + return array[nextInt(array.length)]; + } - default T choose(@Nonnull List list) { - return list.get(nextInt(list.size())); - } + default T choose(@Nonnull List list) { + return list.get(nextInt(list.size())); + } - default T choose(@Nonnull Collection collection) { - return choose(new ArrayList<>(collection)); - } + default T choose(@Nonnull Collection collection) { + return choose(new ArrayList<>(collection)); + } - default void shuffle(@Nonnull List list) { - Collections.shuffle(list, asRandom()); - } + default void shuffle(@Nonnull List list) { + Collections.shuffle(list, asRandom()); + } - default int around(int value, @Nonnegative int range) { - return range(value - range, value + range); - } + default int around(int value, @Nonnegative int range) { + return range(value - range, value + range); + } - default int range(int min, int max) { - if (min >= max) throw new IllegalArgumentException("min >= max"); - return nextInt(max - min) + min; - } + default int range(int min, int max) { + if (min >= max) throw new IllegalArgumentException("min >= max"); + return nextInt(max - min) + min; + } - @Nonnull - @CheckReturnValue - default Random asRandom() { - if (!(this instanceof Random)) - throw new IllegalStateException(this.getClass().getName() + " cannot be converted a java.util.Random"); - return (Random) this; - } + @Nonnull + @CheckReturnValue + default Random asRandom() { + if (!(this instanceof Random)) + throw new IllegalStateException(this.getClass().getName() + " cannot be converted a java.util.Random"); + return (Random) this; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java index 53e228f6a..e1c7a8473 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java @@ -7,30 +7,30 @@ public class NamedThreadFactory implements ThreadFactory { - private static final AtomicInteger poolNumber = new AtomicInteger(1); + private static final AtomicInteger poolNumber = new AtomicInteger(1); - protected final int id = poolNumber.getAndIncrement(); - protected final IntFunction nameFunction; - protected final ThreadGroup group; - protected final AtomicInteger threadNumber = new AtomicInteger(1); + protected final int id = poolNumber.getAndIncrement(); + protected final IntFunction nameFunction; + protected final ThreadGroup group; + protected final AtomicInteger threadNumber = new AtomicInteger(1); - public NamedThreadFactory(@Nonnull IntFunction nameFunction) { + public NamedThreadFactory(@Nonnull IntFunction nameFunction) { this.group = Thread.currentThread().getThreadGroup(); this.nameFunction = nameFunction; - } - - public NamedThreadFactory(@Nonnull String prefix) { - this(id -> prefix + "-" + id); - } - - @Override - public Thread newThread(@Nonnull Runnable task) { - Thread thread = new Thread(group, task, nameFunction.apply(threadNumber.getAndIncrement())); - if (thread.isDaemon()) - thread.setDaemon(false); - if (thread.getPriority() != Thread.NORM_PRIORITY) - thread.setPriority(Thread.NORM_PRIORITY); - return thread; - } + } + + public NamedThreadFactory(@Nonnull String prefix) { + this(id -> prefix + "-" + id); + } + + @Override + public Thread newThread(@Nonnull Runnable task) { + Thread thread = new Thread(group, task, nameFunction.apply(threadNumber.getAndIncrement())); + if (thread.isDaemon()) + thread.setDaemon(false); + if (thread.getPriority() != Thread.NORM_PRIORITY) + thread.setPriority(Thread.NORM_PRIORITY); + return thread; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java index 4a734b55b..7955433a5 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java @@ -8,350 +8,350 @@ public interface NumberFormatter { - @Nonnull - @CheckReturnValue - String format(double value); - - @Nonnull - @CheckReturnValue - default String format(float value) { - return format(Float.valueOf(value)); - } - - @Nonnull - @CheckReturnValue - default String format(long value) { - return format(Long.valueOf(value)); - } - - @Nonnull - @CheckReturnValue - default String format(int value) { - return format(Integer.valueOf(value)); - } - - @Nonnull - @CheckReturnValue - default String format(short value) { - return format(Short.valueOf(value)); - } - - @Nonnull - @CheckReturnValue - default String format(byte value) { - return format(Byte.valueOf(value)); - } - - @Nonnull - @CheckReturnValue - default String format(@Nonnull Number number) { - return format(number.doubleValue()); - } - - public static final NumberFormatter - DEFAULT = fromPattern("0.##", null, false), - INTEGER = value -> (int) value + "", - SPACE_SPLIT = fromPattern("###,##0.###############", null, false, - init -> updateSymbols(init, symbols -> symbols.setGroupingSeparator(' '))), - FLOATING_POINT = fromPattern("0.0", null, false), - DOUBLE_FLOATING_POINT = fromPattern("0.00", null, false), - BIG_FLOATING_POINT = fromPattern("###,##0.00000", null, false), - PERCENTAGE = fromPattern("0.##", "%", true), - FLOATING_PERCENTAGE = fromPattern("0.00", "%", true), - MIDDLE_NUMBER = fromPattern("###,###,##0.#", null, false), - - /** - * days, hours, minutes, seconds - */ - TIME = value -> { - - int seconds = (int) value; - int minutes = seconds / 60; - int hours = minutes / 60; - int days = hours / 24; - int years = days / 365; - - seconds %= 60; - minutes %= 60; - hours %= 24; - days %= 365; - - return ((years > 0 ? years + "y " : "") - + (days > 0 ? days + "d " : "") - + (hours > 0 ? hours + "h " : "") - + (minutes > 0 ? minutes + "m " : "") - + (seconds > 0 || (years == 0 && days == 0 && hours == 0 && minutes == 0) ? seconds + "s" : "")).trim(); - - }, - - /** - * days, hours, minutes - */ - BIG_TIME = value -> { - - int seconds = (int) value; - int minutes = seconds / 60; - int hours = minutes / 60; - int days = hours / 24; - int years = days / 365; - - minutes %= 60; - hours %= 24; - days %= 365; - - return ((years > 0 ? years + "y " : "") - + (days > 0 ? days + "d " : "") - + (hours > 0 ? hours + "h " : "") - + (minutes > 0 || (years == 0 && days == 0 && hours == 0) ? minutes + "m " : "")).trim(); - - }, - - /** - * input: millis - * 1 Tag, H:M:S - */ - GERMAN_TIME = value -> { - - DecimalFormat format = new DecimalFormat("00"); - - long millis = (long) value; - long seconds = millis / 1000; - long minutes = seconds / 60; - long hours = minutes / 60; - long days = hours / 24; - seconds %= 60; - minutes %= 60; - hours %= 24; - - return (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") - + (hours > 0 ? format.format(hours) + ":" : "") - + format.format(minutes) + ":" - + format.format(seconds); - - }, - /** - * input: seconds - * 1 Tag, H:M:S - */ - FULL_GERMAN_TIME_HOURS = value -> { - - long seconds = (long) (value); - long minutes = seconds / 60; - long hours = minutes / 60; - seconds %= 60; - minutes %= 60; - - return hours > 0 ? (hours == 1 ? "1 Stunde" : hours + " Stunden") : (minutes == 1 ? "1 Minute" : minutes + " Minuten"); - }, - - FULL_GERMAN_TIME = value -> { - - long seconds = (long) value; - long minutes = seconds / 60; - long hours = minutes / 60; - long days = hours / 24; - long years = days / 365; - - seconds %= 60; - minutes %= 60; - hours %= 24; - days %= 265; - - return ((years > 0 ? (years == 1 ? "1 Jahr " : years + " Jahre ") : "") - + (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") - + (hours > 0 ? (hours == 1 ? "1 Stunde " : hours + " Stunden ") : "") - + (minutes > 0 ? (minutes == 1 ? "1 Minute " : minutes + " Minuten ") : "") - + (seconds > 0 || years == 0 && hours == 0 && minutes == 0 ? (seconds == 1 ? "1 Sekunde" : seconds + " Sekunden") : "")).trim(); - - }, - - NORMAL_FULL_GERMAN_TIME = value -> { - - long seconds = (long) value; - long minutes = seconds / 60; - long hours = minutes / 60; - long days = hours / 24; - long years = days / 365; - - minutes %= 60; - hours %= 24; - days %= 265; - - return ((years > 0 ? (years == 1 ? "1 Jahr " : years + " Jahre ") : "") - + (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") - + (hours > 0 ? (hours == 1 ? "1 Stunde " : hours + " Stunden ") : "") - + (minutes > 0 || value == 0 ? (minutes == 1 ? "1 Minute " : minutes + " Minuten ") : "")).trim(); - - }, - - BIG_FULL_GERMAN_TIME = value -> { - - long seconds = (long) value; - long minutes = seconds / 60; - long hours = minutes / 60; - long days = hours / 24; - long years = days / 365; - - hours %= 24; - days %= 265; - - return ((years > 0 ? (years == 1 ? "1 Jahr " : years + " Jahre ") : "") - + (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") - + (hours > 0 || years == 0 && days == 0 ? (hours == 1 ? "1 Stunde" : hours + " Stunden") : "")).trim(); - - }, - - /** - * billion, million, thousand, number - */ - BIG_NUMBER = value -> { - - DecimalFormat format = new DecimalFormat("0.##"); - double divide; - String ending = ""; - - // Normal number - if (value < 1000) { - divide = 1; - format = new DecimalFormat("0.#"); - // Thousand - } else if (value < 1000000) { - divide = 1000; - ending = "k"; - // Million - } else if (value < 1000000000) { - divide = 1000000; - ending = "m"; - // Billion (Milliarde) - } else if (value < 1000000000000D) { - divide = 1000000000; - ending = "b"; - // Trillion (Billion) - } else { - divide = 1000000000000D; - ending = "t"; - } - - value /= divide; - return format.format(value) + ending; - - }, - - /** - * input in bytes - * kilobyte, megabyte, gigabyte, terrabyte - */ - DATA_SIZE = value -> { - - if (value < 0) value = 0; - - DecimalFormat format = new DecimalFormat("0.##"); - double divide; - String ending; - - // KiloByte - if (value < 1000000L) { - divide = 1000; - format = new DecimalFormat("0.#"); - ending = "KB"; - } else if (value < 1000000000L) { - // MegaByte - divide = 1000000L; - ending = "MB"; - // GigaByte - } else if (value < 1000000000000L) { - divide = 1000000000L; - ending = "GB"; - // TerraByte - } else { - divide = 1000000000000L; - ending = "TB"; - } - - value /= divide; - return format.format(value) + ending; - - }, - - /** - * input in bytes - * gigabyte, terrabyte, petabyte - */ - BIG_DATA_SIZE = value -> { - - if (value < 0) value = 0; - - DecimalFormat format = new DecimalFormat("0.##"); - double divide; - String ending; - - // GigaByte - if (value < 1000000000000L) { - divide = 1000000000L; - ending = "GB"; - // TerraByte - } else if (value < 1000000000000000L) { - divide = 1000000000000L; - ending = "TB"; - // PetaByte - } else { - divide = 1000000000000000L; - ending = "PB"; - } - - value /= divide; - return format.format(value) + ending; - - }, - ORDINAL = value -> { - - String string = String.valueOf(((long) value)); - int number = Integer.parseInt(string.substring(string.length() - 1)); - String ending = "th"; - - if (value != 11 && value != 12 && value != 13) { - switch (number) { - case 1: - ending = "st"; - break; - case 2: - ending = "nd"; - break; - case 3: - ending = "rd"; - break; - } - } - - return string + ending; - - }, - GERMAN_ORDINAL = fromPattern("0", ".", false); - - @Nonnull - @CheckReturnValue - public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive) { - return fromPattern(pattern, ending, positive, null); - } - - @Nonnull - @CheckReturnValue - public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive, Consumer init) { - DecimalFormat format = new DecimalFormat(pattern); - if (init != null) init.accept(format); - return value -> Double.isNaN(value) ? "NaN" : format.format(positive ? (value > 0 ? value : 0) : value) + (ending != null ? ending : ""); - } - - @Nonnull - @CheckReturnValue - public static DecimalFormatSymbols updateSymbols(@Nonnull DecimalFormatSymbols symbols, @Nonnull Consumer action) { - action.accept(symbols); - return symbols; - } - - @CheckReturnValue - public static void updateSymbols(@Nonnull DecimalFormat format, @Nonnull Consumer action) { - format.setDecimalFormatSymbols(updateSymbols(format.getDecimalFormatSymbols(), action)); - } + @Nonnull + @CheckReturnValue + String format(double value); + + @Nonnull + @CheckReturnValue + default String format(float value) { + return format(Float.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(long value) { + return format(Long.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(int value) { + return format(Integer.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(short value) { + return format(Short.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(byte value) { + return format(Byte.valueOf(value)); + } + + @Nonnull + @CheckReturnValue + default String format(@Nonnull Number number) { + return format(number.doubleValue()); + } + + public static final NumberFormatter + DEFAULT = fromPattern("0.##", null, false), + INTEGER = value -> (int) value + "", + SPACE_SPLIT = fromPattern("###,##0.###############", null, false, + init -> updateSymbols(init, symbols -> symbols.setGroupingSeparator(' '))), + FLOATING_POINT = fromPattern("0.0", null, false), + DOUBLE_FLOATING_POINT = fromPattern("0.00", null, false), + BIG_FLOATING_POINT = fromPattern("###,##0.00000", null, false), + PERCENTAGE = fromPattern("0.##", "%", true), + FLOATING_PERCENTAGE = fromPattern("0.00", "%", true), + MIDDLE_NUMBER = fromPattern("###,###,##0.#", null, false), + + /** + * days, hours, minutes, seconds + */ + TIME = value -> { + + int seconds = (int) value; + int minutes = seconds / 60; + int hours = minutes / 60; + int days = hours / 24; + int years = days / 365; + + seconds %= 60; + minutes %= 60; + hours %= 24; + days %= 365; + + return ((years > 0 ? years + "y " : "") + + (days > 0 ? days + "d " : "") + + (hours > 0 ? hours + "h " : "") + + (minutes > 0 ? minutes + "m " : "") + + (seconds > 0 || (years == 0 && days == 0 && hours == 0 && minutes == 0) ? seconds + "s" : "")).trim(); + + }, + + /** + * days, hours, minutes + */ + BIG_TIME = value -> { + + int seconds = (int) value; + int minutes = seconds / 60; + int hours = minutes / 60; + int days = hours / 24; + int years = days / 365; + + minutes %= 60; + hours %= 24; + days %= 365; + + return ((years > 0 ? years + "y " : "") + + (days > 0 ? days + "d " : "") + + (hours > 0 ? hours + "h " : "") + + (minutes > 0 || (years == 0 && days == 0 && hours == 0) ? minutes + "m " : "")).trim(); + + }, + + /** + * input: millis + * 1 Tag, H:M:S + */ + GERMAN_TIME = value -> { + + DecimalFormat format = new DecimalFormat("00"); + + long millis = (long) value; + long seconds = millis / 1000; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + seconds %= 60; + minutes %= 60; + hours %= 24; + + return (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 ? format.format(hours) + ":" : "") + + format.format(minutes) + ":" + + format.format(seconds); + + }, + /** + * input: seconds + * 1 Tag, H:M:S + */ + FULL_GERMAN_TIME_HOURS = value -> { + + long seconds = (long) (value); + long minutes = seconds / 60; + long hours = minutes / 60; + seconds %= 60; + minutes %= 60; + + return hours > 0 ? (hours == 1 ? "1 Stunde" : hours + " Stunden") : (minutes == 1 ? "1 Minute" : minutes + " Minuten"); + }, + + FULL_GERMAN_TIME = value -> { + + long seconds = (long) value; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + long years = days / 365; + + seconds %= 60; + minutes %= 60; + hours %= 24; + days %= 265; + + return ((years > 0 ? (years == 1 ? "1 Jahr " : years + " Jahre ") : "") + + (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 ? (hours == 1 ? "1 Stunde " : hours + " Stunden ") : "") + + (minutes > 0 ? (minutes == 1 ? "1 Minute " : minutes + " Minuten ") : "") + + (seconds > 0 || years == 0 && hours == 0 && minutes == 0 ? (seconds == 1 ? "1 Sekunde" : seconds + " Sekunden") : "")).trim(); + + }, + + NORMAL_FULL_GERMAN_TIME = value -> { + + long seconds = (long) value; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + long years = days / 365; + + minutes %= 60; + hours %= 24; + days %= 265; + + return ((years > 0 ? (years == 1 ? "1 Jahr " : years + " Jahre ") : "") + + (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 ? (hours == 1 ? "1 Stunde " : hours + " Stunden ") : "") + + (minutes > 0 || value == 0 ? (minutes == 1 ? "1 Minute " : minutes + " Minuten ") : "")).trim(); + + }, + + BIG_FULL_GERMAN_TIME = value -> { + + long seconds = (long) value; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + long years = days / 365; + + hours %= 24; + days %= 265; + + return ((years > 0 ? (years == 1 ? "1 Jahr " : years + " Jahre ") : "") + + (days > 0 ? (days == 1 ? "1 Tag " : days + " Tage ") : "") + + (hours > 0 || years == 0 && days == 0 ? (hours == 1 ? "1 Stunde" : hours + " Stunden") : "")).trim(); + + }, + + /** + * billion, million, thousand, number + */ + BIG_NUMBER = value -> { + + DecimalFormat format = new DecimalFormat("0.##"); + double divide; + String ending = ""; + + // Normal number + if (value < 1000) { + divide = 1; + format = new DecimalFormat("0.#"); + // Thousand + } else if (value < 1000000) { + divide = 1000; + ending = "k"; + // Million + } else if (value < 1000000000) { + divide = 1000000; + ending = "m"; + // Billion (Milliarde) + } else if (value < 1000000000000D) { + divide = 1000000000; + ending = "b"; + // Trillion (Billion) + } else { + divide = 1000000000000D; + ending = "t"; + } + + value /= divide; + return format.format(value) + ending; + + }, + + /** + * input in bytes + * kilobyte, megabyte, gigabyte, terrabyte + */ + DATA_SIZE = value -> { + + if (value < 0) value = 0; + + DecimalFormat format = new DecimalFormat("0.##"); + double divide; + String ending; + + // KiloByte + if (value < 1000000L) { + divide = 1000; + format = new DecimalFormat("0.#"); + ending = "KB"; + } else if (value < 1000000000L) { + // MegaByte + divide = 1000000L; + ending = "MB"; + // GigaByte + } else if (value < 1000000000000L) { + divide = 1000000000L; + ending = "GB"; + // TerraByte + } else { + divide = 1000000000000L; + ending = "TB"; + } + + value /= divide; + return format.format(value) + ending; + + }, + + /** + * input in bytes + * gigabyte, terrabyte, petabyte + */ + BIG_DATA_SIZE = value -> { + + if (value < 0) value = 0; + + DecimalFormat format = new DecimalFormat("0.##"); + double divide; + String ending; + + // GigaByte + if (value < 1000000000000L) { + divide = 1000000000L; + ending = "GB"; + // TerraByte + } else if (value < 1000000000000000L) { + divide = 1000000000000L; + ending = "TB"; + // PetaByte + } else { + divide = 1000000000000000L; + ending = "PB"; + } + + value /= divide; + return format.format(value) + ending; + + }, + ORDINAL = value -> { + + String string = String.valueOf(((long) value)); + int number = Integer.parseInt(string.substring(string.length() - 1)); + String ending = "th"; + + if (value != 11 && value != 12 && value != 13) { + switch (number) { + case 1: + ending = "st"; + break; + case 2: + ending = "nd"; + break; + case 3: + ending = "rd"; + break; + } + } + + return string + ending; + + }, + GERMAN_ORDINAL = fromPattern("0", ".", false); + + @Nonnull + @CheckReturnValue + public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive) { + return fromPattern(pattern, ending, positive, null); + } + + @Nonnull + @CheckReturnValue + public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive, Consumer init) { + DecimalFormat format = new DecimalFormat(pattern); + if (init != null) init.accept(format); + return value -> Double.isNaN(value) ? "NaN" : format.format(positive ? (value > 0 ? value : 0) : value) + (ending != null ? ending : ""); + } + + @Nonnull + @CheckReturnValue + public static DecimalFormatSymbols updateSymbols(@Nonnull DecimalFormatSymbols symbols, @Nonnull Consumer action) { + action.accept(symbols); + return symbols; + } + + @CheckReturnValue + public static void updateSymbols(@Nonnull DecimalFormat format, @Nonnull Consumer action) { + format.setDecimalFormatSymbols(updateSymbols(format.getDecimalFormatSymbols(), action)); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java index a845fbc10..e81ec4ec9 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java @@ -8,142 +8,142 @@ public class RandomWrapper implements IRandom { - private final Random random; - - public RandomWrapper(@Nonnull Random random) { - this.random = random; - } - - @Override - public long getSeed() { - throw new UnsupportedOperationException("Random.getSeed()"); - } - - @Override - public void setSeed(long seed) { - random.setSeed(seed); - } - - @Override - public void nextBytes(@Nonnull byte[] bytes) { - random.nextBytes(bytes); - } - - @Override - public boolean nextBoolean() { - return random.nextBoolean(); - } - - @Override - public int nextInt() { - return random.nextInt(); - } - - @Override - public int nextInt(int bound) { - return random.nextInt(bound); - } - - @Nonnull - @Override - public IntStream ints() { - return random.ints(); - } - - @Nonnull - @Override - public IntStream ints(long streamSize) { - return random.ints(streamSize); - } - - @Nonnull - @Override - public IntStream ints(int randomNumberOrigin, int randomNumberBound) { - return random.ints(randomNumberOrigin, randomNumberBound); - } - - @Nonnull - @Override - public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound) { - return random.ints(streamSize, randomNumberOrigin, randomNumberBound); - } - - @Nonnull - @Override - public LongStream longs() { - return random.longs(); - } - - @Override - public long nextLong() { - return random.nextLong(); - } - - @Nonnull - @Override - public LongStream longs(long streamSize) { - return random.longs(streamSize); - } - - @Nonnull - @Override - public LongStream longs(long randomNumberOrigin, long randomNumberBound) { - return random.longs(randomNumberOrigin, randomNumberBound); - } - - @Nonnull - @Override - public LongStream longs(long streamSize, long randomNumberOrigin, long randomNumberBound) { - return random.longs(streamSize, randomNumberOrigin, randomNumberBound); - } - - @Override - public double nextDouble() { - return random.nextDouble(); - } - - @Override - public double nextGaussian() { - return random.nextGaussian(); - } - - @Nonnull - @Override - public DoubleStream doubles() { - return random.doubles(); - } - - @Nonnull - @Override - public DoubleStream doubles(long streamSize) { - return random.doubles(streamSize); - } - - @Nonnull - @Override - public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) { - return random.doubles(randomNumberOrigin, randomNumberBound); - } - - @Nonnull - @Override - public DoubleStream doubles(long streamSize, double randomNumberOrigin, double randomNumberBound) { - return random.doubles(streamSize, randomNumberOrigin, randomNumberBound); - } - - @Override - public float nextFloat() { - return random.nextFloat(); - } - - @Nonnull - @Override - public Random asRandom() { - return random; - } - - @Override - public String toString() { - return "Random[wrapped=" + random.getClass().getSimpleName() + "]"; - } + private final Random random; + + public RandomWrapper(@Nonnull Random random) { + this.random = random; + } + + @Override + public long getSeed() { + throw new UnsupportedOperationException("Random.getSeed()"); + } + + @Override + public void setSeed(long seed) { + random.setSeed(seed); + } + + @Override + public void nextBytes(@Nonnull byte[] bytes) { + random.nextBytes(bytes); + } + + @Override + public boolean nextBoolean() { + return random.nextBoolean(); + } + + @Override + public int nextInt() { + return random.nextInt(); + } + + @Override + public int nextInt(int bound) { + return random.nextInt(bound); + } + + @Nonnull + @Override + public IntStream ints() { + return random.ints(); + } + + @Nonnull + @Override + public IntStream ints(long streamSize) { + return random.ints(streamSize); + } + + @Nonnull + @Override + public IntStream ints(int randomNumberOrigin, int randomNumberBound) { + return random.ints(randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound) { + return random.ints(streamSize, randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public LongStream longs() { + return random.longs(); + } + + @Override + public long nextLong() { + return random.nextLong(); + } + + @Nonnull + @Override + public LongStream longs(long streamSize) { + return random.longs(streamSize); + } + + @Nonnull + @Override + public LongStream longs(long randomNumberOrigin, long randomNumberBound) { + return random.longs(randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public LongStream longs(long streamSize, long randomNumberOrigin, long randomNumberBound) { + return random.longs(streamSize, randomNumberOrigin, randomNumberBound); + } + + @Override + public double nextDouble() { + return random.nextDouble(); + } + + @Override + public double nextGaussian() { + return random.nextGaussian(); + } + + @Nonnull + @Override + public DoubleStream doubles() { + return random.doubles(); + } + + @Nonnull + @Override + public DoubleStream doubles(long streamSize) { + return random.doubles(streamSize); + } + + @Nonnull + @Override + public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) { + return random.doubles(randomNumberOrigin, randomNumberBound); + } + + @Nonnull + @Override + public DoubleStream doubles(long streamSize, double randomNumberOrigin, double randomNumberBound) { + return random.doubles(streamSize, randomNumberOrigin, randomNumberBound); + } + + @Override + public float nextFloat() { + return random.nextFloat(); + } + + @Nonnull + @Override + public Random asRandom() { + return random; + } + + @Override + public String toString() { + return "Random[wrapped=" + random.getClass().getSimpleName() + "]"; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java b/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java index e1401ba5e..aa8f1bf87 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java @@ -5,43 +5,44 @@ public final class RomanNumerals { - public static final class IllegalRomanNumeralException extends IllegalArgumentException { - - private IllegalRomanNumeralException(int number) { - super("Number " + number + " out of bounds for 0 to 3999"); - } - - } - - private static final TreeMap values = new TreeMap<>(); - - static { - values.put(1000, "M" ); - values.put(900, "CM"); - values.put(500, "D" ); - values.put(400, "CD"); - values.put(100, "C" ); - values.put(90, "XC"); - values.put(50, "L" ); - values.put(40, "XL"); - values.put(10, "X" ); - values.put(9, "IX"); - values.put(5, "V" ); - values.put(4, "IV"); - values.put(1, "I" ); - } - - private RomanNumerals() {} - - @Nonnull - public static String forNumber(int number) { - if (number < 0 || number > 3999) throw new IllegalRomanNumeralException(number); - if (number == 0) return ""; - int i = values.floorKey(number); - if (number == i) { - return values.get(number); - } - return values.get(i) + forNumber(number - i); - } + public static final class IllegalRomanNumeralException extends IllegalArgumentException { + + private IllegalRomanNumeralException(int number) { + super("Number " + number + " out of bounds for 0 to 3999"); + } + + } + + private static final TreeMap values = new TreeMap<>(); + + static { + values.put(1000, "M"); + values.put(900, "CM"); + values.put(500, "D"); + values.put(400, "CD"); + values.put(100, "C"); + values.put(90, "XC"); + values.put(50, "L"); + values.put(40, "XL"); + values.put(10, "X"); + values.put(9, "IX"); + values.put(5, "V"); + values.put(4, "IV"); + values.put(1, "I"); + } + + private RomanNumerals() { + } + + @Nonnull + public static String forNumber(int number) { + if (number < 0 || number > 3999) throw new IllegalRomanNumeralException(number); + if (number == 0) return ""; + int i = values.floorKey(number); + if (number == i) { + return values.get(number); + } + return values.get(i) + forNumber(number - i); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java b/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java index 540c375f1..c6b26b7d5 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java @@ -5,15 +5,15 @@ public class RunnableTimerTask extends TimerTask { - protected final Runnable action; + protected final Runnable action; - public RunnableTimerTask(@Nonnull Runnable action) { - this.action = action; - } + public RunnableTimerTask(@Nonnull Runnable action) { + this.action = action; + } - @Override - public void run() { - action.run(); - } + @Override + public void run() { + action.run(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java index a9fcb48f2..074504c53 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/SeededRandomWrapper.java @@ -8,28 +8,28 @@ */ public class SeededRandomWrapper extends Random implements IRandom { - protected long seed; - - public SeededRandomWrapper() { - super(); - } - - public SeededRandomWrapper(long seed) { - super(seed); - } - - @Override - public void setSeed(long seed) { - super.setSeed(seed); - this.seed = seed; - } - - public long getSeed() { - return seed; - } - - @Override - public String toString() { - return "Random[seed=" + seed + "]"; - } + protected long seed; + + public SeededRandomWrapper() { + super(); + } + + public SeededRandomWrapper(long seed) { + super(seed); + } + + @Override + public void setSeed(long seed) { + super.setSeed(seed); + this.seed = seed; + } + + public long getSeed() { + return seed; + } + + @Override + public String toString() { + return "Random[seed=" + seed + "]"; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/SingletonRandom.java b/plugin/src/main/java/net/codingarea/commons/common/collection/SingletonRandom.java index 93a2ce6ed..6d3ed3b6a 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/SingletonRandom.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/SingletonRandom.java @@ -4,10 +4,10 @@ public class SingletonRandom extends RandomWrapper { - public static final SingletonRandom INSTANCE = new SingletonRandom(); + public static final SingletonRandom INSTANCE = new SingletonRandom(); - private SingletonRandom() { - super(new Random()); - } + private SingletonRandom() { + super(new Random()); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java index 2d0e45d21..0e61626e3 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java @@ -8,21 +8,21 @@ */ public class StringBuilderPrintWriter extends PrintWriter { - protected final StringBuilderWriter writer; + protected final StringBuilderWriter writer; - public StringBuilderPrintWriter() { - super(new StringBuilderWriter()); - writer = (StringBuilderWriter) out; - } + public StringBuilderPrintWriter() { + super(new StringBuilderWriter()); + writer = (StringBuilderWriter) out; + } - @Nonnull - public StringBuilder getBuilder() { - return writer.getBuilder(); - } + @Nonnull + public StringBuilder getBuilder() { + return writer.getBuilder(); + } - @Override - public String toString() { - return getBuilder().toString(); - } + @Override + public String toString() { + return getBuilder().toString(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java index 5ad40651c..0abbd6637 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java @@ -9,60 +9,60 @@ */ public class StringBuilderWriter extends Writer { - private final StringBuilder builder; - - public StringBuilderWriter() { - this.builder = new StringBuilder(); - } - - public StringBuilderWriter(int capacity) { - this.builder = new StringBuilder(capacity); - } - - public StringBuilderWriter(@Nullable StringBuilder builder) { - this.builder = builder != null ? builder : new StringBuilder(); - } - - public Writer append(char value) { - builder.append(value); - return this; - } - - public Writer append(@Nullable CharSequence value) { - builder.append(value); - return this; - } - - public Writer append(@Nullable CharSequence value, int start, int end) { - builder.append(value, start, end); - return this; - } - - public void close() { - } - - public void flush() { - } - - public void write(@Nonnull String value) { - builder.append(value); - } - - public void write(@Nullable char[] value, int offset, int length) { - if (value != null) { - builder.append(value, offset, length); - } - } - - @Nonnull - public StringBuilder getBuilder() { - return this.builder; - } - - @Override - public String toString() { - return this.builder.toString(); - } + private final StringBuilder builder; + + public StringBuilderWriter() { + this.builder = new StringBuilder(); + } + + public StringBuilderWriter(int capacity) { + this.builder = new StringBuilder(capacity); + } + + public StringBuilderWriter(@Nullable StringBuilder builder) { + this.builder = builder != null ? builder : new StringBuilder(); + } + + public Writer append(char value) { + builder.append(value); + return this; + } + + public Writer append(@Nullable CharSequence value) { + builder.append(value); + return this; + } + + public Writer append(@Nullable CharSequence value, int start, int end) { + builder.append(value, start, end); + return this; + } + + public void close() { + } + + public void flush() { + } + + public void write(@Nonnull String value) { + builder.append(value); + } + + public void write(@Nullable char[] value, int offset, int length) { + if (value != null) { + builder.append(value, offset, length); + } + } + + @Nonnull + public StringBuilder getBuilder() { + return this.builder; + } + + @Override + public String toString() { + return this.builder.toString(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java index b480031d2..f7622edc4 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java @@ -10,11 +10,11 @@ @Deprecated public class Triple extends net.codingarea.commons.common.collection.pair.Triple { - public Triple() { - } + public Triple() { + } - public Triple(@Nullable F first, @Nullable S second, @Nullable T third) { - super(first, second, third); - } + public Triple(@Nullable F first, @Nullable S second, @Nullable T third) { + super(first, second, third); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java index 8e9077907..d47bf885b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java @@ -9,11 +9,11 @@ @Deprecated public class Tuple extends net.codingarea.commons.common.collection.pair.Tuple { - public Tuple() { - } + public Tuple() { + } - public Tuple(@Nullable F first, @Nullable S second) { - super(first, second); - } + public Tuple(@Nullable F first, @Nullable S second) { + super(first, second); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java b/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java index 1e8999988..8668f4cc0 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java @@ -8,54 +8,54 @@ */ public class WrappedException extends RuntimeException { - public static class SilentWrappedException extends WrappedException { - - public SilentWrappedException(@Nullable String message, @Nonnull Throwable cause) { - super(message, cause); - } - - public SilentWrappedException(@Nonnull Throwable cause) { - super(cause); - } - - @Override - public synchronized Throwable fillInStackTrace() { - return this; - } - - } - - public WrappedException(@Nullable String message, @Nonnull Throwable cause) { - super(message, cause); - } - - public WrappedException(@Nonnull Throwable cause) { - super(cause); - } - - @Nonnull - @Override - public Throwable getCause() { - return super.getCause(); - } - - @Nonnull - public static RuntimeException rethrow(@Nonnull Throwable ex) { - if (ex instanceof Error) - throw (Error) ex; - if (ex instanceof RuntimeException) - throw (RuntimeException) ex; - throw silent(ex); - } - - @Nonnull - public static WrappedException silent(@Nonnull Throwable cause) { - return new SilentWrappedException(cause); - } - - @Nonnull - public static WrappedException silent(@Nullable String message, @Nonnull Throwable cause) { - return new SilentWrappedException(message, cause); - } + public static class SilentWrappedException extends WrappedException { + + public SilentWrappedException(@Nullable String message, @Nonnull Throwable cause) { + super(message, cause); + } + + public SilentWrappedException(@Nonnull Throwable cause) { + super(cause); + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } + + } + + public WrappedException(@Nullable String message, @Nonnull Throwable cause) { + super(message, cause); + } + + public WrappedException(@Nonnull Throwable cause) { + super(cause); + } + + @Nonnull + @Override + public Throwable getCause() { + return super.getCause(); + } + + @Nonnull + public static RuntimeException rethrow(@Nonnull Throwable ex) { + if (ex instanceof Error) + throw (Error) ex; + if (ex instanceof RuntimeException) + throw (RuntimeException) ex; + throw silent(ex); + } + + @Nonnull + public static WrappedException silent(@Nonnull Throwable cause) { + return new SilentWrappedException(cause); + } + + @Nonnull + public static WrappedException silent(@Nullable String message, @Nonnull Throwable cause) { + return new SilentWrappedException(message, cause); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java index bb4c23a4a..2e41faccb 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java @@ -10,23 +10,23 @@ */ public interface Pair { - /** - * @return The amount of values - */ - @Nonnegative - int amount(); + /** + * @return The amount of values + */ + @Nonnegative + int amount(); - @Nonnull - Object[] values(); + @Nonnull + Object[] values(); - /** - * @return {@code true} when all of the values are null, {@code false} otherwise - */ - boolean allNull(); + /** + * @return {@code true} when all of the values are null, {@code false} otherwise + */ + boolean allNull(); - /** - * @return {@code true} when none of the values are null, {@code false} otherwise - */ - boolean noneNull(); + /** + * @return {@code true} when none of the values are null, {@code false} otherwise + */ + boolean noneNull(); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java index df07b890d..0d61041c3 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java @@ -7,133 +7,133 @@ import java.util.function.Function; /** - * @param The type of the first value - * @param The type of the second value - * @param The type of the third value + * @param The type of the first value + * @param The type of the second value + * @param The type of the third value * @param The type of the fourth value */ public class Quadro implements Pair { - protected F first; - protected S second; - protected T third; - protected FF fourth; - - public Quadro() { - } - - public Quadro(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FF fourth) { - this.first = first; - this.second = second; - this.third = third; - this.fourth = fourth; - } - - @Override - public final int amount() { - return 4; - } - - @Nonnull - @Override - public final Object[] values() { - return new Object[] { first, second, third, first }; - } - - public F getFirst() { - return first; - } - - public S getSecond() { - return second; - } - - public T getThird() { - return third; - } - - public FF getFourth() { - return fourth; - } - - public void setFirst(@Nullable F first) { - this.first = first; - } - - public void setSecond(@Nullable S second) { - this.second = second; - } - - public void setThird(@Nullable T third) { - this.third = third; - } - - public void setFourth(@Nullable FF fourth) { - this.fourth = fourth; - } - - @Nonnull - @CheckReturnValue - public Quadro map(@Nonnull Function firstMapper, - @Nonnull Function secondMapper, - @Nonnull Function thirdMapper, - @Nonnull Function fourthMapper) { - return of(firstMapper.apply(first), secondMapper.apply(second), thirdMapper.apply(third), fourthMapper.apply(fourth)); - } - - public boolean noneNull() { - return first != null && second != null && third != null && fourth != null; - } - - public boolean allNull() { - return first == null && second == null && third == null && fourth != null; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Quadro quadro = (Quadro) o; - return Objects.equals(first, quadro.first) && Objects.equals(second, quadro.second) && Objects.equals(third, quadro.third) && Objects.equals(fourth, quadro.fourth); - } - - @Override - public int hashCode() { - return Objects.hash(first, second, third, fourth); - } - - @Override - public String toString() { - return "Quadro[" + first + ", " + second + ", " + third + ", " + fourth + "]"; - } - - @Nonnull - public static Quadro ofFirst(@Nullable F first) { - return of(first, null, null, null); - } - - @Nonnull - public static Quadro ofSecond(@Nullable S second) { - return of(null, second, null, null); - } - - @Nonnull - public static Quadro ofThird(@Nullable T third) { - return of(null, null, third, null); - } - - @Nonnull - public static Quadro ofFourth(@Nullable FF fourth) { - return of(null, null, null, fourth); - } - - @Nonnull - public static Quadro of(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FF fourth) { - return new Quadro<>(first, second, third, fourth); - } - - @Nonnull - public static Quadro empty() { - return new Quadro<>(); - } + protected F first; + protected S second; + protected T third; + protected FF fourth; + + public Quadro() { + } + + public Quadro(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FF fourth) { + this.first = first; + this.second = second; + this.third = third; + this.fourth = fourth; + } + + @Override + public final int amount() { + return 4; + } + + @Nonnull + @Override + public final Object[] values() { + return new Object[]{first, second, third, first}; + } + + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public T getThird() { + return third; + } + + public FF getFourth() { + return fourth; + } + + public void setFirst(@Nullable F first) { + this.first = first; + } + + public void setSecond(@Nullable S second) { + this.second = second; + } + + public void setThird(@Nullable T third) { + this.third = third; + } + + public void setFourth(@Nullable FF fourth) { + this.fourth = fourth; + } + + @Nonnull + @CheckReturnValue + public Quadro map(@Nonnull Function firstMapper, + @Nonnull Function secondMapper, + @Nonnull Function thirdMapper, + @Nonnull Function fourthMapper) { + return of(firstMapper.apply(first), secondMapper.apply(second), thirdMapper.apply(third), fourthMapper.apply(fourth)); + } + + public boolean noneNull() { + return first != null && second != null && third != null && fourth != null; + } + + public boolean allNull() { + return first == null && second == null && third == null && fourth != null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Quadro quadro = (Quadro) o; + return Objects.equals(first, quadro.first) && Objects.equals(second, quadro.second) && Objects.equals(third, quadro.third) && Objects.equals(fourth, quadro.fourth); + } + + @Override + public int hashCode() { + return Objects.hash(first, second, third, fourth); + } + + @Override + public String toString() { + return "Quadro[" + first + ", " + second + ", " + third + ", " + fourth + "]"; + } + + @Nonnull + public static Quadro ofFirst(@Nullable F first) { + return of(first, null, null, null); + } + + @Nonnull + public static Quadro ofSecond(@Nullable S second) { + return of(null, second, null, null); + } + + @Nonnull + public static Quadro ofThird(@Nullable T third) { + return of(null, null, third, null); + } + + @Nonnull + public static Quadro ofFourth(@Nullable FF fourth) { + return of(null, null, null, fourth); + } + + @Nonnull + public static Quadro of(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FF fourth) { + return new Quadro<>(first, second, third, fourth); + } + + @Nonnull + public static Quadro empty() { + return new Quadro<>(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java index 48c8dfcde..e99ef90a4 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java @@ -13,111 +13,111 @@ */ public class Triple implements Pair { - protected F first; - protected S second; - protected T third; - - public Triple() { - } - - public Triple(@Nullable F first, @Nullable S second, @Nullable T third) { - this.first = first; - this.second = second; - this.third = third; - } - - @Override - public final int amount() { - return 3; - } - - @Nonnull - @Override - public final Object[] values() { - return new Object[] { first, second, third }; - } - - public F getFirst() { - return first; - } - - public S getSecond() { - return second; - } - - public T getThird() { - return third; - } - - public void setFirst(@Nullable F first) { - this.first = first; - } - - public void setSecond(@Nullable S second) { - this.second = second; - } - - public void setThird(@Nullable T third) { - this.third = third; - } - - @Nonnull - @CheckReturnValue - public Triple map(@Nonnull Function firstMapper, - @Nonnull Function secondMapper, - @Nonnull Function thirdMapper) { - return of(firstMapper.apply(first), secondMapper.apply(second), thirdMapper.apply(third)); - } - - public boolean noneNull() { - return first != null && second != null && third != null; - } - - public boolean allNull() { - return first == null && second == null && third == null; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Triple triple = (Triple) o; - return Objects.equals(first, triple.first) && Objects.equals(second, triple.second) && Objects.equals(third, triple.third); - } - - @Override - public int hashCode() { - return Objects.hash(first, second, third); - } - - @Override - public String toString() { - return "Triple[" + first + ", " + second + ", " + third + "]"; - } - - @Nonnull - public static Triple ofFirst(@Nullable F first) { - return of(first, null, null); - } - - @Nonnull - public static Triple ofSecond(@Nullable S second) { - return of(null, second, null); - } - - @Nonnull - public static Triple ofThird(@Nullable T third) { - return of(null, null, third); - } - - @Nonnull - public static Triple of(@Nullable F first, @Nullable S second, @Nullable T third) { - return new Triple<>(first, second, third); - } - - @Nonnull - public static Triple empty() { - return new Triple<>(); - } + protected F first; + protected S second; + protected T third; + + public Triple() { + } + + public Triple(@Nullable F first, @Nullable S second, @Nullable T third) { + this.first = first; + this.second = second; + this.third = third; + } + + @Override + public final int amount() { + return 3; + } + + @Nonnull + @Override + public final Object[] values() { + return new Object[]{first, second, third}; + } + + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public T getThird() { + return third; + } + + public void setFirst(@Nullable F first) { + this.first = first; + } + + public void setSecond(@Nullable S second) { + this.second = second; + } + + public void setThird(@Nullable T third) { + this.third = third; + } + + @Nonnull + @CheckReturnValue + public Triple map(@Nonnull Function firstMapper, + @Nonnull Function secondMapper, + @Nonnull Function thirdMapper) { + return of(firstMapper.apply(first), secondMapper.apply(second), thirdMapper.apply(third)); + } + + public boolean noneNull() { + return first != null && second != null && third != null; + } + + public boolean allNull() { + return first == null && second == null && third == null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Triple triple = (Triple) o; + return Objects.equals(first, triple.first) && Objects.equals(second, triple.second) && Objects.equals(third, triple.third); + } + + @Override + public int hashCode() { + return Objects.hash(first, second, third); + } + + @Override + public String toString() { + return "Triple[" + first + ", " + second + ", " + third + "]"; + } + + @Nonnull + public static Triple ofFirst(@Nullable F first) { + return of(first, null, null); + } + + @Nonnull + public static Triple ofSecond(@Nullable S second) { + return of(null, second, null); + } + + @Nonnull + public static Triple ofThird(@Nullable T third) { + return of(null, null, third); + } + + @Nonnull + public static Triple of(@Nullable F first, @Nullable S second, @Nullable T third) { + return new Triple<>(first, second, third); + } + + @Nonnull + public static Triple empty() { + return new Triple<>(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java index 9d320ba6e..f94e44523 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java @@ -12,95 +12,95 @@ */ public class Tuple implements Pair { - protected F first; - protected S second; - - public Tuple() { - } - - public Tuple(@Nullable F first, @Nullable S second) { - this.first = first; - this.second = second; - } - - @Override - public final int amount() { - return 2; - } - - @Nonnull - @Override - public final Object[] values() { - return new Object[] { first, second }; - } - - public F getFirst() { - return first; - } - - public S getSecond() { - return second; - } - - public void setFirst(@Nullable F first) { - this.first = first; - } - - public void setSecond(@Nullable S second) { - this.second = second; - } - - @Nonnull - @CheckReturnValue - public Tuple map(@Nonnull Function firstMapper, - @Nonnull Function secondMapper) { - return of(firstMapper.apply(first), secondMapper.apply(second)); - } - - public boolean noneNull() { - return first != null && second != null; - } - - public boolean allNull() { - return first == null && second == null; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Tuple tuple = (Tuple) o; - return Objects.equals(first, tuple.first) && Objects.equals(second, tuple.second); - } - - @Override - public int hashCode() { - return Objects.hash(first, second); - } - - @Override - public String toString() { - return "Tuple[" + first + ", " + second + "]"; - } - - @Nonnull - public static Tuple ofFirst(@Nullable F frist) { - return new Tuple<>(frist, null); - } - - @Nonnull - public static Tuple ofSecond(@Nullable S second) { - return new Tuple<>(null, second); - } - - @Nonnull - public static Tuple of(@Nullable F first, @Nullable S second) { - return new Tuple<>(first, second); - } - - @Nonnull - public static Tuple empty() { - return new Tuple<>(); - } + protected F first; + protected S second; + + public Tuple() { + } + + public Tuple(@Nullable F first, @Nullable S second) { + this.first = first; + this.second = second; + } + + @Override + public final int amount() { + return 2; + } + + @Nonnull + @Override + public final Object[] values() { + return new Object[]{first, second}; + } + + public F getFirst() { + return first; + } + + public S getSecond() { + return second; + } + + public void setFirst(@Nullable F first) { + this.first = first; + } + + public void setSecond(@Nullable S second) { + this.second = second; + } + + @Nonnull + @CheckReturnValue + public Tuple map(@Nonnull Function firstMapper, + @Nonnull Function secondMapper) { + return of(firstMapper.apply(first), secondMapper.apply(second)); + } + + public boolean noneNull() { + return first != null && second != null; + } + + public boolean allNull() { + return first == null && second == null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Tuple tuple = (Tuple) o; + return Objects.equals(first, tuple.first) && Objects.equals(second, tuple.second); + } + + @Override + public int hashCode() { + return Objects.hash(first, second); + } + + @Override + public String toString() { + return "Tuple[" + first + ", " + second + "]"; + } + + @Nonnull + public static Tuple ofFirst(@Nullable F frist) { + return new Tuple<>(frist, null); + } + + @Nonnull + public static Tuple ofSecond(@Nullable S second) { + return new Tuple<>(null, second); + } + + @Nonnull + public static Tuple of(@Nullable F first, @Nullable S second) { + return new Tuple<>(first, second); + } + + @Nonnull + public static Tuple empty() { + return new Tuple<>(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java index 87bf70c77..2333ac96b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java @@ -22,97 +22,98 @@ @ReplaceWith("com.google.common.cache.LoadingCache") public class CleanAndWriteDatabaseCache implements DatabaseCache { - protected final Map> cache = new ConcurrentHashMap<>(); - protected final Predicate check; - protected final Function query; - protected final Function fallback; - protected final BiConsumer writer; - protected final long unusedTimeBeforeClean; - protected final long cleanAndWriteInterval; - protected final ILogger logger; - - public CleanAndWriteDatabaseCache(@Nullable ILogger logger, @Nonnegative long unusedTimeBeforeClean, @Nonnegative long cleanAndWriteInterval, @Nonnull String taskName, - @Nonnull Predicate check, @Nonnull Function fallback, - @Nonnull Function query, @Nonnull BiConsumer writer) { - this.logger = logger; - this.unusedTimeBeforeClean = unusedTimeBeforeClean; - this.cleanAndWriteInterval = cleanAndWriteInterval; - this.check = check; - this.query = query; - this.fallback = fallback; - this.writer = writer; - - EXECUTOR.scheduleAtFixedRate(this::writeCache, cleanAndWriteInterval, cleanAndWriteInterval, TimeUnit.MILLISECONDS); - Runtime.getRuntime().addShutdownHook(new Thread(this::writeCache)); - } - - public void writeCache() { - if (logger != null ) logger.debug("Writing & Cleaning cache"); - cleanAndWrite(cache, unusedTimeBeforeClean, logger, check, writer); - } - - @Nonnull - @Override - public V getData(@Nonnull K key) { - Tuple cached = cache.get(key); - if (cached != null) { - cached.setFirst(System.currentTimeMillis()); - return cached.getSecond(); - } - - try { - V data = query.apply(key); - if (logger != null ) logger.trace("Queried data {} for {}", data, key); - cache.put(key, new Tuple<>(System.currentTimeMillis(), data)); - return data; - } catch (Exception ex) { - if (logger != null ) logger.error("Could not get data for {}", key, ex); - return fallback.apply(key); - } - } - - @Override - public boolean contains(@Nonnull K key) { - return cache.containsKey(key); - } - - @Override - public int size() { - return cache.size(); - } - - @Override - public void clear() { - cache.clear(); - } - - public static void cleanAndWrite(@Nonnull Map> cache, @Nonnegative long unusedTimeBeforeClean, @Nullable ILogger logger, - @Nonnull Predicate check, @Nonnull BiConsumer writer) { - long now = System.currentTimeMillis(); - Collection remove = new ArrayList<>(); - cache.forEach((key, pair) -> { - try { - if (now - pair.getFirst() > unusedTimeBeforeClean) { - if (logger != null ) logger.trace("Removing {} from cache, last usage was {}s ago", key, (now - pair.getFirst()) / 1000); - remove.add(key); - } - - V value = pair.getSecond(); - if (!check.test(value)) return; - - if (logger != null ) logger.trace("Writing {}", value); - writer.accept(key, value); - } catch (Exception ex) { - if (logger != null ) logger.error("Unable to write cache for {}", key, ex); - } - }); - remove.forEach(cache::remove); - } - - @Nonnull - @Override - public Map values() { - return Collections.unmodifiableMap(SimpleCollectionUtils.convertMap(cache, k -> k, Tuple::getSecond)); - } + protected final Map> cache = new ConcurrentHashMap<>(); + protected final Predicate check; + protected final Function query; + protected final Function fallback; + protected final BiConsumer writer; + protected final long unusedTimeBeforeClean; + protected final long cleanAndWriteInterval; + protected final ILogger logger; + + public CleanAndWriteDatabaseCache(@Nullable ILogger logger, @Nonnegative long unusedTimeBeforeClean, @Nonnegative long cleanAndWriteInterval, @Nonnull String taskName, + @Nonnull Predicate check, @Nonnull Function fallback, + @Nonnull Function query, @Nonnull BiConsumer writer) { + this.logger = logger; + this.unusedTimeBeforeClean = unusedTimeBeforeClean; + this.cleanAndWriteInterval = cleanAndWriteInterval; + this.check = check; + this.query = query; + this.fallback = fallback; + this.writer = writer; + + EXECUTOR.scheduleAtFixedRate(this::writeCache, cleanAndWriteInterval, cleanAndWriteInterval, TimeUnit.MILLISECONDS); + Runtime.getRuntime().addShutdownHook(new Thread(this::writeCache)); + } + + public void writeCache() { + if (logger != null) logger.debug("Writing & Cleaning cache"); + cleanAndWrite(cache, unusedTimeBeforeClean, logger, check, writer); + } + + @Nonnull + @Override + public V getData(@Nonnull K key) { + Tuple cached = cache.get(key); + if (cached != null) { + cached.setFirst(System.currentTimeMillis()); + return cached.getSecond(); + } + + try { + V data = query.apply(key); + if (logger != null) logger.trace("Queried data {} for {}", data, key); + cache.put(key, new Tuple<>(System.currentTimeMillis(), data)); + return data; + } catch (Exception ex) { + if (logger != null) logger.error("Could not get data for {}", key, ex); + return fallback.apply(key); + } + } + + @Override + public boolean contains(@Nonnull K key) { + return cache.containsKey(key); + } + + @Override + public int size() { + return cache.size(); + } + + @Override + public void clear() { + cache.clear(); + } + + public static void cleanAndWrite(@Nonnull Map> cache, @Nonnegative long unusedTimeBeforeClean, @Nullable ILogger logger, + @Nonnull Predicate check, @Nonnull BiConsumer writer) { + long now = System.currentTimeMillis(); + Collection remove = new ArrayList<>(); + cache.forEach((key, pair) -> { + try { + if (now - pair.getFirst() > unusedTimeBeforeClean) { + if (logger != null) + logger.trace("Removing {} from cache, last usage was {}s ago", key, (now - pair.getFirst()) / 1000); + remove.add(key); + } + + V value = pair.getSecond(); + if (!check.test(value)) return; + + if (logger != null) logger.trace("Writing {}", value); + writer.accept(key, value); + } catch (Exception ex) { + if (logger != null) logger.error("Unable to write cache for {}", key, ex); + } + }); + remove.forEach(cache::remove); + } + + @Nonnull + @Override + public Map values() { + return Collections.unmodifiableMap(SimpleCollectionUtils.convertMap(cache, k -> k, Tuple::getSecond)); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java index 6cf0779c6..c321f8604 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java @@ -19,65 +19,66 @@ @ReplaceWith("com.google.common.cache.Cache") public class CleanWriteableCache implements WriteableCache { - protected final Map> cache = new ConcurrentHashMap<>(); - protected final ILogger logger; - protected final long cleanInterval; - protected final long unusedTimeBeforeClean; + protected final Map> cache = new ConcurrentHashMap<>(); + protected final ILogger logger; + protected final long cleanInterval; + protected final long unusedTimeBeforeClean; - public CleanWriteableCache(@Nullable ILogger logger, @Nonnegative long unusedTimeBeforeClean, @Nonnegative long cleanInterval, @Nonnull String taskName) { - this.logger = logger; - this.cleanInterval = cleanInterval; - this.unusedTimeBeforeClean = unusedTimeBeforeClean; + public CleanWriteableCache(@Nullable ILogger logger, @Nonnegative long unusedTimeBeforeClean, @Nonnegative long cleanInterval, @Nonnull String taskName) { + this.logger = logger; + this.cleanInterval = cleanInterval; + this.unusedTimeBeforeClean = unusedTimeBeforeClean; - EXECUTOR.scheduleAtFixedRate(this::cleanCache, cleanInterval, cleanInterval, TimeUnit.MILLISECONDS); - } + EXECUTOR.scheduleAtFixedRate(this::cleanCache, cleanInterval, cleanInterval, TimeUnit.MILLISECONDS); + } - public void cleanCache() { - if (logger != null ) logger.debug("Cleaning cache"); - long now = System.currentTimeMillis(); - Collection remove = new ArrayList<>(); - cache.forEach((key, pair) -> { - if (now - pair.getFirst() > unusedTimeBeforeClean) { - if (logger != null ) logger.trace("Removing {} from cache, last usage was {}s ago", key, (now - pair.getFirst()) / 1000); - remove.add(key); - } - }); - remove.forEach(cache::remove); - } + public void cleanCache() { + if (logger != null) logger.debug("Cleaning cache"); + long now = System.currentTimeMillis(); + Collection remove = new ArrayList<>(); + cache.forEach((key, pair) -> { + if (now - pair.getFirst() > unusedTimeBeforeClean) { + if (logger != null) + logger.trace("Removing {} from cache, last usage was {}s ago", key, (now - pair.getFirst()) / 1000); + remove.add(key); + } + }); + remove.forEach(cache::remove); + } - @Nullable - @Override - public V getData(@Nonnull K key) { - Tuple pair = cache.get(key); - if (pair == null) return null; - pair.setFirst(System.currentTimeMillis()); - return pair.getSecond(); - } + @Nullable + @Override + public V getData(@Nonnull K key) { + Tuple pair = cache.get(key); + if (pair == null) return null; + pair.setFirst(System.currentTimeMillis()); + return pair.getSecond(); + } - @Override - public void setData(@Nonnull K key, @Nullable V value) { - cache.put(key, new Tuple<>(System.currentTimeMillis(), value)); - } + @Override + public void setData(@Nonnull K key, @Nullable V value) { + cache.put(key, new Tuple<>(System.currentTimeMillis(), value)); + } - @Override - public boolean contains(@Nonnull K key) { - return cache.containsKey(key); - } + @Override + public boolean contains(@Nonnull K key) { + return cache.containsKey(key); + } - @Override - public int size() { - return cache.size(); - } + @Override + public int size() { + return cache.size(); + } - @Override - public void clear() { - cache.clear(); - } + @Override + public void clear() { + cache.clear(); + } - @Nonnull - @Override - public Map values() { - return Collections.unmodifiableMap(SimpleCollectionUtils.convertMap(cache, k -> k, Tuple::getSecond)); - } + @Nonnull + @Override + public Map values() { + return Collections.unmodifiableMap(SimpleCollectionUtils.convertMap(cache, k -> k, Tuple::getSecond)); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java index 1279ae1f5..0c5fd162e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java @@ -14,70 +14,70 @@ public class CoolDownCache { - protected final Map cache = new ConcurrentHashMap<>(); - protected final ILogger logger; - protected final ToLongFunction cooldownTime; - protected final long cleanInterval; - - public CoolDownCache(@Nonnull ILogger logger, @Nonnegative long cleanInterval, @Nonnull String taskName, @Nonnull ToLongFunction cooldownTime) { - this.logger = logger; - this.cooldownTime = cooldownTime; - this.cleanInterval = cleanInterval; - - new Timer(taskName).schedule(new RunnableTimerTask(this::cleanCache), cleanInterval, cleanInterval); - } - - public void cleanCache() { - logger.debug("Cleaning cooldown cache"); - - long now = System.currentTimeMillis(); - Collection remove = new ArrayList<>(); - cache.forEach((key, time) -> { - if (time == null || !isOnCoolDown(now, time, key)) { - logger.trace("Removing {} from cooldown cache", key); - remove.add(key); - } - }); - remove.forEach(cache::remove); - } - - public boolean isOnCoolDown(long now, long suspect, @Nonnull K key) { - long difference = now - suspect; - return difference < getCoolDownTime(key); - } - - public boolean isOnCoolDown(@Nonnull K key) { - Long time = cache.get(key); - if (time == null) return false; - return isOnCoolDown(System.currentTimeMillis(), time, key); - } - - public boolean checkCoolDown(@Nonnull K key) { - boolean cooldown = isOnCoolDown(key); - if (!cooldown) setOnCoolDown(key); - return cooldown; - } - - public void setOnCoolDown(@Nonnull K key) { - cache.put(key, System.currentTimeMillis()); - } - - public long getCoolDown(@Nonnull K key) { - Long time = cache.get(key); - if (time == null) return 0; - return System.currentTimeMillis() - time; - } - - public float getCoolDownSeconds(@Nonnull K key) { - return getCoolDown(key) / 1000f; - } - - public long getCoolDownTime(@Nonnull K key) { - return cooldownTime.applyAsLong(key); - } - - public int size() { - return cache.size(); - } + protected final Map cache = new ConcurrentHashMap<>(); + protected final ILogger logger; + protected final ToLongFunction cooldownTime; + protected final long cleanInterval; + + public CoolDownCache(@Nonnull ILogger logger, @Nonnegative long cleanInterval, @Nonnull String taskName, @Nonnull ToLongFunction cooldownTime) { + this.logger = logger; + this.cooldownTime = cooldownTime; + this.cleanInterval = cleanInterval; + + new Timer(taskName).schedule(new RunnableTimerTask(this::cleanCache), cleanInterval, cleanInterval); + } + + public void cleanCache() { + logger.debug("Cleaning cooldown cache"); + + long now = System.currentTimeMillis(); + Collection remove = new ArrayList<>(); + cache.forEach((key, time) -> { + if (time == null || !isOnCoolDown(now, time, key)) { + logger.trace("Removing {} from cooldown cache", key); + remove.add(key); + } + }); + remove.forEach(cache::remove); + } + + public boolean isOnCoolDown(long now, long suspect, @Nonnull K key) { + long difference = now - suspect; + return difference < getCoolDownTime(key); + } + + public boolean isOnCoolDown(@Nonnull K key) { + Long time = cache.get(key); + if (time == null) return false; + return isOnCoolDown(System.currentTimeMillis(), time, key); + } + + public boolean checkCoolDown(@Nonnull K key) { + boolean cooldown = isOnCoolDown(key); + if (!cooldown) setOnCoolDown(key); + return cooldown; + } + + public void setOnCoolDown(@Nonnull K key) { + cache.put(key, System.currentTimeMillis()); + } + + public long getCoolDown(@Nonnull K key) { + Long time = cache.get(key); + if (time == null) return 0; + return System.currentTimeMillis() - time; + } + + public float getCoolDownSeconds(@Nonnull K key) { + return getCoolDown(key) / 1000f; + } + + public long getCoolDownTime(@Nonnull K key) { + return cooldownTime.applyAsLong(key); + } + + public int size() { + return cache.size(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java index 5afc4e461..544c2e499 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java @@ -5,15 +5,14 @@ import javax.annotation.Nonnull; /** - * @deprecated Use {@link com.google.common.cache.LoadingCache} instead - * * @see com.google.common.cache.LoadingCache + * @deprecated Use {@link com.google.common.cache.LoadingCache} instead */ @Deprecated @ReplaceWith("com.google.common.cache.LoadingCache") public interface DatabaseCache extends ICache { - @Nonnull - V getData(@Nonnull K key); + @Nonnull + V getData(@Nonnull K key); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java index 4a6b49f7f..9a73f8854 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java @@ -10,31 +10,30 @@ import java.util.function.BiConsumer; /** - * @deprecated Use {@link com.google.common.cache.Cache} instead - * * @see com.google.common.cache.Cache + * @deprecated Use {@link com.google.common.cache.Cache} instead */ @Deprecated @ReplaceWith("com.google.common.cache.Cache") public interface ICache { - ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(2, new NamedThreadFactory(threadId -> String.format("CacheTask-%s", threadId))); + ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(2, new NamedThreadFactory(threadId -> String.format("CacheTask-%s", threadId))); - boolean contains(@Nonnull K key); + boolean contains(@Nonnull K key); - int size(); + int size(); - default boolean isEmpty() { - return size() == 0; - } + default boolean isEmpty() { + return size() == 0; + } - void clear(); + void clear(); - @Nonnull - Map values(); + @Nonnull + Map values(); - default void forEach(@Nonnull BiConsumer action) { - values().forEach(action); - } + default void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java index a2c887e25..645e59bd8 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java @@ -9,9 +9,9 @@ @ReplaceWith("com.google.common.cache.Cache") public interface WriteableCache extends ICache { - @Nullable - V getData(@Nonnull K key); + @Nullable + V getData(@Nonnull K key); - void setData(@Nonnull K key, @Nullable V value); + void setData(@Nonnull K key, @Nullable V value); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java index 37b71703f..582372d43 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java @@ -11,159 +11,159 @@ public class CompletableTask implements Task { - static final ExecutorService SERVICE = Executors.newCachedThreadPool(new NamedThreadFactory("TaskProcessor")); - - private final Collection> listeners = new ArrayList<>(); - private final CompletableFuture future; - - private Throwable failure; - - public CompletableTask() { - this(new CompletableFuture<>()); - } - - private CompletableTask(@Nonnull CompletableFuture future) { - this.future = future; - this.future.exceptionally(ex -> { - this.failure = ex; - return null; - }); - } - - @Nonnull - public static Task callAsync(@Nonnull Callable callable) { - CompletableTask task = new CompletableTask<>(); - SERVICE.execute(() -> { - try { - task.complete(callable.call()); - } catch (Throwable ex) { - task.fail(ex); - } - }); - return task; - } - - @Nonnull - public static Task callSync(@Nonnull Callable callable) { - CompletableTask task = new CompletableTask<>(); - try { - task.complete(callable.call()); - } catch (Throwable ex) { - task.fail(ex); - } - return task; - } - - @Nonnull - @Override - public Task addListener(@Nonnull TaskListener listener) { - if (future.isDone()) { - V value = future.getNow(null); - if (future.isCancelled() || value != null) { - listener.onCancelled(this); - } else if (failure != null) { - listener.onFailure(this, failure); - } else { - listener.onComplete(this, value); - } - return this; - } - - listeners.add(listener); - return this; - } - - @Nonnull - @Override - public Task clearListeners() { - this.listeners.clear(); - return this; - } - - public void fail(Throwable throwable) { - this.failure = throwable; - this.future.completeExceptionally(throwable); - for (TaskListener listener : this.listeners) { - listener.onFailure(this, throwable); - } - } - - @Override - public V call() { - if (this.future.isDone()) { - return this.future.getNow(null); - } - throw new UnsupportedOperationException("Use #complete in the CompletableTask"); - } - - public void complete(@Nullable V value) { - future.complete(value); - if (value != null) { - for (TaskListener listener : listeners) { - listener.onComplete(this, value); - } - } else { - for (TaskListener listener : listeners) { - listener.onCancelled(this); - } - } - - } - - @Override - public boolean cancel(boolean b) { - if (this.future.isCancelled()) { - return false; - } - - if (this.future.cancel(b)) { - for (TaskListener listener : this.listeners) { - listener.onCancelled(this); - } - return true; - } - return false; - } - - @Override - public boolean isCancelled() { - return this.future.isCancelled(); - } - - @Override - public boolean isDone() { - return this.future.isDone(); - } - - @Override - public V get() throws InterruptedException, ExecutionException { - return future.get(); - } - - @Override - public V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { - return future.get(timeout, unit); - } - - @Nonnull - @Override - public Task map(@Nullable Function mapper) { - CompletableTask task = new CompletableTask<>(); - this.future.thenAccept(v -> { - try { - task.complete(mapper == null ? null : mapper.apply(v)); - } catch (Throwable ex) { - task.fail(ex); - } - }); - this.onFailure(task.future::completeExceptionally); - this.onCancelled(otherTask -> task.cancel(true)); - return task; - } - - @Nonnull - @Override - public CompletionStage stage() { - return future; - } + static final ExecutorService SERVICE = Executors.newCachedThreadPool(new NamedThreadFactory("TaskProcessor")); + + private final Collection> listeners = new ArrayList<>(); + private final CompletableFuture future; + + private Throwable failure; + + public CompletableTask() { + this(new CompletableFuture<>()); + } + + private CompletableTask(@Nonnull CompletableFuture future) { + this.future = future; + this.future.exceptionally(ex -> { + this.failure = ex; + return null; + }); + } + + @Nonnull + public static Task callAsync(@Nonnull Callable callable) { + CompletableTask task = new CompletableTask<>(); + SERVICE.execute(() -> { + try { + task.complete(callable.call()); + } catch (Throwable ex) { + task.fail(ex); + } + }); + return task; + } + + @Nonnull + public static Task callSync(@Nonnull Callable callable) { + CompletableTask task = new CompletableTask<>(); + try { + task.complete(callable.call()); + } catch (Throwable ex) { + task.fail(ex); + } + return task; + } + + @Nonnull + @Override + public Task addListener(@Nonnull TaskListener listener) { + if (future.isDone()) { + V value = future.getNow(null); + if (future.isCancelled() || value != null) { + listener.onCancelled(this); + } else if (failure != null) { + listener.onFailure(this, failure); + } else { + listener.onComplete(this, value); + } + return this; + } + + listeners.add(listener); + return this; + } + + @Nonnull + @Override + public Task clearListeners() { + this.listeners.clear(); + return this; + } + + public void fail(Throwable throwable) { + this.failure = throwable; + this.future.completeExceptionally(throwable); + for (TaskListener listener : this.listeners) { + listener.onFailure(this, throwable); + } + } + + @Override + public V call() { + if (this.future.isDone()) { + return this.future.getNow(null); + } + throw new UnsupportedOperationException("Use #complete in the CompletableTask"); + } + + public void complete(@Nullable V value) { + future.complete(value); + if (value != null) { + for (TaskListener listener : listeners) { + listener.onComplete(this, value); + } + } else { + for (TaskListener listener : listeners) { + listener.onCancelled(this); + } + } + + } + + @Override + public boolean cancel(boolean b) { + if (this.future.isCancelled()) { + return false; + } + + if (this.future.cancel(b)) { + for (TaskListener listener : this.listeners) { + listener.onCancelled(this); + } + return true; + } + return false; + } + + @Override + public boolean isCancelled() { + return this.future.isCancelled(); + } + + @Override + public boolean isDone() { + return this.future.isDone(); + } + + @Override + public V get() throws InterruptedException, ExecutionException { + return future.get(); + } + + @Override + public V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return future.get(timeout, unit); + } + + @Nonnull + @Override + public Task map(@Nullable Function mapper) { + CompletableTask task = new CompletableTask<>(); + this.future.thenAccept(v -> { + try { + task.complete(mapper == null ? null : mapper.apply(v)); + } catch (Throwable ex) { + task.fail(ex); + } + }); + this.onFailure(task.future::completeExceptionally); + this.onCancelled(otherTask -> task.cancel(true)); + return task; + } + + @Nonnull + @Override + public CompletionStage stage() { + return future; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java index aed5684ba..1ae7724f3 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java @@ -7,102 +7,102 @@ public class CompletedTask implements Task { - private final V value; - private final Throwable failure; - - private CompletableFuture future; - - public CompletedTask(@Nullable V value) { - this.value = value; - this.failure = null; - } - - public CompletedTask(@Nullable Throwable failure) { - this.value = null; - this.failure = failure; - } - - @Nonnull - @Override - public Task addListener(@Nonnull TaskListener listener) { - if (failure != null) { - listener.onFailure(this, failure); - } else if (value != null) { - listener.onComplete(this, value); - } else { - listener.onCancelled(this); - } - - return this; - } - - @Nonnull - @Override - public Task clearListeners() { - return this; - } - - @Nonnull - @Override - public Task map(@Nullable Function mapper) { - if (failure != null) - return new CompletedTask<>(failure); - - return new CompletedTask<>(value == null || mapper == null ? null : mapper.apply(value)); - } - - @Override - public V getOrDefault(long timeout, @Nonnull TimeUnit unit, V def) { - if (value != null) - return value; - - return def; - } - - @Override - public V call() throws Exception { - return value; - } - - @Override - public boolean cancel(boolean mayInterruptIfRunning) { - return false; - } - - @Override - public boolean isCancelled() { - return false; - } - - @Override - public boolean isDone() { - return true; - } - - @Override - public V get() throws InterruptedException, ExecutionException { - return value; - } - - @Override - public V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { - return value; - } - - @Nonnull - @Override - public CompletionStage stage() { - if (future == null) { - future = new CompletableFuture<>(); - - if (failure != null) { - future.completeExceptionally(failure); - } else { - future.complete(value); - } - } - - return future; - } + private final V value; + private final Throwable failure; + + private CompletableFuture future; + + public CompletedTask(@Nullable V value) { + this.value = value; + this.failure = null; + } + + public CompletedTask(@Nullable Throwable failure) { + this.value = null; + this.failure = failure; + } + + @Nonnull + @Override + public Task addListener(@Nonnull TaskListener listener) { + if (failure != null) { + listener.onFailure(this, failure); + } else if (value != null) { + listener.onComplete(this, value); + } else { + listener.onCancelled(this); + } + + return this; + } + + @Nonnull + @Override + public Task clearListeners() { + return this; + } + + @Nonnull + @Override + public Task map(@Nullable Function mapper) { + if (failure != null) + return new CompletedTask<>(failure); + + return new CompletedTask<>(value == null || mapper == null ? null : mapper.apply(value)); + } + + @Override + public V getOrDefault(long timeout, @Nonnull TimeUnit unit, V def) { + if (value != null) + return value; + + return def; + } + + @Override + public V call() throws Exception { + return value; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public boolean isDone() { + return true; + } + + @Override + public V get() throws InterruptedException, ExecutionException { + return value; + } + + @Override + public V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return value; + } + + @Nonnull + @Override + public CompletionStage stage() { + if (future == null) { + future = new CompletableFuture<>(); + + if (failure != null) { + future.completeExceptionally(failure); + } else { + future.complete(value); + } + } + + return future; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java index 8b43122ec..200b6ab27 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java @@ -15,7 +15,7 @@ /** * A task that may complete (done / failed / cancelled) in the future or may already be done. - * + *

* For the completion can be listened by calling {@link #onComplete(Consumer)}, for the cancellation by {@link #onCancelled(Runnable)} and for failure by {@link #onFailure(Consumer)}. * * @see #asyncCall(Callable) @@ -23,206 +23,212 @@ */ public interface Task extends Future, Callable { - @Nonnull - static ExecutorService getAsyncExecutor() { - return CompletableTask.SERVICE; - } - - @Nonnull - static Task empty() { - return completed(null); - } - - @Nonnull - static Task completed(@Nullable V value) { - return new CompletedTask<>(value); - } - - @Nonnull - static Task completedVoid() { - return empty(); - } - - @Nonnull - static Task failed(@Nonnull Throwable failure) { - return new CompletedTask<>(failure); - } - - @Nonnull - static CompletableTask completable() { - return new CompletableTask<>(); - } - - @Nonnull - static Task asyncCall(@Nonnull Callable callable) { - return CompletableTask.callAsync(callable); - } - - @Nonnull - static Task asyncSupply(@Nonnull Supplier supplier) { - return asyncCall(supplier::get); - } - - @Nonnull - static Task asyncRun(@Nonnull Runnable runnable) { - return asyncCall(() -> { runnable.run(); return null; }); - } - - @Nonnull - static Task asyncRunExceptionally(@Nonnull ExceptionallyRunnable runnable) { - return asyncRun(runnable); - } - - @Nonnull - static Task syncCall(@Nonnull Callable callable) { - return CompletableTask.callSync(callable); - } - - @Nonnull - static Task syncSupply(@Nonnull Supplier supplier) { - return syncCall(supplier::get); - } - - @Nonnull - static Task syncRun(@Nonnull Runnable runnable) { - return syncCall(() -> { runnable.run(); return null; }); - } - - @Nonnull - static Task syncRunExceptionally(@Nonnull ExceptionallyRunnable runnable) { - return syncRun(runnable); - } - - @Nonnull - default Task onComplete(@Nonnull Runnable action) { - return onComplete(v -> action.run()); - } - - @Nonnull - default Task onComplete(@Nonnull Consumer action) { - return onComplete((task, value) -> action.accept(value)); - } - - @Nonnull - default Task onComplete(@Nonnull BiConsumer, ? super V> action) { - return addListener(new TaskListener() { - @Override - public void onComplete(@Nonnull Task task, @Nonnull V value) { - action.accept(task, value); - } - }); - } - - @Nonnull - default Task onFailure(@Nonnull Runnable action) { - return onFailure(ex -> action.run()); - } - - @Nonnull - default Task onFailure(@Nonnull Consumer action) { - return onFailure((task, ex) -> action.accept(ex)); - } - - @Nonnull - default Task onFailure(@Nonnull BiConsumer, ? super Throwable> action) { - return addListener(new TaskListener() { - @Override - public void onFailure(@Nonnull Task task, @Nonnull Throwable ex) { - action.accept(task, ex); - } - }); - } - - @Nonnull - default Task throwOnFailure() { - return onFailure(ex -> ex.printStackTrace()); - } - - @Nonnull - default Task onCancelled(@Nonnull Runnable action) { - return onCancelled(task -> action.run()); - } - - @Nonnull - default Task onCancelled(@Nonnull Consumer> action) { - return addListener(new TaskListener() { - @Override - public void onCancelled(@Nonnull Task task) { - action.accept(task); - } - }); - } - - @Nonnull - default Task addListeners(@Nonnull TaskListener... listeners) { - for (TaskListener listener : listeners) - addListener(listener); - - return this; - } - - @Nonnull - Task addListener(@Nonnull TaskListener listener); - - @Nonnull - Task clearListeners(); - - @Override - V get() throws InterruptedException, ExecutionException; - - @Override - V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; - - default V getOrDefault(V def) { - try { - return get(); - } catch (InterruptedException ex) { - throw new WrappedException(ex); - } catch (ExecutionException ex) { - return def; - } - } - - default V getOrDefault(long timeout, @Nonnull TimeUnit unit, V def) { - try { - return this.get(timeout, unit); - } catch (InterruptedException ex) { - throw new WrappedException(ex); - } catch (ExecutionException | TimeoutException ex) { - return def; - } - } - - default V getBeforeTimeout(long timeout, @Nonnull TimeUnit unit) { - try { - return get(timeout, unit); - } catch (ExecutionException | InterruptedException ex) { - throw new WrappedException(ex); - } catch (TimeoutException ex) { - throw new IllegalStateException("Operation timed out (" + timeout + " " + unit + ")"); - } - } - - @Nonnull - Task map(@Nullable Function mapper); - - @Nonnull - default Task mapExceptionally(@Nullable ExceptionallyFunction mapper) { - return map(mapper); - } - - @Nonnull - default Task mapVoid() { - return map(v -> null); - } - - @Nonnull - default Task map(@Nonnull Class target) { - return map(target::cast); - } - - @Nonnull - @CheckReturnValue - CompletionStage stage(); + @Nonnull + static ExecutorService getAsyncExecutor() { + return CompletableTask.SERVICE; + } + + @Nonnull + static Task empty() { + return completed(null); + } + + @Nonnull + static Task completed(@Nullable V value) { + return new CompletedTask<>(value); + } + + @Nonnull + static Task completedVoid() { + return empty(); + } + + @Nonnull + static Task failed(@Nonnull Throwable failure) { + return new CompletedTask<>(failure); + } + + @Nonnull + static CompletableTask completable() { + return new CompletableTask<>(); + } + + @Nonnull + static Task asyncCall(@Nonnull Callable callable) { + return CompletableTask.callAsync(callable); + } + + @Nonnull + static Task asyncSupply(@Nonnull Supplier supplier) { + return asyncCall(supplier::get); + } + + @Nonnull + static Task asyncRun(@Nonnull Runnable runnable) { + return asyncCall(() -> { + runnable.run(); + return null; + }); + } + + @Nonnull + static Task asyncRunExceptionally(@Nonnull ExceptionallyRunnable runnable) { + return asyncRun(runnable); + } + + @Nonnull + static Task syncCall(@Nonnull Callable callable) { + return CompletableTask.callSync(callable); + } + + @Nonnull + static Task syncSupply(@Nonnull Supplier supplier) { + return syncCall(supplier::get); + } + + @Nonnull + static Task syncRun(@Nonnull Runnable runnable) { + return syncCall(() -> { + runnable.run(); + return null; + }); + } + + @Nonnull + static Task syncRunExceptionally(@Nonnull ExceptionallyRunnable runnable) { + return syncRun(runnable); + } + + @Nonnull + default Task onComplete(@Nonnull Runnable action) { + return onComplete(v -> action.run()); + } + + @Nonnull + default Task onComplete(@Nonnull Consumer action) { + return onComplete((task, value) -> action.accept(value)); + } + + @Nonnull + default Task onComplete(@Nonnull BiConsumer, ? super V> action) { + return addListener(new TaskListener() { + @Override + public void onComplete(@Nonnull Task task, @Nonnull V value) { + action.accept(task, value); + } + }); + } + + @Nonnull + default Task onFailure(@Nonnull Runnable action) { + return onFailure(ex -> action.run()); + } + + @Nonnull + default Task onFailure(@Nonnull Consumer action) { + return onFailure((task, ex) -> action.accept(ex)); + } + + @Nonnull + default Task onFailure(@Nonnull BiConsumer, ? super Throwable> action) { + return addListener(new TaskListener() { + @Override + public void onFailure(@Nonnull Task task, @Nonnull Throwable ex) { + action.accept(task, ex); + } + }); + } + + @Nonnull + default Task throwOnFailure() { + return onFailure(ex -> ex.printStackTrace()); + } + + @Nonnull + default Task onCancelled(@Nonnull Runnable action) { + return onCancelled(task -> action.run()); + } + + @Nonnull + default Task onCancelled(@Nonnull Consumer> action) { + return addListener(new TaskListener() { + @Override + public void onCancelled(@Nonnull Task task) { + action.accept(task); + } + }); + } + + @Nonnull + default Task addListeners(@Nonnull TaskListener... listeners) { + for (TaskListener listener : listeners) + addListener(listener); + + return this; + } + + @Nonnull + Task addListener(@Nonnull TaskListener listener); + + @Nonnull + Task clearListeners(); + + @Override + V get() throws InterruptedException, ExecutionException; + + @Override + V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; + + default V getOrDefault(V def) { + try { + return get(); + } catch (InterruptedException ex) { + throw new WrappedException(ex); + } catch (ExecutionException ex) { + return def; + } + } + + default V getOrDefault(long timeout, @Nonnull TimeUnit unit, V def) { + try { + return this.get(timeout, unit); + } catch (InterruptedException ex) { + throw new WrappedException(ex); + } catch (ExecutionException | TimeoutException ex) { + return def; + } + } + + default V getBeforeTimeout(long timeout, @Nonnull TimeUnit unit) { + try { + return get(timeout, unit); + } catch (ExecutionException | InterruptedException ex) { + throw new WrappedException(ex); + } catch (TimeoutException ex) { + throw new IllegalStateException("Operation timed out (" + timeout + " " + unit + ")"); + } + } + + @Nonnull + Task map(@Nullable Function mapper); + + @Nonnull + default Task mapExceptionally(@Nullable ExceptionallyFunction mapper) { + return map(mapper); + } + + @Nonnull + default Task mapVoid() { + return map(v -> null); + } + + @Nonnull + default Task map(@Nonnull Class target) { + return map(target::cast); + } + + @Nonnull + @CheckReturnValue + CompletionStage stage(); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java index f800ae95a..e5d87a35e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java @@ -4,13 +4,13 @@ public interface TaskListener { - default void onComplete(@Nonnull Task task, @Nonnull T value) { - } + default void onComplete(@Nonnull Task task, @Nonnull T value) { + } - default void onCancelled(@Nonnull Task task) { - } + default void onCancelled(@Nonnull Task task) { + } - default void onFailure(@Nonnull Task task, @Nonnull Throwable ex) { - } + default void onFailure(@Nonnull Task task, @Nonnull Throwable ex) { + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Config.java b/plugin/src/main/java/net/codingarea/commons/common/config/Config.java index 54462d54a..ad769e1ad 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/Config.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Config.java @@ -12,86 +12,81 @@ */ public interface Config extends Propertyable { - /** - * Sets the value at the given path. - * - * Setting a value to {@code null} has the same effect as {@link #remove(String) removing} it. - * {@code config.set(path, null)} is equivalent with {@code config.remove(path)} - * - * @param value The value to change to, {@code null} to remove - * @return {@code this} for chaining - * - * @throws ConfigReadOnlyException - * If this is {@link #isReadonly() readonly} - */ - @Nonnull - Config set(@Nonnull String path, @Nullable Object value); - - /** - * @throws ConfigReadOnlyException - * If this is {@link #isReadonly() readonly} - */ - @Nonnull - Config clear(); - - /** - * Removing a value has the same effect as {@link #set(String, Object) setting} it to {@code null} - * {@code config.set(path, null)} is equivalent with {@code config.remove(path)} - * - * @return {@code this} for chaining - * - * @throws ConfigReadOnlyException - * If this is {@link #isReadonly() readonly} - */ - @Nonnull - Config remove(@Nonnull String path); - - boolean isReadonly(); - - /** - * @return A new config which is readonly, or {@code this} if already {@link #isReadonly() readonly} - */ - @Nonnull - @CheckReturnValue - Config readonly(); - - @Nonnull - @Override - default Config apply(@Nonnull Consumer action) { - return (Config) Propertyable.super.apply(action); - } - - @Nonnull - @Override - default Config applyIf(boolean expression, @Nonnull Consumer action) { - return (Config) Propertyable.super.applyIf(expression, action); - } - - @Nonnull - default Config increment(@Nonnull String path, double amount) { - return set(path, getDouble(path) + amount); - } - - @Nonnull - default Config decrement(@Nonnull String path, double amount) { - return set(path, getDouble(path) - amount); - } - - @Nonnull - default Config multiply(@Nonnull String path, double factor) { - return set(path, getDouble(path) * factor); - } - - @Nonnull - default Config divide(@Nonnull String path, double divisor) { - return set(path, getDouble(path) / divisor); - } - - @Nonnull - default Config setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { - if (!contains(path)) - set(path, defaultValue); - return this; - } + /** + * Sets the value at the given path. + *

+ * Setting a value to {@code null} has the same effect as {@link #remove(String) removing} it. + * {@code config.set(path, null)} is equivalent with {@code config.remove(path)} + * + * @param value The value to change to, {@code null} to remove + * @return {@code this} for chaining + * @throws ConfigReadOnlyException If this is {@link #isReadonly() readonly} + */ + @Nonnull + Config set(@Nonnull String path, @Nullable Object value); + + /** + * @throws ConfigReadOnlyException If this is {@link #isReadonly() readonly} + */ + @Nonnull + Config clear(); + + /** + * Removing a value has the same effect as {@link #set(String, Object) setting} it to {@code null} + * {@code config.set(path, null)} is equivalent with {@code config.remove(path)} + * + * @return {@code this} for chaining + * @throws ConfigReadOnlyException If this is {@link #isReadonly() readonly} + */ + @Nonnull + Config remove(@Nonnull String path); + + boolean isReadonly(); + + /** + * @return A new config which is readonly, or {@code this} if already {@link #isReadonly() readonly} + */ + @Nonnull + @CheckReturnValue + Config readonly(); + + @Nonnull + @Override + default Config apply(@Nonnull Consumer action) { + return (Config) Propertyable.super.apply(action); + } + + @Nonnull + @Override + default Config applyIf(boolean expression, @Nonnull Consumer action) { + return (Config) Propertyable.super.applyIf(expression, action); + } + + @Nonnull + default Config increment(@Nonnull String path, double amount) { + return set(path, getDouble(path) + amount); + } + + @Nonnull + default Config decrement(@Nonnull String path, double amount) { + return set(path, getDouble(path) - amount); + } + + @Nonnull + default Config multiply(@Nonnull String path, double factor) { + return set(path, getDouble(path) * factor); + } + + @Nonnull + default Config divide(@Nonnull String path, double divisor) { + return set(path, getDouble(path) / divisor); + } + + @Nonnull + default Config setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { + if (!contains(path)) + set(path, defaultValue); + return this; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Document.java b/plugin/src/main/java/net/codingarea/commons/common/config/Document.java index 17c4a0b4a..dc617554f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/Document.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Document.java @@ -25,321 +25,319 @@ public interface Document extends Config, Json { - /** - * Gets the document located at the given path. - * If there is no document assigned to this path, - * a new document is being created and assigned to this path. - * - * @return the document assigned to this path - */ - @Nonnull - Document getDocument(@Nonnull String path); - - /** - * Returns the list of documents located at the given path. - * The returned list will not contain any null elements. - * If there are no documents, the list will be empty. - * Elements which are no documents in the original list will be skipped. - * If an element is {@code null} an empty document will be added - * if this document is not {@link #isReadonly() readonly}. - * - * @return the list of documents assigned to this path - */ - @Nonnull - List getDocumentList(@Nonnull String path); - - @Nonnull - default List getInstanceList(@Nonnull String path, @Nonnull Class classOfT) { - List documents = getDocumentList(path); - List result = new ArrayList<>(documents.size()); - for (Document document : documents) { - result.add(document.toInstanceOf(classOfT)); - } - return result; - } - - @Nonnull - List getSerializableList(@Nonnull String path, @Nonnull Class classOfT); - - @Nullable - T getSerializable(@Nonnull String path, @Nonnull Class classOfT); - - @Nonnull - T getSerializable(@Nonnull String path, @Nonnull T def); - - @Nonnull - Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper); - - @Nonnull - R mapDocument(@Nonnull String path, @Nonnull Function mapper); - - @Nullable - R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper); - - @Nullable - T toInstanceOf(@Nonnull Class classOfT); - - /** - * Returns the parent document of this document. - * If {@code this} is the {@link #getRoot() root} this method will return {@code null}. - * - * @return the parent document of this document - */ - @Nullable - Document getParent(); - - /** - * Returns the root document of this document. - * If the {@link #getParent() parent} is {@code null} this will return {@code this}. - * - * @return the root document of this document - */ - @Nonnull - Document getRoot(); - - /** - * {@inheritDoc} - */ - @Nonnull - @Override - Document set(@Nonnull String path, @Nullable Object value); - - /** - * {@inheritDoc} - */ - @Nonnull - @Override - Document clear(); - - /** - * {@inheritDoc} - */ - @Nonnull - @Override - Document remove(@Nonnull String path); - - /** - * {@inheritDoc} - */ - @Nonnull - @Override - default Document apply(@Nonnull Consumer action) { - return (Document) Config.super.apply(action); - } - - @Nonnull - @Override - default Document applyIf(boolean expression, @Nonnull Consumer action) { - return (Document) Config.super.applyIf(expression, action); - } - - /** - * {@inheritDoc} - */ - @Nonnull - @Override - default Document setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { - return (Document) Config.super.setIfAbsent(path, defaultValue); - } - - @Nonnull - Document set(@Nonnull Object value); - - /** - * {@inheritDoc} - */ - @Nonnull - @Override - @CheckReturnValue - Document readonly(); - - @Nonnull - Map children(); - - boolean isDocument(@Nonnull String path); - - boolean hasChildren(@Nonnull String path); - - void write(@Nonnull Writer writer) throws IOException; - - default void saveToFile(@Nonnull File file) throws IOException { - FileUtils.createFilesIfNecessary(file); - Writer writer = FileUtils.newBufferedWriter(file); - write(writer); - writer.flush(); - writer.close(); - } - - default void saveToFile(@Nonnull Path file) throws IOException { - FileUtils.createFile(file); - Writer writer = FileUtils.newBufferedWriter(file); - write(writer); - writer.flush(); - writer.close(); - } - - @Nonnull - @CheckReturnValue - default FileDocument asFileDocument(@Nonnull File file) { - return (this instanceof FileDocument && ((FileDocument)this).getFile().equals(file)) - ? (FileDocument) this : FileDocument.wrap(this, file); - } - - @Nonnull - @CheckReturnValue - default FileDocument asFileDocument(@Nonnull Path file) { - return asFileDocument(file.toFile()); - } - - @Nonnull - @CheckReturnValue - default Document copyJson() { - Document document = create(); - this.forEach(document::set); - return document; - } - - /** - * @return an empty and immutable document - * - * @see EmptyDocument - */ - @Nonnull - @CheckReturnValue - static Document empty() { - return EmptyDocument.ROOT; - } - - @Nonnull - @CheckReturnValue - static Document readFile(@Nonnull Class classOfDocument, @Nonnull File file) { - try { - if (file.exists()) { - Constructor constructor = classOfDocument.getConstructor(File.class); - return constructor.newInstance(file); - } else { - Constructor constructor = classOfDocument.getConstructor(); - return constructor.newInstance(); - } - } catch (NoSuchMethodException | InstantiationException | IllegalAccessException ex) { - throw new UnsupportedOperationException(classOfDocument.getName() + " does not support File creation"); - } catch (InvocationTargetException ex) { - throw new WrappedException(ex); - } - } - - @Nonnull - @CheckReturnValue - static Document readFile(@Nonnull Class classOfDocument, @Nonnull Path file) { - return readFile(classOfDocument, file.toFile()); - } - - /** - * @return a json document parsed by the input - * - * @see GsonDocument - */ - @Nonnull - @CheckReturnValue - static Document parseJson(@Nonnull String jsonInput) { - return new GsonDocument(jsonInput); - } - - @Nonnull - @CheckReturnValue - static Document parseJson(@Nonnull Reader reader) throws IOException { - return new GsonDocument(reader); - } - - @Nonnull - @CheckReturnValue - static Document parseJson(@Nonnull InputStream input) throws IOException { - return new GsonDocument(new InputStreamReader(input, StandardCharsets.UTF_8)); - } - - @Nonnull - @CheckReturnValue - static List parseJsonArray(@Nonnull String jsonInput) { - return GsonDocument.convertArrayToDocuments(GsonDocument.GSON.fromJson(jsonInput, JsonArray.class)); - } - - @Nonnull - @CheckReturnValue - static List parseStringArray(@Nonnull String jsonInput) { - return GsonDocument.convertArrayToStrings(GsonDocument.GSON.fromJson(jsonInput, JsonArray.class)); - } - - static void saveArray(@Nonnull Iterable objects, @Nonnull Path file) throws IOException { - FileUtils.createFile(file); - Writer writer = FileUtils.newBufferedWriter(file); - JsonArray array = GsonUtils.convertIterableToJsonArray(GsonDocument.GSON, objects); - (GsonDocument.isWritePrettyJson() ? GsonDocument.GSON_PRETTY_PRINT : GsonDocument.GSON).toJson(array, writer); - writer.flush(); - writer.close(); - } - - @Nonnull - @CheckReturnValue - static Document readJsonFile(@Nonnull File file) { - return readFile(GsonDocument.class, file); - } - - @Nonnull - @CheckReturnValue - static Document readJsonFile(@Nonnull Path file) { - return readJsonFile(file.toFile()); - } - - @Nonnull - @CheckReturnValue - static List readJsonArrayFile(@Nonnull Path file) { - try { - JsonArray array = GsonDocument.GSON.fromJson(FileUtils.newBufferedReader(file), JsonArray.class); - if (array == null) return new ArrayList<>(); - List documents = new ArrayList<>(array.size()); - array.forEach(element -> documents.add(new GsonDocument(element.getAsJsonObject()))); - return documents; - } catch (IOException ex) { - throw new WrappedException(ex); - } - } - - @Nonnull - @CheckReturnValue - static Document readPropertiesFile(@Nonnull File file) { - return readFile(PropertiesDocument.class, file); - } - - @Nonnull - @CheckReturnValue - static Document readPropertiesFile(@Nonnull Path file) { - return readPropertiesFile(file.toFile()); - } - - @Nonnull - @CheckReturnValue - static Document create() { - return new GsonDocument(); - } - - @Nonnull - @CheckReturnValue - static Document of(@Nonnull Object object) { - return new GsonDocument(object); - } - - @Nullable - @CheckReturnValue - static Document ofNullable(@Nullable Object object) { - return object == null ? null : of(object); - } - - @Nonnull - @CheckReturnValue - static List arrayOf(@Nonnull Collection objects) { - List documents = new ArrayList<>(objects.size()); - objects.forEach(object -> documents.add(Document.of(object))); - return documents; - } + /** + * Gets the document located at the given path. + * If there is no document assigned to this path, + * a new document is being created and assigned to this path. + * + * @return the document assigned to this path + */ + @Nonnull + Document getDocument(@Nonnull String path); + + /** + * Returns the list of documents located at the given path. + * The returned list will not contain any null elements. + * If there are no documents, the list will be empty. + * Elements which are no documents in the original list will be skipped. + * If an element is {@code null} an empty document will be added + * if this document is not {@link #isReadonly() readonly}. + * + * @return the list of documents assigned to this path + */ + @Nonnull + List getDocumentList(@Nonnull String path); + + @Nonnull + default List getInstanceList(@Nonnull String path, @Nonnull Class classOfT) { + List documents = getDocumentList(path); + List result = new ArrayList<>(documents.size()); + for (Document document : documents) { + result.add(document.toInstanceOf(classOfT)); + } + return result; + } + + @Nonnull + List getSerializableList(@Nonnull String path, @Nonnull Class classOfT); + + @Nullable + T getSerializable(@Nonnull String path, @Nonnull Class classOfT); + + @Nonnull + T getSerializable(@Nonnull String path, @Nonnull T def); + + @Nonnull + Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper); + + @Nonnull + R mapDocument(@Nonnull String path, @Nonnull Function mapper); + + @Nullable + R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper); + + @Nullable + T toInstanceOf(@Nonnull Class classOfT); + + /** + * Returns the parent document of this document. + * If {@code this} is the {@link #getRoot() root} this method will return {@code null}. + * + * @return the parent document of this document + */ + @Nullable + Document getParent(); + + /** + * Returns the root document of this document. + * If the {@link #getParent() parent} is {@code null} this will return {@code this}. + * + * @return the root document of this document + */ + @Nonnull + Document getRoot(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + Document set(@Nonnull String path, @Nullable Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + Document clear(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + Document remove(@Nonnull String path); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + default Document apply(@Nonnull Consumer action) { + return (Document) Config.super.apply(action); + } + + @Nonnull + @Override + default Document applyIf(boolean expression, @Nonnull Consumer action) { + return (Document) Config.super.applyIf(expression, action); + } + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + default Document setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { + return (Document) Config.super.setIfAbsent(path, defaultValue); + } + + @Nonnull + Document set(@Nonnull Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + @CheckReturnValue + Document readonly(); + + @Nonnull + Map children(); + + boolean isDocument(@Nonnull String path); + + boolean hasChildren(@Nonnull String path); + + void write(@Nonnull Writer writer) throws IOException; + + default void saveToFile(@Nonnull File file) throws IOException { + FileUtils.createFilesIfNecessary(file); + Writer writer = FileUtils.newBufferedWriter(file); + write(writer); + writer.flush(); + writer.close(); + } + + default void saveToFile(@Nonnull Path file) throws IOException { + FileUtils.createFile(file); + Writer writer = FileUtils.newBufferedWriter(file); + write(writer); + writer.flush(); + writer.close(); + } + + @Nonnull + @CheckReturnValue + default FileDocument asFileDocument(@Nonnull File file) { + return (this instanceof FileDocument && ((FileDocument) this).getFile().equals(file)) + ? (FileDocument) this : FileDocument.wrap(this, file); + } + + @Nonnull + @CheckReturnValue + default FileDocument asFileDocument(@Nonnull Path file) { + return asFileDocument(file.toFile()); + } + + @Nonnull + @CheckReturnValue + default Document copyJson() { + Document document = create(); + this.forEach(document::set); + return document; + } + + /** + * @return an empty and immutable document + * @see EmptyDocument + */ + @Nonnull + @CheckReturnValue + static Document empty() { + return EmptyDocument.ROOT; + } + + @Nonnull + @CheckReturnValue + static Document readFile(@Nonnull Class classOfDocument, @Nonnull File file) { + try { + if (file.exists()) { + Constructor constructor = classOfDocument.getConstructor(File.class); + return constructor.newInstance(file); + } else { + Constructor constructor = classOfDocument.getConstructor(); + return constructor.newInstance(); + } + } catch (NoSuchMethodException | InstantiationException | IllegalAccessException ex) { + throw new UnsupportedOperationException(classOfDocument.getName() + " does not support File creation"); + } catch (InvocationTargetException ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + static Document readFile(@Nonnull Class classOfDocument, @Nonnull Path file) { + return readFile(classOfDocument, file.toFile()); + } + + /** + * @return a json document parsed by the input + * @see GsonDocument + */ + @Nonnull + @CheckReturnValue + static Document parseJson(@Nonnull String jsonInput) { + return new GsonDocument(jsonInput); + } + + @Nonnull + @CheckReturnValue + static Document parseJson(@Nonnull Reader reader) throws IOException { + return new GsonDocument(reader); + } + + @Nonnull + @CheckReturnValue + static Document parseJson(@Nonnull InputStream input) throws IOException { + return new GsonDocument(new InputStreamReader(input, StandardCharsets.UTF_8)); + } + + @Nonnull + @CheckReturnValue + static List parseJsonArray(@Nonnull String jsonInput) { + return GsonDocument.convertArrayToDocuments(GsonDocument.GSON.fromJson(jsonInput, JsonArray.class)); + } + + @Nonnull + @CheckReturnValue + static List parseStringArray(@Nonnull String jsonInput) { + return GsonDocument.convertArrayToStrings(GsonDocument.GSON.fromJson(jsonInput, JsonArray.class)); + } + + static void saveArray(@Nonnull Iterable objects, @Nonnull Path file) throws IOException { + FileUtils.createFile(file); + Writer writer = FileUtils.newBufferedWriter(file); + JsonArray array = GsonUtils.convertIterableToJsonArray(GsonDocument.GSON, objects); + (GsonDocument.isWritePrettyJson() ? GsonDocument.GSON_PRETTY_PRINT : GsonDocument.GSON).toJson(array, writer); + writer.flush(); + writer.close(); + } + + @Nonnull + @CheckReturnValue + static Document readJsonFile(@Nonnull File file) { + return readFile(GsonDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static Document readJsonFile(@Nonnull Path file) { + return readJsonFile(file.toFile()); + } + + @Nonnull + @CheckReturnValue + static List readJsonArrayFile(@Nonnull Path file) { + try { + JsonArray array = GsonDocument.GSON.fromJson(FileUtils.newBufferedReader(file), JsonArray.class); + if (array == null) return new ArrayList<>(); + List documents = new ArrayList<>(array.size()); + array.forEach(element -> documents.add(new GsonDocument(element.getAsJsonObject()))); + return documents; + } catch (IOException ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + static Document readPropertiesFile(@Nonnull File file) { + return readFile(PropertiesDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static Document readPropertiesFile(@Nonnull Path file) { + return readPropertiesFile(file.toFile()); + } + + @Nonnull + @CheckReturnValue + static Document create() { + return new GsonDocument(); + } + + @Nonnull + @CheckReturnValue + static Document of(@Nonnull Object object) { + return new GsonDocument(object); + } + + @Nullable + @CheckReturnValue + static Document ofNullable(@Nullable Object object) { + return object == null ? null : of(object); + } + + @Nonnull + @CheckReturnValue + static List arrayOf(@Nonnull Collection objects) { + List documents = new ArrayList<>(objects.size()); + objects.forEach(object -> documents.add(Document.of(object))); + return documents; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java index b6d73f26b..0a568223a 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java @@ -16,157 +16,156 @@ public interface FileDocument extends Document { - /** - * Logger used to log errors which are caught in the safe version of an exceptionally method - */ - ILogger LOGGER = ILogger.forThisClass(); - - default void saveExceptionally() throws IOException { - saveToFile(getFile()); - } - - /** - * Executes {@link #saveExceptionally()} and prints all caught errors to {@link #LOGGER} - * - * @see #saveExceptionally() - */ - default void save() { - try { - saveExceptionally(); - } catch (IOException ex) { - LOGGER.error("Could not save config to file \"{}\"", getFile(), ex); - } - } - - @Nonnull - default Task saveAsync() { - return Task.asyncRunExceptionally(this::save); - } - - /** - * @param async whether this should be saved asynchronously or synchronously - * - * @see #save() - * @see #saveAsync() - */ - default void save(boolean async) { - if (async) saveAsync(); - else save(); - } - - @Nonnull - File getFile(); - - @Nonnull - Path getPath(); - - /** - * {@inheritDoc} - */ - @Nonnull - @Override - FileDocument set(@Nonnull String path, @Nullable Object value); - - /** - * {@inheritDoc} - */ - @Nonnull - @Override - FileDocument set(@Nonnull Object value); - - /** - * {@inheritDoc} - */ - @Nonnull - @Override - FileDocument clear(); - - /** - * {@inheritDoc} - */ - @Nonnull - @Override - FileDocument remove(@Nonnull String path); - - /** - * {@inheritDoc} - */ - @Nonnull - @Override - default FileDocument apply(@Nonnull Consumer action) { - return (FileDocument) Document.super.apply(action); - } - - @Nonnull - @Override - default FileDocument setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { - return (FileDocument) Document.super.setIfAbsent(path, defaultValue); - } - - @Nonnull - @Override - default FileDocument increment(@Nonnull String path, double amount) { - return (FileDocument) Document.super.increment(path, amount); - } - - @Nonnull - @Override - default FileDocument decrement(@Nonnull String path, double amount) { - return (FileDocument) Document.super.decrement(path, amount); - } - - @Nonnull - @Override - default FileDocument multiply(@Nonnull String path, double factor) { - return (FileDocument) Document.super.multiply(path, factor); - } - - @Nonnull - @Override - default FileDocument divide(@Nonnull String path, double divisor) { - return (FileDocument) Document.super.divide(path, divisor); - } - - @Nonnull - @CheckReturnValue - static FileDocument wrap(@Nonnull Document document, @Nonnull File file) { - return new FileDocumentWrapper(file, document); - } - - @Nonnull - @CheckReturnValue - static FileDocument readFile(@Nonnull Class classOfDocument, @Nonnull File file) { - return Document.readFile(classOfDocument, file).asFileDocument(file); - } - - @Nonnull - @CheckReturnValue - static FileDocument readFile(@Nonnull Class classOfDocument, @Nonnull Path file) { - return Document.readFile(classOfDocument, file).asFileDocument(file); - } - - @Nonnull - @CheckReturnValue - static FileDocument readJsonFile(@Nonnull File file) { - return readFile(GsonDocument.class, file); - } - - @Nonnull - @CheckReturnValue - static FileDocument readJsonFile(@Nonnull Path file) { - return readFile(GsonDocument.class, file); - } - - @Nonnull - @CheckReturnValue - static FileDocument readPropertiesFile(@Nonnull File file) { - return readFile(PropertiesDocument.class, file); - } - - @Nonnull - @CheckReturnValue - static FileDocument readPropertiesFile(@Nonnull Path file) { - return readFile(PropertiesDocument.class, file); - } + /** + * Logger used to log errors which are caught in the safe version of an exceptionally method + */ + ILogger LOGGER = ILogger.forThisClass(); + + default void saveExceptionally() throws IOException { + saveToFile(getFile()); + } + + /** + * Executes {@link #saveExceptionally()} and prints all caught errors to {@link #LOGGER} + * + * @see #saveExceptionally() + */ + default void save() { + try { + saveExceptionally(); + } catch (IOException ex) { + LOGGER.error("Could not save config to file \"{}\"", getFile(), ex); + } + } + + @Nonnull + default Task saveAsync() { + return Task.asyncRunExceptionally(this::save); + } + + /** + * @param async whether this should be saved asynchronously or synchronously + * @see #save() + * @see #saveAsync() + */ + default void save(boolean async) { + if (async) saveAsync(); + else save(); + } + + @Nonnull + File getFile(); + + @Nonnull + Path getPath(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument set(@Nonnull String path, @Nullable Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument set(@Nonnull Object value); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument clear(); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + FileDocument remove(@Nonnull String path); + + /** + * {@inheritDoc} + */ + @Nonnull + @Override + default FileDocument apply(@Nonnull Consumer action) { + return (FileDocument) Document.super.apply(action); + } + + @Nonnull + @Override + default FileDocument setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { + return (FileDocument) Document.super.setIfAbsent(path, defaultValue); + } + + @Nonnull + @Override + default FileDocument increment(@Nonnull String path, double amount) { + return (FileDocument) Document.super.increment(path, amount); + } + + @Nonnull + @Override + default FileDocument decrement(@Nonnull String path, double amount) { + return (FileDocument) Document.super.decrement(path, amount); + } + + @Nonnull + @Override + default FileDocument multiply(@Nonnull String path, double factor) { + return (FileDocument) Document.super.multiply(path, factor); + } + + @Nonnull + @Override + default FileDocument divide(@Nonnull String path, double divisor) { + return (FileDocument) Document.super.divide(path, divisor); + } + + @Nonnull + @CheckReturnValue + static FileDocument wrap(@Nonnull Document document, @Nonnull File file) { + return new FileDocumentWrapper(file, document); + } + + @Nonnull + @CheckReturnValue + static FileDocument readFile(@Nonnull Class classOfDocument, @Nonnull File file) { + return Document.readFile(classOfDocument, file).asFileDocument(file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readFile(@Nonnull Class classOfDocument, @Nonnull Path file) { + return Document.readFile(classOfDocument, file).asFileDocument(file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readJsonFile(@Nonnull File file) { + return readFile(GsonDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readJsonFile(@Nonnull Path file) { + return readFile(GsonDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readPropertiesFile(@Nonnull File file) { + return readFile(PropertiesDocument.class, file); + } + + @Nonnull + @CheckReturnValue + static FileDocument readPropertiesFile(@Nonnull Path file) { + return readFile(PropertiesDocument.class, file); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Json.java b/plugin/src/main/java/net/codingarea/commons/common/config/Json.java index efcfb495c..a0090052f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/Json.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Json.java @@ -9,40 +9,40 @@ */ public interface Json { - @Nonnull - String toJson(); - - @Nonnull - String toPrettyJson(); - - @Nonnull - @CheckReturnValue - static Json empty() { - return constant("{}", "{}"); - } - - @Nonnull - @CheckReturnValue - static Json supply(@Nonnull Supplier normal, @Nonnull Supplier pretty) { - return new Json() { - @Nonnull - @Override - public String toJson() { - return normal.get(); - } - - @Nonnull - @Override - public String toPrettyJson() { - return pretty.get(); - } - }; - } - - @Nonnull - @CheckReturnValue - static Json constant(@Nonnull String json, @Nonnull String prettyJson) { - return supply(() -> json, () -> prettyJson); - } + @Nonnull + String toJson(); + + @Nonnull + String toPrettyJson(); + + @Nonnull + @CheckReturnValue + static Json empty() { + return constant("{}", "{}"); + } + + @Nonnull + @CheckReturnValue + static Json supply(@Nonnull Supplier normal, @Nonnull Supplier pretty) { + return new Json() { + @Nonnull + @Override + public String toJson() { + return normal.get(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return pretty.get(); + } + }; + } + + @Nonnull + @CheckReturnValue + static Json constant(@Nonnull String json, @Nonnull String prettyJson) { + return supply(() -> json, () -> prettyJson); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java b/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java index bab183bc2..58ce3da88 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java @@ -13,37 +13,38 @@ public final class PropertyHelper { - private PropertyHelper() {} + private PropertyHelper() { + } - private static final Map> getters = new HashMap<>(); + private static final Map> getters = new HashMap<>(); - static { - getters.put(Character.class, Propertyable::getChar); - getters.put(Boolean.class, Propertyable::getBoolean); - getters.put(Byte.class, Propertyable::getByte); - getters.put(Short.class, Propertyable::getShort); - getters.put(Integer.class, Propertyable::getInt); - getters.put(Long.class, Propertyable::getLong); - getters.put(Float.class, Propertyable::getFloat); - getters.put(Double.class, Propertyable::getDouble); - getters.put(String.class, Propertyable::getString); - getters.put(CharSequence.class, Propertyable::getString); - getters.put(List.class, Propertyable::getStringList); - getters.put(Document.class, (BiFunction) Document::getDocument); - getters.put(String[].class, Propertyable::getStringArray); - getters.put(Date.class, Propertyable::getDate); - getters.put(OffsetDateTime.class, Propertyable::getDateTime); - getters.put(Color.class, Propertyable::getColor); - getters.put(byte[].class, Propertyable::getBinary); - } + static { + getters.put(Character.class, Propertyable::getChar); + getters.put(Boolean.class, Propertyable::getBoolean); + getters.put(Byte.class, Propertyable::getByte); + getters.put(Short.class, Propertyable::getShort); + getters.put(Integer.class, Propertyable::getInt); + getters.put(Long.class, Propertyable::getLong); + getters.put(Float.class, Propertyable::getFloat); + getters.put(Double.class, Propertyable::getDouble); + getters.put(String.class, Propertyable::getString); + getters.put(CharSequence.class, Propertyable::getString); + getters.put(List.class, Propertyable::getStringList); + getters.put(Document.class, (BiFunction) Document::getDocument); + getters.put(String[].class, Propertyable::getStringArray); + getters.put(Date.class, Propertyable::getDate); + getters.put(OffsetDateTime.class, Propertyable::getDateTime); + getters.put(Color.class, Propertyable::getColor); + getters.put(byte[].class, Propertyable::getBinary); + } - @Nullable - public static Date parseDate(@Nullable String string) { - try { - return DateFormat.getDateTimeInstance().parse(string); - } catch (Exception ex) { - return null; - } - } + @Nullable + public static Date parseDate(@Nullable String string) { + try { + return DateFormat.getDateTimeInstance().parse(string); + } catch (Exception ex) { + return null; + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java b/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java index 1149b7be1..1a22c1308 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java @@ -21,179 +21,179 @@ */ public interface Propertyable { - T getInstance(@Nonnull String path, @Nonnull Class classOfT); + T getInstance(@Nonnull String path, @Nonnull Class classOfT); - @Nullable - Object getObject(@Nonnull String path); + @Nullable + Object getObject(@Nonnull String path); - @Nonnull - Object getObject(@Nonnull String path, @Nonnull Object def); + @Nonnull + Object getObject(@Nonnull String path, @Nonnull Object def); - @Nonnull - @SuppressWarnings("unchecked") - default Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { - return Optional.ofNullable(extractor.apply((O) this, key)); - } + @Nonnull + @SuppressWarnings("unchecked") + default Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { + return Optional.ofNullable(extractor.apply((O) this, key)); + } - @Nonnull - @SuppressWarnings("unchecked") - default Propertyable apply(@Nonnull Consumer action) { - action.accept((O) this); - return this; - } + @Nonnull + @SuppressWarnings("unchecked") + default Propertyable apply(@Nonnull Consumer action) { + action.accept((O) this); + return this; + } - @Nonnull - default Propertyable applyIf(boolean expression, @Nonnull Consumer action) { - if (expression) - apply(action); - return this; - } + @Nonnull + default Propertyable applyIf(boolean expression, @Nonnull Consumer action) { + if (expression) + apply(action); + return this; + } - @Nullable - String getString(@Nonnull String path); + @Nullable + String getString(@Nonnull String path); - @Nonnull - String getString(@Nonnull String path, @Nonnull String def); + @Nonnull + String getString(@Nonnull String path, @Nonnull String def); - @Nullable - byte[] getBinary(@Nonnull String path); + @Nullable + byte[] getBinary(@Nonnull String path); - char getChar(@Nonnull String path); + char getChar(@Nonnull String path); - char getChar(@Nonnull String path, char def); + char getChar(@Nonnull String path, char def); - long getLong(@Nonnull String path); + long getLong(@Nonnull String path); - long getLong(@Nonnull String path, long def); + long getLong(@Nonnull String path, long def); - int getInt(@Nonnull String path); + int getInt(@Nonnull String path); - int getInt(@Nonnull String path, int def); + int getInt(@Nonnull String path, int def); - short getShort(@Nonnull String path); + short getShort(@Nonnull String path); - short getShort(@Nonnull String path, short def); + short getShort(@Nonnull String path, short def); - byte getByte(@Nonnull String path); + byte getByte(@Nonnull String path); - byte getByte(@Nonnull String path, byte def); + byte getByte(@Nonnull String path, byte def); - float getFloat(@Nonnull String path); + float getFloat(@Nonnull String path); - float getFloat(@Nonnull String path, float def); + float getFloat(@Nonnull String path, float def); - double getDouble(@Nonnull String path); + double getDouble(@Nonnull String path); - double getDouble(@Nonnull String path, double def); + double getDouble(@Nonnull String path, double def); - boolean getBoolean(@Nonnull String path); + boolean getBoolean(@Nonnull String path); - boolean getBoolean(@Nonnull String path, boolean def); + boolean getBoolean(@Nonnull String path, boolean def); - @Nonnull - List getStringList(@Nonnull String path); + @Nonnull + List getStringList(@Nonnull String path); - @Nonnull - String[] getStringArray(@Nonnull String path); + @Nonnull + String[] getStringArray(@Nonnull String path); - @Nonnull - > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum); + @Nonnull + > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum); - @Nonnull - List getUUIDList(@Nonnull String path); + @Nonnull + List getUUIDList(@Nonnull String path); - @Nonnull - List getCharacterList(@Nonnull String path); + @Nonnull + List getCharacterList(@Nonnull String path); - @Nonnull - List getByteList(@Nonnull String path); + @Nonnull + List getByteList(@Nonnull String path); - @Nonnull - List getShortList(@Nonnull String path); + @Nonnull + List getShortList(@Nonnull String path); - @Nonnull - List getIntegerList(@Nonnull String path); + @Nonnull + List getIntegerList(@Nonnull String path); - @Nonnull - List getLongList(@Nonnull String path); + @Nonnull + List getLongList(@Nonnull String path); - @Nonnull - List getFloatList(@Nonnull String path); + @Nonnull + List getFloatList(@Nonnull String path); - @Nonnull - List getDoubleList(@Nonnull String path); + @Nonnull + List getDoubleList(@Nonnull String path); - @Nullable - UUID getUUID(@Nonnull String path); + @Nullable + UUID getUUID(@Nonnull String path); - @Nonnull - UUID getUUID(@Nonnull String path, @Nonnull UUID def); + @Nonnull + UUID getUUID(@Nonnull String path, @Nonnull UUID def); - @Nullable - OffsetDateTime getDateTime(@Nonnull String path); + @Nullable + OffsetDateTime getDateTime(@Nonnull String path); - @Nonnull - OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def); + @Nonnull + OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def); - @Nullable - Date getDate(@Nonnull String path); + @Nullable + Date getDate(@Nonnull String path); - @Nonnull - Date getDate(@Nonnull String path, @Nonnull Date def); + @Nonnull + Date getDate(@Nonnull String path, @Nonnull Date def); - @Nullable - Color getColor(@Nonnull String path); + @Nullable + Color getColor(@Nonnull String path); - @Nonnull - Color getColor(@Nonnull String path, @Nonnull Color def); + @Nonnull + Color getColor(@Nonnull String path, @Nonnull Color def); - @Nullable - > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum); + @Nullable + > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum); - @Nonnull - > E getEnum(@Nonnull String path, @Nonnull E def); + @Nonnull + > E getEnum(@Nonnull String path, @Nonnull E def); - @Nullable - Class getClass(@Nonnull String path); + @Nullable + Class getClass(@Nonnull String path); - @Nonnull - Class getClass(@Nonnull String path, @Nonnull Class def); + @Nonnull + Class getClass(@Nonnull String path, @Nonnull Class def); - @Nullable - Version getVersion(@Nonnull String path); + @Nullable + Version getVersion(@Nonnull String path); - @Nonnull - Version getVersion(@Nonnull String path, @Nonnull Version def); + @Nonnull + Version getVersion(@Nonnull String path, @Nonnull Version def); - boolean isList(@Nonnull String path); + boolean isList(@Nonnull String path); - boolean isObject(@Nonnull String path); + boolean isObject(@Nonnull String path); - boolean contains(@Nonnull String path); + boolean contains(@Nonnull String path); - boolean isEmpty(); + boolean isEmpty(); - @Nonnegative - int size(); + @Nonnegative + int size(); - @Nonnull - Map values(); + @Nonnull + Map values(); - @Nonnull - Map valuesAsStrings(); + @Nonnull + Map valuesAsStrings(); - @Nonnull - Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper); + @Nonnull + Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper); - @Nonnull - List mapList(@Nonnull String path, @Nonnull Function mapper); + @Nonnull + List mapList(@Nonnull String path, @Nonnull Function mapper); - @Nonnull - Collection keys(); + @Nonnull + Collection keys(); - @Nonnull - Set> entrySet(); + @Nonnull + Set> entrySet(); - void forEach(@Nonnull BiConsumer action); + void forEach(@Nonnull BiConsumer action); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java index cce0be2e8..1c8176767 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java @@ -17,262 +17,262 @@ public abstract class AbstractConfig implements Config { - protected static final ILogger logger = ILogger.forThisClass(); - - @Nonnull - protected T getDef(@Nonnull T def, @Nonnull Supplier getter) { - T value = getter.get(); - return value == null ? def : value; - } - - @Nonnull - @Override - public Object getObject(@Nonnull String path, @Nonnull Object def) { - Object value = getObject(path); - return value == null ? def : value; - } - - @Nonnull - @Override - public String getString(@Nonnull String path, @Nonnull String def) { - return getDef(def, () -> getString(path)); - } - - @Override - public char getChar(@Nonnull String path) { - return getChar(path, (char) 0); - } - - @Override - public char getChar(@Nonnull String path, char def) { - try { - return getString(path).charAt(0); - } catch (NullPointerException | IndexOutOfBoundsException ex) { - return def; - } - } - - @Override - public double getDouble(@Nonnull String path) { - return getDouble(path, 0); - } - - @Override - public float getFloat(@Nonnull String path) { - return getFloat(path, 0); - } - - @Override - public long getLong(@Nonnull String path) { - return getLong(path, 0); - } - - @Override - public int getInt(@Nonnull String path) { - return getInt(path, 0); - } - - @Override - public short getShort(@Nonnull String path) { - return getShort(path, (short) 0); - } - - @Override - public byte getByte(@Nonnull String path) { - return getByte(path, (byte) 0); - } - - @Override - public boolean getBoolean(@Nonnull String path) { - return getBoolean(path, false); - } - - @Nonnull - @Override - public UUID getUUID(@Nonnull String path, @Nonnull UUID def) { - return getDef(def, () -> getUUID(path)); - } - - @Nonnull - @Override - public OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { - return getDef(def, () -> getDateTime(path)); - } - - @Nonnull - @Override - public Date getDate(@Nonnull String path, @Nonnull Date def) { - return getDef(def, () -> getDate(path)); - } - - @Nonnull - @Override - public Color getColor(@Nonnull String path, @Nonnull Color def) { - return getDef(def, () -> getColor(path)); - } - - @Nullable - @Override - public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { - return ReflectionUtils.getEnumOrNull(getString(path), classOfEnum); - } - - @Nonnull - @Override - public > E getEnum(@Nonnull String path, @Nonnull E def) { - E value = getEnum(path, def.getDeclaringClass()); - return value == null ? def : value; - } - - @Nullable - @Override - public Class getClass(@Nonnull String path) { - try { - return Class.forName(getString(path)); - } catch (Exception ex) { - return null; - } - } - - @Nonnull - @Override - public Class getClass(@Nonnull String path, @Nonnull Class def) { - return getDef(def, () -> getClass(path)); - } - - @Nullable - @Override - public Version getVersion(@Nonnull String path) { - return Version.parse(getString(path), null); - } - - @Nonnull - @Override - public Version getVersion(@Nonnull String path, @Nonnull Version def) { - return getDef(def, () -> getVersion(path)); - } - - @Nullable - @Override - public byte[] getBinary(@Nonnull String path) { - String string = getString(path); - if (string == null) return null; - return Base64.getDecoder().decode(string); - } - - @Nonnull - @Override - public String[] getStringArray(@Nonnull String path) { - return getStringList(path).toArray(new String[0]); - } - - @Nonnull - @Override - public > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { - return mapList(path, name -> ReflectionUtils.getEnumOrNull(name, classOfEnum)); - } - - @Nonnull - @Override - public List getCharacterList(@Nonnull String path) { - return mapList(path, string -> string == null || string.length() == 0 ? (char) 0 : string.charAt(0)); - } - - @Nonnull - @Override - public List getUUIDList(@Nonnull String path) { - return mapList(path, UUID::fromString); - } - - @Nonnull - @Override - public List getByteList(@Nonnull String path) { - return mapList(path, Byte::parseByte); - } - - @Nonnull - @Override - public List getShortList(@Nonnull String path) { - return mapList(path, Short::parseShort); - } - - @Nonnull - @Override - public List getIntegerList(@Nonnull String path) { - return mapList(path, Integer::parseInt); - } - - @Nonnull - @Override - public List getLongList(@Nonnull String path) { - return mapList(path, Long::parseLong); - } - - @Nonnull - @Override - public List getFloatList(@Nonnull String path) { - return mapList(path, Float::parseFloat); - } - - @Nonnull - @Override - public List getDoubleList(@Nonnull String path) { - return mapList(path, Double::parseDouble); - } - - @Nonnull - @Override - public List mapList(@Nonnull String path, @Nonnull Function mapper) { - List list = getStringList(path); - List result = new ArrayList<>(list.size()); - for (String string : list) { - try { - result.add(mapper.apply(string)); - } catch (Exception ex) { - logger.error("Unable to map values for '{}'", string, ex); - } - } - return result; - } - - @Override - public boolean isEmpty() { - return size() == 0; - } - - @Nonnull - @Override - public Map valuesAsStrings() { - Map map = new HashMap<>(); - values().forEach((key, value) -> map.put(key, String.valueOf(value))); - return map; - } - - @Nonnull - @Override - public Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { - return map(valuesAsStrings(), keyMapper, valueMapper); - } - - @Nonnull - @Override - public Set> entrySet() { - return values().entrySet(); - } - - @Nonnull - public Map map(@Nonnull Map values, - @Nonnull Function keyMapper, - @Nonnull Function valueMapper) { - Map result = new HashMap<>(); - values.forEach((key, value) -> { - try { - result.put(keyMapper.apply(key), valueMapper.apply(value)); - } catch (Exception ex) { - logger.error("Unable to map values for '{}'='{}'", key, value, ex); - } - }); - return result; - } + protected static final ILogger logger = ILogger.forThisClass(); + + @Nonnull + protected T getDef(@Nonnull T def, @Nonnull Supplier getter) { + T value = getter.get(); + return value == null ? def : value; + } + + @Nonnull + @Override + public Object getObject(@Nonnull String path, @Nonnull Object def) { + Object value = getObject(path); + return value == null ? def : value; + } + + @Nonnull + @Override + public String getString(@Nonnull String path, @Nonnull String def) { + return getDef(def, () -> getString(path)); + } + + @Override + public char getChar(@Nonnull String path) { + return getChar(path, (char) 0); + } + + @Override + public char getChar(@Nonnull String path, char def) { + try { + return getString(path).charAt(0); + } catch (NullPointerException | IndexOutOfBoundsException ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path) { + return getDouble(path, 0); + } + + @Override + public float getFloat(@Nonnull String path) { + return getFloat(path, 0); + } + + @Override + public long getLong(@Nonnull String path) { + return getLong(path, 0); + } + + @Override + public int getInt(@Nonnull String path) { + return getInt(path, 0); + } + + @Override + public short getShort(@Nonnull String path) { + return getShort(path, (short) 0); + } + + @Override + public byte getByte(@Nonnull String path) { + return getByte(path, (byte) 0); + } + + @Override + public boolean getBoolean(@Nonnull String path) { + return getBoolean(path, false); + } + + @Nonnull + @Override + public UUID getUUID(@Nonnull String path, @Nonnull UUID def) { + return getDef(def, () -> getUUID(path)); + } + + @Nonnull + @Override + public OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { + return getDef(def, () -> getDateTime(path)); + } + + @Nonnull + @Override + public Date getDate(@Nonnull String path, @Nonnull Date def) { + return getDef(def, () -> getDate(path)); + } + + @Nonnull + @Override + public Color getColor(@Nonnull String path, @Nonnull Color def) { + return getDef(def, () -> getColor(path)); + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return ReflectionUtils.getEnumOrNull(getString(path), classOfEnum); + } + + @Nonnull + @Override + public > E getEnum(@Nonnull String path, @Nonnull E def) { + E value = getEnum(path, def.getDeclaringClass()); + return value == null ? def : value; + } + + @Nullable + @Override + public Class getClass(@Nonnull String path) { + try { + return Class.forName(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nonnull + @Override + public Class getClass(@Nonnull String path, @Nonnull Class def) { + return getDef(def, () -> getClass(path)); + } + + @Nullable + @Override + public Version getVersion(@Nonnull String path) { + return Version.parse(getString(path), null); + } + + @Nonnull + @Override + public Version getVersion(@Nonnull String path, @Nonnull Version def) { + return getDef(def, () -> getVersion(path)); + } + + @Nullable + @Override + public byte[] getBinary(@Nonnull String path) { + String string = getString(path); + if (string == null) return null; + return Base64.getDecoder().decode(string); + } + + @Nonnull + @Override + public String[] getStringArray(@Nonnull String path) { + return getStringList(path).toArray(new String[0]); + } + + @Nonnull + @Override + public > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { + return mapList(path, name -> ReflectionUtils.getEnumOrNull(name, classOfEnum)); + } + + @Nonnull + @Override + public List getCharacterList(@Nonnull String path) { + return mapList(path, string -> string == null || string.length() == 0 ? (char) 0 : string.charAt(0)); + } + + @Nonnull + @Override + public List getUUIDList(@Nonnull String path) { + return mapList(path, UUID::fromString); + } + + @Nonnull + @Override + public List getByteList(@Nonnull String path) { + return mapList(path, Byte::parseByte); + } + + @Nonnull + @Override + public List getShortList(@Nonnull String path) { + return mapList(path, Short::parseShort); + } + + @Nonnull + @Override + public List getIntegerList(@Nonnull String path) { + return mapList(path, Integer::parseInt); + } + + @Nonnull + @Override + public List getLongList(@Nonnull String path) { + return mapList(path, Long::parseLong); + } + + @Nonnull + @Override + public List getFloatList(@Nonnull String path) { + return mapList(path, Float::parseFloat); + } + + @Nonnull + @Override + public List getDoubleList(@Nonnull String path) { + return mapList(path, Double::parseDouble); + } + + @Nonnull + @Override + public List mapList(@Nonnull String path, @Nonnull Function mapper) { + List list = getStringList(path); + List result = new ArrayList<>(list.size()); + for (String string : list) { + try { + result.add(mapper.apply(string)); + } catch (Exception ex) { + logger.error("Unable to map values for '{}'", string, ex); + } + } + return result; + } + + @Override + public boolean isEmpty() { + return size() == 0; + } + + @Nonnull + @Override + public Map valuesAsStrings() { + Map map = new HashMap<>(); + values().forEach((key, value) -> map.put(key, String.valueOf(value))); + return map; + } + + @Nonnull + @Override + public Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return map(valuesAsStrings(), keyMapper, valueMapper); + } + + @Nonnull + @Override + public Set> entrySet() { + return values().entrySet(); + } + + @Nonnull + public Map map(@Nonnull Map values, + @Nonnull Function keyMapper, + @Nonnull Function valueMapper) { + Map result = new HashMap<>(); + values.forEach((key, value) -> { + try { + result.put(keyMapper.apply(key), valueMapper.apply(value)); + } catch (Exception ex) { + logger.error("Unable to map values for '{}'='{}'", key, value, ex); + } + }); + return result; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java index 6f13c5f75..6ab9842e1 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java @@ -17,146 +17,146 @@ public abstract class AbstractDocument extends AbstractConfig implements Document { - protected final Document root, parent; - - public AbstractDocument(@Nonnull Document root, @Nullable Document parent) { - this.root = root; - this.parent = parent; - } - - public AbstractDocument() { - this.root = this; - this.parent = null; - } - - @Nonnull - @Override - public T getSerializable(@Nonnull String path, @Nonnull T def) { - T value = getSerializable(path, (Class) def.getClass()); - return value == null ? def : value; - } - - @Nullable - @Override - public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { - if (!contains(path)) return null; - return BukkitReflectionSerializationUtils.deserializeObject(getDocument(path).values(), classOfT); - } - - @Nonnull - @Override - public List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { - return getDocumentList(path).stream() - .map(Document::values) - .map(map -> BukkitReflectionSerializationUtils.deserializeObject(map, classOfT)) - .collect(Collectors.toList()); - } - - @Nonnull - @Override - public Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { - return map(children(), keyMapper, valueMapper); - } - - @Nonnull - @Override - public R mapDocument(@Nonnull String path, @Nonnull Function mapper) { - Document document = getDocument(path); - return mapper.apply(document); - } - - @Nullable - @Override - public R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { - if (!contains(path)) return null; - return mapDocument(path, mapper); - } - - @Nonnull - @Override - public Document getDocument(@Nonnull String path) { - Document document = getDocument0(path, root, this); - return isReadonly() && !document.isReadonly() ? new ReadOnlyDocumentWrapper(document) : document; - } - - @Nonnull - @Override - public Document set(@Nonnull String path, @Nullable Object value) { - if (isReadonly()) throw new ConfigReadOnlyException("set"); - - if (value instanceof byte[]) - value = Base64.getEncoder().encodeToString((byte[]) value); - - set0(path, value); - return this; - } - - @Nonnull - @Override - public Document set(@Nonnull Object object) { - if (isReadonly()) throw new ConfigReadOnlyException("set"); - - Document.of(object).forEach(this::set); - return this; - } - - @Nonnull - @Override - public Document remove(@Nonnull String path) { - if (isReadonly()) throw new ConfigReadOnlyException("remove"); - remove0(path); - return this; - } - - @Nonnull - @Override - public Document clear() { - if (isReadonly()) throw new ConfigReadOnlyException("clear"); - clear0(); - return this; - } - - @Nonnull - @CheckReturnValue - public Document readonly() { - return isReadonly() ? this : new ReadOnlyDocumentWrapper(this); - } - - @Nonnull - protected abstract Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent); - - protected abstract void set0(@Nonnull String path, @Nullable Object value); - - protected abstract void remove0(@Nonnull String path); - - protected abstract void clear0(); - - @Nonnull - @Override - public Map children() { - Map map = new HashMap<>(); - keys().forEach(key -> { - if (!isDocument(key)) return; - map.put(key, getDocument(key)); - }); - return map; - } - - @Override - public boolean hasChildren(@Nonnull String path) { - return !getDocument(path).isEmpty(); - } - - @Nonnull - @Override - public Document getRoot() { - return root; - } - - @Nullable - @Override - public Document getParent() { - return parent; - } + protected final Document root, parent; + + public AbstractDocument(@Nonnull Document root, @Nullable Document parent) { + this.root = root; + this.parent = parent; + } + + public AbstractDocument() { + this.root = this; + this.parent = null; + } + + @Nonnull + @Override + public T getSerializable(@Nonnull String path, @Nonnull T def) { + T value = getSerializable(path, (Class) def.getClass()); + return value == null ? def : value; + } + + @Nullable + @Override + public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + if (!contains(path)) return null; + return BukkitReflectionSerializationUtils.deserializeObject(getDocument(path).values(), classOfT); + } + + @Nonnull + @Override + public List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { + return getDocumentList(path).stream() + .map(Document::values) + .map(map -> BukkitReflectionSerializationUtils.deserializeObject(map, classOfT)) + .collect(Collectors.toList()); + } + + @Nonnull + @Override + public Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return map(children(), keyMapper, valueMapper); + } + + @Nonnull + @Override + public R mapDocument(@Nonnull String path, @Nonnull Function mapper) { + Document document = getDocument(path); + return mapper.apply(document); + } + + @Nullable + @Override + public R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { + if (!contains(path)) return null; + return mapDocument(path, mapper); + } + + @Nonnull + @Override + public Document getDocument(@Nonnull String path) { + Document document = getDocument0(path, root, this); + return isReadonly() && !document.isReadonly() ? new ReadOnlyDocumentWrapper(document) : document; + } + + @Nonnull + @Override + public Document set(@Nonnull String path, @Nullable Object value) { + if (isReadonly()) throw new ConfigReadOnlyException("set"); + + if (value instanceof byte[]) + value = Base64.getEncoder().encodeToString((byte[]) value); + + set0(path, value); + return this; + } + + @Nonnull + @Override + public Document set(@Nonnull Object object) { + if (isReadonly()) throw new ConfigReadOnlyException("set"); + + Document.of(object).forEach(this::set); + return this; + } + + @Nonnull + @Override + public Document remove(@Nonnull String path) { + if (isReadonly()) throw new ConfigReadOnlyException("remove"); + remove0(path); + return this; + } + + @Nonnull + @Override + public Document clear() { + if (isReadonly()) throw new ConfigReadOnlyException("clear"); + clear0(); + return this; + } + + @Nonnull + @CheckReturnValue + public Document readonly() { + return isReadonly() ? this : new ReadOnlyDocumentWrapper(this); + } + + @Nonnull + protected abstract Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent); + + protected abstract void set0(@Nonnull String path, @Nullable Object value); + + protected abstract void remove0(@Nonnull String path); + + protected abstract void clear0(); + + @Nonnull + @Override + public Map children() { + Map map = new HashMap<>(); + keys().forEach(key -> { + if (!isDocument(key)) return; + map.put(key, getDocument(key)); + }); + return map; + } + + @Override + public boolean hasChildren(@Nonnull String path) { + return !getDocument(path).isEmpty(); + } + + @Nonnull + @Override + public Document getRoot() { + return root; + } + + @Nullable + @Override + public Document getParent() { + return parent; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java index 21deb8ae5..42a9acb81 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java @@ -21,498 +21,498 @@ public class EmptyDocument implements Document { - public static final EmptyDocument ROOT = new EmptyDocument(); - - protected final Document root, parent; - - public EmptyDocument(@Nonnull Document root, @Nullable Document parent) { - this.root = root; - this.parent = parent; - } - - public EmptyDocument() { - this.root = this; - this.parent = null; - } - - @Nonnull - @Override - public Document getDocument(@Nonnull String path) { - return new EmptyDocument(); - } - - @Nonnull - @Override - public R mapDocument(@Nonnull String path, @Nonnull Function mapper) { - return mapper.apply(Document.empty()); - } - - @Nullable - @Override - public R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { - return null; - } - - @Nonnull - @Override - public List getDocumentList(@Nonnull String path) { - return new ArrayList<>(); - } - - @Nonnull - @Override - public List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { - return new ArrayList<>(); - } - - @Nonnull - @Override - public Document set(@Nonnull String path, @Nullable Object value) { - throw new ConfigReadOnlyException("set"); - } - - @Nonnull - @Override - public Document set(@Nonnull Object value) { - throw new ConfigReadOnlyException("set"); - } - - @Nonnull - @Override - public Document clear() { - return this; - } - - @Nonnull - @Override - public Document remove(@Nonnull String path) { - return this; - } - - @Override - public void write(@Nonnull Writer writer) throws IOException { - throw new UnsupportedOperationException("EmptyDocument.write(Writer)"); - } - - @Override - public void saveToFile(@Nonnull File file) throws IOException { - throw new UnsupportedOperationException("EmptyDocument.save(File)"); - } - - @Nullable - @Override - public Object getObject(@Nonnull String path) { - return null; - } - - @Nonnull - @Override - public Object getObject(@Nonnull String path, @Nonnull Object def) { - return def; - } - - @Override - public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { - return null; - } - - @Override - public T toInstanceOf(@Nonnull Class classOfT) { - throw new UnsupportedOperationException(); - } - - @Nonnull - @Override - public Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { - return Optional.empty(); - } - - @Nullable - @Override - public String getString(@Nonnull String path) { - return null; - } - - @Nonnull - @Override - public String getString(@Nonnull String path, @Nonnull String def) { - return def; - } - - @Override - public char getChar(@Nonnull String path) { - return 0; - } - - @Override - public char getChar(@Nonnull String path, char def) { - return def; - } - - @Override - public long getLong(@Nonnull String path) { - return 0; - } - - @Override - public long getLong(@Nonnull String path, long def) { - return def; - } - - @Override - public int getInt(@Nonnull String path) { - return 0; - } - - @Override - public int getInt(@Nonnull String path, int def) { - return def; - } - - @Override - public short getShort(@Nonnull String path) { - return 0; - } - - @Override - public short getShort(@Nonnull String path, short def) { - return def; - } - - @Override - public byte getByte(@Nonnull String path) { - return 0; - } - - @Override - public byte getByte(@Nonnull String path, byte def) { - return def; - } - - @Override - public float getFloat(@Nonnull String path) { - return 0; - } - - @Override - public float getFloat(@Nonnull String path, float def) { - return def; - } - - @Override - public double getDouble(@Nonnull String path) { - return 0; - } - - @Override - public double getDouble(@Nonnull String path, double def) { - return def; - } - - @Override - public boolean getBoolean(@Nonnull String path) { - return false; - } - - @Override - public boolean getBoolean(@Nonnull String path, boolean def) { - return def; - } - - @Nullable - @Override - public byte[] getBinary(@Nonnull String path) { - return null; - } - - @Nonnull - @Override - public List getStringList(@Nonnull String path) { - return new ArrayList<>(); - } - - @Nonnull - @Override - public String[] getStringArray(@Nonnull String path) { - return new String[0]; - } - - @Nonnull - @Override - public > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { - return new ArrayList<>(); - } - - @Nonnull - @Override - public List mapList(@Nonnull String path, @Nonnull Function mapper) { - return new ArrayList<>(); - } - - @Nonnull - @Override - public List getUUIDList(@Nonnull String path) { - return new ArrayList<>(); - } - - @Nonnull - @Override - public List getCharacterList(@Nonnull String path) { - return new ArrayList<>(); - } - - @Nonnull - @Override - public List getByteList(@Nonnull String path) { - return new ArrayList<>(); - } - - @Nonnull - @Override - public List getShortList(@Nonnull String path) { - return new ArrayList<>(); - } - - @Nonnull - @Override - public List getIntegerList(@Nonnull String path) { - return new ArrayList<>(); - } - - @Nonnull - @Override - public List getLongList(@Nonnull String path) { - return new ArrayList<>(); - } - - @Nonnull - @Override - public List getFloatList(@Nonnull String path) { - return new ArrayList<>(); - } - - @Nonnull - @Override - public List getDoubleList(@Nonnull String path) { - return new ArrayList<>(); - } - - @Nullable - @Override - public UUID getUUID(@Nonnull String path) { - return null; - } - - @Nonnull - @Override - public UUID getUUID(@Nonnull String path, @Nonnull UUID def) { - return def; - } - - @Nullable - @Override - public Date getDate(@Nonnull String path) { - return null; - } - - @Nonnull - @Override - public Date getDate(@Nonnull String path, @Nonnull Date def) { - return def; - } - - @Nullable - @Override - public OffsetDateTime getDateTime(@Nonnull String path) { - return null; - } - - @Nonnull - @Override - public OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { - return def; - } - - @Nullable - @Override - public Color getColor(@Nonnull String path) { - return null; - } - - @Nonnull - @Override - public Color getColor(@Nonnull String path, @Nonnull Color def) { - return def; - } - - @Nullable - @Override - public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { - return null; - } - - @Nonnull - @Override - public > E getEnum(@Nonnull String path, @Nonnull E def) { - return def; - } - - @Nullable - @Override - public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { - return null; - } - - @Nonnull - @Override - public T getSerializable(@Nonnull String path, @Nonnull T def) { - return def; - } - - @Nullable - @Override - public Class getClass(@Nonnull String path) { - return null; - } - - @Nonnull - @Override - public Class getClass(@Nonnull String path, @Nonnull Class def) { - return def; - } - - @Nullable - @Override - public Version getVersion(@Nonnull String path) { - return null; - } - - @Nonnull - @Override - public Version getVersion(@Nonnull String path, @Nonnull Version def) { - return def; - } - - @Override - public boolean contains(@Nonnull String path) { - return false; - } - - @Override - public boolean isEmpty() { - return true; - } - - @Override - public boolean hasChildren(@Nonnull String path) { - return false; - } - - @Override - public boolean isList(@Nonnull String path) { - return false; - } - - @Override - public boolean isObject(@Nonnull String path) { - return false; - } - - @Override - public boolean isDocument(@Nonnull String path) { - return false; - } - - @Override - public int size() { - return 0; - } - - @Nonnull - @Override - public Map values() { - return Collections.emptyMap(); - } - - @Nonnull - @Override - public Map valuesAsStrings() { - return new HashMap<>(); - } - - @Nonnull - @Override - public Map children() { - return new HashMap<>(); - } - - @Nonnull - @Override - public Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { - return new HashMap<>(); - } - - @Nonnull - @Override - public Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { - return new HashMap<>(); - } - - @Nonnull - @Override - public Collection keys() { - return Collections.emptyList(); - } - - @Nonnull - @Override - public Set> entrySet() { - return Collections.emptySet(); - } - - @Override - public void forEach(@Nonnull BiConsumer action) { - } - - @Nonnull - @Override - public String toJson() { - return "{}"; - } - - @Nonnull - @Override - public String toPrettyJson() { - return "{}"; - } - - @Nonnull - @Override - public String toString() { - return "{}"; - } - - @Override - public boolean isReadonly() { - return true; - } - - @Nonnull - @Override - public Document readonly() { - return this; - } - - @Nullable - @Override - public Document getParent() { - return parent; - } - - @Nonnull - @Override - public Document getRoot() { - return root; - } + public static final EmptyDocument ROOT = new EmptyDocument(); + + protected final Document root, parent; + + public EmptyDocument(@Nonnull Document root, @Nullable Document parent) { + this.root = root; + this.parent = parent; + } + + public EmptyDocument() { + this.root = this; + this.parent = null; + } + + @Nonnull + @Override + public Document getDocument(@Nonnull String path) { + return new EmptyDocument(); + } + + @Nonnull + @Override + public R mapDocument(@Nonnull String path, @Nonnull Function mapper) { + return mapper.apply(Document.empty()); + } + + @Nullable + @Override + public R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { + return null; + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public Document set(@Nonnull String path, @Nullable Object value) { + throw new ConfigReadOnlyException("set"); + } + + @Nonnull + @Override + public Document set(@Nonnull Object value) { + throw new ConfigReadOnlyException("set"); + } + + @Nonnull + @Override + public Document clear() { + return this; + } + + @Nonnull + @Override + public Document remove(@Nonnull String path) { + return this; + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + throw new UnsupportedOperationException("EmptyDocument.write(Writer)"); + } + + @Override + public void saveToFile(@Nonnull File file) throws IOException { + throw new UnsupportedOperationException("EmptyDocument.save(File)"); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Object getObject(@Nonnull String path, @Nonnull Object def) { + return def; + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return null; + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + throw new UnsupportedOperationException(); + } + + @Nonnull + @Override + public Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { + return Optional.empty(); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public String getString(@Nonnull String path, @Nonnull String def) { + return def; + } + + @Override + public char getChar(@Nonnull String path) { + return 0; + } + + @Override + public char getChar(@Nonnull String path, char def) { + return def; + } + + @Override + public long getLong(@Nonnull String path) { + return 0; + } + + @Override + public long getLong(@Nonnull String path, long def) { + return def; + } + + @Override + public int getInt(@Nonnull String path) { + return 0; + } + + @Override + public int getInt(@Nonnull String path, int def) { + return def; + } + + @Override + public short getShort(@Nonnull String path) { + return 0; + } + + @Override + public short getShort(@Nonnull String path, short def) { + return def; + } + + @Override + public byte getByte(@Nonnull String path) { + return 0; + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + return def; + } + + @Override + public float getFloat(@Nonnull String path) { + return 0; + } + + @Override + public float getFloat(@Nonnull String path, float def) { + return def; + } + + @Override + public double getDouble(@Nonnull String path) { + return 0; + } + + @Override + public double getDouble(@Nonnull String path, double def) { + return def; + } + + @Override + public boolean getBoolean(@Nonnull String path) { + return false; + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + return def; + } + + @Nullable + @Override + public byte[] getBinary(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public String[] getStringArray(@Nonnull String path) { + return new String[0]; + } + + @Nonnull + @Override + public > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List mapList(@Nonnull String path, @Nonnull Function mapper) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getUUIDList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getCharacterList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getByteList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getShortList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getIntegerList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getLongList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getFloatList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nonnull + @Override + public List getDoubleList(@Nonnull String path) { + return new ArrayList<>(); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public UUID getUUID(@Nonnull String path, @Nonnull UUID def) { + return def; + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Date getDate(@Nonnull String path, @Nonnull Date def) { + return def; + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { + return def; + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Color getColor(@Nonnull String path, @Nonnull Color def) { + return def; + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return null; + } + + @Nonnull + @Override + public > E getEnum(@Nonnull String path, @Nonnull E def) { + return def; + } + + @Nullable + @Override + public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + return null; + } + + @Nonnull + @Override + public T getSerializable(@Nonnull String path, @Nonnull T def) { + return def; + } + + @Nullable + @Override + public Class getClass(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Class getClass(@Nonnull String path, @Nonnull Class def) { + return def; + } + + @Nullable + @Override + public Version getVersion(@Nonnull String path) { + return null; + } + + @Nonnull + @Override + public Version getVersion(@Nonnull String path, @Nonnull Version def) { + return def; + } + + @Override + public boolean contains(@Nonnull String path) { + return false; + } + + @Override + public boolean isEmpty() { + return true; + } + + @Override + public boolean hasChildren(@Nonnull String path) { + return false; + } + + @Override + public boolean isList(@Nonnull String path) { + return false; + } + + @Override + public boolean isObject(@Nonnull String path) { + return false; + } + + @Override + public boolean isDocument(@Nonnull String path) { + return false; + } + + @Override + public int size() { + return 0; + } + + @Nonnull + @Override + public Map values() { + return Collections.emptyMap(); + } + + @Nonnull + @Override + public Map valuesAsStrings() { + return new HashMap<>(); + } + + @Nonnull + @Override + public Map children() { + return new HashMap<>(); + } + + @Nonnull + @Override + public Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return new HashMap<>(); + } + + @Nonnull + @Override + public Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return new HashMap<>(); + } + + @Nonnull + @Override + public Collection keys() { + return Collections.emptyList(); + } + + @Nonnull + @Override + public Set> entrySet() { + return Collections.emptySet(); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + } + + @Nonnull + @Override + public String toJson() { + return "{}"; + } + + @Nonnull + @Override + public String toPrettyJson() { + return "{}"; + } + + @Nonnull + @Override + public String toString() { + return "{}"; + } + + @Override + public boolean isReadonly() { + return true; + } + + @Nonnull + @Override + public Document readonly() { + return this; + } + + @Nullable + @Override + public Document getParent() { + return parent; + } + + @Nonnull + @Override + public Document getRoot() { + return root; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java index 50262eaf0..92a957a2f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java @@ -26,483 +26,487 @@ public class GsonDocument extends AbstractDocument { - static { - GsonBuilder builder = new GsonBuilder() - .disableHtmlEscaping() - .registerTypeAdapterFactory(GsonTypeAdapter.newPredictableFactory(BukkitReflectionSerializationUtils::isSerializable, new BukkitReflectionSerializableTypeAdapter())) - .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Document.class, new DocumentTypeAdapter())) - .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Pair.class, new PairTypeAdapter())) - .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Class.class, new ClassTypeAdapter())) - .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Color.class, new ColorTypeAdapter())) - ; - - GSON = builder.create(); - GSON_PRETTY_PRINT = builder.setPrettyPrinting().create(); - } - - // Not implemented in some versions of gson - TypeAdapter NUMBER = new TypeAdapter() { - @Override - public void write(JsonWriter out, Number value) throws IOException { - out.value(value); - } - @Override - public Number read(JsonReader in) throws IOException { - JsonToken jsonToken = in.peek(); - switch (jsonToken) { - case NUMBER: - case STRING: - return new LazilyParsedNumber(in.nextString()); - case BOOLEAN: - default: - throw new JsonSyntaxException("Expecting number, got: " + jsonToken); - case NULL: - in.nextNull(); - return null; - } - } - }; - - public static final Gson GSON, GSON_PRETTY_PRINT; - - private static boolean cleanupEmptyObjects = false; - private static boolean cleanupEmptyArrays = false; - private static boolean writePrettyJson = true; - - public static void setCleanupEmptyArrays(boolean clean) { - cleanupEmptyArrays = clean; - } - - public static void setCleanupEmptyObjects(boolean clean) { - cleanupEmptyObjects = clean; - } - - public static void setWritePrettyJson(boolean pretty) { - writePrettyJson = pretty; - } - - public static boolean isWritePrettyJson() { - return writePrettyJson; - } - - @Nonnull - public static List convertArrayToDocuments(@Nonnull JsonArray array) { - List list = new ArrayList<>(array.size()); - for (JsonElement element : array) { - if (!element.isJsonObject()) continue; - list.add(new GsonDocument(element.getAsJsonObject())); - } - return list; - } - - @Nonnull - public static List convertArrayToStrings(@Nonnull JsonArray array) { - List list = new ArrayList<>(array.size()); - for (JsonElement element : array) { - if (!element.isJsonObject()) continue; - list.add(element.getAsString()); - } - return list; - } - - protected JsonObject jsonObject; - - public GsonDocument(@Nonnull File file) throws IOException { - this(FileUtils.newBufferedReader(file)); - } - - public GsonDocument(@Nonnull Reader reader) throws IOException { - this(new BufferedReader(reader)); - } - - public GsonDocument(@Nonnull BufferedReader reader) throws IOException { - this(reader.ready() ? GSON.fromJson(reader, JsonObject.class) : new JsonObject()); - } - - public GsonDocument(@Nonnull String json) { - this(GSON.fromJson(json, JsonObject.class)); - } - - public GsonDocument(@Nonnull String json, @Nonnull Document root, @Nullable Document parent) { - this(GSON.fromJson(json, JsonObject.class), root, parent); - } - - public GsonDocument(@Nullable JsonObject jsonObject) { - this.jsonObject = jsonObject == null ? new JsonObject() : jsonObject; - } - - public GsonDocument(@Nullable JsonObject jsonObject, @Nonnull Document root, @Nullable Document parent) { - super(root, parent); - this.jsonObject = jsonObject == null ? new JsonObject() : jsonObject; - } - - public GsonDocument(@Nonnull Map values) { - this(); - GsonUtils.setDocumentProperties(GSON, jsonObject, values); - } - - public GsonDocument() { - this(new JsonObject()); - } - - public GsonDocument(@Nonnull Object object) { - this(GSON.toJsonTree(object).getAsJsonObject()); - } - - @Nullable - @Override - public String getString(@Nonnull String path) { - JsonElement element = getElement(path).orElse(null); - return GsonUtils.convertJsonElementToString(element); - } - - @Nullable - @Override - public Object getObject(@Nonnull String path) { - JsonElement element = getElement(path).orElse(null); - return GsonUtils.unpackJsonElement(element); - } - - @Nullable - @Override - public T getInstance(@Nonnull String path, @Nonnull Class classOfType) { - JsonElement element = getElement(path).orElse(null); - return GSON.fromJson(element, classOfType); - } - - @Override - public T toInstanceOf(@Nonnull Class classOfT) { - if (isEmpty()) return null; - return GSON.fromJson(jsonObject, classOfT); - } - - @Nullable - @Override - public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { - return getInstance(path, classOfT); - } - - @Nonnull - @Override - public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { - JsonElement element = getElement(path).orElse(null); - if (element == null || !element.isJsonObject()) setElement(path, element = new JsonObject()); - return new GsonDocument(element.getAsJsonObject(), root, parent); - } - - @Nonnull - @Override - public List getDocumentList(@Nonnull String path) { - JsonElement element = getElement(path).orElse(new JsonArray()); - if (element.isJsonNull()) return new ArrayList<>(); - JsonArray array = element.getAsJsonArray(); - List documents = new ArrayList<>(array.size()); - for (JsonElement current : array) { - if (current == null || current.isJsonNull()) documents.add(new GsonDocument((JsonObject) null, root, this)); - else if (current.isJsonObject()) documents.add(new GsonDocument(current.getAsJsonObject(), root, this)); - } - return documents; - } - - @Override - public char getChar(@Nonnull String path) { - return getChar(path, (char) 0); - } - - @Override - public char getChar(@Nonnull String path, char def) { - return getPrimitive(path).map(JsonPrimitive::getAsCharacter).orElse(def); - } - - @Override - public long getLong(@Nonnull String path, long def) { - return getPrimitive(path).map(JsonPrimitive::getAsLong).orElse(def); - } - - @Override - public int getInt(@Nonnull String path, int def) { - return getPrimitive(path).map(JsonPrimitive::getAsInt).orElse(def); - } - - @Override - public short getShort(@Nonnull String path, short def) { - return getPrimitive(path).map(JsonPrimitive::getAsShort).orElse(def); - } - - @Override - public byte getByte(@Nonnull String path, byte def) { - return getPrimitive(path).map(JsonPrimitive::getAsByte).orElse(def); - } - - @Override - public double getDouble(@Nonnull String path, double def) { - return getPrimitive(path).map(JsonPrimitive::getAsDouble).orElse(def); - } - - @Override - public float getFloat(@Nonnull String path, float def) { - return getPrimitive(path).map(JsonPrimitive::getAsFloat).orElse(def); - } - - @Override - public boolean getBoolean(@Nonnull String path, boolean def) { - return getPrimitive(path).map(JsonPrimitive::getAsBoolean).orElse(def); - } - - @Nonnull - @Override - public List getStringList(@Nonnull String path) { - JsonElement element = getElement(path).orElse(null); - if (element == null || element.isJsonNull()) return new ArrayList<>(); - if (element.isJsonPrimitive()) return new ArrayList<>(Collections.singletonList(GsonUtils.convertJsonElementToString(element))); - if (element.isJsonObject()) throw new IllegalStateException("Cannot extract list out of json object at '" + path + "'"); - return GsonUtils.convertJsonArrayToStringList(element.getAsJsonArray()); - } - - @Nullable - @Override - public UUID getUUID(@Nonnull String path) { - return getInstance(path, UUID.class); - } - - @Nullable - @Override - public Date getDate(@Nonnull String path) { - return getInstance(path, Date.class); - } - - @Nullable - @Override - public OffsetDateTime getDateTime(@Nonnull String path) { - return getInstance(path, OffsetDateTime.class); - } - - @Nullable - @Override - public Color getColor(@Nonnull String path) { - return getInstance(path, Color.class); - } - - @Nullable - @Override - public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { - return getInstance(path, classOfEnum); - } - - @Override - public boolean isList(@Nonnull String path) { - return checkElement(path, JsonElement::isJsonArray); - } - - @Override - public boolean isDocument(@Nonnull String path) { - return checkElement(path, JsonElement::isJsonObject); - } - - @Override - public boolean isObject(@Nonnull String path) { - return checkElement(path, JsonElement::isJsonPrimitive); - } - - private boolean checkElement(@Nonnull String path, @Nonnull Function check) { - return getElement(path).map(check).orElse(false); - } - - @Override - public boolean contains(@Nonnull String path) { - return getElement(path).isPresent(); - } - - @Override - public int size() { - return GsonUtils.getSize(jsonObject); - } - - @Override - public void set0(@Nonnull String path, @Nullable Object value) { - setElement(path, value); - } - - @Nonnull - @Override - public Document set(@Nonnull Object object) { - JsonObject json = GSON.toJsonTree(object).getAsJsonObject(); - for (Entry entry : json.entrySet()) { - jsonObject.add(entry.getKey(), entry.getValue()); - } - return this; - } - - @Override - public void clear0() { - jsonObject = new JsonObject(); - } - - @Override - public void remove0(@Nonnull String path) { - setElement(path, null); - } - - @Nonnull - @Override - public Map values() { - return GsonUtils.convertJsonObjectToMap(jsonObject); - } - - @Override - public void forEach(@Nonnull BiConsumer action) { - values().forEach(action); - } - - @Nonnull - @Override - public Collection keys() { - Collection keys = new ArrayList<>(size()); - for (Entry entry : jsonObject.entrySet()) { - keys.add(entry.getKey()); - } - return keys; - } - - @Nonnull - private Optional getPrimitive(@Nonnull String path) { - return getElement(path) - .filter(JsonPrimitive.class::isInstance) - .map(JsonPrimitive.class::cast); - } - - @Nonnull - private Optional getElement(@Nonnull String path) { - return getElement(path, jsonObject); - } - - @Nonnull - private Optional getElement(@Nonnull String path, @Nonnull JsonObject object) { - - JsonElement fullPathElement = object.get(path); - if (fullPathElement != null) return Optional.of(fullPathElement); - - int index = path.indexOf('.'); - if (index == -1) return Optional.empty(); - - String child = path.substring(0, index); - String newPath = path.substring(index + 1); - - JsonElement element = object.get(child); - if (element == null || element.isJsonNull()) return Optional.empty(); - - return getElement(newPath, element.getAsJsonObject()); - - } - - private void setElement(@Nonnull String path, @Nullable Object value) { - - LinkedList paths = determinePath(path); - JsonObject object = jsonObject; - - for (int i = 0; i < paths.size() - 1; i++) { - - String current = paths.get(i); - JsonElement element = object.get(current); - if (element == null || element.isJsonNull()) { - if (value == null) return; // There's noting to remove - object.add(current, element = new JsonObject()); - } - - if (!element.isJsonObject()) throw new IllegalArgumentException("Cannot replace '" + current + "' on '" + path + "'; It's not an object (" + element.getClass().getName() + ")"); - object = element.getAsJsonObject(); - - } - - String lastPath = paths.getLast(); - JsonElement jsonValue = - value instanceof JsonElement ? (JsonElement) value - : value == null ? JsonNull.INSTANCE - : value instanceof Number ? NUMBER.toJsonTree((Number) value) - : value instanceof Boolean ? TypeAdapters.BOOLEAN.toJsonTree((boolean) value) - : value instanceof Character ? TypeAdapters.CHARACTER.toJsonTree((char) value) - : GSON.toJsonTree(value); - object.add(lastPath, jsonValue); - - } - - @Nonnull - private LinkedList determinePath(@Nonnull String path) { - - LinkedList paths = new LinkedList<>(); - String pathCopy = path; - int index; - while ((index = pathCopy.indexOf('.')) != -1) { - String child = pathCopy.substring(0, index); - pathCopy = pathCopy.substring(index + 1); - paths.add(child); - } - paths.add(pathCopy); - - return paths; - - } - - @Nonnull - @Override - public String toJson() { - return GSON.toJson(jsonObject); - } - - @Nonnull - @Override - public String toPrettyJson() { - return GSON_PRETTY_PRINT.toJson(jsonObject); - } - - @Override - public String toString() { - return toJson(); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - GsonDocument that = (GsonDocument) o; - return jsonObject.equals(that.jsonObject); - } - - @Override - public int hashCode() { - return jsonObject.hashCode(); - } - - @Override - public void write(@Nonnull Writer writer) throws IOException { - cleanup(); - (writePrettyJson ? GSON_PRETTY_PRINT : GSON).toJson(jsonObject, writer); - } - - @Nonnull - public JsonObject getJsonObject() { - return jsonObject; - } - - @Override - public boolean isReadonly() { - return false; - } - - public void cleanup() { - cleanup(jsonObject); - } - - public static void cleanup(@Nonnull JsonObject jsonObject) { - Iterator> iterator = jsonObject.entrySet().iterator(); - while (iterator.hasNext()) { - Entry entry = iterator.next(); - JsonElement value = entry.getValue(); - if (value.isJsonObject()) cleanup(value.getAsJsonObject()); + static { + GsonBuilder builder = new GsonBuilder() + .disableHtmlEscaping() + .registerTypeAdapterFactory(GsonTypeAdapter.newPredictableFactory(BukkitReflectionSerializationUtils::isSerializable, new BukkitReflectionSerializableTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Document.class, new DocumentTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Pair.class, new PairTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Class.class, new ClassTypeAdapter())) + .registerTypeAdapterFactory(GsonTypeAdapter.newTypeHierarchyFactory(Color.class, new ColorTypeAdapter())); + + GSON = builder.create(); + GSON_PRETTY_PRINT = builder.setPrettyPrinting().create(); + } + + // Not implemented in some versions of gson + TypeAdapter NUMBER = new TypeAdapter() { + @Override + public void write(JsonWriter out, Number value) throws IOException { + out.value(value); + } + + @Override + public Number read(JsonReader in) throws IOException { + JsonToken jsonToken = in.peek(); + switch (jsonToken) { + case NUMBER: + case STRING: + return new LazilyParsedNumber(in.nextString()); + case BOOLEAN: + default: + throw new JsonSyntaxException("Expecting number, got: " + jsonToken); + case NULL: + in.nextNull(); + return null; + } + } + }; + + public static final Gson GSON, GSON_PRETTY_PRINT; + + private static boolean cleanupEmptyObjects = false; + private static boolean cleanupEmptyArrays = false; + private static boolean writePrettyJson = true; + + public static void setCleanupEmptyArrays(boolean clean) { + cleanupEmptyArrays = clean; + } + + public static void setCleanupEmptyObjects(boolean clean) { + cleanupEmptyObjects = clean; + } + + public static void setWritePrettyJson(boolean pretty) { + writePrettyJson = pretty; + } + + public static boolean isWritePrettyJson() { + return writePrettyJson; + } + + @Nonnull + public static List convertArrayToDocuments(@Nonnull JsonArray array) { + List list = new ArrayList<>(array.size()); + for (JsonElement element : array) { + if (!element.isJsonObject()) continue; + list.add(new GsonDocument(element.getAsJsonObject())); + } + return list; + } + + @Nonnull + public static List convertArrayToStrings(@Nonnull JsonArray array) { + List list = new ArrayList<>(array.size()); + for (JsonElement element : array) { + if (!element.isJsonObject()) continue; + list.add(element.getAsString()); + } + return list; + } + + protected JsonObject jsonObject; + + public GsonDocument(@Nonnull File file) throws IOException { + this(FileUtils.newBufferedReader(file)); + } + + public GsonDocument(@Nonnull Reader reader) throws IOException { + this(new BufferedReader(reader)); + } + + public GsonDocument(@Nonnull BufferedReader reader) throws IOException { + this(reader.ready() ? GSON.fromJson(reader, JsonObject.class) : new JsonObject()); + } + + public GsonDocument(@Nonnull String json) { + this(GSON.fromJson(json, JsonObject.class)); + } + + public GsonDocument(@Nonnull String json, @Nonnull Document root, @Nullable Document parent) { + this(GSON.fromJson(json, JsonObject.class), root, parent); + } + + public GsonDocument(@Nullable JsonObject jsonObject) { + this.jsonObject = jsonObject == null ? new JsonObject() : jsonObject; + } + + public GsonDocument(@Nullable JsonObject jsonObject, @Nonnull Document root, @Nullable Document parent) { + super(root, parent); + this.jsonObject = jsonObject == null ? new JsonObject() : jsonObject; + } + + public GsonDocument(@Nonnull Map values) { + this(); + GsonUtils.setDocumentProperties(GSON, jsonObject, values); + } + + public GsonDocument() { + this(new JsonObject()); + } + + public GsonDocument(@Nonnull Object object) { + this(GSON.toJsonTree(object).getAsJsonObject()); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + JsonElement element = getElement(path).orElse(null); + return GsonUtils.convertJsonElementToString(element); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + JsonElement element = getElement(path).orElse(null); + return GsonUtils.unpackJsonElement(element); + } + + @Nullable + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfType) { + JsonElement element = getElement(path).orElse(null); + return GSON.fromJson(element, classOfType); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + if (isEmpty()) return null; + return GSON.fromJson(jsonObject, classOfT); + } + + @Nullable + @Override + public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + return getInstance(path, classOfT); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + JsonElement element = getElement(path).orElse(null); + if (element == null || !element.isJsonObject()) setElement(path, element = new JsonObject()); + return new GsonDocument(element.getAsJsonObject(), root, parent); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + JsonElement element = getElement(path).orElse(new JsonArray()); + if (element.isJsonNull()) return new ArrayList<>(); + JsonArray array = element.getAsJsonArray(); + List documents = new ArrayList<>(array.size()); + for (JsonElement current : array) { + if (current == null || current.isJsonNull()) documents.add(new GsonDocument((JsonObject) null, root, this)); + else if (current.isJsonObject()) documents.add(new GsonDocument(current.getAsJsonObject(), root, this)); + } + return documents; + } + + @Override + public char getChar(@Nonnull String path) { + return getChar(path, (char) 0); + } + + @Override + public char getChar(@Nonnull String path, char def) { + return getPrimitive(path).map(JsonPrimitive::getAsCharacter).orElse(def); + } + + @Override + public long getLong(@Nonnull String path, long def) { + return getPrimitive(path).map(JsonPrimitive::getAsLong).orElse(def); + } + + @Override + public int getInt(@Nonnull String path, int def) { + return getPrimitive(path).map(JsonPrimitive::getAsInt).orElse(def); + } + + @Override + public short getShort(@Nonnull String path, short def) { + return getPrimitive(path).map(JsonPrimitive::getAsShort).orElse(def); + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + return getPrimitive(path).map(JsonPrimitive::getAsByte).orElse(def); + } + + @Override + public double getDouble(@Nonnull String path, double def) { + return getPrimitive(path).map(JsonPrimitive::getAsDouble).orElse(def); + } + + @Override + public float getFloat(@Nonnull String path, float def) { + return getPrimitive(path).map(JsonPrimitive::getAsFloat).orElse(def); + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + return getPrimitive(path).map(JsonPrimitive::getAsBoolean).orElse(def); + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + JsonElement element = getElement(path).orElse(null); + if (element == null || element.isJsonNull()) return new ArrayList<>(); + if (element.isJsonPrimitive()) + return new ArrayList<>(Collections.singletonList(GsonUtils.convertJsonElementToString(element))); + if (element.isJsonObject()) + throw new IllegalStateException("Cannot extract list out of json object at '" + path + "'"); + return GsonUtils.convertJsonArrayToStringList(element.getAsJsonArray()); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + return getInstance(path, UUID.class); + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + return getInstance(path, Date.class); + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + return getInstance(path, OffsetDateTime.class); + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + return getInstance(path, Color.class); + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return getInstance(path, classOfEnum); + } + + @Override + public boolean isList(@Nonnull String path) { + return checkElement(path, JsonElement::isJsonArray); + } + + @Override + public boolean isDocument(@Nonnull String path) { + return checkElement(path, JsonElement::isJsonObject); + } + + @Override + public boolean isObject(@Nonnull String path) { + return checkElement(path, JsonElement::isJsonPrimitive); + } + + private boolean checkElement(@Nonnull String path, @Nonnull Function check) { + return getElement(path).map(check).orElse(false); + } + + @Override + public boolean contains(@Nonnull String path) { + return getElement(path).isPresent(); + } + + @Override + public int size() { + return GsonUtils.getSize(jsonObject); + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + setElement(path, value); + } + + @Nonnull + @Override + public Document set(@Nonnull Object object) { + JsonObject json = GSON.toJsonTree(object).getAsJsonObject(); + for (Entry entry : json.entrySet()) { + jsonObject.add(entry.getKey(), entry.getValue()); + } + return this; + } + + @Override + public void clear0() { + jsonObject = new JsonObject(); + } + + @Override + public void remove0(@Nonnull String path) { + setElement(path, null); + } + + @Nonnull + @Override + public Map values() { + return GsonUtils.convertJsonObjectToMap(jsonObject); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } + + @Nonnull + @Override + public Collection keys() { + Collection keys = new ArrayList<>(size()); + for (Entry entry : jsonObject.entrySet()) { + keys.add(entry.getKey()); + } + return keys; + } + + @Nonnull + private Optional getPrimitive(@Nonnull String path) { + return getElement(path) + .filter(JsonPrimitive.class::isInstance) + .map(JsonPrimitive.class::cast); + } + + @Nonnull + private Optional getElement(@Nonnull String path) { + return getElement(path, jsonObject); + } + + @Nonnull + private Optional getElement(@Nonnull String path, @Nonnull JsonObject object) { + + JsonElement fullPathElement = object.get(path); + if (fullPathElement != null) return Optional.of(fullPathElement); + + int index = path.indexOf('.'); + if (index == -1) return Optional.empty(); + + String child = path.substring(0, index); + String newPath = path.substring(index + 1); + + JsonElement element = object.get(child); + if (element == null || element.isJsonNull()) return Optional.empty(); + + return getElement(newPath, element.getAsJsonObject()); + + } + + private void setElement(@Nonnull String path, @Nullable Object value) { + + LinkedList paths = determinePath(path); + JsonObject object = jsonObject; + + for (int i = 0; i < paths.size() - 1; i++) { + + String current = paths.get(i); + JsonElement element = object.get(current); + if (element == null || element.isJsonNull()) { + if (value == null) return; // There's noting to remove + object.add(current, element = new JsonObject()); + } + + if (!element.isJsonObject()) + throw new IllegalArgumentException("Cannot replace '" + current + "' on '" + path + "'; It's not an object (" + element.getClass().getName() + ")"); + object = element.getAsJsonObject(); + + } + + String lastPath = paths.getLast(); + JsonElement jsonValue = + value instanceof JsonElement ? (JsonElement) value + : value == null ? JsonNull.INSTANCE + : value instanceof Number ? NUMBER.toJsonTree((Number) value) + : value instanceof Boolean ? TypeAdapters.BOOLEAN.toJsonTree((boolean) value) + : value instanceof Character ? TypeAdapters.CHARACTER.toJsonTree((char) value) + : GSON.toJsonTree(value); + object.add(lastPath, jsonValue); + + } + + @Nonnull + private LinkedList determinePath(@Nonnull String path) { + + LinkedList paths = new LinkedList<>(); + String pathCopy = path; + int index; + while ((index = pathCopy.indexOf('.')) != -1) { + String child = pathCopy.substring(0, index); + pathCopy = pathCopy.substring(index + 1); + paths.add(child); + } + paths.add(pathCopy); + + return paths; + + } + + @Nonnull + @Override + public String toJson() { + return GSON.toJson(jsonObject); + } + + @Nonnull + @Override + public String toPrettyJson() { + return GSON_PRETTY_PRINT.toJson(jsonObject); + } + + @Override + public String toString() { + return toJson(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + GsonDocument that = (GsonDocument) o; + return jsonObject.equals(that.jsonObject); + } + + @Override + public int hashCode() { + return jsonObject.hashCode(); + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + cleanup(); + (writePrettyJson ? GSON_PRETTY_PRINT : GSON).toJson(jsonObject, writer); + } + + @Nonnull + public JsonObject getJsonObject() { + return jsonObject; + } + + @Override + public boolean isReadonly() { + return false; + } + + public void cleanup() { + cleanup(jsonObject); + } + + public static void cleanup(@Nonnull JsonObject jsonObject) { + Iterator> iterator = jsonObject.entrySet().iterator(); + while (iterator.hasNext()) { + Entry entry = iterator.next(); + JsonElement value = entry.getValue(); + if (value.isJsonObject()) cleanup(value.getAsJsonObject()); // if (cleanupNulls && value.isJsonNull()) iterator.remove(); - if (cleanupEmptyObjects && value.isJsonObject() && GsonUtils.getSize(value.getAsJsonObject()) == 0) iterator.remove(); - if (cleanupEmptyArrays && value.isJsonArray() && value.getAsJsonArray().size() == 0) iterator.remove(); - } - } + if (cleanupEmptyObjects && value.isJsonObject() && GsonUtils.getSize(value.getAsJsonObject()) == 0) + iterator.remove(); + if (cleanupEmptyArrays && value.isJsonArray() && value.getAsJsonArray().size() == 0) iterator.remove(); + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java index b0b194d05..1a2e1d693 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java @@ -24,269 +24,271 @@ */ public class MapDocument extends AbstractDocument { - private final Map values; - - public MapDocument(@Nonnull Map values) { - Preconditions.checkNotNull(values, "Map cannot be null"); - this.values = values; - } - - public MapDocument(@Nonnull Map values, @Nonnull Document root, @Nullable Document parent) { - super(root, parent); - this.values = values; - } - - public MapDocument() { - this(new LinkedHashMap<>()); - } - - @Override - public boolean isReadonly() { - return false; - } - - @Nonnull - @Override - public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { - Object value = this.values.computeIfAbsent(path, key -> new HashMap<>()); - if (value instanceof Map) return new MapDocument((Map) value, root, parent); - if (value instanceof Document) return (Document) value; - if (value instanceof String) return new GsonDocument((String) value, root, parent); - throw new IllegalStateException("Expected java.util.Map, found " + values.getClass().getName()); - } - - @Nonnull - @Override - public List getDocumentList(@Nonnull String path) { - List documents = new ArrayList<>(); - Object value = values.get(path); - if (value instanceof List) { - List list = (List) value; - for (Object object : list) { - if (object instanceof Map) documents.add(new MapDocument((Map) object, root, parent)); - if (object instanceof Document) documents.add((Document) object); - if (object instanceof String) documents.add(new GsonDocument((String) object, root, this)); - } - } - return documents; - } - - @Override - public void set0(@Nonnull String path, @Nullable Object value) { - values.put(path, value); - } - - @Override - public void clear0() { - values.clear(); - } - - @Override - public void remove0(@Nonnull String path) { - values.remove(path); - } - - @Override - public void write(@Nonnull Writer writer) throws IOException { - new GsonDocument(values).write(writer); - } - - @Nonnull - @Override - public String toJson() { - return new GsonDocument(values).toJson(); - } - - @Nonnull - @Override - public String toPrettyJson() { - return new GsonDocument(values).toPrettyJson(); - } - - @Nullable - @Override - public Object getObject(@Nonnull String path) { - return values.get(path); - } - - @Override - public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { - return classOfT.cast(getObject(path)); - } - - @Override - public T toInstanceOf(@Nonnull Class classOfT) { - return copyJson().toInstanceOf(classOfT); - } - - @Nullable - @Override - public String getString(@Nonnull String path) { - Object value = values.get(path); - return value == null ? null : value.toString(); - } - - @Override - public long getLong(@Nonnull String path, long def) { - try { - return Long.parseLong(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public int getInt(@Nonnull String path, int def) { - try { - return Integer.parseInt(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public short getShort(@Nonnull String path, short def) { - try { - return Short.parseShort(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public byte getByte(@Nonnull String path, byte def) { - try { - return Byte.parseByte(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public float getFloat(@Nonnull String path, float def) { - try { - return Float.parseFloat(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public double getDouble(@Nonnull String path, double def) { - try { - return Double.parseDouble(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public boolean getBoolean(@Nonnull String path, boolean def) { - try { - if (!contains(path)) return def; - switch (getString(path).toLowerCase()) { - case "true": - case "1": - return true; - default: - return false; - } - } catch (Exception ex) { - return def; - } - } - - @Nonnull - @Override - public List getStringList(@Nonnull String path) { - Object object = getObject(path); - if (object == null) return Collections.emptyList(); - if (object instanceof Iterable) return StreamSupport.stream(((Iterable)object).spliterator(), false).map(String::valueOf).collect(Collectors.toList()); - if (object instanceof String) return GsonUtils.convertJsonArrayToStringList(GsonDocument.GSON.fromJson((String) object, JsonArray.class)); - throw new IllegalStateException("Cannot convert " + object.getClass() + " to a list"); - } - - @Nullable - @Override - public UUID getUUID(@Nonnull String path) { - try { - Object object = getObject(path); - if (object instanceof UUID) return (UUID) object; - return UUID.fromString(String.valueOf(object)); - } catch (Exception ex) { - return null; - } - } - - @Nullable - @Override - public Date getDate(@Nonnull String path) { - Object object = getObject(path); - if (object instanceof String) return PropertyHelper.parseDate((String) object); - if (object instanceof Date) return (Date) object; - return null; - } - - @Nullable - @Override - public OffsetDateTime getDateTime(@Nonnull String path) { - Object object = getObject(path); - if (object instanceof CharSequence) return OffsetDateTime.parse((CharSequence) object); - if (object instanceof OffsetDateTime) return (OffsetDateTime) object; - return null; - } - - @Nullable - @Override - public Color getColor(@Nonnull String path) { - Object object = getObject(path); - if (object instanceof Color) return (Color) object; - if (object instanceof String) return Color.decode((String) object); - return null; - } - - @Override - public boolean isList(@Nonnull String path) { - Object value = values.get(path); - return value instanceof Iterable || (value != null && value.getClass().isArray()); - } - - @Override - public boolean isObject(@Nonnull String path) { - return !isDocument(path) && !isList(path); - } - - @Override - public boolean isDocument(@Nonnull String path) { - Object value = values.get(path); - return value instanceof Map || value instanceof Document; - } - - @Override - public boolean contains(@Nonnull String path) { - return values.containsKey(path); - } - - @Override - public int size() { - return values.size(); - } - - @Nonnull - @Override - public Map values() { - return Collections.unmodifiableMap(values); - } - - @Nonnull - @Override - public Collection keys() { - return values.keySet(); - } - - @Override - public void forEach(@Nonnull BiConsumer action) { - values.forEach(action); - } + private final Map values; + + public MapDocument(@Nonnull Map values) { + Preconditions.checkNotNull(values, "Map cannot be null"); + this.values = values; + } + + public MapDocument(@Nonnull Map values, @Nonnull Document root, @Nullable Document parent) { + super(root, parent); + this.values = values; + } + + public MapDocument() { + this(new LinkedHashMap<>()); + } + + @Override + public boolean isReadonly() { + return false; + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + Object value = this.values.computeIfAbsent(path, key -> new HashMap<>()); + if (value instanceof Map) return new MapDocument((Map) value, root, parent); + if (value instanceof Document) return (Document) value; + if (value instanceof String) return new GsonDocument((String) value, root, parent); + throw new IllegalStateException("Expected java.util.Map, found " + values.getClass().getName()); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + List documents = new ArrayList<>(); + Object value = values.get(path); + if (value instanceof List) { + List list = (List) value; + for (Object object : list) { + if (object instanceof Map) documents.add(new MapDocument((Map) object, root, parent)); + if (object instanceof Document) documents.add((Document) object); + if (object instanceof String) documents.add(new GsonDocument((String) object, root, this)); + } + } + return documents; + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + values.put(path, value); + } + + @Override + public void clear0() { + values.clear(); + } + + @Override + public void remove0(@Nonnull String path) { + values.remove(path); + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + new GsonDocument(values).write(writer); + } + + @Nonnull + @Override + public String toJson() { + return new GsonDocument(values).toJson(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return new GsonDocument(values).toPrettyJson(); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return values.get(path); + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return classOfT.cast(getObject(path)); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + Object value = values.get(path); + return value == null ? null : value.toString(); + } + + @Override + public long getLong(@Nonnull String path, long def) { + try { + return Long.parseLong(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public int getInt(@Nonnull String path, int def) { + try { + return Integer.parseInt(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public short getShort(@Nonnull String path, short def) { + try { + return Short.parseShort(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + try { + return Byte.parseByte(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public float getFloat(@Nonnull String path, float def) { + try { + return Float.parseFloat(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path, double def) { + try { + return Double.parseDouble(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + try { + if (!contains(path)) return def; + switch (getString(path).toLowerCase()) { + case "true": + case "1": + return true; + default: + return false; + } + } catch (Exception ex) { + return def; + } + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + Object object = getObject(path); + if (object == null) return Collections.emptyList(); + if (object instanceof Iterable) + return StreamSupport.stream(((Iterable) object).spliterator(), false).map(String::valueOf).collect(Collectors.toList()); + if (object instanceof String) + return GsonUtils.convertJsonArrayToStringList(GsonDocument.GSON.fromJson((String) object, JsonArray.class)); + throw new IllegalStateException("Cannot convert " + object.getClass() + " to a list"); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + try { + Object object = getObject(path); + if (object instanceof UUID) return (UUID) object; + return UUID.fromString(String.valueOf(object)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + Object object = getObject(path); + if (object instanceof String) return PropertyHelper.parseDate((String) object); + if (object instanceof Date) return (Date) object; + return null; + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + Object object = getObject(path); + if (object instanceof CharSequence) return OffsetDateTime.parse((CharSequence) object); + if (object instanceof OffsetDateTime) return (OffsetDateTime) object; + return null; + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + Object object = getObject(path); + if (object instanceof Color) return (Color) object; + if (object instanceof String) return Color.decode((String) object); + return null; + } + + @Override + public boolean isList(@Nonnull String path) { + Object value = values.get(path); + return value instanceof Iterable || (value != null && value.getClass().isArray()); + } + + @Override + public boolean isObject(@Nonnull String path) { + return !isDocument(path) && !isList(path); + } + + @Override + public boolean isDocument(@Nonnull String path) { + Object value = values.get(path); + return value instanceof Map || value instanceof Document; + } + + @Override + public boolean contains(@Nonnull String path) { + return values.containsKey(path); + } + + @Override + public int size() { + return values.size(); + } + + @Nonnull + @Override + public Map values() { + return Collections.unmodifiableMap(values); + } + + @Nonnull + @Override + public Collection keys() { + return values.keySet(); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values.forEach(action); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java index 58fa7b100..67086b69e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java @@ -24,262 +24,262 @@ */ public class PropertiesDocument extends AbstractDocument { - protected final Properties properties; - - public PropertiesDocument(@Nullable Properties properties) { - this.properties = properties == null ? new Properties() : properties; - } - - public PropertiesDocument(@Nonnull File file) throws IOException { - properties = new Properties(); - properties.load(FileUtils.newBufferedReader(file)); - } - - @Nonnull - @Override - public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { - throw new UnsupportedOperationException("PropertiesDocument.getDocument(String)"); - } - - @Nonnull - @Override - public List getDocumentList(@Nonnull String path) { - throw new UnsupportedOperationException("PropertiesDocument.getDocumentList(String)"); - } - - @Nonnull - @Override - public List getStringList(@Nonnull String path) { - throw new UnsupportedOperationException("PropertiesDocument.getList(String)"); - } - - @Nullable - @Override - public Object getObject(@Nonnull String path) { - return properties.get(path); - } - - @Override - public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { - return classOfT.cast(getObject(path)); - } - - @Override - public T toInstanceOf(@Nonnull Class classOfT) { - return copyJson().toInstanceOf(classOfT); - } - - @Nullable - @Override - public String getString(@Nonnull String path) { - return properties.getProperty(path); - } - - @Override - public long getLong(@Nonnull String path, long def) { - try { - return Long.parseLong(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public int getInt(@Nonnull String path, int def) { - try { - return Integer.parseInt(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public short getShort(@Nonnull String path, short def) { - try { - return Short.parseShort(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public byte getByte(@Nonnull String path, byte def) { - try { - return Byte.parseByte(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public float getFloat(@Nonnull String path, float def) { - try { - return Float.parseFloat(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public double getDouble(@Nonnull String path, double def) { - try { - return Double.parseDouble(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public boolean getBoolean(@Nonnull String path, boolean def) { - if (!contains(path)) return def; - return Boolean.parseBoolean(getString(path)); - } - - @Nullable - @Override - public UUID getUUID(@Nonnull String path) { - try { - return UUID.fromString(getString(path)); - } catch (Exception ex) { - return null; - } - } - - @Nullable - @Override - public Date getDate(@Nonnull String path) { - return PropertyHelper.parseDate(getString(path)); - } - - @Nullable - @Override - public OffsetDateTime getDateTime(@Nonnull String path) { - try { - return OffsetDateTime.parse(getString(path)); - } catch (Exception ex) { - return null; - } - } - - @Nullable - @Override - public Color getColor(@Nonnull String path) { - String string = getString(path); - return string == null ? null : Color.decode(string); - } - - @Nullable - @Override - public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { - try { - String name = getString(path); - if (name == null) return null; - return Enum.valueOf(classOfEnum, name); - } catch (Throwable ex) { - return null; - } - } - - @Override - public boolean contains(@Nonnull String path) { - return properties.containsKey(path); - } - - @Override - public boolean isList(@Nonnull String path) { - return false; - } - - @Override - public boolean isObject(@Nonnull String path) { - return true; - } - - @Override - public boolean isDocument(@Nonnull String path) { - return false; - } - - @Override - public int size() { - return properties.size(); - } - - @Nonnull - @Override - public Map values() { - Map map = new LinkedHashMap<>(); - for (Entry entry : properties.entrySet()) { - map.put((String) entry.getKey(), entry.getValue()); - } - return map; - } - - @Nonnull - @Override - public Collection keys() { - return properties.stringPropertyNames(); - } - - @Override - public void forEach(@Nonnull BiConsumer action) { - values().forEach(action); - } - - @Override - public void set0(@Nonnull String path, @Nullable Object value) { - final String asString; - if (value instanceof Color) { - asString = Colors.asHex((Color) value); - } else { - asString = String.valueOf(value); - } - - properties.setProperty(path, asString); - } - - @Override - public void clear0() { - properties.clear(); - } - - @Override - public void remove0(@Nonnull String path) { - properties.remove(path); - } - - @Override - public void write(@Nonnull Writer writer) throws IOException { - properties.store(writer, null); - } - - @Nonnull - public Properties getProperties() { - return properties; - } - - @Nonnull - @Override - public String toJson() { - return copyJson().toJson(); - } - - @Nonnull - @Override - public String toPrettyJson() { - return copyJson().toPrettyJson(); - } - - @Nonnull - @Override - public Document copyJson() { - Map map = new HashMap<>(); - PropertiesUtils.setProperties(properties, map); - return new GsonDocument(map); - } - - @Override - public boolean isReadonly() { - return false; - } + protected final Properties properties; + + public PropertiesDocument(@Nullable Properties properties) { + this.properties = properties == null ? new Properties() : properties; + } + + public PropertiesDocument(@Nonnull File file) throws IOException { + properties = new Properties(); + properties.load(FileUtils.newBufferedReader(file)); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + throw new UnsupportedOperationException("PropertiesDocument.getDocument(String)"); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + throw new UnsupportedOperationException("PropertiesDocument.getDocumentList(String)"); + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + throw new UnsupportedOperationException("PropertiesDocument.getList(String)"); + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return properties.get(path); + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return classOfT.cast(getObject(path)); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + return properties.getProperty(path); + } + + @Override + public long getLong(@Nonnull String path, long def) { + try { + return Long.parseLong(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public int getInt(@Nonnull String path, int def) { + try { + return Integer.parseInt(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public short getShort(@Nonnull String path, short def) { + try { + return Short.parseShort(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + try { + return Byte.parseByte(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public float getFloat(@Nonnull String path, float def) { + try { + return Float.parseFloat(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path, double def) { + try { + return Double.parseDouble(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + if (!contains(path)) return def; + return Boolean.parseBoolean(getString(path)); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + try { + return UUID.fromString(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + return PropertyHelper.parseDate(getString(path)); + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + try { + return OffsetDateTime.parse(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + String string = getString(path); + return string == null ? null : Color.decode(string); + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + try { + String name = getString(path); + if (name == null) return null; + return Enum.valueOf(classOfEnum, name); + } catch (Throwable ex) { + return null; + } + } + + @Override + public boolean contains(@Nonnull String path) { + return properties.containsKey(path); + } + + @Override + public boolean isList(@Nonnull String path) { + return false; + } + + @Override + public boolean isObject(@Nonnull String path) { + return true; + } + + @Override + public boolean isDocument(@Nonnull String path) { + return false; + } + + @Override + public int size() { + return properties.size(); + } + + @Nonnull + @Override + public Map values() { + Map map = new LinkedHashMap<>(); + for (Entry entry : properties.entrySet()) { + map.put((String) entry.getKey(), entry.getValue()); + } + return map; + } + + @Nonnull + @Override + public Collection keys() { + return properties.stringPropertyNames(); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + final String asString; + if (value instanceof Color) { + asString = Colors.asHex((Color) value); + } else { + asString = String.valueOf(value); + } + + properties.setProperty(path, asString); + } + + @Override + public void clear0() { + properties.clear(); + } + + @Override + public void remove0(@Nonnull String path) { + properties.remove(path); + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + properties.store(writer, null); + } + + @Nonnull + public Properties getProperties() { + return properties; + } + + @Nonnull + @Override + public String toJson() { + return copyJson().toJson(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return copyJson().toPrettyJson(); + } + + @Nonnull + @Override + public Document copyJson() { + Map map = new HashMap<>(); + PropertiesUtils.setProperties(properties, map); + return new GsonDocument(map); + } + + @Override + public boolean isReadonly() { + return false; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java index 03bdf14d3..f7ec8d1cf 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java @@ -25,331 +25,331 @@ public class YamlDocument extends AbstractDocument { - protected final ConfigurationSection config; - - public YamlDocument() { - this.config = new YamlConfiguration(); - } - - public YamlDocument(@Nonnull ConfigurationSection config) { - this.config = config; - } - - public YamlDocument(@Nonnull ConfigurationSection config, @Nonnull Document root, @Nullable Document parent) { - super(root, parent); - this.config = config; - } - - public YamlDocument(@Nonnull File file) { - this(YamlConfiguration.loadConfiguration(file)); - } - - @Nullable - @Override - public String getString(@Nonnull String path) { - return config.getString(path); - } - - @Nonnull - @Override - public String getString(@Nonnull String path, @Nonnull String def) { - String string = config.getString(path, def); - return string == null ? def : string; - } - - @Nullable - @Override - public Object getObject(@Nonnull String path) { - return config.get(path); - } - - @Nonnull - @Override - public Object getObject(@Nonnull String path, @Nonnull Object def) { - Object value = config.get(path, def); - return value == null ? def : value; - } - - @Override - public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { - return copyJson().getInstance(path, classOfT); - } - - @Override - public T toInstanceOf(@Nonnull Class classOfT) { - return copyJson().toInstanceOf(classOfT); - } - - @Nonnull - @Override - public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { - ConfigurationSection section = config.getConfigurationSection(path); - if (section == null) section = config.createSection(path); - return new YamlDocument(section, root, parent); - } - - @Nonnull - @Override - public List getDocumentList(@Nonnull String path) { - List> maps = config.getMapList(path); - List documents = new ArrayList<>(maps.size()); - for (Map map : maps) { - documents.add(new MapDocument((Map) map, root, this)); - } - return documents; - } - - @Override - public long getLong(@Nonnull String path) { - return config.getLong(path); - } - - @Override - public long getLong(@Nonnull String path, long def) { - return config.getLong(path, def); - } - - @Override - public int getInt(@Nonnull String path) { - return config.getInt(path); - } - - @Override - public int getInt(@Nonnull String path, int def) { - return config.getInt(path, def); - } - - @Override - public short getShort(@Nonnull String path) { - return (short) config.getInt(path); - } - - @Override - public short getShort(@Nonnull String path, short def) { - return (short) config.getInt(path, def); - } - - @Override - public byte getByte(@Nonnull String path) { - return (byte) config.getInt(path); - } - - @Override - public byte getByte(@Nonnull String path, byte def) { - return (byte) config.getInt(path, def); - } - - @Override - public char getChar(@Nonnull String path) { - return getChar(path, (char) 0); - } - - @Override - public char getChar(@Nonnull String path, char def) { - try { - return getString(path).charAt(0); - } catch (NullPointerException | StringIndexOutOfBoundsException ex) { - return def; - } - } - - @Override - public double getDouble(@Nonnull String path) { - return config.getDouble(path); - } - - @Override - public double getDouble(@Nonnull String path, double def) { - return config.getDouble(path, def); - } - - @Override - public float getFloat(@Nonnull String path) { - return (float) config.getDouble(path); - } - - @Override - public float getFloat(@Nonnull String path, float def) { - return (float) config.getDouble(path, def); - } - - @Override - public boolean getBoolean(@Nonnull String path) { - return config.getBoolean(path); - } - - @Override - public boolean getBoolean(@Nonnull String path, boolean def) { - return config.getBoolean(path, def); - } - - @Nonnull - @Override - public List getStringList(@Nonnull String path) { - return config.getStringList(path); - } - - @Nullable - @Override - public UUID getUUID(@Nonnull String path) { - try { - return UUID.fromString(getString(path)); - } catch (Exception ex) { - return null; - } - } - - @Nullable - @Override - public Date getDate(@Nonnull String path) { - try { - return DateFormat.getDateTimeInstance().parse(path); - } catch (Exception ex) { - return null; - } - } - - @Nullable - @Override - public OffsetDateTime getDateTime(@Nonnull String path) { - try { - return OffsetDateTime.parse(getString(path)); - } catch (Exception ex) { - return null; - } - } - - @Nullable - @Override - public Color getColor(@Nonnull String path) { - try { - return Color.decode(getString(path)); - } catch (Exception ex) { - return null; - } - } - - @Nullable - @Override - public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { - try { - String name = getString(path); - if (name == null) return null; - return Enum.valueOf(classOfEnum, name); - } catch (Throwable ex) { - return null; - } - } - - @Override - public boolean isList(@Nonnull String path) { - return config.isList(path); - } - - @Override - public boolean isObject(@Nonnull String path) { - return !isDocument(path) && !isList(path); - } - - @Override - public boolean isDocument(@Nonnull String path) { - return config.get(path) instanceof ConfigurationSection; - } - - @Override - public boolean contains(@Nonnull String path) { - return config.contains(path, true); - } - - @Override - public int size() { - return config.getValues(false).size(); - } - - @Override - public void set0(@Nonnull String path, @Nullable Object value) { - if (value instanceof Enum) { - Enum enun = (Enum) value; - value = enun.name(); - } - config.set(path, value); - } - - @Override - public void remove0(@Nonnull String path) { - config.set(path, null); - } - - @Override - public void clear0() { - for (String key : config.getKeys(true)) { - config.set(key, null); - } - } - - @Nonnull - @Override - public Map values() { - return config.getValues(true); - } - - @Nonnull - @Override - public Collection keys() { - return config.getKeys(false); - } - - @Override - public void forEach(@Nonnull BiConsumer action) { - values().forEach(action); - } - - @Override - public String toString() { - - DumperOptions yamlOptions = new DumperOptions(); - LoaderOptions loaderOptions = new LoaderOptions(); - Representer yamlRepresenter = new YamlRepresenter(); - Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions, loaderOptions); - - yamlOptions.setIndent(2); - yamlOptions.setDefaultFlowStyle(FlowStyle.BLOCK); - yamlRepresenter.setDefaultFlowStyle(FlowStyle.BLOCK); - String dump = yaml.dump(config.getValues(false)); - if (dump.equals("{}\n")) { - dump = ""; - } - - return dump; - - } - - @Override - public void write(@Nonnull Writer writer) throws IOException { - writer.write(toString()); - } - - @Nonnull - @Override - public Document copyJson() { - return new GsonDocument(values()); - } - - @Nonnull - @Override - public String toJson() { - return copyJson().toJson(); - } - - @Nonnull - @Override - public String toPrettyJson() { - return copyJson().toPrettyJson(); - } - - @Override - public boolean isReadonly() { - return false; - } + protected final ConfigurationSection config; + + public YamlDocument() { + this.config = new YamlConfiguration(); + } + + public YamlDocument(@Nonnull ConfigurationSection config) { + this.config = config; + } + + public YamlDocument(@Nonnull ConfigurationSection config, @Nonnull Document root, @Nullable Document parent) { + super(root, parent); + this.config = config; + } + + public YamlDocument(@Nonnull File file) { + this(YamlConfiguration.loadConfiguration(file)); + } + + @Nullable + @Override + public String getString(@Nonnull String path) { + return config.getString(path); + } + + @Nonnull + @Override + public String getString(@Nonnull String path, @Nonnull String def) { + String string = config.getString(path, def); + return string == null ? def : string; + } + + @Nullable + @Override + public Object getObject(@Nonnull String path) { + return config.get(path); + } + + @Nonnull + @Override + public Object getObject(@Nonnull String path, @Nonnull Object def) { + Object value = config.get(path, def); + return value == null ? def : value; + } + + @Override + public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return copyJson().getInstance(path, classOfT); + } + + @Override + public T toInstanceOf(@Nonnull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + ConfigurationSection section = config.getConfigurationSection(path); + if (section == null) section = config.createSection(path); + return new YamlDocument(section, root, parent); + } + + @Nonnull + @Override + public List getDocumentList(@Nonnull String path) { + List> maps = config.getMapList(path); + List documents = new ArrayList<>(maps.size()); + for (Map map : maps) { + documents.add(new MapDocument((Map) map, root, this)); + } + return documents; + } + + @Override + public long getLong(@Nonnull String path) { + return config.getLong(path); + } + + @Override + public long getLong(@Nonnull String path, long def) { + return config.getLong(path, def); + } + + @Override + public int getInt(@Nonnull String path) { + return config.getInt(path); + } + + @Override + public int getInt(@Nonnull String path, int def) { + return config.getInt(path, def); + } + + @Override + public short getShort(@Nonnull String path) { + return (short) config.getInt(path); + } + + @Override + public short getShort(@Nonnull String path, short def) { + return (short) config.getInt(path, def); + } + + @Override + public byte getByte(@Nonnull String path) { + return (byte) config.getInt(path); + } + + @Override + public byte getByte(@Nonnull String path, byte def) { + return (byte) config.getInt(path, def); + } + + @Override + public char getChar(@Nonnull String path) { + return getChar(path, (char) 0); + } + + @Override + public char getChar(@Nonnull String path, char def) { + try { + return getString(path).charAt(0); + } catch (NullPointerException | StringIndexOutOfBoundsException ex) { + return def; + } + } + + @Override + public double getDouble(@Nonnull String path) { + return config.getDouble(path); + } + + @Override + public double getDouble(@Nonnull String path, double def) { + return config.getDouble(path, def); + } + + @Override + public float getFloat(@Nonnull String path) { + return (float) config.getDouble(path); + } + + @Override + public float getFloat(@Nonnull String path, float def) { + return (float) config.getDouble(path, def); + } + + @Override + public boolean getBoolean(@Nonnull String path) { + return config.getBoolean(path); + } + + @Override + public boolean getBoolean(@Nonnull String path, boolean def) { + return config.getBoolean(path, def); + } + + @Nonnull + @Override + public List getStringList(@Nonnull String path) { + return config.getStringList(path); + } + + @Nullable + @Override + public UUID getUUID(@Nonnull String path) { + try { + return UUID.fromString(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Date getDate(@Nonnull String path) { + try { + return DateFormat.getDateTimeInstance().parse(path); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@Nonnull String path) { + try { + return OffsetDateTime.parse(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public Color getColor(@Nonnull String path) { + try { + return Color.decode(getString(path)); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @Override + public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + try { + String name = getString(path); + if (name == null) return null; + return Enum.valueOf(classOfEnum, name); + } catch (Throwable ex) { + return null; + } + } + + @Override + public boolean isList(@Nonnull String path) { + return config.isList(path); + } + + @Override + public boolean isObject(@Nonnull String path) { + return !isDocument(path) && !isList(path); + } + + @Override + public boolean isDocument(@Nonnull String path) { + return config.get(path) instanceof ConfigurationSection; + } + + @Override + public boolean contains(@Nonnull String path) { + return config.contains(path, true); + } + + @Override + public int size() { + return config.getValues(false).size(); + } + + @Override + public void set0(@Nonnull String path, @Nullable Object value) { + if (value instanceof Enum) { + Enum enun = (Enum) value; + value = enun.name(); + } + config.set(path, value); + } + + @Override + public void remove0(@Nonnull String path) { + config.set(path, null); + } + + @Override + public void clear0() { + for (String key : config.getKeys(true)) { + config.set(key, null); + } + } + + @Nonnull + @Override + public Map values() { + return config.getValues(true); + } + + @Nonnull + @Override + public Collection keys() { + return config.getKeys(false); + } + + @Override + public void forEach(@Nonnull BiConsumer action) { + values().forEach(action); + } + + @Override + public String toString() { + + DumperOptions yamlOptions = new DumperOptions(); + LoaderOptions loaderOptions = new LoaderOptions(); + Representer yamlRepresenter = new YamlRepresenter(); + Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions, loaderOptions); + + yamlOptions.setIndent(2); + yamlOptions.setDefaultFlowStyle(FlowStyle.BLOCK); + yamlRepresenter.setDefaultFlowStyle(FlowStyle.BLOCK); + String dump = yaml.dump(config.getValues(false)); + if (dump.equals("{}\n")) { + dump = ""; + } + + return dump; + + } + + @Override + public void write(@Nonnull Writer writer) throws IOException { + writer.write(toString()); + } + + @Nonnull + @Override + public Document copyJson() { + return new GsonDocument(values()); + } + + @Nonnull + @Override + public String toJson() { + return copyJson().toJson(); + } + + @Nonnull + @Override + public String toPrettyJson() { + return copyJson().toPrettyJson(); + } + + @Override + public boolean isReadonly() { + return false; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java index ed36fd787..f4252eb6f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java @@ -16,45 +16,45 @@ public class BukkitReflectionSerializableTypeAdapter implements GsonTypeAdapter { - public static final String ALTERNATE_KEY = "classOfType", KEY = "=="; + public static final String ALTERNATE_KEY = "classOfType", KEY = "=="; - @Override - public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Object object) throws IOException { + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Object object) throws IOException { - Map map = BukkitReflectionSerializationUtils.serializeObject(object); - if (map == null) return; + Map map = BukkitReflectionSerializationUtils.serializeObject(object); + if (map == null) return; - JsonObject json = new JsonObject(); - json.addProperty(KEY, BukkitReflectionSerializationUtils.getSerializationName(object.getClass())); - GsonUtils.setDocumentProperties(gson, json, map); - TypeAdapters.JSON_ELEMENT.write(writer, json); + JsonObject json = new JsonObject(); + json.addProperty(KEY, BukkitReflectionSerializationUtils.getSerializationName(object.getClass())); + GsonUtils.setDocumentProperties(gson, json, map); + TypeAdapters.JSON_ELEMENT.write(writer, json); - } + } - @Override - public Object read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + @Override + public Object read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { - JsonElement element = TypeAdapters.JSON_ELEMENT.read(reader); - if (element == null || !element.isJsonObject()) return null; + JsonElement element = TypeAdapters.JSON_ELEMENT.read(reader); + if (element == null || !element.isJsonObject()) return null; - JsonObject json = element.getAsJsonObject(); - String classOfType = Optional.ofNullable(findClassContainer(json)).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsString).orElse(null); + JsonObject json = element.getAsJsonObject(); + String classOfType = Optional.ofNullable(findClassContainer(json)).filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsString).orElse(null); - Class clazz = null; - try { - clazz = Class.forName(classOfType); - } catch (ClassNotFoundException | NullPointerException ex) { - } + Class clazz = null; + try { + clazz = Class.forName(classOfType); + } catch (ClassNotFoundException | NullPointerException ex) { + } - Map map = GsonUtils.convertJsonObjectToMap(json); - return BukkitReflectionSerializationUtils.deserializeObject(map, clazz); + Map map = GsonUtils.convertJsonObjectToMap(json); + return BukkitReflectionSerializationUtils.deserializeObject(map, clazz); - } + } - private JsonElement findClassContainer(@Nonnull JsonObject json) { - if (json.has(ALTERNATE_KEY)) - return json.get(ALTERNATE_KEY); - return json.get(KEY); - } + private JsonElement findClassContainer(@Nonnull JsonObject json) { + if (json.has(ALTERNATE_KEY)) + return json.get(ALTERNATE_KEY); + return json.get(KEY); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java index 3b85bbd16..01c511c19 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java @@ -10,23 +10,23 @@ public class ClassTypeAdapter implements GsonTypeAdapter> { - @Override - public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Class object) throws IOException { - TypeAdapters.STRING.write(writer, object.getName()); - } + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Class object) throws IOException { + TypeAdapters.STRING.write(writer, object.getName()); + } - @Override - public Class read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { - try { + @Override + public Class read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + try { - String value = reader.nextString(); - if (value == null) return null; + String value = reader.nextString(); + if (value == null) return null; - return Class.forName(value); + return Class.forName(value); - } catch (ClassNotFoundException ex) { - return null; - } - } + } catch (ClassNotFoundException ex) { + return null; + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java index 6a172a83f..9dc2bb966 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java @@ -12,16 +12,16 @@ public class ColorTypeAdapter implements GsonTypeAdapter { - @Override - public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Color color) throws IOException { - TypeAdapters.STRING.write(writer, Colors.asHex(color)); - } + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Color color) throws IOException { + TypeAdapters.STRING.write(writer, Colors.asHex(color)); + } - @Override - public Color read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { - String value = TypeAdapters.STRING.read(reader); - if (value == null) return null; - return Color.decode(value); - } + @Override + public Color read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + String value = TypeAdapters.STRING.read(reader); + if (value == null) return null; + return Color.decode(value); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java index fffa43204..ab4a111a6 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java @@ -13,34 +13,34 @@ public class DocumentTypeAdapter implements GsonTypeAdapter { - @Override - public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Document document) throws IOException { - if (document instanceof GsonDocument) { - GsonDocument gsonDocument = (GsonDocument) document; - TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); - return; - } - - Document copiedDocument = document.copyJson(); - if (copiedDocument instanceof GsonDocument) { - GsonDocument gsonDocument = (GsonDocument) copiedDocument; - TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); - return; - } - - GsonDocument gsonDocument = new GsonDocument(document.values()); - TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); - - } - - @Override - public Document read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { - JsonElement jsonElement = TypeAdapters.JSON_ELEMENT.read(reader); - if (jsonElement != null && jsonElement.isJsonObject()) { - return new GsonDocument(jsonElement.getAsJsonObject()); - } else { - return null; - } - } + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Document document) throws IOException { + if (document instanceof GsonDocument) { + GsonDocument gsonDocument = (GsonDocument) document; + TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); + return; + } + + Document copiedDocument = document.copyJson(); + if (copiedDocument instanceof GsonDocument) { + GsonDocument gsonDocument = (GsonDocument) copiedDocument; + TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); + return; + } + + GsonDocument gsonDocument = new GsonDocument(document.values()); + TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); + + } + + @Override + public Document read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + JsonElement jsonElement = TypeAdapters.JSON_ELEMENT.read(reader); + if (jsonElement != null && jsonElement.isJsonObject()) { + return new GsonDocument(jsonElement.getAsJsonObject()); + } else { + return null; + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java index e8f72f78b..147b299f9 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java @@ -14,49 +14,49 @@ @SuppressWarnings("unchecked") public interface GsonTypeAdapter { - void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull T object) throws IOException; - - T read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException; - - default TypeAdapter toTypeAdapter(@Nonnull Gson gson) { - return new TypeAdapter() { - @Override - public void write(JsonWriter writer, T object) throws IOException { - if (object == null) { - writer.nullValue(); - return; - } - GsonTypeAdapter.this.write(gson, writer, object); - } - - @Override - public T read(JsonReader reader) throws IOException { - return GsonTypeAdapter.this.read(gson, reader); - } - }; - } - - @Nonnull - static TypeAdapterFactory newTypeHierarchyFactory(@Nonnull Class clazz, @Nonnull GsonTypeAdapter adapter) { - return new TypeAdapterFactory() { - @Override - public TypeAdapter create(Gson gson, TypeToken token) { - Class requestedType = token.getRawType(); - if (!clazz.isAssignableFrom(requestedType)) return null; - - return (TypeAdapter) adapter.toTypeAdapter(gson); - } - }; - } - - @Nonnull - static TypeAdapterFactory newPredictableFactory(@Nonnull Predicate> predicate, @Nonnull GsonTypeAdapter adapter) { - return new TypeAdapterFactory() { - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - return predicate.test(type.getRawType()) ? (TypeAdapter) adapter.toTypeAdapter(gson) : null; - } - }; - } + void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull T object) throws IOException; + + T read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException; + + default TypeAdapter toTypeAdapter(@Nonnull Gson gson) { + return new TypeAdapter() { + @Override + public void write(JsonWriter writer, T object) throws IOException { + if (object == null) { + writer.nullValue(); + return; + } + GsonTypeAdapter.this.write(gson, writer, object); + } + + @Override + public T read(JsonReader reader) throws IOException { + return GsonTypeAdapter.this.read(gson, reader); + } + }; + } + + @Nonnull + static TypeAdapterFactory newTypeHierarchyFactory(@Nonnull Class clazz, @Nonnull GsonTypeAdapter adapter) { + return new TypeAdapterFactory() { + @Override + public TypeAdapter create(Gson gson, TypeToken token) { + Class requestedType = token.getRawType(); + if (!clazz.isAssignableFrom(requestedType)) return null; + + return (TypeAdapter) adapter.toTypeAdapter(gson); + } + }; + } + + @Nonnull + static TypeAdapterFactory newPredictableFactory(@Nonnull Predicate> predicate, @Nonnull GsonTypeAdapter adapter) { + return new TypeAdapterFactory() { + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + return predicate.test(type.getRawType()) ? (TypeAdapter) adapter.toTypeAdapter(gson) : null; + } + }; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java index f8f9c2a91..0b3deebc2 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java @@ -14,24 +14,28 @@ public class PairTypeAdapter implements GsonTypeAdapter { - @Override - public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Pair object) throws IOException { - Object[] values = object.values(); - JsonArray array = new JsonArray(values.length); // TODO fix(deps) version ambiguity - for (Object value : values) { - array.add(gson.toJsonTree(value)); - } - } + @Override + public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Pair object) throws IOException { + Object[] values = object.values(); + JsonArray array = new JsonArray(values.length); // TODO fix(deps) version ambiguity + for (Object value : values) { + array.add(gson.toJsonTree(value)); + } + } - @Override - public Pair read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { - JsonArray array = gson.fromJson(reader, JsonArray.class); - int size = array.size(); - switch (size) { - case 2: return Tuple.of(array.get(0), array.get(1)); - case 3: return Triple.of(array.get(0), array.get(1), array.get(2)); - case 4: return Quadro.of(array.get(0), array.get(1), array.get(2), array.get(3)); - default:throw new IllegalStateException("No Pair known for amount of " + size); - } - } + @Override + public Pair read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + JsonArray array = gson.fromJson(reader, JsonArray.class); + int size = array.size(); + switch (size) { + case 2: + return Tuple.of(array.get(0), array.get(1)); + case 3: + return Triple.of(array.get(0), array.get(1), array.get(2)); + case 4: + return Quadro.of(array.get(0), array.get(1), array.get(2), array.get(3)); + default: + throw new IllegalStateException("No Pair known for amount of " + size); + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java index 4267a567c..11dd71c28 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java @@ -7,20 +7,20 @@ public final class ReadOnlyDocumentWrapper implements WrappedDocument { - private final Document document; + private final Document document; - public ReadOnlyDocumentWrapper(@Nonnull Document document) { - this.document = document; - } + public ReadOnlyDocumentWrapper(@Nonnull Document document) { + this.document = document; + } - @Override - public Document getWrappedDocument() { - return document; - } + @Override + public Document getWrappedDocument() { + return document; + } - @Override - public boolean isReadonly() { - return true; - } + @Override + public boolean isReadonly() { + return true; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java index 4cbb0a0f9..976232f9b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java @@ -10,53 +10,53 @@ public class FileDocumentWrapper implements WrappedDocument, FileDocument { - protected final Document document; - protected final File file; - - public FileDocumentWrapper(@Nonnull File file, @Nonnull Document document) { - this.file = file; - this.document = document; - } - - @Override - public Document getWrappedDocument() { - return document; - } - - @Nonnull - @Override - public File getFile() { - return file; - } - - @Nonnull - @Override - public Path getPath() { - return file.toPath(); - } - - @Nonnull - @Override - public FileDocument set(@Nonnull String path, @Nullable Object value) { - return WrappedDocument.super.set(path, value); - } - - @Nonnull - @Override - public FileDocument set(@Nonnull Object value) { - return WrappedDocument.super.set(value); - } - - @Nonnull - @Override - public FileDocument clear() { - return WrappedDocument.super.clear(); - } - - @Nonnull - @Override - public FileDocument remove(@Nonnull String path) { - return WrappedDocument.super.remove(path); - } + protected final Document document; + protected final File file; + + public FileDocumentWrapper(@Nonnull File file, @Nonnull Document document) { + this.file = file; + this.document = document; + } + + @Override + public Document getWrappedDocument() { + return document; + } + + @Nonnull + @Override + public File getFile() { + return file; + } + + @Nonnull + @Override + public Path getPath() { + return file.toPath(); + } + + @Nonnull + @Override + public FileDocument set(@Nonnull String path, @Nullable Object value) { + return WrappedDocument.super.set(path, value); + } + + @Nonnull + @Override + public FileDocument set(@Nonnull Object value) { + return WrappedDocument.super.set(value); + } + + @Nonnull + @Override + public FileDocument clear() { + return WrappedDocument.super.clear(); + } + + @Nonnull + @Override + public FileDocument remove(@Nonnull String path) { + return WrappedDocument.super.remove(path); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java index 989c393e4..03ab050c5 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java @@ -21,490 +21,490 @@ public interface WrappedDocument extends Document { - Document getWrappedDocument(); - - @Override - default boolean isReadonly() { - return getWrappedDocument().isReadonly(); - } - - @Nonnull - @Override - default Document getDocument(@Nonnull String path) { - return getWrappedDocument().getDocument(path); - } - - @Nonnull - @Override - default List getDocumentList(@Nonnull String path) { - return getWrappedDocument().getDocumentList(path); - } - - @Nonnull - @Override - default List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { - return getWrappedDocument().getSerializableList(path, classOfT); - } - - @Nonnull - @Override - default D set(@Nonnull String path, @Nullable Object value) { - getWrappedDocument().set(path, value); - return self(); - } - - @Nonnull - @Override - default D set(@Nonnull Object value) { - getWrappedDocument().set(value); - return self(); - } - - @Nonnull - @Override - default D clear() { - getWrappedDocument().clear(); - return self(); - } - - @Nonnull - @Override - default D remove(@Nonnull String path) { - getWrappedDocument().remove(path); - return self(); - } - - @Override - default void write(@Nonnull Writer writer) throws IOException { - getWrappedDocument().write(writer); - } - - @Override - default void saveToFile(@Nonnull File file) throws IOException { - getWrappedDocument().saveToFile(file); - } - - @Nonnull - @Override - default String toJson() { - return getWrappedDocument().toJson(); - } - - @Nonnull - @Override - default String toPrettyJson() { - return getWrappedDocument().toPrettyJson(); - } - - @Override - default T getInstance(@Nonnull String path, @Nonnull Class classOfT) { - return getWrappedDocument().getInstance(path, classOfT); - } - - @Override - default T toInstanceOf(@Nonnull Class classOfT) { - return getWrappedDocument().toInstanceOf(classOfT); - } - - @Nullable - @Override - default Object getObject(@Nonnull String path) { - return getWrappedDocument().getObject(path); - } - - @Nonnull - @Override - default Object getObject(@Nonnull String path, @Nonnull Object def) { - return getWrappedDocument().getObject(path, def); - } - - @Nonnull - @Override - default Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { - return getWrappedDocument().getOptional(key, extractor); - } - - @Nullable - @Override - default String getString(@Nonnull String path) { - return getWrappedDocument().getString(path); - } - - @Nonnull - @Override - default String getString(@Nonnull String path, @Nonnull String def) { - return getWrappedDocument().getString(path, def); - } - - @Override - default char getChar(@Nonnull String path) { - return getWrappedDocument().getChar(path); - } - - @Override - default char getChar(@Nonnull String path, char def) { - return getWrappedDocument().getChar(path, def); - } - - @Override - default long getLong(@Nonnull String path) { - return getWrappedDocument().getLong(path); - } - - @Override - default long getLong(@Nonnull String path, long def) { - return getWrappedDocument().getLong(path, def); - } - - @Override - default int getInt(@Nonnull String path) { - return getWrappedDocument().getInt(path); - } - - @Override - default int getInt(@Nonnull String path, int def) { - return getWrappedDocument().getInt(path, def); - } - - @Override - default short getShort(@Nonnull String path) { - return getWrappedDocument().getShort(path); - } - - @Override - default short getShort(@Nonnull String path, short def) { - return getWrappedDocument().getShort(path, def); - } - - @Override - default byte getByte(@Nonnull String path) { - return getWrappedDocument().getByte(path); - } - - @Override - default byte getByte(@Nonnull String path, byte def) { - return getWrappedDocument().getByte(path, def); - } - - @Override - default float getFloat(@Nonnull String path) { - return getWrappedDocument().getFloat(path); - } - - @Override - default float getFloat(@Nonnull String path, float def) { - return getWrappedDocument().getFloat(path, def); - } - - @Override - default double getDouble(@Nonnull String path) { - return getWrappedDocument().getDouble(path); - } - - @Override - default double getDouble(@Nonnull String path, double def) { - return getWrappedDocument().getDouble(path, def); - } - - @Override - default boolean getBoolean(@Nonnull String path) { - return getWrappedDocument().getBoolean(path); - } - - @Override - default boolean getBoolean(@Nonnull String path, boolean def) { - return getWrappedDocument().getBoolean(path, def); - } - - @Nonnull - @Override - default List getStringList(@Nonnull String path) { - return getWrappedDocument().getStringList(path); - } - - @Nonnull - @Override - default String[] getStringArray(@Nonnull String path) { - return getWrappedDocument().getStringArray(path); - } - - @Nonnull - @Override - default List mapList(@Nonnull String path, @Nonnull Function mapper) { - return getWrappedDocument().mapList(path, mapper); - } - - @Nonnull - @Override - default > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { - return getWrappedDocument().getEnumList(path, classOfEnum); - } - - @Nonnull - @Override - default List getUUIDList(@Nonnull String path) { - return getWrappedDocument().getUUIDList(path); - } - - @Nonnull - @Override - default List getCharacterList(@Nonnull String path) { - return getWrappedDocument().getCharacterList(path); - } - - @Nonnull - @Override - default List getByteList(@Nonnull String path) { - return getWrappedDocument().getByteList(path); - } - - @Nonnull - @Override - default List getShortList(@Nonnull String path) { - return getWrappedDocument().getShortList(path); - } - - @Nonnull - @Override - default List getIntegerList(@Nonnull String path) { - return getWrappedDocument().getIntegerList(path); - } - - @Nonnull - @Override - default List getLongList(@Nonnull String path) { - return getWrappedDocument().getLongList(path); - } - - @Nonnull - @Override - default List getFloatList(@Nonnull String path) { - return getWrappedDocument().getFloatList(path); - } - - @Nonnull - @Override - default List getDoubleList(@Nonnull String path) { - return getWrappedDocument().getDoubleList(path); - } - - @Nullable - @Override - default UUID getUUID(@Nonnull String path) { - return getWrappedDocument().getUUID(path); - } - - @Nonnull - @Override - default UUID getUUID(@Nonnull String path, @Nonnull UUID def) { - return getWrappedDocument().getUUID(path, def); - } - - @Nullable - @Override - default Date getDate(@Nonnull String path) { - return getWrappedDocument().getDate(path); - } - - @Nonnull - @Override - default Date getDate(@Nonnull String path, @Nonnull Date def) { - return getWrappedDocument().getDate(path, def); - } - - @Nullable - @Override - default OffsetDateTime getDateTime(@Nonnull String path) { - return getWrappedDocument().getDateTime(path); - } - - @Nonnull - @Override - default OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { - return getWrappedDocument().getDateTime(path, def); - } - - @Nullable - @Override - default Color getColor(@Nonnull String path) { - return getWrappedDocument().getColor(path); - } - - @Nonnull - @Override - default Color getColor(@Nonnull String path, @Nonnull Color def) { - return getWrappedDocument().getColor(path, def); - } - - @Nullable - @Override - default > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { - return getWrappedDocument().getEnum(path, classOfEnum); - } - - @Nonnull - @Override - default > E getEnum(@Nonnull String path, @Nonnull E def) { - return getWrappedDocument().getEnum(path, def); - } - - @Nullable - @Override - default T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { - return getWrappedDocument().getSerializable(path, classOfT); - } - - @Nonnull - @Override - default T getSerializable(@Nonnull String path, @Nonnull T def) { - return getWrappedDocument().getSerializable(path, def); - } - - @Nullable - @Override - default Class getClass(@Nonnull String path) { - return getWrappedDocument().getClass(path); - } - - @Nonnull - @Override - default Class getClass(@Nonnull String path, @Nonnull Class def) { - return getWrappedDocument().getClass(path, def); - } - - @Nullable - @Override - default Version getVersion(@Nonnull String path) { - return getWrappedDocument().getVersion(path); - } - - @Nonnull - @Override - default Version getVersion(@Nonnull String path, @Nonnull Version def) { - return getWrappedDocument().getVersion(path, def); - } - - @Nullable - @Override - default byte[] getBinary(@Nonnull String path) { - return getWrappedDocument().getBinary(path); - } - - @Override - default boolean contains(@Nonnull String path) { - return getWrappedDocument().contains(path); - } - - @Override - default boolean hasChildren(@Nonnull String path) { - return getWrappedDocument().hasChildren(path); - } - - @Override - default boolean isObject(@Nonnull String path) { - return getWrappedDocument().isObject(path); - } - - @Override - default boolean isList(@Nonnull String path) { - return getWrappedDocument().isList(path); - } - - @Override - default boolean isDocument(@Nonnull String path) { - return getWrappedDocument().isDocument(path); - } - - @Override - default boolean isEmpty() { - return getWrappedDocument().isEmpty(); - } - - @Override - default int size() { - return getWrappedDocument().size(); - } - - @Nonnull - @Override - default Map values() { - return getWrappedDocument().values(); - } - - @Nonnull - @Override - default Map valuesAsStrings() { - return getWrappedDocument().valuesAsStrings(); - } - - @Nonnull - @Override - default Map children() { - return getWrappedDocument().children(); - } - - @Nonnull - @Override - default Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { - return getWrappedDocument().mapValues(keyMapper, valueMapper); - } - - @Nonnull - @Override - default Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { - return getWrappedDocument().mapDocuments(keyMapper, valueMapper); - } - - @Nonnull - @Override - default R mapDocument(@Nonnull String path, @Nonnull Function mapper) { - return getWrappedDocument().mapDocument(path, mapper); - } - - @Nullable - @Override - default R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { - return getWrappedDocument().mapDocumentNullable(path, mapper); - } - - @Nonnull - @Override - default Collection keys() { - return getWrappedDocument().keys(); - } - - @Nonnull - @Override - default Set> entrySet() { - return getWrappedDocument().entrySet(); - } - - @Override - default void forEach(@Nonnull BiConsumer action) { - getWrappedDocument().forEach(action); - } - - @Nonnull - @Override - default Document readonly() { - return getWrappedDocument().readonly(); - } - - @Nullable - @Override - default Document getParent() { - return getWrappedDocument().getParent(); - } - - @Nonnull - @Override - default Document getRoot() { - return getWrappedDocument().getRoot(); - } - - @SuppressWarnings("unchecked") - default D self() { - return (D) this; - } + Document getWrappedDocument(); + + @Override + default boolean isReadonly() { + return getWrappedDocument().isReadonly(); + } + + @Nonnull + @Override + default Document getDocument(@Nonnull String path) { + return getWrappedDocument().getDocument(path); + } + + @Nonnull + @Override + default List getDocumentList(@Nonnull String path) { + return getWrappedDocument().getDocumentList(path); + } + + @Nonnull + @Override + default List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { + return getWrappedDocument().getSerializableList(path, classOfT); + } + + @Nonnull + @Override + default D set(@Nonnull String path, @Nullable Object value) { + getWrappedDocument().set(path, value); + return self(); + } + + @Nonnull + @Override + default D set(@Nonnull Object value) { + getWrappedDocument().set(value); + return self(); + } + + @Nonnull + @Override + default D clear() { + getWrappedDocument().clear(); + return self(); + } + + @Nonnull + @Override + default D remove(@Nonnull String path) { + getWrappedDocument().remove(path); + return self(); + } + + @Override + default void write(@Nonnull Writer writer) throws IOException { + getWrappedDocument().write(writer); + } + + @Override + default void saveToFile(@Nonnull File file) throws IOException { + getWrappedDocument().saveToFile(file); + } + + @Nonnull + @Override + default String toJson() { + return getWrappedDocument().toJson(); + } + + @Nonnull + @Override + default String toPrettyJson() { + return getWrappedDocument().toPrettyJson(); + } + + @Override + default T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + return getWrappedDocument().getInstance(path, classOfT); + } + + @Override + default T toInstanceOf(@Nonnull Class classOfT) { + return getWrappedDocument().toInstanceOf(classOfT); + } + + @Nullable + @Override + default Object getObject(@Nonnull String path) { + return getWrappedDocument().getObject(path); + } + + @Nonnull + @Override + default Object getObject(@Nonnull String path, @Nonnull Object def) { + return getWrappedDocument().getObject(path, def); + } + + @Nonnull + @Override + default Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { + return getWrappedDocument().getOptional(key, extractor); + } + + @Nullable + @Override + default String getString(@Nonnull String path) { + return getWrappedDocument().getString(path); + } + + @Nonnull + @Override + default String getString(@Nonnull String path, @Nonnull String def) { + return getWrappedDocument().getString(path, def); + } + + @Override + default char getChar(@Nonnull String path) { + return getWrappedDocument().getChar(path); + } + + @Override + default char getChar(@Nonnull String path, char def) { + return getWrappedDocument().getChar(path, def); + } + + @Override + default long getLong(@Nonnull String path) { + return getWrappedDocument().getLong(path); + } + + @Override + default long getLong(@Nonnull String path, long def) { + return getWrappedDocument().getLong(path, def); + } + + @Override + default int getInt(@Nonnull String path) { + return getWrappedDocument().getInt(path); + } + + @Override + default int getInt(@Nonnull String path, int def) { + return getWrappedDocument().getInt(path, def); + } + + @Override + default short getShort(@Nonnull String path) { + return getWrappedDocument().getShort(path); + } + + @Override + default short getShort(@Nonnull String path, short def) { + return getWrappedDocument().getShort(path, def); + } + + @Override + default byte getByte(@Nonnull String path) { + return getWrappedDocument().getByte(path); + } + + @Override + default byte getByte(@Nonnull String path, byte def) { + return getWrappedDocument().getByte(path, def); + } + + @Override + default float getFloat(@Nonnull String path) { + return getWrappedDocument().getFloat(path); + } + + @Override + default float getFloat(@Nonnull String path, float def) { + return getWrappedDocument().getFloat(path, def); + } + + @Override + default double getDouble(@Nonnull String path) { + return getWrappedDocument().getDouble(path); + } + + @Override + default double getDouble(@Nonnull String path, double def) { + return getWrappedDocument().getDouble(path, def); + } + + @Override + default boolean getBoolean(@Nonnull String path) { + return getWrappedDocument().getBoolean(path); + } + + @Override + default boolean getBoolean(@Nonnull String path, boolean def) { + return getWrappedDocument().getBoolean(path, def); + } + + @Nonnull + @Override + default List getStringList(@Nonnull String path) { + return getWrappedDocument().getStringList(path); + } + + @Nonnull + @Override + default String[] getStringArray(@Nonnull String path) { + return getWrappedDocument().getStringArray(path); + } + + @Nonnull + @Override + default List mapList(@Nonnull String path, @Nonnull Function mapper) { + return getWrappedDocument().mapList(path, mapper); + } + + @Nonnull + @Override + default > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { + return getWrappedDocument().getEnumList(path, classOfEnum); + } + + @Nonnull + @Override + default List getUUIDList(@Nonnull String path) { + return getWrappedDocument().getUUIDList(path); + } + + @Nonnull + @Override + default List getCharacterList(@Nonnull String path) { + return getWrappedDocument().getCharacterList(path); + } + + @Nonnull + @Override + default List getByteList(@Nonnull String path) { + return getWrappedDocument().getByteList(path); + } + + @Nonnull + @Override + default List getShortList(@Nonnull String path) { + return getWrappedDocument().getShortList(path); + } + + @Nonnull + @Override + default List getIntegerList(@Nonnull String path) { + return getWrappedDocument().getIntegerList(path); + } + + @Nonnull + @Override + default List getLongList(@Nonnull String path) { + return getWrappedDocument().getLongList(path); + } + + @Nonnull + @Override + default List getFloatList(@Nonnull String path) { + return getWrappedDocument().getFloatList(path); + } + + @Nonnull + @Override + default List getDoubleList(@Nonnull String path) { + return getWrappedDocument().getDoubleList(path); + } + + @Nullable + @Override + default UUID getUUID(@Nonnull String path) { + return getWrappedDocument().getUUID(path); + } + + @Nonnull + @Override + default UUID getUUID(@Nonnull String path, @Nonnull UUID def) { + return getWrappedDocument().getUUID(path, def); + } + + @Nullable + @Override + default Date getDate(@Nonnull String path) { + return getWrappedDocument().getDate(path); + } + + @Nonnull + @Override + default Date getDate(@Nonnull String path, @Nonnull Date def) { + return getWrappedDocument().getDate(path, def); + } + + @Nullable + @Override + default OffsetDateTime getDateTime(@Nonnull String path) { + return getWrappedDocument().getDateTime(path); + } + + @Nonnull + @Override + default OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { + return getWrappedDocument().getDateTime(path, def); + } + + @Nullable + @Override + default Color getColor(@Nonnull String path) { + return getWrappedDocument().getColor(path); + } + + @Nonnull + @Override + default Color getColor(@Nonnull String path, @Nonnull Color def) { + return getWrappedDocument().getColor(path, def); + } + + @Nullable + @Override + default > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + return getWrappedDocument().getEnum(path, classOfEnum); + } + + @Nonnull + @Override + default > E getEnum(@Nonnull String path, @Nonnull E def) { + return getWrappedDocument().getEnum(path, def); + } + + @Nullable + @Override + default T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + return getWrappedDocument().getSerializable(path, classOfT); + } + + @Nonnull + @Override + default T getSerializable(@Nonnull String path, @Nonnull T def) { + return getWrappedDocument().getSerializable(path, def); + } + + @Nullable + @Override + default Class getClass(@Nonnull String path) { + return getWrappedDocument().getClass(path); + } + + @Nonnull + @Override + default Class getClass(@Nonnull String path, @Nonnull Class def) { + return getWrappedDocument().getClass(path, def); + } + + @Nullable + @Override + default Version getVersion(@Nonnull String path) { + return getWrappedDocument().getVersion(path); + } + + @Nonnull + @Override + default Version getVersion(@Nonnull String path, @Nonnull Version def) { + return getWrappedDocument().getVersion(path, def); + } + + @Nullable + @Override + default byte[] getBinary(@Nonnull String path) { + return getWrappedDocument().getBinary(path); + } + + @Override + default boolean contains(@Nonnull String path) { + return getWrappedDocument().contains(path); + } + + @Override + default boolean hasChildren(@Nonnull String path) { + return getWrappedDocument().hasChildren(path); + } + + @Override + default boolean isObject(@Nonnull String path) { + return getWrappedDocument().isObject(path); + } + + @Override + default boolean isList(@Nonnull String path) { + return getWrappedDocument().isList(path); + } + + @Override + default boolean isDocument(@Nonnull String path) { + return getWrappedDocument().isDocument(path); + } + + @Override + default boolean isEmpty() { + return getWrappedDocument().isEmpty(); + } + + @Override + default int size() { + return getWrappedDocument().size(); + } + + @Nonnull + @Override + default Map values() { + return getWrappedDocument().values(); + } + + @Nonnull + @Override + default Map valuesAsStrings() { + return getWrappedDocument().valuesAsStrings(); + } + + @Nonnull + @Override + default Map children() { + return getWrappedDocument().children(); + } + + @Nonnull + @Override + default Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return getWrappedDocument().mapValues(keyMapper, valueMapper); + } + + @Nonnull + @Override + default Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + return getWrappedDocument().mapDocuments(keyMapper, valueMapper); + } + + @Nonnull + @Override + default R mapDocument(@Nonnull String path, @Nonnull Function mapper) { + return getWrappedDocument().mapDocument(path, mapper); + } + + @Nullable + @Override + default R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { + return getWrappedDocument().mapDocumentNullable(path, mapper); + } + + @Nonnull + @Override + default Collection keys() { + return getWrappedDocument().keys(); + } + + @Nonnull + @Override + default Set> entrySet() { + return getWrappedDocument().entrySet(); + } + + @Override + default void forEach(@Nonnull BiConsumer action) { + getWrappedDocument().forEach(action); + } + + @Nonnull + @Override + default Document readonly() { + return getWrappedDocument().readonly(); + } + + @Nullable + @Override + default Document getParent() { + return getWrappedDocument().getParent(); + } + + @Nonnull + @Override + default Document getRoot() { + return getWrappedDocument().getRoot(); + } + + @SuppressWarnings("unchecked") + default D self() { + return (D) this; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java b/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java index 7fa62c991..07db92082 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java @@ -4,8 +4,8 @@ public final class ConfigReadOnlyException extends IllegalStateException { - public ConfigReadOnlyException(@Nonnull String action) { - super("Config." + action); - } + public ConfigReadOnlyException(@Nonnull String action) { + super("Config." + action); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java b/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java index 2af90f2c1..0adf55e34 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java @@ -10,41 +10,42 @@ public final class TimingsHelper { - public static final ILogger LOGGER = ILogger.forThisClass(); - private static final Map timings = new ConcurrentHashMap<>(); - - private TimingsHelper() {} - - public static void start(@Nonnull String id) { - timings.put(id, System.currentTimeMillis()); - } - - public static void stop(@Nonnull String id) { - Long start = timings.remove(id); - if (start == null) { - LOGGER.warn("Stopped timing {} which was not started before", id); - return; - } - - long time = System.currentTimeMillis() - start; - LOGGER.debug("Finished timings '{}' within {}ms ({}s)", id, time, NumberFormatter.DOUBLE_FLOATING_POINT.format(time / 1000d)); - } - - public static void restart(@Nonnull String id) { - stop(id); - start(id); - } - - public static void start() { - start(ReflectionUtils.getCallerName()); - } - - public static void stop() { - stop(ReflectionUtils.getCallerName()); - } - - public static void restart() { - restart(ReflectionUtils.getCallerName()); - } + public static final ILogger LOGGER = ILogger.forThisClass(); + private static final Map timings = new ConcurrentHashMap<>(); + + private TimingsHelper() { + } + + public static void start(@Nonnull String id) { + timings.put(id, System.currentTimeMillis()); + } + + public static void stop(@Nonnull String id) { + Long start = timings.remove(id); + if (start == null) { + LOGGER.warn("Stopped timing {} which was not started before", id); + return; + } + + long time = System.currentTimeMillis() - start; + LOGGER.debug("Finished timings '{}' within {}ms ({}s)", id, time, NumberFormatter.DOUBLE_FLOATING_POINT.format(time / 1000d)); + } + + public static void restart(@Nonnull String id) { + stop(id); + start(id); + } + + public static void start() { + start(ReflectionUtils.getCallerName()); + } + + public static void stop() { + stop(ReflectionUtils.getCallerName()); + } + + public static void restart() { + restart(ReflectionUtils.getCallerName()); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java index 49eeec955..f1d30ba76 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java +++ b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java @@ -17,482 +17,482 @@ public class DiscordWebhook { - protected String url; - protected String content; - protected String username; - protected String avatarUrl; - protected boolean tts; - protected List embeds = new ArrayList<>(); - - private DiscordWebhook() { - } - - /** - * Constructs a new DiscordWebhook instance - * - * @param url The webhook URL obtained in Discord - */ - public DiscordWebhook(@Nonnull String url) { - this.url = url; - } - - public DiscordWebhook(@Nonnull String url, @Nonnull String username) { - this.url = url; - this.username = username; - } - - public DiscordWebhook(@Nonnull String url, @Nonnull String username, @Nonnull String avatarUrl) { - this.url = url; - this.username = username; - this.avatarUrl = avatarUrl; - } - - public DiscordWebhook(@Nonnull String url, @Nonnull String username, @Nonnull String avatarUrl, @Nonnull String content, @Nonnull List embeds, boolean tts) { - this.url = url; - this.username = username; - this.avatarUrl = avatarUrl; - this.content = content; - this.embeds = embeds; - this.tts = tts; - } - - @Nonnull - public DiscordWebhook setUrl(@Nonnull String url) { - this.url = url; - return this; - } - - @Nonnull - public DiscordWebhook setContent(@Nullable String content) { - this.content = content; - return this; - } - - @Nonnull - public DiscordWebhook setUsername(@Nullable String username) { - this.username = username; - return this; - } - - @Nonnull - public DiscordWebhook setAvatarUrl(@Nullable String avatarUrl) { - this.avatarUrl = avatarUrl; - return this; - } - - @Nonnull - public DiscordWebhook setTts(boolean tts) { - this.tts = tts; - return this; - } - - @Nonnull - public DiscordWebhook addEmbed(EmbedObject embed) { - this.embeds.add(embed); - return this; - } - - public void execute() throws IOException { - if (content == null && embeds.isEmpty()) - throw new IllegalArgumentException("Set content or add at least one EmbedObject"); - - Document json = Document.create(); - - json.set("content", content); - json.set("username", username); - json.set("avatar_url", avatarUrl); - json.set("tts", tts); - - if (!embeds.isEmpty()) { - List embedObjects = new ArrayList<>(); - - for (EmbedObject embed : embeds) { - Document jsonEmbed = Document.create(); - - jsonEmbed.set("title", embed.getTitle()); - jsonEmbed.set("description", embed.getDescription()); - jsonEmbed.set("url", embed.getUrl()); - - if (embed.getColor() != null) { - Color color = embed.getColor(); - int rgb = color.getRed(); - rgb = (rgb << 8) + color.getGreen(); - rgb = (rgb << 8) + color.getBlue(); - - jsonEmbed.set("color", rgb); - } - - EmbedObject.Footer footer = embed.getFooter(); - EmbedObject.Image image = embed.getImage(); - EmbedObject.Thumbnail thumbnail = embed.getThumbnail(); - EmbedObject.Author author = embed.getAuthor(); - List fields = embed.getFields(); - - if (footer != null) { - Document jsonFooter =Document.create(); - - jsonFooter.set("text", footer.getText()); - jsonFooter.set("icon_url", footer.getIconUrl()); - jsonEmbed.set("footer", jsonFooter); - } - - if (image != null) { - Document jsonImage = Document.create(); - - jsonImage.set("url", image.getUrl()); - jsonEmbed.set("image", jsonImage); - } - - if (thumbnail != null) { - Document jsonThumbnail = Document.create(); - - jsonThumbnail.set("url", thumbnail.getUrl()); - jsonEmbed.set("thumbnail", jsonThumbnail); - } - - if (author != null) { - Document jsonAuthor = Document.create(); - - jsonAuthor.set("name", author.getName()); - jsonAuthor.set("url", author.getUrl()); - jsonAuthor.set("icon_url", author.getIconUrl()); - jsonEmbed.set("author", jsonAuthor); - } - - List jsonFields = new ArrayList<>(); - for (EmbedObject.Field field : fields) { - Document jsonField = Document.create(); - - jsonField.set("name", field.getName()); - jsonField.set("value", field.getValue()); - jsonField.set("inline", field.isInline()); - - jsonFields.add(jsonField); - } - - jsonEmbed.set("fields", jsonFields.toArray()); - embedObjects.add(jsonEmbed); - } - - json.set("embeds", embedObjects.toArray()); - } - - URL url = new URL(this.url); - HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); - connection.setRequestMethod("POST"); - connection.setDoOutput(true); - connection.setDoInput(true); - connection.setConnectTimeout(2500); - connection.setReadTimeout(1000); - connection.setRequestProperty("User-Agent", "Mozilla/5.0"); - connection.setRequestProperty("Accept", "*/*"); - connection.setRequestProperty("Content-Type", "application/json"); - - OutputStream output = connection.getOutputStream(); - output.write(json.toString().getBytes(StandardCharsets.UTF_8)); - output.flush(); - output.close(); - - connection.getInputStream().close(); - connection.disconnect(); - } - - @Nonnull - public DiscordWebhook replaceEverywhere(@Nonnull String trigger, @Nonnull String replacement) { - if (content != null) content = content.replace(trigger, replacement); - if (username != null) username = username.replace(trigger, replacement); - for (EmbedObject embed : embeds) { - if (embed.author.name != null) embed.author.name = embed.author.name.replace(trigger, replacement); - if (embed.description != null) embed.description = embed.description.replace(trigger, replacement); - if (embed.title != null) embed.title = embed.title.replace(trigger, replacement); - if (embed.footer.text != null) embed.footer.text = embed.footer.text.replace(trigger, replacement); - for (EmbedObject.Field field : embed.fields) { - if (field.name != null) field.name = field.name.replace(trigger, replacement); - if (field.value != null) field.value = field.value.replace(trigger, replacement); - } - } - return this; - } - - public static class EmbedObject { - - protected String title; - protected String description; - protected String url; - protected Color color; - - protected Footer footer; - protected Thumbnail thumbnail; - protected Image image; - protected Author author; - protected List fields = new ArrayList<>(); - - public EmbedObject() { - } - - public EmbedObject(@Nullable String title, @Nullable String description, @Nullable String url, @Nullable Color color, - @Nullable Footer footer, @Nullable Thumbnail thumbnail, @Nullable Image image, @Nullable Author author, - @Nonnull List fields) { - this.title = title; - this.description = description; - this.url = url; - this.color = color; - this.footer = footer; - this.thumbnail = thumbnail; - this.image = image; - this.author = author; - this.fields = fields; - } - - public String getTitle() { - return title; - } - - public String getDescription() { - return description; - } - - public String getUrl() { - return url; - } - - public Color getColor() { - return color; - } - - public Footer getFooter() { - return footer; - } - - public Thumbnail getThumbnail() { - return thumbnail; - } - - public Image getImage() { - return image; - } - - public Author getAuthor() { - return author; - } - - public List getFields() { - return fields; - } - - @Nonnull - public EmbedObject setTitle(String title) { - this.title = title; - return this; - } - - @Nonnull - public EmbedObject setDescription(String description) { - this.description = description; - return this; - } - - @Nonnull - public EmbedObject setUrl(String url) { - this.url = url; - return this; - } - - @Nonnull - public EmbedObject setColor(Color color) { - this.color = color; - return this; - } - - @Nonnull - public EmbedObject setFooter(String text, String icon) { - this.footer = new Footer(text, icon); - return this; - } - - @Nonnull - public EmbedObject setThumbnail(String url) { - this.thumbnail = new Thumbnail(url); - return this; - } - - @Nonnull - public EmbedObject setImage(String url) { - this.image = new Image(url); - return this; - } - - @Nonnull - public EmbedObject setAuthor(String name, String url, String icon) { - this.author = new Author(name, url, icon); - return this; - } - - @Nonnull - public EmbedObject addField(String name, String value, boolean inline) { - this.fields.add(new Field(name, value, inline)); - return this; - } - - @Override - public EmbedObject clone() { - return new EmbedObject( - title, description, url, color, - footer == null ? null : footer.clone(), - thumbnail == null ? null : thumbnail.clone(), - image == null ? null : image.clone(), - author == null ? null : author.clone(), - DiscordWebhook.clone(fields, Field::clone) - ); - } - - public static class Footer { - - protected String text; - protected String iconUrl; - - private Footer() { - } - - public Footer(String text, String iconUrl) { - this.text = text; - this.iconUrl = iconUrl; - } - - private String getText() { - return text; - } - - private String getIconUrl() { - return iconUrl; - } - - @Override - protected Footer clone() { - return new Footer(text, iconUrl); - } - } - - public static class Thumbnail { - - private String url; - - private Thumbnail() { - } - - public Thumbnail(String url) { - this.url = url; - } - - private String getUrl() { - return url; - } - - @Override - protected Thumbnail clone() { - return new Thumbnail(url); - } - } - - public static class Image { - - private String url; - - private Image() { - } - - public Image(String url) { - this.url = url; - } - - private String getUrl() { - return url; - } - - @Override - public Image clone() { - return new Image(url); - } - } - - public static class Author { - - private String name; - private String url; - private String iconUrl; - - private Author() { - } - - public Author(String name, String url, String iconUrl) { - this.name = name; - this.url = url; - this.iconUrl = iconUrl; - } - - private String getName() { - return name; - } - - private String getUrl() { - return url; - } - - private String getIconUrl() { - return iconUrl; - } - - @Override - protected Author clone() { - return new Author(name, url, iconUrl); - } - } - - public static class Field { - - private String name; - private String value; - private boolean inline; - - private Field() { - } - - private Field(String name, String value, boolean inline) { - this.name = name; - this.value = value; - this.inline = inline; - } - - private String getName() { - return name; - } - - private String getValue() { - return value; - } - - private boolean isInline() { - return inline; - } - - @Override - protected Field clone() { - return new Field(name, value, inline); - } - } - } - - @Override - public DiscordWebhook clone() { - return new DiscordWebhook(url, username, avatarUrl, content, clone(embeds, EmbedObject::clone), tts); - } - - @Nonnull - protected static List clone(@Nonnull Collection collection, @Nonnull Function cloner) { - List list = new ArrayList<>(collection.size()); - for (T current : collection) { - list.add(cloner.apply(current)); - } - return list; - } + protected String url; + protected String content; + protected String username; + protected String avatarUrl; + protected boolean tts; + protected List embeds = new ArrayList<>(); + + private DiscordWebhook() { + } + + /** + * Constructs a new DiscordWebhook instance + * + * @param url The webhook URL obtained in Discord + */ + public DiscordWebhook(@Nonnull String url) { + this.url = url; + } + + public DiscordWebhook(@Nonnull String url, @Nonnull String username) { + this.url = url; + this.username = username; + } + + public DiscordWebhook(@Nonnull String url, @Nonnull String username, @Nonnull String avatarUrl) { + this.url = url; + this.username = username; + this.avatarUrl = avatarUrl; + } + + public DiscordWebhook(@Nonnull String url, @Nonnull String username, @Nonnull String avatarUrl, @Nonnull String content, @Nonnull List embeds, boolean tts) { + this.url = url; + this.username = username; + this.avatarUrl = avatarUrl; + this.content = content; + this.embeds = embeds; + this.tts = tts; + } + + @Nonnull + public DiscordWebhook setUrl(@Nonnull String url) { + this.url = url; + return this; + } + + @Nonnull + public DiscordWebhook setContent(@Nullable String content) { + this.content = content; + return this; + } + + @Nonnull + public DiscordWebhook setUsername(@Nullable String username) { + this.username = username; + return this; + } + + @Nonnull + public DiscordWebhook setAvatarUrl(@Nullable String avatarUrl) { + this.avatarUrl = avatarUrl; + return this; + } + + @Nonnull + public DiscordWebhook setTts(boolean tts) { + this.tts = tts; + return this; + } + + @Nonnull + public DiscordWebhook addEmbed(EmbedObject embed) { + this.embeds.add(embed); + return this; + } + + public void execute() throws IOException { + if (content == null && embeds.isEmpty()) + throw new IllegalArgumentException("Set content or add at least one EmbedObject"); + + Document json = Document.create(); + + json.set("content", content); + json.set("username", username); + json.set("avatar_url", avatarUrl); + json.set("tts", tts); + + if (!embeds.isEmpty()) { + List embedObjects = new ArrayList<>(); + + for (EmbedObject embed : embeds) { + Document jsonEmbed = Document.create(); + + jsonEmbed.set("title", embed.getTitle()); + jsonEmbed.set("description", embed.getDescription()); + jsonEmbed.set("url", embed.getUrl()); + + if (embed.getColor() != null) { + Color color = embed.getColor(); + int rgb = color.getRed(); + rgb = (rgb << 8) + color.getGreen(); + rgb = (rgb << 8) + color.getBlue(); + + jsonEmbed.set("color", rgb); + } + + EmbedObject.Footer footer = embed.getFooter(); + EmbedObject.Image image = embed.getImage(); + EmbedObject.Thumbnail thumbnail = embed.getThumbnail(); + EmbedObject.Author author = embed.getAuthor(); + List fields = embed.getFields(); + + if (footer != null) { + Document jsonFooter = Document.create(); + + jsonFooter.set("text", footer.getText()); + jsonFooter.set("icon_url", footer.getIconUrl()); + jsonEmbed.set("footer", jsonFooter); + } + + if (image != null) { + Document jsonImage = Document.create(); + + jsonImage.set("url", image.getUrl()); + jsonEmbed.set("image", jsonImage); + } + + if (thumbnail != null) { + Document jsonThumbnail = Document.create(); + + jsonThumbnail.set("url", thumbnail.getUrl()); + jsonEmbed.set("thumbnail", jsonThumbnail); + } + + if (author != null) { + Document jsonAuthor = Document.create(); + + jsonAuthor.set("name", author.getName()); + jsonAuthor.set("url", author.getUrl()); + jsonAuthor.set("icon_url", author.getIconUrl()); + jsonEmbed.set("author", jsonAuthor); + } + + List jsonFields = new ArrayList<>(); + for (EmbedObject.Field field : fields) { + Document jsonField = Document.create(); + + jsonField.set("name", field.getName()); + jsonField.set("value", field.getValue()); + jsonField.set("inline", field.isInline()); + + jsonFields.add(jsonField); + } + + jsonEmbed.set("fields", jsonFields.toArray()); + embedObjects.add(jsonEmbed); + } + + json.set("embeds", embedObjects.toArray()); + } + + URL url = new URL(this.url); + HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setDoInput(true); + connection.setConnectTimeout(2500); + connection.setReadTimeout(1000); + connection.setRequestProperty("User-Agent", "Mozilla/5.0"); + connection.setRequestProperty("Accept", "*/*"); + connection.setRequestProperty("Content-Type", "application/json"); + + OutputStream output = connection.getOutputStream(); + output.write(json.toString().getBytes(StandardCharsets.UTF_8)); + output.flush(); + output.close(); + + connection.getInputStream().close(); + connection.disconnect(); + } + + @Nonnull + public DiscordWebhook replaceEverywhere(@Nonnull String trigger, @Nonnull String replacement) { + if (content != null) content = content.replace(trigger, replacement); + if (username != null) username = username.replace(trigger, replacement); + for (EmbedObject embed : embeds) { + if (embed.author.name != null) embed.author.name = embed.author.name.replace(trigger, replacement); + if (embed.description != null) embed.description = embed.description.replace(trigger, replacement); + if (embed.title != null) embed.title = embed.title.replace(trigger, replacement); + if (embed.footer.text != null) embed.footer.text = embed.footer.text.replace(trigger, replacement); + for (EmbedObject.Field field : embed.fields) { + if (field.name != null) field.name = field.name.replace(trigger, replacement); + if (field.value != null) field.value = field.value.replace(trigger, replacement); + } + } + return this; + } + + public static class EmbedObject { + + protected String title; + protected String description; + protected String url; + protected Color color; + + protected Footer footer; + protected Thumbnail thumbnail; + protected Image image; + protected Author author; + protected List fields = new ArrayList<>(); + + public EmbedObject() { + } + + public EmbedObject(@Nullable String title, @Nullable String description, @Nullable String url, @Nullable Color color, + @Nullable Footer footer, @Nullable Thumbnail thumbnail, @Nullable Image image, @Nullable Author author, + @Nonnull List fields) { + this.title = title; + this.description = description; + this.url = url; + this.color = color; + this.footer = footer; + this.thumbnail = thumbnail; + this.image = image; + this.author = author; + this.fields = fields; + } + + public String getTitle() { + return title; + } + + public String getDescription() { + return description; + } + + public String getUrl() { + return url; + } + + public Color getColor() { + return color; + } + + public Footer getFooter() { + return footer; + } + + public Thumbnail getThumbnail() { + return thumbnail; + } + + public Image getImage() { + return image; + } + + public Author getAuthor() { + return author; + } + + public List getFields() { + return fields; + } + + @Nonnull + public EmbedObject setTitle(String title) { + this.title = title; + return this; + } + + @Nonnull + public EmbedObject setDescription(String description) { + this.description = description; + return this; + } + + @Nonnull + public EmbedObject setUrl(String url) { + this.url = url; + return this; + } + + @Nonnull + public EmbedObject setColor(Color color) { + this.color = color; + return this; + } + + @Nonnull + public EmbedObject setFooter(String text, String icon) { + this.footer = new Footer(text, icon); + return this; + } + + @Nonnull + public EmbedObject setThumbnail(String url) { + this.thumbnail = new Thumbnail(url); + return this; + } + + @Nonnull + public EmbedObject setImage(String url) { + this.image = new Image(url); + return this; + } + + @Nonnull + public EmbedObject setAuthor(String name, String url, String icon) { + this.author = new Author(name, url, icon); + return this; + } + + @Nonnull + public EmbedObject addField(String name, String value, boolean inline) { + this.fields.add(new Field(name, value, inline)); + return this; + } + + @Override + public EmbedObject clone() { + return new EmbedObject( + title, description, url, color, + footer == null ? null : footer.clone(), + thumbnail == null ? null : thumbnail.clone(), + image == null ? null : image.clone(), + author == null ? null : author.clone(), + DiscordWebhook.clone(fields, Field::clone) + ); + } + + public static class Footer { + + protected String text; + protected String iconUrl; + + private Footer() { + } + + public Footer(String text, String iconUrl) { + this.text = text; + this.iconUrl = iconUrl; + } + + private String getText() { + return text; + } + + private String getIconUrl() { + return iconUrl; + } + + @Override + protected Footer clone() { + return new Footer(text, iconUrl); + } + } + + public static class Thumbnail { + + private String url; + + private Thumbnail() { + } + + public Thumbnail(String url) { + this.url = url; + } + + private String getUrl() { + return url; + } + + @Override + protected Thumbnail clone() { + return new Thumbnail(url); + } + } + + public static class Image { + + private String url; + + private Image() { + } + + public Image(String url) { + this.url = url; + } + + private String getUrl() { + return url; + } + + @Override + public Image clone() { + return new Image(url); + } + } + + public static class Author { + + private String name; + private String url; + private String iconUrl; + + private Author() { + } + + public Author(String name, String url, String iconUrl) { + this.name = name; + this.url = url; + this.iconUrl = iconUrl; + } + + private String getName() { + return name; + } + + private String getUrl() { + return url; + } + + private String getIconUrl() { + return iconUrl; + } + + @Override + protected Author clone() { + return new Author(name, url, iconUrl); + } + } + + public static class Field { + + private String name; + private String value; + private boolean inline; + + private Field() { + } + + private Field(String name, String value, boolean inline) { + this.name = name; + this.value = value; + this.inline = inline; + } + + private String getName() { + return name; + } + + private String getValue() { + return value; + } + + private boolean isInline() { + return inline; + } + + @Override + protected Field clone() { + return new Field(name, value, inline); + } + } + } + + @Override + public DiscordWebhook clone() { + return new DiscordWebhook(url, username, avatarUrl, content, clone(embeds, EmbedObject::clone), tts); + } + + @Nonnull + protected static List clone(@Nonnull Collection collection, @Nonnull Function cloner) { + List list = new ArrayList<>(collection.size()); + for (T current : collection) { + list.add(cloner.apply(current)); + } + return list; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiConsumer.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiConsumer.java index 5bca8f733..b5d2e1f34 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiConsumer.java +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiConsumer.java @@ -7,15 +7,15 @@ @FunctionalInterface public interface ExceptionallyBiConsumer extends BiConsumer { - @Override - default void accept(T t, U u) { - try { - acceptExceptionally(t, u); - } catch (Exception ex) { - throw WrappedException.rethrow(ex); - } - } + @Override + default void accept(T t, U u) { + try { + acceptExceptionally(t, u); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } - void acceptExceptionally(T t, U u) throws Exception; + void acceptExceptionally(T t, U u) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiFunction.java index 6977e1ea6..464f78963 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiFunction.java +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyBiFunction.java @@ -7,15 +7,15 @@ @FunctionalInterface public interface ExceptionallyBiFunction extends BiFunction { - @Override - default R apply(T t, U u) { - try { - return applyExceptionally(t, u); - } catch (Exception ex) { - throw WrappedException.rethrow(ex); - } - } + @Override + default R apply(T t, U u) { + try { + return applyExceptionally(t, u); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } - R applyExceptionally(T t, U u) throws Exception; + R applyExceptionally(T t, U u) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyConsumer.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyConsumer.java index 99f90b68d..d41be9ca9 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyConsumer.java +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyConsumer.java @@ -7,15 +7,15 @@ @FunctionalInterface public interface ExceptionallyConsumer extends Consumer { - @Override - default void accept(T t) { - try { - acceptExceptionally(t); - } catch (Exception ex) { - throw WrappedException.rethrow(ex); - } - } + @Override + default void accept(T t) { + try { + acceptExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } - void acceptExceptionally(T t) throws Exception; + void acceptExceptionally(T t) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyDoubleFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyDoubleFunction.java index 007c6d3e7..ad466a501 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyDoubleFunction.java +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyDoubleFunction.java @@ -7,15 +7,15 @@ @FunctionalInterface public interface ExceptionallyDoubleFunction extends DoubleFunction { - @Override - default R apply(double value) { - try { - return applyExceptionally(value); - } catch (Exception ex) { - throw WrappedException.rethrow(ex); - } - } + @Override + default R apply(double value) { + try { + return applyExceptionally(value); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } - R applyExceptionally(double value) throws Exception; + R applyExceptionally(double value) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java index 182afce47..3c7bff9a9 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java @@ -9,21 +9,21 @@ @FunctionalInterface public interface ExceptionallyFunction extends Function { - @Override - default R apply(T t) { - try { - return applyExceptionally(t); - } catch (Exception ex) { - throw WrappedException.rethrow(ex); - } - } + @Override + default R apply(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } - R applyExceptionally(T t) throws Exception; + R applyExceptionally(T t) throws Exception; - @Nonnull - @CheckReturnValue - static ExceptionallyFunction identity() { - return t -> t; - } + @Nonnull + @CheckReturnValue + static ExceptionallyFunction identity() { + return t -> t; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyIntFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyIntFunction.java index c15637c63..269278e59 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyIntFunction.java +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyIntFunction.java @@ -7,15 +7,15 @@ @FunctionalInterface public interface ExceptionallyIntFunction extends IntFunction { - @Override - default R apply(int value) { - try { - return applyExceptionally(value); - } catch (Exception ex) { - throw WrappedException.rethrow(ex); - } - } + @Override + default R apply(int value) { + try { + return applyExceptionally(value); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } - R applyExceptionally(int value) throws Exception; + R applyExceptionally(int value) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyLongFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyLongFunction.java index e3cd46a66..21a63d49b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyLongFunction.java +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyLongFunction.java @@ -7,15 +7,15 @@ @FunctionalInterface public interface ExceptionallyLongFunction extends LongFunction { - @Override - default R apply(long value) { - try { - return applyExceptionally(value); - } catch (Exception ex) { - throw WrappedException.rethrow(ex); - } - } + @Override + default R apply(long value) { + try { + return applyExceptionally(value); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } - R applyExceptionally(long value) throws Exception; + R applyExceptionally(long value) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyRunnable.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyRunnable.java index b15ce02c7..84ee5138f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyRunnable.java +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyRunnable.java @@ -7,21 +7,21 @@ @FunctionalInterface public interface ExceptionallyRunnable extends Runnable, Callable { - @Override - default void run() { - try { - runExceptionally(); - } catch (Exception ex) { - throw WrappedException.rethrow(ex); - } - } + @Override + default void run() { + try { + runExceptionally(); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } - @Override - default Void call() throws Exception { - runExceptionally(); - return null; - } + @Override + default Void call() throws Exception { + runExceptionally(); + return null; + } - void runExceptionally() throws Exception; + void runExceptionally() throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallySupplier.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallySupplier.java index 5aab4b750..43624b73a 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallySupplier.java +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallySupplier.java @@ -8,20 +8,20 @@ @FunctionalInterface public interface ExceptionallySupplier extends Supplier, Callable { - @Override - default T get() { - try { - return getExceptionally(); - } catch (Exception ex) { - throw WrappedException.rethrow(ex); - } - } + @Override + default T get() { + try { + return getExceptionally(); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } - @Override - default T call() throws Exception { - return getExceptionally(); - } + @Override + default T call() throws Exception { + return getExceptionally(); + } - T getExceptionally() throws Exception; + T getExceptionally() throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToDoubleFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToDoubleFunction.java index 759fd6f38..29e982567 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToDoubleFunction.java +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToDoubleFunction.java @@ -7,15 +7,15 @@ @FunctionalInterface public interface ExceptionallyToDoubleFunction extends ToDoubleFunction { - @Override - default double applyAsDouble(T t) { - try { - return applyExceptionally(t); - } catch (Exception ex) { - throw WrappedException.rethrow(ex); - } - } + @Override + default double applyAsDouble(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } - double applyExceptionally(T T) throws Exception; + double applyExceptionally(T T) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToIntFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToIntFunction.java index 98e5520e9..2b06e59d3 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToIntFunction.java +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToIntFunction.java @@ -7,15 +7,15 @@ @FunctionalInterface public interface ExceptionallyToIntFunction extends ToIntFunction { - @Override - default int applyAsInt(T t) { - try { - return applyExceptionally(t); - } catch (Exception ex) { - throw WrappedException.rethrow(ex); - } - } + @Override + default int applyAsInt(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } - int applyExceptionally(T t) throws Exception; + int applyExceptionally(T t) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToLongFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToLongFunction.java index 6ace6ef31..b57d2e5bc 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToLongFunction.java +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyToLongFunction.java @@ -7,15 +7,15 @@ @FunctionalInterface public interface ExceptionallyToLongFunction extends ToLongFunction { - @Override - default long applyAsLong(T t) { - try { - return applyExceptionally(t); - } catch (Exception ex) { - throw WrappedException.rethrow(ex); - } - } + @Override + default long applyAsLong(T t) { + try { + return applyExceptionally(t); + } catch (Exception ex) { + throw WrappedException.rethrow(ex); + } + } - long applyExceptionally(T t) throws Exception; + long applyExceptionally(T t) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java index 02ec550a7..203aae04b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java @@ -23,260 +23,261 @@ public interface ILogger { - final class Holder { - - private static ILoggerFactory factory; - private static Data data; - - private static class Data { - private boolean slf4j, slf4jApi; - } - - @Nonnull - private static Data getData() { - if (data == null) - createData(); - - return data; - } - - private static synchronized void createData() { - boolean slf4j = false; - boolean slf4jApi = true; - - try { - Class.forName("org.slf4j.impl.StaticLoggerBinder"); - slf4j = true; - } catch (ClassNotFoundException eStatic) { // there was no static logger binder (SLF4J pre-1.8.x) - try { - Class serviceProviderInterface = Class.forName("org.slf4j.spi.SLF4JServiceProvider"); - // check if there is a service implementation for the service, indicating a provider for SLF4J 1.8.x+ is installed - slf4j = ServiceLoader.load(serviceProviderInterface).iterator().hasNext(); - } catch (ClassNotFoundException eService) { // there was no service provider interface (SLF4J 1.8.x+) - try { - // prints warning of missing implementation - LoggerFactory.getLogger(ILogger.class); - } catch (NoClassDefFoundError eApi) { - slf4jApi = false; - } - } - } - - data = new Data(); - data.slf4j = slf4j; - data.slf4jApi = slf4jApi; - } - - @Nonnull - public static ILoggerFactory getFactory() { - if (factory == null) - factory = getFallbackFactory(); - - return factory; - } - - @Nonnull - private static ILoggerFactory getFallbackFactory() { - return isSlf4jImplAvailable() ? new Slf4jLoggerFactory() : - isSlf4jApiAvailable() ? new DefaultLoggerFactory(SimpleLogger::new) : - new DefaultLoggerFactory(FallbackLogger::new); - } - - private Holder() {} - - } - - static boolean isSlf4jImplAvailable() { - return Holder.getData().slf4j; - } - - static boolean isSlf4jApiAvailable() { - return Holder.getData().slf4jApi; - } - - @Nonnull - @CheckReturnValue - static ILogger forName(@Nullable String name) { - return getFactory().forName(name); - } - - @Nonnull - @CheckReturnValue - static ILogger forClass(@Nullable Class clazz) { - return forName(clazz == null ? null : clazz.getSimpleName()); - } - - @Nonnull - @CheckReturnValue - static ILogger forClassOf(@Nonnull Object object) { - return forClass(object.getClass()); - } - - @Nonnull - @CheckReturnValue - static ILogger forThisClass() { - return forClass(ReflectionUtils.getCaller()); - } - - @Nonnull - @CheckReturnValue - static JavaILogger forJavaLogger(@Nonnull java.util.logging.Logger logger) { - return new JavaLoggerWrapper(logger); - } - - @Nonnull - @CheckReturnValue - static ILogger forSlf4jLogger(@Nonnull org.slf4j.Logger logger) { - return logger instanceof ILogger ? (ILogger) logger : new Slf4jLoggerWrapper(logger); - } - - static void setFactory(@Nonnull ILoggerFactory factory) { - Preconditions.checkNotNull(factory); - Holder.factory = factory; - } - - static void setConstantFactory(@Nonnull ILogger logger) { - setFactory(new ConstantLoggerFactory(logger)); - } - - @Nonnull - static ILoggerFactory getFactory() { - return Holder.getFactory(); - } - - void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args); - - default void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { - log(level, String.valueOf(message), args); - } - - default void error(@Nullable String message, @Nonnull Object... args) { - log(LogLevel.ERROR, message, args); - } - - default void error(@Nullable Object message, @Nonnull Object... args) { - log(LogLevel.ERROR, message, args); - } - - default void warn(@Nullable String message, @Nonnull Object... args) { - log(LogLevel.WARN, message, args); - } - - default void warn(@Nullable Object message, @Nonnull Object... args) { - log(LogLevel.WARN, message, args); - } - - default void info(@Nullable String message, @Nonnull Object... args) { - log(LogLevel.INFO, message, args); - } - - default void info(@Nullable Object message, @Nonnull Object... args) { - log(LogLevel.INFO, message, args); - } - - default void status(@Nullable String message, @Nonnull Object... args) { - log(LogLevel.STATUS, message, args); - } - - default void status(@Nullable Object message, @Nonnull Object... args) { - log(LogLevel.STATUS, message, args); - } - - default void extended(@Nullable String message, @Nonnull Object... args) { - log(LogLevel.EXTENDED, message, args); - } - - default void extended(@Nullable Object message, @Nonnull Object... args) { - log(LogLevel.EXTENDED, message, args); - } - - default void debug(@Nullable String message, @Nonnull Object... args) { - log(LogLevel.DEBUG, message, args); - } - - default void debug(@Nullable Object message, @Nonnull Object... args) { - log(LogLevel.DEBUG, message, args); - } - - default void trace(@Nullable String message, @Nonnull Object... args) { - log(LogLevel.TRACE, message, args); - } - - default void trace(@Nullable Object message, @Nonnull Object... args) { - log(LogLevel.TRACE, message, args); - } - - default boolean isLevelEnabled(@Nonnull LogLevel level) { - return level.isShownAtLoggerLevel(getMinLevel()); - } - - default boolean isTraceEnabled() { - return isLevelEnabled(LogLevel.TRACE); - } - - default boolean isDebugEnabled() { - return isLevelEnabled(LogLevel.DEBUG); - } - - default boolean isExtendedEnabled() { - return isLevelEnabled(LogLevel.EXTENDED); - } - - default boolean isInfoEnabled() { - return isLevelEnabled(LogLevel.INFO); - } - - default boolean isWarnEnabled() { - return isLevelEnabled(LogLevel.WARN); - } - - default boolean isErrorEnabled() { - return isLevelEnabled(LogLevel.ERROR); - } - - @Nonnull - LogLevel getMinLevel(); - - @Nonnull - ILogger setMinLevel(@Nonnull LogLevel level); - - @Nonnull - @CheckReturnValue - default Slf4jILogger slf4j() { - if (this instanceof Slf4jILogger) - return (Slf4jILogger) this; - throw new IllegalStateException(this.getClass().getName() + " cannot be converted to Slf4jILogger"); - } - - @Nonnull - @CheckReturnValue - default JavaILogger java() { - if (this instanceof JavaILogger) - return (JavaILogger) this; - throw new IllegalStateException(this.getClass().getName() + " cannot be converted to JavaILogger"); - } - - @Nonnull - @CheckReturnValue - default PrintStream asPrintStream(@Nonnull LogLevel level) { - try { - return new PrintStream(new LogOutputStream(this, level), true, StandardCharsets.UTF_8.name()); - } catch (Exception ex) { - throw new WrappedException(ex); - } - } - - @Nonnull - @CheckReturnValue - static String formatMessage(@Nullable Object messageObject, @Nonnull Object... args) { - StringBuilder message = new StringBuilder(String.valueOf(messageObject)); - for (Object arg : args) { - if (arg instanceof Throwable) continue; - int index = message.indexOf("{}"); - if (index == -1) break; - message.replace(index, index+2, String.valueOf(arg)); - } - return message.toString(); - } + final class Holder { + + private static ILoggerFactory factory; + private static Data data; + + private static class Data { + private boolean slf4j, slf4jApi; + } + + @Nonnull + private static Data getData() { + if (data == null) + createData(); + + return data; + } + + private static synchronized void createData() { + boolean slf4j = false; + boolean slf4jApi = true; + + try { + Class.forName("org.slf4j.impl.StaticLoggerBinder"); + slf4j = true; + } catch (ClassNotFoundException eStatic) { // there was no static logger binder (SLF4J pre-1.8.x) + try { + Class serviceProviderInterface = Class.forName("org.slf4j.spi.SLF4JServiceProvider"); + // check if there is a service implementation for the service, indicating a provider for SLF4J 1.8.x+ is installed + slf4j = ServiceLoader.load(serviceProviderInterface).iterator().hasNext(); + } catch (ClassNotFoundException eService) { // there was no service provider interface (SLF4J 1.8.x+) + try { + // prints warning of missing implementation + LoggerFactory.getLogger(ILogger.class); + } catch (NoClassDefFoundError eApi) { + slf4jApi = false; + } + } + } + + data = new Data(); + data.slf4j = slf4j; + data.slf4jApi = slf4jApi; + } + + @Nonnull + public static ILoggerFactory getFactory() { + if (factory == null) + factory = getFallbackFactory(); + + return factory; + } + + @Nonnull + private static ILoggerFactory getFallbackFactory() { + return isSlf4jImplAvailable() ? new Slf4jLoggerFactory() : + isSlf4jApiAvailable() ? new DefaultLoggerFactory(SimpleLogger::new) : + new DefaultLoggerFactory(FallbackLogger::new); + } + + private Holder() { + } + + } + + static boolean isSlf4jImplAvailable() { + return Holder.getData().slf4j; + } + + static boolean isSlf4jApiAvailable() { + return Holder.getData().slf4jApi; + } + + @Nonnull + @CheckReturnValue + static ILogger forName(@Nullable String name) { + return getFactory().forName(name); + } + + @Nonnull + @CheckReturnValue + static ILogger forClass(@Nullable Class clazz) { + return forName(clazz == null ? null : clazz.getSimpleName()); + } + + @Nonnull + @CheckReturnValue + static ILogger forClassOf(@Nonnull Object object) { + return forClass(object.getClass()); + } + + @Nonnull + @CheckReturnValue + static ILogger forThisClass() { + return forClass(ReflectionUtils.getCaller()); + } + + @Nonnull + @CheckReturnValue + static JavaILogger forJavaLogger(@Nonnull java.util.logging.Logger logger) { + return new JavaLoggerWrapper(logger); + } + + @Nonnull + @CheckReturnValue + static ILogger forSlf4jLogger(@Nonnull org.slf4j.Logger logger) { + return logger instanceof ILogger ? (ILogger) logger : new Slf4jLoggerWrapper(logger); + } + + static void setFactory(@Nonnull ILoggerFactory factory) { + Preconditions.checkNotNull(factory); + Holder.factory = factory; + } + + static void setConstantFactory(@Nonnull ILogger logger) { + setFactory(new ConstantLoggerFactory(logger)); + } + + @Nonnull + static ILoggerFactory getFactory() { + return Holder.getFactory(); + } + + void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args); + + default void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + log(level, String.valueOf(message), args); + } + + default void error(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + default void error(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + default void warn(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + default void warn(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + default void info(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + default void info(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + default void status(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + default void status(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + default void extended(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.EXTENDED, message, args); + } + + default void extended(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.EXTENDED, message, args); + } + + default void debug(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + default void debug(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + default void trace(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.TRACE, message, args); + } + + default void trace(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.TRACE, message, args); + } + + default boolean isLevelEnabled(@Nonnull LogLevel level) { + return level.isShownAtLoggerLevel(getMinLevel()); + } + + default boolean isTraceEnabled() { + return isLevelEnabled(LogLevel.TRACE); + } + + default boolean isDebugEnabled() { + return isLevelEnabled(LogLevel.DEBUG); + } + + default boolean isExtendedEnabled() { + return isLevelEnabled(LogLevel.EXTENDED); + } + + default boolean isInfoEnabled() { + return isLevelEnabled(LogLevel.INFO); + } + + default boolean isWarnEnabled() { + return isLevelEnabled(LogLevel.WARN); + } + + default boolean isErrorEnabled() { + return isLevelEnabled(LogLevel.ERROR); + } + + @Nonnull + LogLevel getMinLevel(); + + @Nonnull + ILogger setMinLevel(@Nonnull LogLevel level); + + @Nonnull + @CheckReturnValue + default Slf4jILogger slf4j() { + if (this instanceof Slf4jILogger) + return (Slf4jILogger) this; + throw new IllegalStateException(this.getClass().getName() + " cannot be converted to Slf4jILogger"); + } + + @Nonnull + @CheckReturnValue + default JavaILogger java() { + if (this instanceof JavaILogger) + return (JavaILogger) this; + throw new IllegalStateException(this.getClass().getName() + " cannot be converted to JavaILogger"); + } + + @Nonnull + @CheckReturnValue + default PrintStream asPrintStream(@Nonnull LogLevel level) { + try { + return new PrintStream(new LogOutputStream(this, level), true, StandardCharsets.UTF_8.name()); + } catch (Exception ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + @CheckReturnValue + static String formatMessage(@Nullable Object messageObject, @Nonnull Object... args) { + StringBuilder message = new StringBuilder(String.valueOf(messageObject)); + for (Object arg : args) { + if (arg instanceof Throwable) continue; + int index = message.indexOf("{}"); + if (index == -1) break; + message.replace(index, index + 2, String.valueOf(arg)); + } + return message.toString(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java index fed7742e6..25f4528cc 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java @@ -6,10 +6,10 @@ public interface ILoggerFactory { - @Nonnull - @CheckReturnValue + @Nonnull + @CheckReturnValue ILogger forName(@Nullable String name); - void setDefaultLevel(@Nonnull LogLevel level); + void setDefaultLevel(@Nonnull LogLevel level); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java index ddf6d01c8..13d78cecf 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java @@ -5,78 +5,78 @@ public enum LogLevel { - TRACE (0, "TRACE", "trace", Level.FINEST, false), - DEBUG (2, "DEBUG", "debug", Level.FINER, false), - EXTENDED(5, "EXTENDED", "extended", Level.FINE, false), - STATUS (7, "STATUS", "status", Level.CONFIG, false), - INFO (10, "INFO", "info", Level.INFO, false), - WARN (15, "WARN", "warn", Level.WARNING, true), - ERROR (25, "ERROR", "error", Level.SEVERE, true); + TRACE(0, "TRACE", "trace", Level.FINEST, false), + DEBUG(2, "DEBUG", "debug", Level.FINER, false), + EXTENDED(5, "EXTENDED", "extended", Level.FINE, false), + STATUS(7, "STATUS", "status", Level.CONFIG, false), + INFO(10, "INFO", "info", Level.INFO, false), + WARN(15, "WARN", "warn", Level.WARNING, true), + ERROR(25, "ERROR", "error", Level.SEVERE, true); - private final String uppercaseName, lowercaseName; - private final Level javaLevel; - private final int value; - private final boolean highlighted; + private final String uppercaseName, lowercaseName; + private final Level javaLevel; + private final int value; + private final boolean highlighted; - LogLevel(int value, @Nonnull String uppercaseName, @Nonnull String lowercaseName, @Nonnull Level javaLevel, boolean highlighted) { - this.uppercaseName = uppercaseName; - this.lowercaseName = lowercaseName; - this.javaLevel = javaLevel; - this.value = value; - this.highlighted = highlighted; - } + LogLevel(int value, @Nonnull String uppercaseName, @Nonnull String lowercaseName, @Nonnull Level javaLevel, boolean highlighted) { + this.uppercaseName = uppercaseName; + this.lowercaseName = lowercaseName; + this.javaLevel = javaLevel; + this.value = value; + this.highlighted = highlighted; + } - @Nonnull - public Level getJavaUtilLevel() { - return javaLevel; - } + @Nonnull + public Level getJavaUtilLevel() { + return javaLevel; + } - public boolean isShownAtLoggerLevel(@Nonnull LogLevel loggerLevel) { - return this.getValue() >= loggerLevel.getValue(); - } + public boolean isShownAtLoggerLevel(@Nonnull LogLevel loggerLevel) { + return this.getValue() >= loggerLevel.getValue(); + } - public int getValue() { - return value; - } + public int getValue() { + return value; + } - @Nonnull - public String getLowerCaseName() { - return lowercaseName; - } + @Nonnull + public String getLowerCaseName() { + return lowercaseName; + } - @Nonnull - public String getUpperCaseName() { - return uppercaseName; - } + @Nonnull + public String getUpperCaseName() { + return uppercaseName; + } - public boolean isHighlighted() { - return highlighted; - } + public boolean isHighlighted() { + return highlighted; + } - @Nonnull - public static LogLevel fromJavaLevel(@Nonnull Level level) { - for (LogLevel logLevel : values()) { - if (logLevel.getJavaUtilLevel().intValue() == level.intValue()) - return logLevel; - } - return INFO; - } + @Nonnull + public static LogLevel fromJavaLevel(@Nonnull Level level) { + for (LogLevel logLevel : values()) { + if (logLevel.getJavaUtilLevel().intValue() == level.intValue()) + return logLevel; + } + return INFO; + } - @Nonnull - public static LogLevel fromValue(int value) { - for (LogLevel level : values()) { - if (level.getValue() == value) - return level; - } - return INFO; - } + @Nonnull + public static LogLevel fromValue(int value) { + for (LogLevel level : values()) { + if (level.getValue() == value) + return level; + } + return INFO; + } - @Nonnull - public static LogLevel fromName(@Nonnull String name) { - for (LogLevel level : values()) { - if (level.getUpperCaseName().equalsIgnoreCase(name)) - return level; - } - return INFO; - } + @Nonnull + public static LogLevel fromName(@Nonnull String name) { + for (LogLevel level : values()) { + if (level.getUpperCaseName().equalsIgnoreCase(name)) + return level; + } + return INFO; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java index 7095492ed..de7b796a9 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java @@ -7,22 +7,22 @@ public class LogOutputStream extends ByteArrayOutputStream { - private final ILogger logger; - private final LogLevel level; + private final ILogger logger; + private final LogLevel level; - public LogOutputStream(@Nonnull ILogger logger, @Nonnull LogLevel level) { - this.logger = logger; - this.level = level; - } + public LogOutputStream(@Nonnull ILogger logger, @Nonnull LogLevel level) { + this.logger = logger; + this.level = level; + } - @Override - public void flush() throws IOException { - String input = this.toString(StandardCharsets.UTF_8.name()); - this.reset(); + @Override + public void flush() throws IOException { + String input = this.toString(StandardCharsets.UTF_8.name()); + this.reset(); - if (input != null && !input.isEmpty() && !input.equals(System.lineSeparator())) { - logger.log(level, input); - } - } + if (input != null && !input.isEmpty() && !input.equals(System.lineSeparator())) { + logger.log(level, input); + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java index 06deb942a..54e721dae 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java @@ -5,43 +5,43 @@ public interface LoggingApiUser { - @Nonnull + @Nonnull ILogger getTargetLogger(); - default void error(@Nullable Object message, @Nonnull Object... args) { - getTargetLogger().error(message, args); - } + default void error(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().error(message, args); + } - default void warn(@Nullable Object message, @Nonnull Object... args) { - getTargetLogger().warn(message, args); - } + default void warn(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().warn(message, args); + } - default void info(@Nullable Object message, @Nonnull Object... args) { - getTargetLogger().info(message, args); - } + default void info(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().info(message, args); + } - default void status(@Nullable Object message, @Nonnull Object... args) { - getTargetLogger().status(message, args); - } + default void status(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().status(message, args); + } - default void extended(@Nullable Object message, @Nonnull Object... args) { - getTargetLogger().extended(message, args); - } + default void extended(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().extended(message, args); + } - default void debug(@Nullable Object message, @Nonnull Object... args) { - getTargetLogger().debug(message, args); - } + default void debug(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().debug(message, args); + } - default void trace(@Nullable Object message, @Nonnull Object... args) { - getTargetLogger().trace(message, args); - } + default void trace(@Nullable Object message, @Nonnull Object... args) { + getTargetLogger().trace(message, args); + } - default boolean isTraceEnabled() { - return getTargetLogger().isTraceEnabled(); - } + default boolean isTraceEnabled() { + return getTargetLogger().isTraceEnabled(); + } - default boolean isDebugEnabled() { - return getTargetLogger().isDebugEnabled(); - } + default boolean isDebugEnabled() { + return getTargetLogger().isDebugEnabled(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java index c4731eead..37cde09d7 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java @@ -9,151 +9,151 @@ public interface WrappedILogger extends ILogger { - @Nonnull - ILogger getWrappedLogger(); - - @Override - default void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { - getWrappedLogger().log(level, message, args); - } - - @Override - default void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { - getWrappedLogger().log(level, message, args); - } - - @Override - default void error(@Nullable String message, @Nonnull Object... args) { - getWrappedLogger().error(message, args); - } - - @Override - default void error(@Nullable Object message, @Nonnull Object... args) { - getWrappedLogger().error(message, args); - } - - @Override - default void warn(@Nullable String message, @Nonnull Object... args) { - getWrappedLogger().warn(message, args); - } - - @Override - default void warn(@Nullable Object message, @Nonnull Object... args) { - getWrappedLogger().warn(message, args); - } - - @Override - default void info(@Nullable String message, @Nonnull Object... args) { - getWrappedLogger().info(message, args); - } - - @Override - default void info(@Nullable Object message, @Nonnull Object... args) { - getWrappedLogger().info(message, args); - } - - @Override - default void status(@Nullable String message, @Nonnull Object... args) { - getWrappedLogger().status(message, args); - } - - @Override - default void status(@Nullable Object message, @Nonnull Object... args) { - getWrappedLogger().status(message, args); - } - - @Override - default void extended(@Nullable String message, @Nonnull Object... args) { - getWrappedLogger().extended(message, args); - } - - @Override - default void extended(@Nullable Object message, @Nonnull Object... args) { - getWrappedLogger().extended(message, args); - } - - @Override - default void debug(@Nullable String message, @Nonnull Object... args) { - getWrappedLogger().debug(message, args); - } - - @Override - default void debug(@Nullable Object message, @Nonnull Object... args) { - getWrappedLogger().debug(message, args); - } - - @Override - default void trace(@Nullable String message, @Nonnull Object... args) { - getWrappedLogger().trace(message, args); - } - - @Override - default void trace(@Nullable Object message, @Nonnull Object... args) { - getWrappedLogger().trace(message, args); - } - - @Override - default boolean isLevelEnabled(@Nonnull LogLevel level) { - return getWrappedLogger().isLevelEnabled(level); - } - - @Override - default boolean isTraceEnabled() { - return getWrappedLogger().isTraceEnabled(); - } - - @Override - default boolean isDebugEnabled() { - return getWrappedLogger().isDebugEnabled(); - } - - @Override - default boolean isExtendedEnabled() { - return getWrappedLogger().isExtendedEnabled(); - } - - @Override - default boolean isInfoEnabled() { - return getWrappedLogger().isInfoEnabled(); - } - - @Override - default boolean isWarnEnabled() { - return getWrappedLogger().isWarnEnabled(); - } - - @Override - default boolean isErrorEnabled() { - return getWrappedLogger().isErrorEnabled(); - } - - @Nonnull - @Override - default LogLevel getMinLevel() { - return getWrappedLogger().getMinLevel(); - } - - @Nonnull - @Override - default ILogger setMinLevel(@Nonnull LogLevel level) { - return getWrappedLogger().setMinLevel(level); - } - - @Nonnull - @Override - default Slf4jILogger slf4j() { - return getWrappedLogger().slf4j(); - } - - @Nonnull - @Override - default JavaILogger java() { - return getWrappedLogger().java(); - } - - @Nonnull - @Override - default PrintStream asPrintStream(@Nonnull LogLevel level) { - return getWrappedLogger().asPrintStream(level); - } + @Nonnull + ILogger getWrappedLogger(); + + @Override + default void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + getWrappedLogger().log(level, message, args); + } + + @Override + default void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().log(level, message, args); + } + + @Override + default void error(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().error(message, args); + } + + @Override + default void error(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().error(message, args); + } + + @Override + default void warn(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().warn(message, args); + } + + @Override + default void warn(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().warn(message, args); + } + + @Override + default void info(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().info(message, args); + } + + @Override + default void info(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().info(message, args); + } + + @Override + default void status(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().status(message, args); + } + + @Override + default void status(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().status(message, args); + } + + @Override + default void extended(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().extended(message, args); + } + + @Override + default void extended(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().extended(message, args); + } + + @Override + default void debug(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().debug(message, args); + } + + @Override + default void debug(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().debug(message, args); + } + + @Override + default void trace(@Nullable String message, @Nonnull Object... args) { + getWrappedLogger().trace(message, args); + } + + @Override + default void trace(@Nullable Object message, @Nonnull Object... args) { + getWrappedLogger().trace(message, args); + } + + @Override + default boolean isLevelEnabled(@Nonnull LogLevel level) { + return getWrappedLogger().isLevelEnabled(level); + } + + @Override + default boolean isTraceEnabled() { + return getWrappedLogger().isTraceEnabled(); + } + + @Override + default boolean isDebugEnabled() { + return getWrappedLogger().isDebugEnabled(); + } + + @Override + default boolean isExtendedEnabled() { + return getWrappedLogger().isExtendedEnabled(); + } + + @Override + default boolean isInfoEnabled() { + return getWrappedLogger().isInfoEnabled(); + } + + @Override + default boolean isWarnEnabled() { + return getWrappedLogger().isWarnEnabled(); + } + + @Override + default boolean isErrorEnabled() { + return getWrappedLogger().isErrorEnabled(); + } + + @Nonnull + @Override + default LogLevel getMinLevel() { + return getWrappedLogger().getMinLevel(); + } + + @Nonnull + @Override + default ILogger setMinLevel(@Nonnull LogLevel level) { + return getWrappedLogger().setMinLevel(level); + } + + @Nonnull + @Override + default Slf4jILogger slf4j() { + return getWrappedLogger().slf4j(); + } + + @Nonnull + @Override + default JavaILogger java() { + return getWrappedLogger().java(); + } + + @Nonnull + @Override + default PrintStream asPrintStream(@Nonnull LogLevel level) { + return getWrappedLogger().asPrintStream(level); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java index e19b07015..b3386d795 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java @@ -9,15 +9,15 @@ public class HandledAsyncLogger extends HandledLogger { - protected final Executor executor = Executors.newSingleThreadExecutor(new NamedThreadFactory("AsyncLogTask")); + protected final Executor executor = Executors.newSingleThreadExecutor(new NamedThreadFactory("AsyncLogTask")); - public HandledAsyncLogger(@Nonnull LogLevel initialLevel) { - super(initialLevel); - } + public HandledAsyncLogger(@Nonnull LogLevel initialLevel) { + super(initialLevel); + } - @Override - protected void log0(@Nonnull LogEntry entry) { - executor.execute(() -> logNow(entry)); - } + @Override + protected void log0(@Nonnull LogEntry entry) { + executor.execute(() -> logNow(entry)); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java index cde16aac4..76b2b8f6b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java @@ -12,58 +12,58 @@ public abstract class HandledLogger implements ILogger { - protected final Collection handlers = new CopyOnWriteArrayList<>(); - protected LogLevel level; + protected final Collection handlers = new CopyOnWriteArrayList<>(); + protected LogLevel level; - public HandledLogger(@Nonnull LogLevel initialLevel) { - this.level = initialLevel; - } + public HandledLogger(@Nonnull LogLevel initialLevel) { + this.level = initialLevel; + } - @Override - public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { - if (!level.isShownAtLoggerLevel(this.level)) return; - Throwable exception = null; - for (Object arg : args) { - if (arg instanceof Throwable) - exception = (Throwable) arg; - } - log0(new LogEntry(Instant.now(), Thread.currentThread().getName(), ILogger.formatMessage(message, args), level, exception)); - } + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + if (!level.isShownAtLoggerLevel(this.level)) return; + Throwable exception = null; + for (Object arg : args) { + if (arg instanceof Throwable) + exception = (Throwable) arg; + } + log0(new LogEntry(Instant.now(), Thread.currentThread().getName(), ILogger.formatMessage(message, args), level, exception)); + } - public void log(@Nonnull LogEntry entry) { - if (!entry.getLevel().isShownAtLoggerLevel(this.level)) return; - log0(entry); - } + public void log(@Nonnull LogEntry entry) { + if (!entry.getLevel().isShownAtLoggerLevel(this.level)) return; + log0(entry); + } - protected abstract void log0(@Nonnull LogEntry entry); + protected abstract void log0(@Nonnull LogEntry entry); - protected void logNow(@Nonnull LogEntry entry) { - for (LogHandler handler : handlers) { - try { - handler.handle(entry); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } + protected void logNow(@Nonnull LogEntry entry) { + for (LogHandler handler : handlers) { + try { + handler.handle(entry); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } - @Nonnull - public HandledLogger addHandler(@Nonnull LogHandler... handler) { - handlers.addAll(Arrays.asList(handler)); - return this; - } + @Nonnull + public HandledLogger addHandler(@Nonnull LogHandler... handler) { + handlers.addAll(Arrays.asList(handler)); + return this; + } - @Nonnull - @Override - public LogLevel getMinLevel() { - return level; - } + @Nonnull + @Override + public LogLevel getMinLevel() { + return level; + } - @Nonnull - @Override - public ILogger setMinLevel(@Nonnull LogLevel level) { - this.level = level; - return this; - } + @Nonnull + @Override + public ILogger setMinLevel(@Nonnull LogLevel level) { + this.level = level; + return this; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java index 0a62ac68b..95b2de1fc 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java @@ -6,12 +6,12 @@ public class HandledSyncLogger extends HandledLogger { - public HandledSyncLogger(@Nonnull LogLevel initialLevel) { - super(initialLevel); - } + public HandledSyncLogger(@Nonnull LogLevel initialLevel) { + super(initialLevel); + } - @Override - protected void log0(@Nonnull LogEntry entry) { - logNow(entry); - } + @Override + protected void log0(@Nonnull LogEntry entry) { + logNow(entry); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java index 5068d301b..2c0b38f2c 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java @@ -8,42 +8,42 @@ public class LogEntry { - private Instant timestamp; - private String threadName; - private String message; - private LogLevel level; - private Throwable exception; - - public LogEntry(@Nonnull Instant timestamp, @Nonnull String threadName, @Nonnull String message, @Nonnull LogLevel level, @Nullable Throwable exception) { - this.timestamp = timestamp; - this.threadName = threadName; - this.message = message; - this.level = level; - this.exception = exception; - } - - @Nonnull - public Instant getTimestamp() { - return timestamp; - } - - @Nonnull - public String getThreadName() { - return threadName; - } - - @Nonnull - public String getMessage() { - return message; - } - - @Nonnull - public LogLevel getLevel() { - return level; - } - - @Nullable - public Throwable getException() { - return exception; - } + private Instant timestamp; + private String threadName; + private String message; + private LogLevel level; + private Throwable exception; + + public LogEntry(@Nonnull Instant timestamp, @Nonnull String threadName, @Nonnull String message, @Nonnull LogLevel level, @Nullable Throwable exception) { + this.timestamp = timestamp; + this.threadName = threadName; + this.message = message; + this.level = level; + this.exception = exception; + } + + @Nonnull + public Instant getTimestamp() { + return timestamp; + } + + @Nonnull + public String getThreadName() { + return threadName; + } + + @Nonnull + public String getMessage() { + return message; + } + + @Nonnull + public LogLevel getLevel() { + return level; + } + + @Nullable + public Throwable getException() { + return exception; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java index 36141fed5..01f9f09ca 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java @@ -6,8 +6,8 @@ public interface LogHandler { - DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss.SSS"); + DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss.SSS"); - void handle(@Nonnull LogEntry entry) throws Exception; + void handle(@Nonnull LogEntry entry) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java index 711a8ab54..49eb8665d 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java @@ -10,16 +10,16 @@ */ public class BukkitLoggerWrapper extends JavaLoggerWrapper { - public BukkitLoggerWrapper(@Nonnull Logger logger) { - super(logger); - } + public BukkitLoggerWrapper(@Nonnull Logger logger) { + super(logger); + } - @Nonnull - @Override - protected Level mapLevel(@Nonnull Level level) { - if (isLoggable(level) && level.intValue() < Level.INFO.intValue()) - return Level.INFO; - return level; - } + @Nonnull + @Override + protected Level mapLevel(@Nonnull Level level) { + if (isLoggable(level) && level.intValue() < Level.INFO.intValue()) + return Level.INFO; + return level; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java index 4a5e83e9c..eaf5a4d4d 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java @@ -12,51 +12,51 @@ public class FallbackLogger implements ILogger { - protected final PrintStream stream = System.err; - protected final String name; - - protected LogLevel level = LogLevel.INFO; - - public FallbackLogger(@Nullable String name) { - this.name = name; - } - - public FallbackLogger() { - this(null); - } - - @Override - public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { - if (!isLevelEnabled(level)) return; - stream.println(getLogMessage(level, ILogger.formatMessage(message, args), name)); - for (Object arg : args) { - if (!(arg instanceof Throwable)) continue; - ((Throwable)arg).printStackTrace(stream); - } - } - - @Nonnull - @Override - public FallbackLogger setMinLevel(@Nonnull LogLevel level) { - this.level = level; - return this; - } - - @Nonnull - @Override - public LogLevel getMinLevel() { - return level; - } - - @Nonnull - @CheckReturnValue - public static String getLogMessage(@Nonnull LogLevel level, @Nonnull String message, @Nullable String name) { - Thread thread = Thread.currentThread(); - String threadName = thread.getName(); - String time = OffsetDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")); - return name == null ? - String.format("[%s: %s/%s]: %s", time, threadName, level.getUpperCaseName(), message) : - String.format("[%s: %s/%s] %s: %s", time, threadName, level.getUpperCaseName(), name, message); - } + protected final PrintStream stream = System.err; + protected final String name; + + protected LogLevel level = LogLevel.INFO; + + public FallbackLogger(@Nullable String name) { + this.name = name; + } + + public FallbackLogger() { + this(null); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + if (!isLevelEnabled(level)) return; + stream.println(getLogMessage(level, ILogger.formatMessage(message, args), name)); + for (Object arg : args) { + if (!(arg instanceof Throwable)) continue; + ((Throwable) arg).printStackTrace(stream); + } + } + + @Nonnull + @Override + public FallbackLogger setMinLevel(@Nonnull LogLevel level) { + this.level = level; + return this; + } + + @Nonnull + @Override + public LogLevel getMinLevel() { + return level; + } + + @Nonnull + @CheckReturnValue + public static String getLogMessage(@Nonnull LogLevel level, @Nonnull String message, @Nullable String name) { + Thread thread = Thread.currentThread(); + String threadName = thread.getName(); + String time = OffsetDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")); + return name == null ? + String.format("[%s: %s/%s]: %s", time, threadName, level.getUpperCaseName(), message) : + String.format("[%s: %s/%s] %s: %s", time, threadName, level.getUpperCaseName(), name, message); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java index f0c64bf8d..43e5d6424 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java @@ -12,391 +12,391 @@ public class JavaLoggerWrapper extends JavaILogger { - protected final Logger logger; - - public JavaLoggerWrapper(@Nonnull Logger logger) { - super(null, null); - this.logger = logger; - } - - @Override - public boolean getUseParentHandlers() { - return logger.getUseParentHandlers(); - } - - @Override - public Filter getFilter() { - return logger.getFilter(); - } - - @Override - public Handler[] getHandlers() { - return logger.getHandlers(); - } - - @Override - public Level getLevel() { - return logger.getLevel(); - } - - @Override - public Logger getParent() { - return logger.getParent(); - } - - @Override - public ResourceBundle getResourceBundle() { - return logger.getResourceBundle(); - } - - @Override - public String getResourceBundleName() { - return logger.getResourceBundleName(); - } - - @Override - public void log(LogRecord record) { - mapLevel(record); - logger.log(record); - } - - @Override - public void log(Level level, String msg, Object[] params) { - logger.log(mapLevel(level), msg, params); - } - - @Override - public void log(Level level, String msg, Object param1) { - logger.log(mapLevel(level), msg, param1); - } - - @Override - public void log(Level level, Supplier msgSupplier) { - logger.log(mapLevel(level), msgSupplier); - } - - @Override - public void log(Level level, String msg) { - logger.log(mapLevel(level), msg); - } - - @Override - public void log(Level level, String msg, Throwable thrown) { - logger.log(mapLevel(level), msg, thrown); - } - - @Override - public void log(Level level, Throwable thrown, Supplier msgSupplier) { - logger.log(mapLevel(level), thrown, msgSupplier); - } - - @Override - public void logp(Level level, String sourceClass, String sourceMethod, String msg) { - logger.logp(mapLevel(level), sourceClass, sourceMethod, msg); - } - - @Override - public void logp(Level level, String sourceClass, String sourceMethod, Supplier msgSupplier) { - logger.logp(mapLevel(level), sourceClass, sourceMethod, msgSupplier); - } - - @Override - public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) { - logger.logp(mapLevel(level), sourceClass, sourceMethod, msg, param1); - } - - @Override - public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object[] params) { - logger.logp(mapLevel(level), sourceClass, sourceMethod, msg, params); - } - - @Override - public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) { - logger.logp(mapLevel(level), sourceClass, sourceMethod, msg, thrown); - } - - @Override - public void logp(Level level, String sourceClass, String sourceMethod, Throwable thrown, Supplier msgSupplier) { - logger.logp(mapLevel(level), sourceClass, sourceMethod, thrown, msgSupplier); - } - - @Override - public void logrb(Level level, String sourceClass, String sourceMethod, ResourceBundle bundle, String msg, Object... params) { - logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundle, msg, params); - } - - @Override - public void logrb(Level level, String sourceClass, String sourceMethod, ResourceBundle bundle, String msg, Throwable thrown) { - logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundle, msg, thrown); - } - - @Override - public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg) { - logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg); - } - - @Override - public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object param1) { - logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg, param1); - } - - @Override - public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object[] params) { - logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg, params); - } - - @Override - public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Throwable thrown) { - logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg, thrown); - } - - @Override - public boolean isLoggable(Level level) { - return logger.isLoggable(level); - } - - @Override - public void setLevel(Level newLevel) throws SecurityException { - logger.setLevel(newLevel); - } - - @Override - public void setFilter(Filter newFilter) throws SecurityException { - logger.setFilter(newFilter); - } - - @Override - public void setParent(Logger parent) { - logger.setParent(parent); - } - - @Override - public void setResourceBundle(ResourceBundle bundle) { - logger.setResourceBundle(bundle); - } - - @Override - public void setUseParentHandlers(boolean useParentHandlers) { - logger.setUseParentHandlers(useParentHandlers); - } - - @Override - public void severe(String msg) { - logger.severe(msg); - } - - @Override - public void severe(Supplier msgSupplier) { - logger.severe(msgSupplier); - } - - @Override - public void entering(String sourceClass, String sourceMethod) { - logger.entering(sourceClass, sourceMethod); - } - - @Override - public void entering(String sourceClass, String sourceMethod, Object param1) { - logger.entering(sourceClass, sourceMethod, param1); - } - - @Override - public void entering(String sourceClass, String sourceMethod, Object[] params) { - logger.entering(sourceClass, sourceMethod, params); - } - - @Override - public void exiting(String sourceClass, String sourceMethod) { - logger.exiting(sourceClass, sourceMethod); - } - - @Override - public void exiting(String sourceClass, String sourceMethod, Object result) { - logger.exiting(sourceClass, sourceMethod, result); - } - - @Override - public void throwing(String sourceClass, String sourceMethod, Throwable thrown) { - logger.throwing(sourceClass, sourceMethod, thrown); - } - - @Override - public void warning(String msg) { - logger.warning(msg); - } - - @Override - public void info(String msg) { - logger.info(msg); - } - - @Override - public void config(String msg) { - logger.config(msg); - } - - @Override - public void fine(String msg) { - logger.fine(msg); - } - - @Override - public void finer(String msg) { - logger.finer(msg); - } - - @Override - public void finest(String msg) { - logger.finest(msg); - } - - @Override - public void warning(Supplier msgSupplier) { - logger.warning(msgSupplier); - } - - @Override - public void info(Supplier msgSupplier) { - logger.info(msgSupplier); - } - - @Override - public void config(Supplier msgSupplier) { - logger.config(msgSupplier); - } - - @Override - public void fine(Supplier msgSupplier) { - logger.fine(msgSupplier); - } - - @Override - public void finer(Supplier msgSupplier) { - logger.finer(msgSupplier); - } - - @Override - public void finest(Supplier msgSupplier) { - logger.finest(msgSupplier); - } - - @Override - public void addHandler(Handler handler) throws SecurityException { - logger.addHandler(handler); - } - - @Override - public void removeHandler(Handler handler) throws SecurityException { - logger.removeHandler(handler); - } - - @Override - public int hashCode() { - return logger.hashCode(); - } - - @Override - public boolean equals(Object obj) { - return logger.equals(obj); - } - - @Override - public String toString() { - return logger.toString(); - } - - protected void mapLevel(@Nonnull LogRecord record) { - record.setLevel(mapLevel(record.getLevel())); - } - - @Nonnull - protected Level mapLevel(@Nonnull Level level) { - return level; - } - - @Nonnull - @Override - public JavaILogger setMinLevel(@Nonnull LogLevel level) { - setLevel(level.getJavaUtilLevel()); - return this; - } - - @Nonnull - @Override - public LogLevel getMinLevel() { - return LogLevel.fromJavaLevel(logger.getLevel()); - } - - @Override - public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { - Throwable thrown = null; - for (Object arg : args) { - if (arg instanceof Throwable) - thrown = (Throwable) arg; - } - log(level.getJavaUtilLevel(), ILogger.formatMessage(message, args), thrown); - } - - @Override - public void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { - log(level, String.valueOf(message), args); - } - - @Override - public void error(@Nullable String message, @Nonnull Object... args) { - log(LogLevel.ERROR, message, args); - } - - @Override - public void error(@Nullable Object message, @Nonnull Object... args) { - log(LogLevel.ERROR, message, args); - } - - @Override - public void warn(@Nullable String message, @Nonnull Object... args) { - log(LogLevel.WARN, message, args); - } - - @Override - public void warn(@Nullable Object message, @Nonnull Object... args) { - log(LogLevel.WARN, message, args); - } - - @Override - public void info(@Nullable String message, @Nonnull Object... args) { - log(LogLevel.INFO, message, args); - } - - @Override - public void info(@Nullable Object message, @Nonnull Object... args) { - log(LogLevel.INFO, message, args); - } - - @Override - public void status(@Nullable String message, @Nonnull Object... args) { - log(LogLevel.STATUS, message, args); - } - - @Override - public void status(@Nullable Object message, @Nonnull Object... args) { - log(LogLevel.STATUS, message, args); - } - - @Override - public void debug(@Nullable String message, @Nonnull Object... args) { - log(LogLevel.DEBUG, message, args); - } - - @Override - public void debug(@Nullable Object message, @Nonnull Object... args) { - log(LogLevel.DEBUG, message, args); - } - - - @Override - public boolean isTraceEnabled() { - return isLevelEnabled(LogLevel.TRACE); - } + protected final Logger logger; + + public JavaLoggerWrapper(@Nonnull Logger logger) { + super(null, null); + this.logger = logger; + } + + @Override + public boolean getUseParentHandlers() { + return logger.getUseParentHandlers(); + } + + @Override + public Filter getFilter() { + return logger.getFilter(); + } + + @Override + public Handler[] getHandlers() { + return logger.getHandlers(); + } + + @Override + public Level getLevel() { + return logger.getLevel(); + } + + @Override + public Logger getParent() { + return logger.getParent(); + } + + @Override + public ResourceBundle getResourceBundle() { + return logger.getResourceBundle(); + } + + @Override + public String getResourceBundleName() { + return logger.getResourceBundleName(); + } + + @Override + public void log(LogRecord record) { + mapLevel(record); + logger.log(record); + } + + @Override + public void log(Level level, String msg, Object[] params) { + logger.log(mapLevel(level), msg, params); + } + + @Override + public void log(Level level, String msg, Object param1) { + logger.log(mapLevel(level), msg, param1); + } + + @Override + public void log(Level level, Supplier msgSupplier) { + logger.log(mapLevel(level), msgSupplier); + } + + @Override + public void log(Level level, String msg) { + logger.log(mapLevel(level), msg); + } + + @Override + public void log(Level level, String msg, Throwable thrown) { + logger.log(mapLevel(level), msg, thrown); + } + + @Override + public void log(Level level, Throwable thrown, Supplier msgSupplier) { + logger.log(mapLevel(level), thrown, msgSupplier); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, Supplier msgSupplier) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msgSupplier); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg, param1); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object[] params) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg, params); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, msg, thrown); + } + + @Override + public void logp(Level level, String sourceClass, String sourceMethod, Throwable thrown, Supplier msgSupplier) { + logger.logp(mapLevel(level), sourceClass, sourceMethod, thrown, msgSupplier); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, ResourceBundle bundle, String msg, Object... params) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundle, msg, params); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, ResourceBundle bundle, String msg, Throwable thrown) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundle, msg, thrown); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object param1) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg, param1); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Object[] params) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg, params); + } + + @Override + public void logrb(Level level, String sourceClass, String sourceMethod, String bundleName, String msg, Throwable thrown) { + logger.logrb(mapLevel(level), sourceClass, sourceMethod, bundleName, msg, thrown); + } + + @Override + public boolean isLoggable(Level level) { + return logger.isLoggable(level); + } + + @Override + public void setLevel(Level newLevel) throws SecurityException { + logger.setLevel(newLevel); + } + + @Override + public void setFilter(Filter newFilter) throws SecurityException { + logger.setFilter(newFilter); + } + + @Override + public void setParent(Logger parent) { + logger.setParent(parent); + } + + @Override + public void setResourceBundle(ResourceBundle bundle) { + logger.setResourceBundle(bundle); + } + + @Override + public void setUseParentHandlers(boolean useParentHandlers) { + logger.setUseParentHandlers(useParentHandlers); + } + + @Override + public void severe(String msg) { + logger.severe(msg); + } + + @Override + public void severe(Supplier msgSupplier) { + logger.severe(msgSupplier); + } + + @Override + public void entering(String sourceClass, String sourceMethod) { + logger.entering(sourceClass, sourceMethod); + } + + @Override + public void entering(String sourceClass, String sourceMethod, Object param1) { + logger.entering(sourceClass, sourceMethod, param1); + } + + @Override + public void entering(String sourceClass, String sourceMethod, Object[] params) { + logger.entering(sourceClass, sourceMethod, params); + } + + @Override + public void exiting(String sourceClass, String sourceMethod) { + logger.exiting(sourceClass, sourceMethod); + } + + @Override + public void exiting(String sourceClass, String sourceMethod, Object result) { + logger.exiting(sourceClass, sourceMethod, result); + } + + @Override + public void throwing(String sourceClass, String sourceMethod, Throwable thrown) { + logger.throwing(sourceClass, sourceMethod, thrown); + } + + @Override + public void warning(String msg) { + logger.warning(msg); + } + + @Override + public void info(String msg) { + logger.info(msg); + } + + @Override + public void config(String msg) { + logger.config(msg); + } + + @Override + public void fine(String msg) { + logger.fine(msg); + } + + @Override + public void finer(String msg) { + logger.finer(msg); + } + + @Override + public void finest(String msg) { + logger.finest(msg); + } + + @Override + public void warning(Supplier msgSupplier) { + logger.warning(msgSupplier); + } + + @Override + public void info(Supplier msgSupplier) { + logger.info(msgSupplier); + } + + @Override + public void config(Supplier msgSupplier) { + logger.config(msgSupplier); + } + + @Override + public void fine(Supplier msgSupplier) { + logger.fine(msgSupplier); + } + + @Override + public void finer(Supplier msgSupplier) { + logger.finer(msgSupplier); + } + + @Override + public void finest(Supplier msgSupplier) { + logger.finest(msgSupplier); + } + + @Override + public void addHandler(Handler handler) throws SecurityException { + logger.addHandler(handler); + } + + @Override + public void removeHandler(Handler handler) throws SecurityException { + logger.removeHandler(handler); + } + + @Override + public int hashCode() { + return logger.hashCode(); + } + + @Override + public boolean equals(Object obj) { + return logger.equals(obj); + } + + @Override + public String toString() { + return logger.toString(); + } + + protected void mapLevel(@Nonnull LogRecord record) { + record.setLevel(mapLevel(record.getLevel())); + } + + @Nonnull + protected Level mapLevel(@Nonnull Level level) { + return level; + } + + @Nonnull + @Override + public JavaILogger setMinLevel(@Nonnull LogLevel level) { + setLevel(level.getJavaUtilLevel()); + return this; + } + + @Nonnull + @Override + public LogLevel getMinLevel() { + return LogLevel.fromJavaLevel(logger.getLevel()); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + Throwable thrown = null; + for (Object arg : args) { + if (arg instanceof Throwable) + thrown = (Throwable) arg; + } + log(level.getJavaUtilLevel(), ILogger.formatMessage(message, args), thrown); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + log(level, String.valueOf(message), args); + } + + @Override + public void error(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + @Override + public void error(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.ERROR, message, args); + } + + @Override + public void warn(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + @Override + public void warn(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.WARN, message, args); + } + + @Override + public void info(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + @Override + public void info(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.INFO, message, args); + } + + @Override + public void status(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + @Override + public void status(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.STATUS, message, args); + } + + @Override + public void debug(@Nullable String message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + @Override + public void debug(@Nullable Object message, @Nonnull Object... args) { + log(LogLevel.DEBUG, message, args); + } + + + @Override + public boolean isTraceEnabled() { + return isLevelEnabled(LogLevel.TRACE); + } // @Override // public void trace(String msg) { diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java index d99ca1fa4..5fdc7351e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java @@ -9,357 +9,357 @@ public class SimpleLogger extends FallbackLogger implements Slf4jILogger { - public SimpleLogger(@Nullable String name) { - super(name); - } - - public SimpleLogger() { - super(); - } - - @Override - public void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { - super.log(level, message, args); - } - - @Override - public void error(@Nullable String message, @Nonnull Object... args) { - super.error(message, args); - } - - @Override - public void error(@Nullable Object message, @Nonnull Object... args) { - super.error(message, args); - } - - @Override - public void warn(@Nullable String message, @Nonnull Object... args) { - super.warn(message, args); - } - - @Override - public void warn(@Nullable Object message, @Nonnull Object... args) { - super.warn(message, args); - } - - @Override - public void info(@Nullable String message, @Nonnull Object... args) { - super.info(message, args); - } - - @Override - public void info(@Nullable Object message, @Nonnull Object... args) { - super.info(message, args); - } - - @Override - public void status(@Nullable String message, @Nonnull Object... args) { - super.status(message, args); - } - - @Override - public void status(@Nullable Object message, @Nonnull Object... args) { - super.status(message, args); - } - - @Override - public void debug(@Nullable String message, @Nonnull Object... args) { - super.debug(message, args); - } - - @Override - public void debug(@Nullable Object message, @Nonnull Object... args) { - super.debug(message, args); - } - - @Override - public void trace(@Nullable String message, @Nonnull Object... args) { - super.trace(message, args); - } - - @Override - public void trace(@Nullable Object message, @Nonnull Object... args) { - super.trace(message, args); - } - - @Override - public String getName() { - return name; - } - - @Override - public boolean isTraceEnabled() { - return isLevelEnabled(LogLevel.TRACE); - } - - @Override - public void trace(String msg) { - trace(msg, new Object[0]); - } - - @Override - public void trace(String format, Object arg) { - trace(format, new Object[] { arg }); - } - - @Override - public void trace(String format, Object arg1, Object arg2) { - trace(format, new Object[] { arg1, arg2 }); - } - - @Override - public void trace(String msg, Throwable t) { - trace(msg, new Object[] { t }); - } - - @Override - public boolean isTraceEnabled(Marker marker) { - return isTraceEnabled(); - } - - @Override - public void trace(Marker marker, String msg) { - trace(msg); - } - - @Override - public void trace(Marker marker, String format, Object arg) { - trace(format, arg); - } - - @Override - public void trace(Marker marker, String format, Object arg1, Object arg2) { - trace(format, arg1, arg2); - } - - @Override - public void trace(Marker marker, String format, Object... argArray) { - trace(format, argArray); - } - - @Override - public void trace(Marker marker, String msg, Throwable t) { - trace(msg, t); - } - - @Override - public boolean isDebugEnabled() { - return isLevelEnabled(LogLevel.DEBUG); - } - - @Override - public void debug(String msg) { - debug(msg, new Object[0]); - } - - @Override - public void debug(String format, Object arg) { - debug(format, new Object[] { arg }); - } - - @Override - public void debug(String format, Object arg1, Object arg2) { - debug(format, new Object[] { arg1, arg2 }); - } - - @Override - public void debug(String msg, Throwable t) { - debug(msg, new Object[] { t }); - } - - @Override - public boolean isDebugEnabled(Marker marker) { - return isDebugEnabled(); - } - - @Override - public void debug(Marker marker, String msg) { - debug(msg); - } - - @Override - public void debug(Marker marker, String format, Object arg) { - debug(format, arg); - } - - @Override - public void debug(Marker marker, String format, Object arg1, Object arg2) { - debug(format, arg1, arg2); - } - - @Override - public void debug(Marker marker, String format, Object... arguments) { - debug(format, arguments); - } - - @Override - public void debug(Marker marker, String msg, Throwable t) { - debug(msg, t); - } - - @Override - public boolean isInfoEnabled() { - return isLevelEnabled(LogLevel.INFO); - } - - @Override - public void info(String msg) { - info(msg, new Object[0]); - } - - @Override - public void info(String format, Object arg) { - info(format, new Object[] { arg }); - } - - @Override - public void info(String format, Object arg1, Object arg2) { - info(format, new Object[] { arg1, arg2 }); - } - - @Override - public void info(String msg, Throwable t) { - info(msg, new Object[] { t }); - } - - @Override - public boolean isInfoEnabled(Marker marker) { - return isInfoEnabled(); - } - - @Override - public void info(Marker marker, String msg) { - info(msg); - } - - @Override - public void info(Marker marker, String format, Object arg) { - info(format, arg); - } - - @Override - public void info(Marker marker, String format, Object arg1, Object arg2) { - info(format, arg1, arg2); - } - - @Override - public void info(Marker marker, String format, Object... arguments) { - info(format, arguments); - } - - @Override - public void info(Marker marker, String msg, Throwable t) { - info(msg, t); - } - - @Override - public boolean isWarnEnabled() { - return isLevelEnabled(LogLevel.WARN); - } - - @Override - public void warn(String msg) { - warn(msg, new Object[0]); - } - - @Override - public void warn(String format, Object arg) { - warn(format, new Object[] { arg }); - } - - @Override - public void warn(String format, Object arg1, Object arg2) { - warn(format, new Object[] { arg1, arg2 }); - } - - @Override - public void warn(String msg, Throwable t) { - warn(msg, new Object[] { t }); - } - - @Override - public boolean isWarnEnabled(Marker marker) { - return isWarnEnabled(); - } - - @Override - public void warn(Marker marker, String msg) { - warn(marker); - } - - @Override - public void warn(Marker marker, String format, Object arg) { - warn(format, arg); - } - - @Override - public void warn(Marker marker, String format, Object arg1, Object arg2) { - warn(format, arg1, arg2); - } - - @Override - public void warn(Marker marker, String format, Object... arguments) { - warn(format, arguments); - } - - @Override - public void warn(Marker marker, String msg, Throwable t) { - warn(msg, t); - } - - @Override - public boolean isErrorEnabled() { - return isLevelEnabled(LogLevel.ERROR); - } - - @Override - public void error(String msg) { - error(msg, new Object[0]); - } - - @Override - public void error(String format, Object arg) { - error(format, new Object[] { arg }); - } - - @Override - public void error(String format, Object arg1, Object arg2) { - error(format, new Object[] { arg1, arg2 }); - } - - @Override - public void error(String msg, Throwable t) { - error(msg, new Object[] { t }); - } - - @Override - public boolean isErrorEnabled(Marker marker) { - return isErrorEnabled(); - } - - @Override - public void error(Marker marker, String msg) { - error(msg); - } - - @Override - public void error(Marker marker, String format, Object arg) { - error(format, arg); - } - - @Override - public void error(Marker marker, String format, Object arg1, Object arg2) { - error(format, arg1, arg2); - } - - @Override - public void error(Marker marker, String format, Object... arguments) { - error(format, arguments); - } - - @Override - public void error(Marker marker, String msg, Throwable t) { - error(msg, t); - } + public SimpleLogger(@Nullable String name) { + super(name); + } + + public SimpleLogger() { + super(); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + super.log(level, message, args); + } + + @Override + public void error(@Nullable String message, @Nonnull Object... args) { + super.error(message, args); + } + + @Override + public void error(@Nullable Object message, @Nonnull Object... args) { + super.error(message, args); + } + + @Override + public void warn(@Nullable String message, @Nonnull Object... args) { + super.warn(message, args); + } + + @Override + public void warn(@Nullable Object message, @Nonnull Object... args) { + super.warn(message, args); + } + + @Override + public void info(@Nullable String message, @Nonnull Object... args) { + super.info(message, args); + } + + @Override + public void info(@Nullable Object message, @Nonnull Object... args) { + super.info(message, args); + } + + @Override + public void status(@Nullable String message, @Nonnull Object... args) { + super.status(message, args); + } + + @Override + public void status(@Nullable Object message, @Nonnull Object... args) { + super.status(message, args); + } + + @Override + public void debug(@Nullable String message, @Nonnull Object... args) { + super.debug(message, args); + } + + @Override + public void debug(@Nullable Object message, @Nonnull Object... args) { + super.debug(message, args); + } + + @Override + public void trace(@Nullable String message, @Nonnull Object... args) { + super.trace(message, args); + } + + @Override + public void trace(@Nullable Object message, @Nonnull Object... args) { + super.trace(message, args); + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean isTraceEnabled() { + return isLevelEnabled(LogLevel.TRACE); + } + + @Override + public void trace(String msg) { + trace(msg, new Object[0]); + } + + @Override + public void trace(String format, Object arg) { + trace(format, new Object[]{arg}); + } + + @Override + public void trace(String format, Object arg1, Object arg2) { + trace(format, new Object[]{arg1, arg2}); + } + + @Override + public void trace(String msg, Throwable t) { + trace(msg, new Object[]{t}); + } + + @Override + public boolean isTraceEnabled(Marker marker) { + return isTraceEnabled(); + } + + @Override + public void trace(Marker marker, String msg) { + trace(msg); + } + + @Override + public void trace(Marker marker, String format, Object arg) { + trace(format, arg); + } + + @Override + public void trace(Marker marker, String format, Object arg1, Object arg2) { + trace(format, arg1, arg2); + } + + @Override + public void trace(Marker marker, String format, Object... argArray) { + trace(format, argArray); + } + + @Override + public void trace(Marker marker, String msg, Throwable t) { + trace(msg, t); + } + + @Override + public boolean isDebugEnabled() { + return isLevelEnabled(LogLevel.DEBUG); + } + + @Override + public void debug(String msg) { + debug(msg, new Object[0]); + } + + @Override + public void debug(String format, Object arg) { + debug(format, new Object[]{arg}); + } + + @Override + public void debug(String format, Object arg1, Object arg2) { + debug(format, new Object[]{arg1, arg2}); + } + + @Override + public void debug(String msg, Throwable t) { + debug(msg, new Object[]{t}); + } + + @Override + public boolean isDebugEnabled(Marker marker) { + return isDebugEnabled(); + } + + @Override + public void debug(Marker marker, String msg) { + debug(msg); + } + + @Override + public void debug(Marker marker, String format, Object arg) { + debug(format, arg); + } + + @Override + public void debug(Marker marker, String format, Object arg1, Object arg2) { + debug(format, arg1, arg2); + } + + @Override + public void debug(Marker marker, String format, Object... arguments) { + debug(format, arguments); + } + + @Override + public void debug(Marker marker, String msg, Throwable t) { + debug(msg, t); + } + + @Override + public boolean isInfoEnabled() { + return isLevelEnabled(LogLevel.INFO); + } + + @Override + public void info(String msg) { + info(msg, new Object[0]); + } + + @Override + public void info(String format, Object arg) { + info(format, new Object[]{arg}); + } + + @Override + public void info(String format, Object arg1, Object arg2) { + info(format, new Object[]{arg1, arg2}); + } + + @Override + public void info(String msg, Throwable t) { + info(msg, new Object[]{t}); + } + + @Override + public boolean isInfoEnabled(Marker marker) { + return isInfoEnabled(); + } + + @Override + public void info(Marker marker, String msg) { + info(msg); + } + + @Override + public void info(Marker marker, String format, Object arg) { + info(format, arg); + } + + @Override + public void info(Marker marker, String format, Object arg1, Object arg2) { + info(format, arg1, arg2); + } + + @Override + public void info(Marker marker, String format, Object... arguments) { + info(format, arguments); + } + + @Override + public void info(Marker marker, String msg, Throwable t) { + info(msg, t); + } + + @Override + public boolean isWarnEnabled() { + return isLevelEnabled(LogLevel.WARN); + } + + @Override + public void warn(String msg) { + warn(msg, new Object[0]); + } + + @Override + public void warn(String format, Object arg) { + warn(format, new Object[]{arg}); + } + + @Override + public void warn(String format, Object arg1, Object arg2) { + warn(format, new Object[]{arg1, arg2}); + } + + @Override + public void warn(String msg, Throwable t) { + warn(msg, new Object[]{t}); + } + + @Override + public boolean isWarnEnabled(Marker marker) { + return isWarnEnabled(); + } + + @Override + public void warn(Marker marker, String msg) { + warn(marker); + } + + @Override + public void warn(Marker marker, String format, Object arg) { + warn(format, arg); + } + + @Override + public void warn(Marker marker, String format, Object arg1, Object arg2) { + warn(format, arg1, arg2); + } + + @Override + public void warn(Marker marker, String format, Object... arguments) { + warn(format, arguments); + } + + @Override + public void warn(Marker marker, String msg, Throwable t) { + warn(msg, t); + } + + @Override + public boolean isErrorEnabled() { + return isLevelEnabled(LogLevel.ERROR); + } + + @Override + public void error(String msg) { + error(msg, new Object[0]); + } + + @Override + public void error(String format, Object arg) { + error(format, new Object[]{arg}); + } + + @Override + public void error(String format, Object arg1, Object arg2) { + error(format, new Object[]{arg1, arg2}); + } + + @Override + public void error(String msg, Throwable t) { + error(msg, new Object[]{t}); + } + + @Override + public boolean isErrorEnabled(Marker marker) { + return isErrorEnabled(); + } + + @Override + public void error(Marker marker, String msg) { + error(msg); + } + + @Override + public void error(Marker marker, String format, Object arg) { + error(format, arg); + } + + @Override + public void error(Marker marker, String format, Object arg1, Object arg2) { + error(format, arg1, arg2); + } + + @Override + public void error(Marker marker, String format, Object... arguments) { + error(format, arguments); + } + + @Override + public void error(Marker marker, String msg, Throwable t) { + error(msg, t); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java index cc1b66a52..0462ffdbb 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java @@ -9,165 +9,165 @@ public class Slf4jILoggerWrapper extends MarkerIgnoringBase implements WrappedILogger, Slf4jILogger { - private final ILogger logger; - - public Slf4jILoggerWrapper(@Nonnull ILogger logger) { - this.logger = logger; - } - - @Nonnull - @Override - public ILogger getWrappedLogger() { - return logger; - } - - @Override - public boolean isTraceEnabled() { - return logger.isTraceEnabled(); - } - - @Override - public void trace(String message) { - logger.trace(message); - } - - @Override - public void trace(String message, Object arg) { - logger.trace(message, arg); - } - - @Override - public void trace(String message, Object arg1, Object arg2) { - logger.trace(message, arg1, arg2); - } - - @Override - public void trace(String message, Object... args) { - logger.trace(message, args); - } - - @Override - public void trace(String message, Throwable ex) { - logger.trace(message, ex); - } - - @Override - public boolean isDebugEnabled() { - return logger.isDebugEnabled(); - } - - @Override - public void debug(String message) { - logger.debug(message); - } - - @Override - public void debug(String message, Object arg) { - logger.debug(message, arg); - } - - @Override - public void debug(String message, Object arg1, Object arg2) { - logger.debug(message, arg1, arg2); - } - - @Override - public void debug(String message, Object... args) { - logger.debug(message, args); - } - - @Override - public void debug(String message, Throwable ex) { - logger.debug(message, ex); - } - - @Override - public boolean isInfoEnabled() { - return logger.isInfoEnabled(); - } - - @Override - public void info(String message) { - logger.info(message); - } - - @Override - public void info(String message, Object arg) { - logger.info(message, arg); - } - - @Override - public void info(String message, Object arg1, Object arg2) { - logger.info(message, arg1, arg2); - } - - @Override - public void info(String message, Object... args) { - logger.info(message, args); - } - - @Override - public void info(String message, Throwable ex) { - logger.info(message, ex); - } - - @Override - public boolean isWarnEnabled() { - return logger.isWarnEnabled(); - } - - @Override - public void warn(String message) { - logger.warn(message); - } - - @Override - public void warn(String message, Object arg) { - logger.warn(message, arg); - } - - @Override - public void warn(String message, Object... args) { - logger.warn(message, args); - } - - @Override - public void warn(String message, Object arg1, Object arg2) { - logger.warn(message, arg1, arg2); - } - - @Override - public void warn(String message, Throwable ex) { - logger.warn(message, ex); - } - - @Override - public boolean isErrorEnabled() { - return logger.isWarnEnabled(); - } - - @Override - public void error(String message) { - logger.error(message); - } - - @Override - public void error(String message, Object arg) { - logger.error(message, arg); - } - - @Override - public void error(String message, Object arg1, Object arg2) { - logger.error(message, arg1, arg2); - } - - @Override - public void error(String message, Object... args) { - logger.error(message, args); - } - - @Override - public void error(String message, Throwable ex) { - logger.error(message, ex); - } + private final ILogger logger; + + public Slf4jILoggerWrapper(@Nonnull ILogger logger) { + this.logger = logger; + } + + @Nonnull + @Override + public ILogger getWrappedLogger() { + return logger; + } + + @Override + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + @Override + public void trace(String message) { + logger.trace(message); + } + + @Override + public void trace(String message, Object arg) { + logger.trace(message, arg); + } + + @Override + public void trace(String message, Object arg1, Object arg2) { + logger.trace(message, arg1, arg2); + } + + @Override + public void trace(String message, Object... args) { + logger.trace(message, args); + } + + @Override + public void trace(String message, Throwable ex) { + logger.trace(message, ex); + } + + @Override + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + @Override + public void debug(String message) { + logger.debug(message); + } + + @Override + public void debug(String message, Object arg) { + logger.debug(message, arg); + } + + @Override + public void debug(String message, Object arg1, Object arg2) { + logger.debug(message, arg1, arg2); + } + + @Override + public void debug(String message, Object... args) { + logger.debug(message, args); + } + + @Override + public void debug(String message, Throwable ex) { + logger.debug(message, ex); + } + + @Override + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + @Override + public void info(String message) { + logger.info(message); + } + + @Override + public void info(String message, Object arg) { + logger.info(message, arg); + } + + @Override + public void info(String message, Object arg1, Object arg2) { + logger.info(message, arg1, arg2); + } + + @Override + public void info(String message, Object... args) { + logger.info(message, args); + } + + @Override + public void info(String message, Throwable ex) { + logger.info(message, ex); + } + + @Override + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + @Override + public void warn(String message) { + logger.warn(message); + } + + @Override + public void warn(String message, Object arg) { + logger.warn(message, arg); + } + + @Override + public void warn(String message, Object... args) { + logger.warn(message, args); + } + + @Override + public void warn(String message, Object arg1, Object arg2) { + logger.warn(message, arg1, arg2); + } + + @Override + public void warn(String message, Throwable ex) { + logger.warn(message, ex); + } + + @Override + public boolean isErrorEnabled() { + return logger.isWarnEnabled(); + } + + @Override + public void error(String message) { + logger.error(message); + } + + @Override + public void error(String message, Object arg) { + logger.error(message, arg); + } + + @Override + public void error(String message, Object arg1, Object arg2) { + logger.error(message, arg1, arg2); + } + + @Override + public void error(String message, Object... args) { + logger.error(message, args); + } + + @Override + public void error(String message, Throwable ex) { + logger.error(message, ex); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java index 079877479..567dadc8d 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java @@ -11,359 +11,359 @@ public class Slf4jLoggerWrapper implements Slf4jILogger { - protected final Logger logger; - - public Slf4jLoggerWrapper(@Nonnull Logger logger) { - this.logger = logger; - } - - @Override - public String getName() { - return logger.getName(); - } - - @Override - public boolean isTraceEnabled() { - return logger.isTraceEnabled(); - } - - @Override - public void trace(String msg) { - logger.trace(msg); - } - - @Override - public void trace(String format, Object arg) { - logger.trace(format, arg); - } - - @Override - public void trace(String format, Object arg1, Object arg2) { - logger.trace(format, arg1, arg2); - } - - @Override - public void trace(String format, Object... arguments) { - logger.trace(format, arguments); - } - - @Override - public void trace(String msg, Throwable t) { - logger.trace(msg, t); - } - - @Override - public boolean isTraceEnabled(Marker marker) { - return logger.isTraceEnabled(marker); - } - - @Override - public void trace(Marker marker, String msg) { - logger.trace(marker, msg); - } - - @Override - public void trace(Marker marker, String format, Object arg) { - logger.trace(marker, format, arg); - } - - @Override - public void trace(Marker marker, String format, Object arg1, Object arg2) { - logger.trace(marker, format, arg1, arg2); - } - - @Override - public void trace(Marker marker, String format, Object... argArray) { - logger.trace(marker, format, argArray); - } - - @Override - public void trace(Marker marker, String msg, Throwable t) { - logger.trace(marker, msg, t); - } - - @Override - public boolean isDebugEnabled() { - return logger.isDebugEnabled(); - } - - @Override - public void debug(String msg) { - logger.debug(msg); - } - - @Override - public void debug(String format, Object arg) { - logger.debug(format, arg); - } - - @Override - public void debug(String format, Object arg1, Object arg2) { - logger.debug(format, arg1, arg2); - } - - @Override - public void debug(String format, Object... arguments) { - logger.debug(format, arguments); - } - - @Override - public void debug(String msg, Throwable t) { - logger.debug(msg, t); - } - - @Override - public boolean isDebugEnabled(Marker marker) { - return logger.isDebugEnabled(marker); - } - - @Override - public void debug(Marker marker, String msg) { - logger.debug(marker, msg); - } - - @Override - public void debug(Marker marker, String format, Object arg) { - logger.debug(marker, format, arg); - } - - @Override - public void debug(Marker marker, String format, Object arg1, Object arg2) { - logger.debug(marker, format, arg1, arg2); - } - - @Override - public void debug(Marker marker, String format, Object... arguments) { - logger.debug(marker, format, arguments); - } - - @Override - public void debug(Marker marker, String msg, Throwable t) { - logger.debug(marker, msg, t); - } - - @Override - public boolean isInfoEnabled() { - return logger.isInfoEnabled(); - } - - @Override - public void info(String msg) { - logger.info(msg); - } - - @Override - public void info(String format, Object arg) { - logger.info(format, arg); - } - - @Override - public void info(String format, Object arg1, Object arg2) { - logger.info(format, arg1, arg2); - } - - @Override - public void info(String format, Object... arguments) { - logger.info(format, arguments); - } - - @Override - public void info(String msg, Throwable t) { - logger.info(msg, t); - } - - @Override - public boolean isInfoEnabled(Marker marker) { - return logger.isInfoEnabled(marker); - } - - @Override - public void info(Marker marker, String msg) { - logger.info(marker, msg); - } - - @Override - public void info(Marker marker, String format, Object arg) { - logger.info(marker, format, arg); - } - - @Override - public void info(Marker marker, String format, Object arg1, Object arg2) { - logger.info(marker, format, arg1, arg2); - } - - @Override - public void info(Marker marker, String format, Object... arguments) { - logger.info(marker, format, arguments); - } - - @Override - public void info(Marker marker, String msg, Throwable t) { - logger.info(marker, msg, t); - } - - @Override - public boolean isWarnEnabled() { - return logger.isWarnEnabled(); - } - - @Override - public void warn(String msg) { - logger.warn(msg); - } - - @Override - public void warn(String format, Object arg) { - logger.warn(format, arg); - } - - @Override - public void warn(String format, Object... arguments) { - logger.warn(format, arguments); - } - - @Override - public void warn(String format, Object arg1, Object arg2) { - logger.warn(format, arg1, arg2); - } - - @Override - public void warn(String msg, Throwable t) { - logger.warn(msg, t); - } - - @Override - public boolean isWarnEnabled(Marker marker) { - return logger.isWarnEnabled(marker); - } - - @Override - public void warn(Marker marker, String msg) { - logger.warn(marker, msg); - } - - @Override - public void warn(Marker marker, String format, Object arg) { - logger.warn(marker, format, arg); - } - - @Override - public void warn(Marker marker, String format, Object arg1, Object arg2) { - logger.warn(marker, format, arg1, arg2); - } - - @Override - public void warn(Marker marker, String format, Object... arguments) { - logger.warn(marker, format, arguments); - } - - @Override - public void warn(Marker marker, String msg, Throwable t) { - logger.warn(marker, msg, t); - } - - @Override - public boolean isErrorEnabled() { - return logger.isErrorEnabled(); - } - - @Override - public void error(String msg) { - logger.error(msg); - } - - @Override - public void error(String format, Object arg) { - logger.error(format, arg); - } - - @Override - public void error(String format, Object arg1, Object arg2) { - logger.error(format, arg1, arg2); - } - - @Override - public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { - switch (level) { - case TRACE: - trace(message, args); - return; - case DEBUG: - case EXTENDED: - debug(message, args); - return; - case STATUS: - case INFO: - info(message, args); - return; - case WARN: - warn(message, args); - return; - case ERROR: - error(message, args); - } - } - - @Override - public void error(String format, Object... arguments) { - logger.error(format, arguments); - } - - @Override - public void error(String msg, Throwable t) { - logger.error(msg, t); - } - - @Override - public boolean isErrorEnabled(Marker marker) { - return logger.isErrorEnabled(marker); - } - - @Override - public void error(Marker marker, String msg) { - logger.error(marker, msg); - } - - @Override - public void error(Marker marker, String format, Object arg) { - logger.error(marker, format, arg); - } - - @Override - public void error(Marker marker, String format, Object arg1, Object arg2) { - logger.error(marker, format, arg1, arg2); - } - - @Override - public void error(Marker marker, String format, Object... arguments) { - logger.error(marker, format, arguments); - } - - @Override - public void error(Marker marker, String msg, Throwable t) { - logger.error(marker, msg, t); - } - - @Nonnull - @Override - public LogLevel getMinLevel() { - if (logger.isTraceEnabled()) { - return LogLevel.TRACE; - } else if (logger.isDebugEnabled()) { - return LogLevel.DEBUG; - } else if (logger.isInfoEnabled()) { - return LogLevel.INFO; - } else if (logger.isWarnEnabled()) { - return LogLevel.WARN; - } else { - return LogLevel.ERROR; - } - } - - @Nonnull - @Override - public ILogger setMinLevel(@Nonnull LogLevel level) { - return this; - } + protected final Logger logger; + + public Slf4jLoggerWrapper(@Nonnull Logger logger) { + this.logger = logger; + } + + @Override + public String getName() { + return logger.getName(); + } + + @Override + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + @Override + public void trace(String msg) { + logger.trace(msg); + } + + @Override + public void trace(String format, Object arg) { + logger.trace(format, arg); + } + + @Override + public void trace(String format, Object arg1, Object arg2) { + logger.trace(format, arg1, arg2); + } + + @Override + public void trace(String format, Object... arguments) { + logger.trace(format, arguments); + } + + @Override + public void trace(String msg, Throwable t) { + logger.trace(msg, t); + } + + @Override + public boolean isTraceEnabled(Marker marker) { + return logger.isTraceEnabled(marker); + } + + @Override + public void trace(Marker marker, String msg) { + logger.trace(marker, msg); + } + + @Override + public void trace(Marker marker, String format, Object arg) { + logger.trace(marker, format, arg); + } + + @Override + public void trace(Marker marker, String format, Object arg1, Object arg2) { + logger.trace(marker, format, arg1, arg2); + } + + @Override + public void trace(Marker marker, String format, Object... argArray) { + logger.trace(marker, format, argArray); + } + + @Override + public void trace(Marker marker, String msg, Throwable t) { + logger.trace(marker, msg, t); + } + + @Override + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + @Override + public void debug(String msg) { + logger.debug(msg); + } + + @Override + public void debug(String format, Object arg) { + logger.debug(format, arg); + } + + @Override + public void debug(String format, Object arg1, Object arg2) { + logger.debug(format, arg1, arg2); + } + + @Override + public void debug(String format, Object... arguments) { + logger.debug(format, arguments); + } + + @Override + public void debug(String msg, Throwable t) { + logger.debug(msg, t); + } + + @Override + public boolean isDebugEnabled(Marker marker) { + return logger.isDebugEnabled(marker); + } + + @Override + public void debug(Marker marker, String msg) { + logger.debug(marker, msg); + } + + @Override + public void debug(Marker marker, String format, Object arg) { + logger.debug(marker, format, arg); + } + + @Override + public void debug(Marker marker, String format, Object arg1, Object arg2) { + logger.debug(marker, format, arg1, arg2); + } + + @Override + public void debug(Marker marker, String format, Object... arguments) { + logger.debug(marker, format, arguments); + } + + @Override + public void debug(Marker marker, String msg, Throwable t) { + logger.debug(marker, msg, t); + } + + @Override + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + @Override + public void info(String msg) { + logger.info(msg); + } + + @Override + public void info(String format, Object arg) { + logger.info(format, arg); + } + + @Override + public void info(String format, Object arg1, Object arg2) { + logger.info(format, arg1, arg2); + } + + @Override + public void info(String format, Object... arguments) { + logger.info(format, arguments); + } + + @Override + public void info(String msg, Throwable t) { + logger.info(msg, t); + } + + @Override + public boolean isInfoEnabled(Marker marker) { + return logger.isInfoEnabled(marker); + } + + @Override + public void info(Marker marker, String msg) { + logger.info(marker, msg); + } + + @Override + public void info(Marker marker, String format, Object arg) { + logger.info(marker, format, arg); + } + + @Override + public void info(Marker marker, String format, Object arg1, Object arg2) { + logger.info(marker, format, arg1, arg2); + } + + @Override + public void info(Marker marker, String format, Object... arguments) { + logger.info(marker, format, arguments); + } + + @Override + public void info(Marker marker, String msg, Throwable t) { + logger.info(marker, msg, t); + } + + @Override + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + @Override + public void warn(String msg) { + logger.warn(msg); + } + + @Override + public void warn(String format, Object arg) { + logger.warn(format, arg); + } + + @Override + public void warn(String format, Object... arguments) { + logger.warn(format, arguments); + } + + @Override + public void warn(String format, Object arg1, Object arg2) { + logger.warn(format, arg1, arg2); + } + + @Override + public void warn(String msg, Throwable t) { + logger.warn(msg, t); + } + + @Override + public boolean isWarnEnabled(Marker marker) { + return logger.isWarnEnabled(marker); + } + + @Override + public void warn(Marker marker, String msg) { + logger.warn(marker, msg); + } + + @Override + public void warn(Marker marker, String format, Object arg) { + logger.warn(marker, format, arg); + } + + @Override + public void warn(Marker marker, String format, Object arg1, Object arg2) { + logger.warn(marker, format, arg1, arg2); + } + + @Override + public void warn(Marker marker, String format, Object... arguments) { + logger.warn(marker, format, arguments); + } + + @Override + public void warn(Marker marker, String msg, Throwable t) { + logger.warn(marker, msg, t); + } + + @Override + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } + + @Override + public void error(String msg) { + logger.error(msg); + } + + @Override + public void error(String format, Object arg) { + logger.error(format, arg); + } + + @Override + public void error(String format, Object arg1, Object arg2) { + logger.error(format, arg1, arg2); + } + + @Override + public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + switch (level) { + case TRACE: + trace(message, args); + return; + case DEBUG: + case EXTENDED: + debug(message, args); + return; + case STATUS: + case INFO: + info(message, args); + return; + case WARN: + warn(message, args); + return; + case ERROR: + error(message, args); + } + } + + @Override + public void error(String format, Object... arguments) { + logger.error(format, arguments); + } + + @Override + public void error(String msg, Throwable t) { + logger.error(msg, t); + } + + @Override + public boolean isErrorEnabled(Marker marker) { + return logger.isErrorEnabled(marker); + } + + @Override + public void error(Marker marker, String msg) { + logger.error(marker, msg); + } + + @Override + public void error(Marker marker, String format, Object arg) { + logger.error(marker, format, arg); + } + + @Override + public void error(Marker marker, String format, Object arg1, Object arg2) { + logger.error(marker, format, arg1, arg2); + } + + @Override + public void error(Marker marker, String format, Object... arguments) { + logger.error(marker, format, arguments); + } + + @Override + public void error(Marker marker, String msg, Throwable t) { + logger.error(marker, msg, t); + } + + @Nonnull + @Override + public LogLevel getMinLevel() { + if (logger.isTraceEnabled()) { + return LogLevel.TRACE; + } else if (logger.isDebugEnabled()) { + return LogLevel.DEBUG; + } else if (logger.isInfoEnabled()) { + return LogLevel.INFO; + } else if (logger.isWarnEnabled()) { + return LogLevel.WARN; + } else { + return LogLevel.ERROR; + } + } + + @Nonnull + @Override + public ILogger setMinLevel(@Nonnull LogLevel level) { + return this; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java index 2f4a6067d..f073b4aa0 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java @@ -9,21 +9,21 @@ public class ConstantLoggerFactory implements ILoggerFactory { - protected final ILogger logger; - - public ConstantLoggerFactory(@Nonnull ILogger logger) { - this.logger = logger; - } - - @Nonnull - @Override - public ILogger forName(@Nullable String name) { - return logger; - } - - @Override - public void setDefaultLevel(@Nonnull LogLevel level) { - logger.setMinLevel(level); - } + protected final ILogger logger; + + public ConstantLoggerFactory(@Nonnull ILogger logger) { + this.logger = logger; + } + + @Nonnull + @Override + public ILogger forName(@Nullable String name) { + return logger; + } + + @Override + public void setDefaultLevel(@Nonnull LogLevel level) { + logger.setMinLevel(level); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java index 7825389f4..6ded66533 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java @@ -13,24 +13,24 @@ public class DefaultLoggerFactory implements ILoggerFactory { - protected final Map loggers = new ConcurrentHashMap<>(); - protected final Function creator; - protected LogLevel level = LogLevel.DEBUG; - - public DefaultLoggerFactory(@Nonnull Function creator) { - this.creator = creator; - } - - @Nonnull - @Override - @CheckReturnValue - public synchronized ILogger forName(@Nullable String name) { - return loggers.computeIfAbsent(name == null ? "anonymous" : name, unused -> creator.apply(name).setMinLevel(level)); - } - - @Override - public void setDefaultLevel(@Nonnull LogLevel level) { - this.level = level; - } + protected final Map loggers = new ConcurrentHashMap<>(); + protected final Function creator; + protected LogLevel level = LogLevel.DEBUG; + + public DefaultLoggerFactory(@Nonnull Function creator) { + this.creator = creator; + } + + @Nonnull + @Override + @CheckReturnValue + public synchronized ILogger forName(@Nullable String name) { + return loggers.computeIfAbsent(name == null ? "anonymous" : name, unused -> creator.apply(name).setMinLevel(level)); + } + + @Override + public void setDefaultLevel(@Nonnull LogLevel level) { + this.level = level; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java index e3948466a..5357c563f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java @@ -10,16 +10,16 @@ public class Slf4jLoggerFactory implements ILoggerFactory { - @Nonnull - @Override - public ILogger forName(@Nullable String name) { - return ILogger.forSlf4jLogger( - LoggerFactory.getLogger(name == null ? "Logger" : name) - ); - } + @Nonnull + @Override + public ILogger forName(@Nullable String name) { + return ILogger.forSlf4jLogger( + LoggerFactory.getLogger(name == null ? "Logger" : name) + ); + } - @Override - public void setDefaultLevel(@Nonnull LogLevel level) { - } + @Override + public void setDefaultLevel(@Nonnull LogLevel level) { + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java index fde8ffb8d..e6d559bb5 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java @@ -8,12 +8,12 @@ public abstract class JavaILogger extends Logger implements ILogger { - protected JavaILogger(String name, String resourceBundleName) { - super(name, resourceBundleName); - } + protected JavaILogger(String name, String resourceBundleName) { + super(name, resourceBundleName); + } - @Nonnull - @Override - public abstract JavaILogger setMinLevel(@Nonnull LogLevel level); + @Nonnull + @Override + public abstract JavaILogger setMinLevel(@Nonnull LogLevel level); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java index 05afb6c81..123980c8f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java @@ -8,34 +8,34 @@ public interface Slf4jILogger extends ILogger, Logger { - @Override - boolean isTraceEnabled(); + @Override + boolean isTraceEnabled(); - @Override - boolean isDebugEnabled(); + @Override + boolean isDebugEnabled(); - @Override - boolean isInfoEnabled(); + @Override + boolean isInfoEnabled(); - @Override - boolean isWarnEnabled(); + @Override + boolean isWarnEnabled(); - @Override - boolean isErrorEnabled(); + @Override + boolean isErrorEnabled(); - @Override - void trace(@Nullable String message, @Nonnull Object... args); + @Override + void trace(@Nullable String message, @Nonnull Object... args); - @Override - void debug(@Nullable String message, @Nonnull Object... args); + @Override + void debug(@Nullable String message, @Nonnull Object... args); - @Override - void info(@Nullable String message, @Nonnull Object... args); + @Override + void info(@Nullable String message, @Nonnull Object... args); - @Override - void warn(@Nullable String message, @Nonnull Object... args); + @Override + void warn(@Nullable String message, @Nonnull Object... args); - @Override - void error(@Nullable String message, @Nonnull Object... args); + @Override + void error(@Nullable String message, @Nonnull Object... args); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java index fc9a86c16..cba509034 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java @@ -10,92 +10,94 @@ public final class BukkitReflectionSerializationUtils { - private BukkitReflectionSerializationUtils() {} - - protected static final ILogger logger = ILogger.forThisClass(); - - public static boolean isSerializable(@Nonnull Class clazz) { - try { - clazz.getMethod("serialize"); - return true; - } catch (Throwable ex) { - return false; - } - } - - @Nullable - public static Map serializeObject(@Nonnull Object object) { - Class classOfObject = object.getClass(); - try { - - Method method = classOfObject.getMethod("serialize"); - method.setAccessible(true); - Object serialized = method.invoke(object); - - if (!(serialized instanceof Map)) throw new IllegalArgumentException(method + " does not return a Map"); - - @SuppressWarnings("unchecked") - Map map = (Map) serialized; - return map; - - } catch (Throwable ex) { - logger.error("Could not serialize object of type {}", classOfObject, ex); - return null; - } - } - - @Nullable - @SuppressWarnings("unchecked") - public static T deserializeObject(@Nonnull Map map, @Nullable Class classOfT) { - try { - - Class configurationSerializationClass = Class.forName("org.bukkit.configuration.serialization.ConfigurationSerialization"); - Method method = configurationSerializationClass.getMethod("deserializeObject", Map.class); - method.setAccessible(true); - Object object = method.invoke(null, map); - - return (T) object; - - } catch (Throwable ex) { - } - - if (classOfT == null) - return null; - - try { - - Method method = classOfT.getMethod("deserialize", Map.class); - method.setAccessible(true); - Object object = method.invoke(null, map); - - if (!classOfT.isInstance(object)) throw new IllegalStateException("Deserialization of " + classOfT.getName() + " failed: returned " + (object == null ? null : object.getClass().getName())); - return classOfT.cast(object); - - } catch (Throwable ex) { - logger.error("Could not deserialize object of type {}", classOfT, ex); - return null; - } - } - - @Nonnull - public static String getSerializationName(@Nonnull Class clazz) { - for (Annotation annotation : clazz.getAnnotations()) { - Class annotationType = annotation.annotationType(); - Object value = ReflectionUtils.getAnnotationValue(annotation); - switch (annotationType.getSimpleName()) { - case "DelegateDeserialization": - case "DelegateSerialization": - case "SerializableAs": - if (value instanceof Class) { - return getSerializationName((Class) value); - } else if (value instanceof String) { - return (String) value; - } - break; - } - } - - return clazz.getName(); - } + private BukkitReflectionSerializationUtils() { + } + + protected static final ILogger logger = ILogger.forThisClass(); + + public static boolean isSerializable(@Nonnull Class clazz) { + try { + clazz.getMethod("serialize"); + return true; + } catch (Throwable ex) { + return false; + } + } + + @Nullable + public static Map serializeObject(@Nonnull Object object) { + Class classOfObject = object.getClass(); + try { + + Method method = classOfObject.getMethod("serialize"); + method.setAccessible(true); + Object serialized = method.invoke(object); + + if (!(serialized instanceof Map)) throw new IllegalArgumentException(method + " does not return a Map"); + + @SuppressWarnings("unchecked") + Map map = (Map) serialized; + return map; + + } catch (Throwable ex) { + logger.error("Could not serialize object of type {}", classOfObject, ex); + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static T deserializeObject(@Nonnull Map map, @Nullable Class classOfT) { + try { + + Class configurationSerializationClass = Class.forName("org.bukkit.configuration.serialization.ConfigurationSerialization"); + Method method = configurationSerializationClass.getMethod("deserializeObject", Map.class); + method.setAccessible(true); + Object object = method.invoke(null, map); + + return (T) object; + + } catch (Throwable ex) { + } + + if (classOfT == null) + return null; + + try { + + Method method = classOfT.getMethod("deserialize", Map.class); + method.setAccessible(true); + Object object = method.invoke(null, map); + + if (!classOfT.isInstance(object)) + throw new IllegalStateException("Deserialization of " + classOfT.getName() + " failed: returned " + (object == null ? null : object.getClass().getName())); + return classOfT.cast(object); + + } catch (Throwable ex) { + logger.error("Could not deserialize object of type {}", classOfT, ex); + return null; + } + } + + @Nonnull + public static String getSerializationName(@Nonnull Class clazz) { + for (Annotation annotation : clazz.getAnnotations()) { + Class annotationType = annotation.annotationType(); + Object value = ReflectionUtils.getAnnotationValue(annotation); + switch (annotationType.getSimpleName()) { + case "DelegateDeserialization": + case "DelegateSerialization": + case "SerializableAs": + if (value instanceof Class) { + return getSerializationName((Class) value); + } else if (value instanceof String) { + return (String) value; + } + break; + } + } + + return clazz.getName(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java index b8733488f..2efedc666 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java @@ -26,540 +26,541 @@ public final class FileUtils { - public static final InputStream EMPTY_STREAM = new ByteArrayInputStream(new byte[0]); - private static final Map ZIP_FILE_SYSTEM_PROPERTIES = ImmutableMap - .of("create", "false", "encoding", "UTF-8"); - private static Path tempDirectory; - - private FileUtils() {} - - @Nullable - public static Path getTempDirectory() { - return tempDirectory; - } - - public static void setTempDirectory(@Nullable Path tempDirectory) { - FileUtils.tempDirectory = tempDirectory; - } - - @Nonnull - public static BufferedWriter newBufferedWriter(@Nonnull File file) throws IOException { - return newBufferedWriter(file.toPath()); - } - - @Nonnull - public static BufferedReader newBufferedReader(@Nonnull File file) throws IOException { - return newBufferedReader(file.toPath()); - } - - @Nonnull - public static BufferedWriter newBufferedWriter(@Nonnull Path file) throws IOException { - return Files.newBufferedWriter(file, StandardCharsets.UTF_8); - } - - @Nonnull - public static BufferedReader newBufferedReader(@Nonnull Path file) throws IOException { - return Files.newBufferedReader(file, StandardCharsets.UTF_8); - } - - @Nonnull - public static String getFileExtension(@Nonnull File file) { - return getFileExtension(file.getName()); - } - - @Nonnull - public static String getFileExtension(@Nonnull Path file) { - return getFileExtension(file.toString()); - } - - @Nonnull - public static String getFileExtension(@Nonnull String filename) { - return StringUtils.getAfterLastIndex(filename, ".").toLowerCase(); - } - - @Nonnull - public static String getFileName(@Nonnull File file) { - return getFileName(file.getName()); - } - - @Nonnull - public static String getFileName(@Nonnull Path file) { - return getFileName(file.toString()); - } - - @Nonnull - public static String getFileName(@Nonnull String filename) { - filename = stripFolders(filename); - int index = filename.lastIndexOf('.'); - if (index == -1) return filename; - return filename.substring(0, index); - } - - @Nonnull - @CheckReturnValue - public static String getRealFileName(@Nonnull File file) { - return getRealFileName(file.getName()); - } - - @Nonnull - @CheckReturnValue - public static String getRealFileName(@Nonnull Path file) { - return getRealFileName(file.toString()); - } - - @Nonnull - @CheckReturnValue - public static String getRealFileName(@Nonnull String filename) { - return stripFolders(filename); - } - - @Nonnull - @CheckReturnValue - private static String stripFolders(@Nonnull String filename) { - int index = filename.lastIndexOf(File.pathSeparator); - if (index == -1) return filename; - return filename.substring(index + 1); - } - - public static void createFilesIfNecessary(@Nonnull File file) throws IOException { - if (file.exists()) return; - - if (file.isDirectory()) { - file.mkdirs(); - } else if (file.getParentFile() != null) { - file.getParentFile().mkdirs(); - } - - file.createNewFile(); - } - - public static void deleteWorldFolder(@Nonnull File path) { - if (path.exists()) { - File[] files = path.listFiles(); - if (files == null) return; - for (File currentFile : files) { - if (currentFile.isDirectory()) { - // Don't delete directories or we'Ll minecraft won't create them again - deleteWorldFolder(currentFile); - } else { - if (currentFile.getName().equals("session.lock")) continue; // Don't delete or we'll get lots of exceptions - currentFile.delete(); - } - } - } - } - - public static byte[] toByteArray(@Nullable InputStream inputStream) { - return toByteArray(inputStream, new byte[8192]); - } - - public static byte[] toByteArray(@Nullable InputStream inputStream, byte[] buffer) { - if (inputStream == null) { - return null; - } - - try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { - copy(inputStream, byteArrayOutputStream, buffer); - return byteArrayOutputStream.toByteArray(); - } catch (IOException exception) { - exception.printStackTrace(); - } - - return null; - } - - public static void openZipFileSystem(@Nonnull Path path, @Nonnull ExceptionallyConsumer consumer) { - try (FileSystem fileSystem = FileSystems - .newFileSystem(URI.create("jar:" + path.toUri()), ZIP_FILE_SYSTEM_PROPERTIES)) { - consumer.accept(fileSystem); - } catch (Throwable throwable) { - throwable.printStackTrace(); - } - } - - public static void copy(InputStream inputStream, OutputStream outputStream) throws IOException { - copy(inputStream, outputStream, new byte[8192]); - } - - public static void copy(InputStream inputStream, OutputStream outputStream, byte[] buffer) throws IOException { - copy(inputStream, outputStream, buffer, null); - } - - public static void copy(InputStream inputStream, OutputStream outputStream, byte[] buffer, - Consumer lengthInputListener) throws IOException { - int len; - while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) { - if (lengthInputListener != null) { - lengthInputListener.accept(len); - } - - outputStream.write(buffer, 0, len); - outputStream.flush(); - } - } - - public static void copy(Path from, Path to) throws IOException { - copy(from, to, new byte[8192]); - } - - public static void copy(Path from, Path to, byte[] buffer) throws IOException { - if (from == null || to == null || !Files.exists(from)) { - return; - } - - if (Files.notExists(to)) { - createDirectory(to.getParent()); - } - - try (InputStream stream = Files.newInputStream(from); OutputStream target = Files.newOutputStream(to)) { - copy(stream, target, buffer); - } - } - - public static void copyFilesToDirectory(Path from, Path to) { - walkFileTree(from, (root, current) -> { - if (!Files.isDirectory(current)) { - try { - FileUtils.copy(current, to.resolve(from.relativize(current))); - } catch (IOException exception) { - exception.printStackTrace(); - } - } - }); - } - - public static void copyFilesToDirectory(Path from, Path to, DirectoryStream.Filter filter) { - if (filter == null) { - copyFilesToDirectory(from, to); - } else { - walkFileTree(from, (root, current) -> { - if (!Files.isDirectory(current)) { - try { - FileUtils.copy(current, to.resolve(from.relativize(current))); - } catch (IOException exception) { - exception.printStackTrace(); - } - } - }, true, filter); - } - } - - public static void delete(Path file) { - if (file == null || Files.notExists(file)) { - return; - } - - if (Files.isDirectory(file)) { - walkFileTree(file, (root, current) -> FileUtils.deleteFile(current)); - } - - FileUtils.deleteFile(file); - } - - public static long size(@Nonnull Path path) { - try { - return Files.size(path); - } catch (IOException ex) { - throw new WrappedException(ex); - } - } - - /** - * Converts a bunch of directories to a byte array - * - * @param directories The directories which should get converted - * @return A byte array of a zip file created from the provided directories - * @deprecated May cause a heap space (over)load - */ - @Deprecated - public static byte[] convert(Path... directories) { - if (directories == null) { - return emptyZipByteArray(); - } - - try (ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream()) { - try (ZipOutputStream zipOutputStream = new ZipOutputStream(byteBuffer, StandardCharsets.UTF_8)) { - for (Path directory : directories) { - zipDir(zipOutputStream, directory, null); - } - } - - return byteBuffer.toByteArray(); - - } catch (IOException ex) { - ex.printStackTrace(); - } - - return emptyZipByteArray(); - } - - @Nonnull - public static Path createTempFile() { - if (tempDirectory != null) - return createTempFile(UUID.randomUUID()); - - try { - File file = File.createTempFile(UUID.randomUUID().toString(), null); - file.deleteOnExit(); - return file.toPath(); - } catch (IOException ex) { - throw new WrappedException(ex); - } - } - - @Nonnull - public static Path createTempFile(@Nonnull UUID uuid) { - Preconditions.checkNotNull(tempDirectory, "The temp directory cannot be null"); - Path file = tempDirectory.resolve(uuid.toString()); - createFile(file); - return file; - } - - public static void setAttribute(@Nonnull Path path, @Nonnull String attribute, @Nullable Object value, @Nonnull LinkOption... options) { - try { - Files.setAttribute(path, attribute, value, options); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - - public static void setHiddenAttribute(@Nonnull Path path, boolean hidden) { - setAttribute(path, "dos:hidden", hidden, LinkOption.NOFOLLOW_LINKS); - } - - @Nonnull - public static InputStream zipToStream(@Nonnull Path directory) throws IOException { - return zipToStream(directory, null); - } - - @Nonnull - public static InputStream zipToStream(@Nonnull Path directory, @Nullable Predicate fileFilter) throws IOException { - Path target = createTempFile(); - zipToFile(directory, target, path -> !target.equals(path) && (fileFilter == null || fileFilter.test(path))); - return Files.newInputStream(target, StandardOpenOption.DELETE_ON_CLOSE, LinkOption.NOFOLLOW_LINKS); - } - - @Nullable - public static Path zipToFile(Path directory, Path target) { - return zipToFile(directory, target, null); - } - - @Nullable - public static Path zipToFile(Path directory, Path target, Predicate fileFilter) { - if (directory == null || !Files.exists(directory)) { - return null; - } - - delete(target); - try (OutputStream outputStream = Files.newOutputStream(target, StandardOpenOption.CREATE)) { - zipStream(directory, outputStream, fileFilter); - return target; - } catch (IOException ex) { - ex.printStackTrace(); - } - - return null; - } - - private static void zipStream(Path source, OutputStream buffer, Predicate fileFilter) throws IOException { - try (ZipOutputStream zipOutputStream = new ZipOutputStream(buffer, StandardCharsets.UTF_8)) { - if (Files.exists(source)) { - zipDir(zipOutputStream, source, fileFilter); - } - } - } - - private static void zipDir(ZipOutputStream zipOutputStream, Path directory, Predicate fileFilter) throws IOException { - Files.walkFileTree( - directory, - new SimpleFileVisitor() { - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - if (fileFilter != null && !fileFilter.test(file)) { - return FileVisitResult.CONTINUE; - } - - try { - zipOutputStream.putNextEntry(new ZipEntry(directory.relativize(file).toString().replace("\\", "/"))); - Files.copy(file, zipOutputStream); - zipOutputStream.closeEntry(); - } catch (IOException ex) { - zipOutputStream.closeEntry(); - throw ex; - } - return FileVisitResult.CONTINUE; - } - } - ); - } - - public static Path extract(Path zipPath, Path targetDirectory) throws IOException { - if (zipPath == null || targetDirectory == null || !Files.exists(zipPath)) { - return targetDirectory; - } - - try (InputStream input = Files.newInputStream(zipPath)) { - return extract(input, targetDirectory); - } - } - - public static Path extract(InputStream input, Path targetDirectory) throws IOException { - if (input == null || targetDirectory == null) { - return targetDirectory; - } - - extract0(new ZipInputStream(input, StandardCharsets.UTF_8), targetDirectory); - - return targetDirectory; - } - - public static Path extract(byte[] zipData, Path targetDirectory) throws IOException { - if (zipData == null || zipData.length == 0 || targetDirectory == null) { - return targetDirectory; - } - - try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(zipData)) { - extract0(new ZipInputStream(byteArrayInputStream, StandardCharsets.UTF_8), targetDirectory); - } - - return targetDirectory; - } - - public static void extract0(ZipInputStream zipInputStream, Path targetDirectory) throws IOException { - ZipEntry zipEntry; - while ((zipEntry = zipInputStream.getNextEntry()) != null) { - extractEntry(zipInputStream, zipEntry, targetDirectory); - zipInputStream.closeEntry(); - } - } - - public static byte[] emptyZipByteArray() { - byte[] bytes = null; - - try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { - ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream, StandardCharsets.UTF_8); - zipOutputStream.close(); - - bytes = byteArrayOutputStream.toByteArray(); - } catch (IOException exception) { - exception.printStackTrace(); - } - - return bytes; - } - - private static void extractEntry(ZipInputStream zipInputStream, ZipEntry zipEntry, Path targetDirectory) - throws IOException { - Path file = targetDirectory.resolve(zipEntry.getName()); - ensureChild(targetDirectory, file); - - if (zipEntry.isDirectory()) { - if (!Files.exists(file)) { - Files.createDirectories(file); - } - } else { - Path parent = file.getParent(); - if (!Files.exists(parent)) { - Files.createDirectories(parent); - } - - if (Files.exists(file)) { - Files.delete(file); - } - - Files.createFile(file); - try (OutputStream outputStream = Files.newOutputStream(file)) { - copy(zipInputStream, outputStream); - } - } - } - - public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer) { - walkFileTree(rootDirectoryPath, consumer, true); - } - - public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer, boolean visitDirectories) { - walkFileTree(rootDirectoryPath, consumer, visitDirectories, "*"); - } - - public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer, boolean visitDirectories, - String glob) { - if (Files.notExists(rootDirectoryPath)) { - return; - } - try (DirectoryStream stream = Files.newDirectoryStream(rootDirectoryPath, glob)) { - for (Path path : stream) { - if (Files.isDirectory(path) && visitDirectories) { - walkFileTree(path, consumer, true, glob); - } - consumer.accept(rootDirectoryPath, path); - } - } catch (IOException exception) { - exception.printStackTrace(); - } - } - - public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer, boolean visitDirectories, - DirectoryStream.Filter filter) { - if (Files.notExists(rootDirectoryPath)) { - return; - } - try (DirectoryStream stream = Files.newDirectoryStream(rootDirectoryPath, filter)) { - for (Path path : stream) { - if (Files.isDirectory(path) && visitDirectories) { - walkFileTree(path, consumer, true, filter); - } - consumer.accept(rootDirectoryPath, path); - } - } catch (IOException exception) { - exception.printStackTrace(); - } - } - - public static void createDirectory(@Nullable Path directoryPath) { - if (directoryPath != null && Files.notExists(directoryPath)) { - try { - Files.createDirectories(directoryPath); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - } - - public static void createFile(@Nullable Path filePath) { - if (filePath != null && Files.notExists(filePath)) { - try { - if (filePath.getParent() != null) - Files.createDirectories(filePath.getParent()); - Files.createFile(filePath); - } catch (IOException ex) { - } - } - } - - public static void deleteFile(Path file) { - try { - Files.deleteIfExists(file); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - - private static void ensureChild(Path root, Path child) { - Path rootNormal = root.normalize().toAbsolutePath(); - Path childNormal = child.normalize().toAbsolutePath(); - - if (childNormal.getNameCount() <= rootNormal.getNameCount() || !childNormal.startsWith(rootNormal)) { - throw new IllegalStateException("Child " + childNormal + " is not in root path " + rootNormal); - } - } - - @Nonnull - public static Stream list(@Nonnull Path directory) { - try { - return Files.list(directory); - } catch (IOException ex) { - throw new WrappedException(ex); - } - } + public static final InputStream EMPTY_STREAM = new ByteArrayInputStream(new byte[0]); + private static final Map ZIP_FILE_SYSTEM_PROPERTIES = ImmutableMap + .of("create", "false", "encoding", "UTF-8"); + private static Path tempDirectory; + + private FileUtils() { + } + + @Nullable + public static Path getTempDirectory() { + return tempDirectory; + } + + public static void setTempDirectory(@Nullable Path tempDirectory) { + FileUtils.tempDirectory = tempDirectory; + } + + @Nonnull + public static BufferedWriter newBufferedWriter(@Nonnull File file) throws IOException { + return newBufferedWriter(file.toPath()); + } + + @Nonnull + public static BufferedReader newBufferedReader(@Nonnull File file) throws IOException { + return newBufferedReader(file.toPath()); + } + + @Nonnull + public static BufferedWriter newBufferedWriter(@Nonnull Path file) throws IOException { + return Files.newBufferedWriter(file, StandardCharsets.UTF_8); + } + + @Nonnull + public static BufferedReader newBufferedReader(@Nonnull Path file) throws IOException { + return Files.newBufferedReader(file, StandardCharsets.UTF_8); + } + + @Nonnull + public static String getFileExtension(@Nonnull File file) { + return getFileExtension(file.getName()); + } + + @Nonnull + public static String getFileExtension(@Nonnull Path file) { + return getFileExtension(file.toString()); + } + + @Nonnull + public static String getFileExtension(@Nonnull String filename) { + return StringUtils.getAfterLastIndex(filename, ".").toLowerCase(); + } + + @Nonnull + public static String getFileName(@Nonnull File file) { + return getFileName(file.getName()); + } + + @Nonnull + public static String getFileName(@Nonnull Path file) { + return getFileName(file.toString()); + } + + @Nonnull + public static String getFileName(@Nonnull String filename) { + filename = stripFolders(filename); + int index = filename.lastIndexOf('.'); + if (index == -1) return filename; + return filename.substring(0, index); + } + + @Nonnull + @CheckReturnValue + public static String getRealFileName(@Nonnull File file) { + return getRealFileName(file.getName()); + } + + @Nonnull + @CheckReturnValue + public static String getRealFileName(@Nonnull Path file) { + return getRealFileName(file.toString()); + } + + @Nonnull + @CheckReturnValue + public static String getRealFileName(@Nonnull String filename) { + return stripFolders(filename); + } + + @Nonnull + @CheckReturnValue + private static String stripFolders(@Nonnull String filename) { + int index = filename.lastIndexOf(File.pathSeparator); + if (index == -1) return filename; + return filename.substring(index + 1); + } + + public static void createFilesIfNecessary(@Nonnull File file) throws IOException { + if (file.exists()) return; + + if (file.isDirectory()) { + file.mkdirs(); + } else if (file.getParentFile() != null) { + file.getParentFile().mkdirs(); + } + + file.createNewFile(); + } + + public static void deleteWorldFolder(@Nonnull File path) { + if (path.exists()) { + File[] files = path.listFiles(); + if (files == null) return; + for (File currentFile : files) { + if (currentFile.isDirectory()) { + // Don't delete directories or we'Ll minecraft won't create them again + deleteWorldFolder(currentFile); + } else { + if (currentFile.getName().equals("session.lock")) continue; // Don't delete or we'll get lots of exceptions + currentFile.delete(); + } + } + } + } + + public static byte[] toByteArray(@Nullable InputStream inputStream) { + return toByteArray(inputStream, new byte[8192]); + } + + public static byte[] toByteArray(@Nullable InputStream inputStream, byte[] buffer) { + if (inputStream == null) { + return null; + } + + try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { + copy(inputStream, byteArrayOutputStream, buffer); + return byteArrayOutputStream.toByteArray(); + } catch (IOException exception) { + exception.printStackTrace(); + } + + return null; + } + + public static void openZipFileSystem(@Nonnull Path path, @Nonnull ExceptionallyConsumer consumer) { + try (FileSystem fileSystem = FileSystems + .newFileSystem(URI.create("jar:" + path.toUri()), ZIP_FILE_SYSTEM_PROPERTIES)) { + consumer.accept(fileSystem); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } + } + + public static void copy(InputStream inputStream, OutputStream outputStream) throws IOException { + copy(inputStream, outputStream, new byte[8192]); + } + + public static void copy(InputStream inputStream, OutputStream outputStream, byte[] buffer) throws IOException { + copy(inputStream, outputStream, buffer, null); + } + + public static void copy(InputStream inputStream, OutputStream outputStream, byte[] buffer, + Consumer lengthInputListener) throws IOException { + int len; + while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) { + if (lengthInputListener != null) { + lengthInputListener.accept(len); + } + + outputStream.write(buffer, 0, len); + outputStream.flush(); + } + } + + public static void copy(Path from, Path to) throws IOException { + copy(from, to, new byte[8192]); + } + + public static void copy(Path from, Path to, byte[] buffer) throws IOException { + if (from == null || to == null || !Files.exists(from)) { + return; + } + + if (Files.notExists(to)) { + createDirectory(to.getParent()); + } + + try (InputStream stream = Files.newInputStream(from); OutputStream target = Files.newOutputStream(to)) { + copy(stream, target, buffer); + } + } + + public static void copyFilesToDirectory(Path from, Path to) { + walkFileTree(from, (root, current) -> { + if (!Files.isDirectory(current)) { + try { + FileUtils.copy(current, to.resolve(from.relativize(current))); + } catch (IOException exception) { + exception.printStackTrace(); + } + } + }); + } + + public static void copyFilesToDirectory(Path from, Path to, DirectoryStream.Filter filter) { + if (filter == null) { + copyFilesToDirectory(from, to); + } else { + walkFileTree(from, (root, current) -> { + if (!Files.isDirectory(current)) { + try { + FileUtils.copy(current, to.resolve(from.relativize(current))); + } catch (IOException exception) { + exception.printStackTrace(); + } + } + }, true, filter); + } + } + + public static void delete(Path file) { + if (file == null || Files.notExists(file)) { + return; + } + + if (Files.isDirectory(file)) { + walkFileTree(file, (root, current) -> FileUtils.deleteFile(current)); + } + + FileUtils.deleteFile(file); + } + + public static long size(@Nonnull Path path) { + try { + return Files.size(path); + } catch (IOException ex) { + throw new WrappedException(ex); + } + } + + /** + * Converts a bunch of directories to a byte array + * + * @param directories The directories which should get converted + * @return A byte array of a zip file created from the provided directories + * @deprecated May cause a heap space (over)load + */ + @Deprecated + public static byte[] convert(Path... directories) { + if (directories == null) { + return emptyZipByteArray(); + } + + try (ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream()) { + try (ZipOutputStream zipOutputStream = new ZipOutputStream(byteBuffer, StandardCharsets.UTF_8)) { + for (Path directory : directories) { + zipDir(zipOutputStream, directory, null); + } + } + + return byteBuffer.toByteArray(); + + } catch (IOException ex) { + ex.printStackTrace(); + } + + return emptyZipByteArray(); + } + + @Nonnull + public static Path createTempFile() { + if (tempDirectory != null) + return createTempFile(UUID.randomUUID()); + + try { + File file = File.createTempFile(UUID.randomUUID().toString(), null); + file.deleteOnExit(); + return file.toPath(); + } catch (IOException ex) { + throw new WrappedException(ex); + } + } + + @Nonnull + public static Path createTempFile(@Nonnull UUID uuid) { + Preconditions.checkNotNull(tempDirectory, "The temp directory cannot be null"); + Path file = tempDirectory.resolve(uuid.toString()); + createFile(file); + return file; + } + + public static void setAttribute(@Nonnull Path path, @Nonnull String attribute, @Nullable Object value, @Nonnull LinkOption... options) { + try { + Files.setAttribute(path, attribute, value, options); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + public static void setHiddenAttribute(@Nonnull Path path, boolean hidden) { + setAttribute(path, "dos:hidden", hidden, LinkOption.NOFOLLOW_LINKS); + } + + @Nonnull + public static InputStream zipToStream(@Nonnull Path directory) throws IOException { + return zipToStream(directory, null); + } + + @Nonnull + public static InputStream zipToStream(@Nonnull Path directory, @Nullable Predicate fileFilter) throws IOException { + Path target = createTempFile(); + zipToFile(directory, target, path -> !target.equals(path) && (fileFilter == null || fileFilter.test(path))); + return Files.newInputStream(target, StandardOpenOption.DELETE_ON_CLOSE, LinkOption.NOFOLLOW_LINKS); + } + + @Nullable + public static Path zipToFile(Path directory, Path target) { + return zipToFile(directory, target, null); + } + + @Nullable + public static Path zipToFile(Path directory, Path target, Predicate fileFilter) { + if (directory == null || !Files.exists(directory)) { + return null; + } + + delete(target); + try (OutputStream outputStream = Files.newOutputStream(target, StandardOpenOption.CREATE)) { + zipStream(directory, outputStream, fileFilter); + return target; + } catch (IOException ex) { + ex.printStackTrace(); + } + + return null; + } + + private static void zipStream(Path source, OutputStream buffer, Predicate fileFilter) throws IOException { + try (ZipOutputStream zipOutputStream = new ZipOutputStream(buffer, StandardCharsets.UTF_8)) { + if (Files.exists(source)) { + zipDir(zipOutputStream, source, fileFilter); + } + } + } + + private static void zipDir(ZipOutputStream zipOutputStream, Path directory, Predicate fileFilter) throws IOException { + Files.walkFileTree( + directory, + new SimpleFileVisitor() { + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + if (fileFilter != null && !fileFilter.test(file)) { + return FileVisitResult.CONTINUE; + } + + try { + zipOutputStream.putNextEntry(new ZipEntry(directory.relativize(file).toString().replace("\\", "/"))); + Files.copy(file, zipOutputStream); + zipOutputStream.closeEntry(); + } catch (IOException ex) { + zipOutputStream.closeEntry(); + throw ex; + } + return FileVisitResult.CONTINUE; + } + } + ); + } + + public static Path extract(Path zipPath, Path targetDirectory) throws IOException { + if (zipPath == null || targetDirectory == null || !Files.exists(zipPath)) { + return targetDirectory; + } + + try (InputStream input = Files.newInputStream(zipPath)) { + return extract(input, targetDirectory); + } + } + + public static Path extract(InputStream input, Path targetDirectory) throws IOException { + if (input == null || targetDirectory == null) { + return targetDirectory; + } + + extract0(new ZipInputStream(input, StandardCharsets.UTF_8), targetDirectory); + + return targetDirectory; + } + + public static Path extract(byte[] zipData, Path targetDirectory) throws IOException { + if (zipData == null || zipData.length == 0 || targetDirectory == null) { + return targetDirectory; + } + + try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(zipData)) { + extract0(new ZipInputStream(byteArrayInputStream, StandardCharsets.UTF_8), targetDirectory); + } + + return targetDirectory; + } + + public static void extract0(ZipInputStream zipInputStream, Path targetDirectory) throws IOException { + ZipEntry zipEntry; + while ((zipEntry = zipInputStream.getNextEntry()) != null) { + extractEntry(zipInputStream, zipEntry, targetDirectory); + zipInputStream.closeEntry(); + } + } + + public static byte[] emptyZipByteArray() { + byte[] bytes = null; + + try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { + ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream, StandardCharsets.UTF_8); + zipOutputStream.close(); + + bytes = byteArrayOutputStream.toByteArray(); + } catch (IOException exception) { + exception.printStackTrace(); + } + + return bytes; + } + + private static void extractEntry(ZipInputStream zipInputStream, ZipEntry zipEntry, Path targetDirectory) + throws IOException { + Path file = targetDirectory.resolve(zipEntry.getName()); + ensureChild(targetDirectory, file); + + if (zipEntry.isDirectory()) { + if (!Files.exists(file)) { + Files.createDirectories(file); + } + } else { + Path parent = file.getParent(); + if (!Files.exists(parent)) { + Files.createDirectories(parent); + } + + if (Files.exists(file)) { + Files.delete(file); + } + + Files.createFile(file); + try (OutputStream outputStream = Files.newOutputStream(file)) { + copy(zipInputStream, outputStream); + } + } + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer) { + walkFileTree(rootDirectoryPath, consumer, true); + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer, boolean visitDirectories) { + walkFileTree(rootDirectoryPath, consumer, visitDirectories, "*"); + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer, boolean visitDirectories, + String glob) { + if (Files.notExists(rootDirectoryPath)) { + return; + } + try (DirectoryStream stream = Files.newDirectoryStream(rootDirectoryPath, glob)) { + for (Path path : stream) { + if (Files.isDirectory(path) && visitDirectories) { + walkFileTree(path, consumer, true, glob); + } + consumer.accept(rootDirectoryPath, path); + } + } catch (IOException exception) { + exception.printStackTrace(); + } + } + + public static void walkFileTree(Path rootDirectoryPath, BiConsumer consumer, boolean visitDirectories, + DirectoryStream.Filter filter) { + if (Files.notExists(rootDirectoryPath)) { + return; + } + try (DirectoryStream stream = Files.newDirectoryStream(rootDirectoryPath, filter)) { + for (Path path : stream) { + if (Files.isDirectory(path) && visitDirectories) { + walkFileTree(path, consumer, true, filter); + } + consumer.accept(rootDirectoryPath, path); + } + } catch (IOException exception) { + exception.printStackTrace(); + } + } + + public static void createDirectory(@Nullable Path directoryPath) { + if (directoryPath != null && Files.notExists(directoryPath)) { + try { + Files.createDirectories(directoryPath); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + + public static void createFile(@Nullable Path filePath) { + if (filePath != null && Files.notExists(filePath)) { + try { + if (filePath.getParent() != null) + Files.createDirectories(filePath.getParent()); + Files.createFile(filePath); + } catch (IOException ex) { + } + } + } + + public static void deleteFile(Path file) { + try { + Files.deleteIfExists(file); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + private static void ensureChild(Path root, Path child) { + Path rootNormal = root.normalize().toAbsolutePath(); + Path childNormal = child.normalize().toAbsolutePath(); + + if (childNormal.getNameCount() <= rootNormal.getNameCount() || !childNormal.startsWith(rootNormal)) { + throw new IllegalStateException("Child " + childNormal + " is not in root path " + rootNormal); + } + } + + @Nonnull + public static Stream list(@Nonnull Path directory) { + try { + return Files.list(directory); + } catch (IOException ex) { + throw new WrappedException(ex); + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java index 4f7d07eee..bade80ed0 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java @@ -13,115 +13,116 @@ @SuppressWarnings("unchecked") public final class GsonUtils { - private GsonUtils() {} - - @Nullable - public static Object unpackJsonElement(@Nullable JsonElement element) { - if (element == null || element.isJsonNull()) - return null; - if (element.isJsonObject()) - return convertJsonObjectToMap(element.getAsJsonObject()); - if (element.isJsonArray()) - return convertJsonArrayToStringList(element.getAsJsonArray()); - if (element.isJsonPrimitive()) { - JsonPrimitive primitive = element.getAsJsonPrimitive(); - if (primitive.isNumber()) return primitive.getAsNumber(); - if (primitive.isString()) return primitive.getAsString(); - if (primitive.isBoolean()) return primitive.getAsBoolean(); - } - return element; - } - - @Nullable - public static String convertJsonElementToString(@Nullable JsonElement element) { - if (element == null || element.isJsonNull()) - return null; - if (element.isJsonPrimitive()) { - JsonPrimitive primitive = element.getAsJsonPrimitive(); - if (primitive.isString()) return primitive.getAsString(); - if (primitive.isNumber()) return primitive.getAsNumber() + ""; - if (primitive.isBoolean()) return primitive.getAsBoolean() + ""; - } - return element.toString(); - } - - @Nonnull - public static Map convertJsonObjectToMap(@Nonnull JsonObject object) { - Map map = new LinkedHashMap<>(); - convertJsonObjectToMap(object, map); - return map; - } - - public static void convertJsonObjectToMap(@Nonnull JsonObject object, @Nonnull Map map) { - for (Entry entry : object.entrySet()) { - map.put(entry.getKey(), unpackJsonElement(entry.getValue())); - } - } - - - @Nonnull - public static List convertJsonArrayToStringList(@Nonnull JsonArray array) { - List list = new ArrayList<>(array.size()); - for (JsonElement element : array) { - list.add(convertJsonElementToString(element)); - } - return list; - } - - @Nonnull - public static String[] convertJsonArrayToStringArray(@Nonnull JsonArray array) { - String[] list = new String[array.size()]; - for (int i = 0; i < array.size(); i++) { - list[i] = convertJsonElementToString(array.get(i)); - } - return list; - } - - @Nonnull - public static JsonArray convertIterableToJsonArray(@Nonnull Gson gson, @Nonnull Iterable iterable) { - JsonArray array = new JsonArray(); - iterable.forEach(object -> array.add(gson.toJsonTree(object))); - return array; - } - - @Nonnull - public static JsonArray convertArrayToJsonArray(@Nonnull Gson gson, @Nonnull Object array) { - JsonArray jsonArray = new JsonArray(); - ReflectionUtils.forEachInArray(array, object -> jsonArray.add(gson.toJsonTree(object))); - return jsonArray; - } - - public static void setDocumentProperties(@Nonnull Gson gson, @Nonnull JsonObject object, @Nonnull Map values) { - for (Entry entry : values.entrySet()) { - Object value = entry.getValue(); - - if (value == null) { - object.add(entry.getKey(), null); - } else if (value instanceof JsonElement) { - object.add(entry.getKey(), (JsonElement) value); - } else if (value instanceof Iterable) { - Iterable iterable = (Iterable) value; - object.add(entry.getKey(), convertIterableToJsonArray(gson, iterable)); - } else if (value.getClass().isArray()) { - object.add(entry.getKey(), convertArrayToJsonArray(gson, value)); - } else if (value instanceof Map) { - Map map = (Map) value; - JsonObject newObject = new JsonObject(); - object.add(entry.getKey(), newObject); - setDocumentProperties(gson, newObject, map); - } else { - object.add(entry.getKey(), gson.toJsonTree(value)); - } - } - } - - public static int getSize(@Nonnull JsonObject object) { - try { - return object.size(); - } catch (NoSuchMethodError ignored) { - } - - return object.entrySet().size(); - } + private GsonUtils() { + } + + @Nullable + public static Object unpackJsonElement(@Nullable JsonElement element) { + if (element == null || element.isJsonNull()) + return null; + if (element.isJsonObject()) + return convertJsonObjectToMap(element.getAsJsonObject()); + if (element.isJsonArray()) + return convertJsonArrayToStringList(element.getAsJsonArray()); + if (element.isJsonPrimitive()) { + JsonPrimitive primitive = element.getAsJsonPrimitive(); + if (primitive.isNumber()) return primitive.getAsNumber(); + if (primitive.isString()) return primitive.getAsString(); + if (primitive.isBoolean()) return primitive.getAsBoolean(); + } + return element; + } + + @Nullable + public static String convertJsonElementToString(@Nullable JsonElement element) { + if (element == null || element.isJsonNull()) + return null; + if (element.isJsonPrimitive()) { + JsonPrimitive primitive = element.getAsJsonPrimitive(); + if (primitive.isString()) return primitive.getAsString(); + if (primitive.isNumber()) return primitive.getAsNumber() + ""; + if (primitive.isBoolean()) return primitive.getAsBoolean() + ""; + } + return element.toString(); + } + + @Nonnull + public static Map convertJsonObjectToMap(@Nonnull JsonObject object) { + Map map = new LinkedHashMap<>(); + convertJsonObjectToMap(object, map); + return map; + } + + public static void convertJsonObjectToMap(@Nonnull JsonObject object, @Nonnull Map map) { + for (Entry entry : object.entrySet()) { + map.put(entry.getKey(), unpackJsonElement(entry.getValue())); + } + } + + + @Nonnull + public static List convertJsonArrayToStringList(@Nonnull JsonArray array) { + List list = new ArrayList<>(array.size()); + for (JsonElement element : array) { + list.add(convertJsonElementToString(element)); + } + return list; + } + + @Nonnull + public static String[] convertJsonArrayToStringArray(@Nonnull JsonArray array) { + String[] list = new String[array.size()]; + for (int i = 0; i < array.size(); i++) { + list[i] = convertJsonElementToString(array.get(i)); + } + return list; + } + + @Nonnull + public static JsonArray convertIterableToJsonArray(@Nonnull Gson gson, @Nonnull Iterable iterable) { + JsonArray array = new JsonArray(); + iterable.forEach(object -> array.add(gson.toJsonTree(object))); + return array; + } + + @Nonnull + public static JsonArray convertArrayToJsonArray(@Nonnull Gson gson, @Nonnull Object array) { + JsonArray jsonArray = new JsonArray(); + ReflectionUtils.forEachInArray(array, object -> jsonArray.add(gson.toJsonTree(object))); + return jsonArray; + } + + public static void setDocumentProperties(@Nonnull Gson gson, @Nonnull JsonObject object, @Nonnull Map values) { + for (Entry entry : values.entrySet()) { + Object value = entry.getValue(); + + if (value == null) { + object.add(entry.getKey(), null); + } else if (value instanceof JsonElement) { + object.add(entry.getKey(), (JsonElement) value); + } else if (value instanceof Iterable) { + Iterable iterable = (Iterable) value; + object.add(entry.getKey(), convertIterableToJsonArray(gson, iterable)); + } else if (value.getClass().isArray()) { + object.add(entry.getKey(), convertArrayToJsonArray(gson, value)); + } else if (value instanceof Map) { + Map map = (Map) value; + JsonObject newObject = new JsonObject(); + object.add(entry.getKey(), newObject); + setDocumentProperties(gson, newObject, map); + } else { + object.add(entry.getKey(), gson.toJsonTree(value)); + } + } + } + + public static int getSize(@Nonnull JsonObject object) { + try { + return object.size(); + } catch (NoSuchMethodError ignored) { + } + + return object.entrySet().size(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java index 6be9f8af1..3fed7ad6b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java @@ -16,94 +16,93 @@ public final class ImageUtils { - private ImageUtils() {} - - /** - * @param height The y-position of the text - * @return The width of the text added in pixels - */ - public static int addCenteredText(@Nonnull Graphics2D graphics, @Nonnull String text, int height) { - TextLayout layout = getTextLayout(graphics, text); - int lineWidth = (int) layout.getBounds().getWidth(); - graphics.drawString(text, graphics.getDeviceConfiguration().getBounds().width / 2 - lineWidth / 2, height); - return lineWidth; - - } - - /** - * @return The ending position of the text - */ - public static int addText(@Nonnull Graphics2D graphics, @Nonnull String text, int height, int x) { - TextLayout layout = getTextLayout(graphics, text); - graphics.drawString(text, x, height); - return (int) (x + layout.getBounds().getWidth()); - } - - /** - * @return Returns where the text has started - */ - public static int addTextEndingAt(@Nonnull Graphics2D graphics, @Nonnull String text, int height, int endX) { - TextLayout layout = getTextLayout(graphics, text); - int position = (int) (endX - layout.getBounds().getWidth()); - graphics.drawString(text, position, height); - return position; - } - - /** - * @param height The y-position of the text - */ - public static void addTextEndingAtMid(@Nonnull Graphics2D graphics, @Nonnull String text, int height) { - TextLayout layout = getTextLayout(graphics, text); - int lineWidth = (int) layout.getBounds().getWidth(); - graphics.drawString(text, graphics.getClipBounds().width / 2 - lineWidth, height); - } - - /** - * Reads a image from url using {@link ImageIO#read(InputStream)} and returns it - * - * @param url The URL the image is stored to - * - * @throws IOException - * When something goes wrong while connecting or reading the image - */ - public static BufferedImage loadUrl(@Nonnull String url) throws IOException { - URLConnection connection = IOUtils.createConnection(url); - return ImageIO.read(connection.getInputStream()); - } - - public static BufferedImage loadResource(@Nonnull String path) throws IOException { - InputStream stream = ImageUtils.class.getClassLoader().getResourceAsStream(path); - return ImageIO.read(stream); - } - - public static BufferedImage loadFile(@Nonnull File file) throws IOException { - return ImageIO.read(file); - } - - @Nonnull - public static TextLayout getTextLayout(@Nonnull Graphics2D graphics, @Nonnull String text) { - return new TextLayout(text, graphics.getFont(), graphics.getFontRenderContext()); - } - - public static void darkenImage(@Nonnull BufferedImage image) { - for (int i = 0; i < image.getWidth(); i++) { - for (int j = 0; j < image.getHeight(); j++) { - image.setRGB(i, j, new Color(image.getRGB(i, j)).darker().getRGB()); - } - } - } - - @Nonnull - @CheckReturnValue - public static BufferedImage replaceTransparency(@Nonnull BufferedImage image, @Nullable Color replacementColor) { - if (replacementColor == null) replacementColor = new Color(0, 0, 0, 0); - BufferedImage created = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = created.createGraphics(); - graphics.setColor(replacementColor); - graphics.fillRect(0, 0, image.getWidth(), image.getHeight()); - graphics.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null); - graphics.dispose(); - return created; - } + private ImageUtils() { + } + + /** + * @param height The y-position of the text + * @return The width of the text added in pixels + */ + public static int addCenteredText(@Nonnull Graphics2D graphics, @Nonnull String text, int height) { + TextLayout layout = getTextLayout(graphics, text); + int lineWidth = (int) layout.getBounds().getWidth(); + graphics.drawString(text, graphics.getDeviceConfiguration().getBounds().width / 2 - lineWidth / 2, height); + return lineWidth; + + } + + /** + * @return The ending position of the text + */ + public static int addText(@Nonnull Graphics2D graphics, @Nonnull String text, int height, int x) { + TextLayout layout = getTextLayout(graphics, text); + graphics.drawString(text, x, height); + return (int) (x + layout.getBounds().getWidth()); + } + + /** + * @return Returns where the text has started + */ + public static int addTextEndingAt(@Nonnull Graphics2D graphics, @Nonnull String text, int height, int endX) { + TextLayout layout = getTextLayout(graphics, text); + int position = (int) (endX - layout.getBounds().getWidth()); + graphics.drawString(text, position, height); + return position; + } + + /** + * @param height The y-position of the text + */ + public static void addTextEndingAtMid(@Nonnull Graphics2D graphics, @Nonnull String text, int height) { + TextLayout layout = getTextLayout(graphics, text); + int lineWidth = (int) layout.getBounds().getWidth(); + graphics.drawString(text, graphics.getClipBounds().width / 2 - lineWidth, height); + } + + /** + * Reads a image from url using {@link ImageIO#read(InputStream)} and returns it + * + * @param url The URL the image is stored to + * @throws IOException When something goes wrong while connecting or reading the image + */ + public static BufferedImage loadUrl(@Nonnull String url) throws IOException { + URLConnection connection = IOUtils.createConnection(url); + return ImageIO.read(connection.getInputStream()); + } + + public static BufferedImage loadResource(@Nonnull String path) throws IOException { + InputStream stream = ImageUtils.class.getClassLoader().getResourceAsStream(path); + return ImageIO.read(stream); + } + + public static BufferedImage loadFile(@Nonnull File file) throws IOException { + return ImageIO.read(file); + } + + @Nonnull + public static TextLayout getTextLayout(@Nonnull Graphics2D graphics, @Nonnull String text) { + return new TextLayout(text, graphics.getFont(), graphics.getFontRenderContext()); + } + + public static void darkenImage(@Nonnull BufferedImage image) { + for (int i = 0; i < image.getWidth(); i++) { + for (int j = 0; j < image.getHeight(); j++) { + image.setRGB(i, j, new Color(image.getRGB(i, j)).darker().getRGB()); + } + } + } + + @Nonnull + @CheckReturnValue + public static BufferedImage replaceTransparency(@Nonnull BufferedImage image, @Nullable Color replacementColor) { + if (replacementColor == null) replacementColor = new Color(0, 0, 0, 0); + BufferedImage created = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics = created.createGraphics(); + graphics.setColor(replacementColor); + graphics.fillRect(0, 0, image.getWidth(), image.getHeight()); + graphics.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null); + graphics.dispose(); + return created; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/MathHelper.java b/plugin/src/main/java/net/codingarea/commons/common/misc/MathHelper.java index 1663748b7..b36a410ca 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/MathHelper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/MathHelper.java @@ -2,11 +2,12 @@ public final class MathHelper { - private MathHelper() {} + private MathHelper() { + } - public static double percentage(double total, double proportion) { - if (proportion == 0) return 0; - return (proportion * 100) / total; - } + public static double percentage(double total, double proportion) { + if (proportion == 0) return 0; + return (proportion * 100) / total; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java index 8b84e8f64..5db7e5452 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java @@ -7,12 +7,13 @@ public final class PropertiesUtils { - private PropertiesUtils() {} + private PropertiesUtils() { + } - public static void setProperties(@Nonnull Properties properties, @Nonnull Map map) { - for (Entry entry : properties.entrySet()) { - map.put((String) entry.getKey(), entry.getValue()); - } - } + public static void setProperties(@Nonnull Properties properties, @Nonnull Map map) { + for (Entry entry : properties.entrySet()) { + map.put((String) entry.getKey(), entry.getValue()); + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java index c4d997ff9..6af4038bc 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java @@ -19,91 +19,90 @@ public final class ReflectionUtils { - private ReflectionUtils() {} - - @Nonnull - public static Collection getPublicMethodsAnnotatedWith(@Nonnull Class clazz, @Nonnull Class classOfAnnotation) { - List annotatedMethods = new ArrayList<>(); - for (Method method : clazz.getMethods()) { - if (!method.isAnnotationPresent(classOfAnnotation)) continue; - annotatedMethods.add(method); - } - return annotatedMethods; - } - - @Nonnull - public static Collection getMethodsAnnotatedWith(@Nonnull Class clazz, @Nonnull Class classOfAnnotation) { - List annotatedMethods = new ArrayList<>(); - for (Class currentClass : ClassWalker.walk(clazz)) { - for (Method method : currentClass.getDeclaredMethods()) { - if (!method.isAnnotationPresent(classOfAnnotation)) continue; - annotatedMethods.add(method); - } - } - return annotatedMethods; - } - - @Nonnull - public static Method getInheritedPrivateMethod(@Nonnull Class clazz, @Nonnull String name, @Nonnull Class... parameterTypes) throws NoSuchMethodException { - for (Class current : ClassWalker.walk(clazz)) { - try { - return current.getDeclaredMethod(name, parameterTypes); - } catch (Throwable ex) { - } - } - - throw new NoSuchMethodException(name); - } - - @Nonnull - public static Field getInheritedPrivateField(@Nonnull Class clazz, @Nonnull String name) throws NoSuchFieldException { - for (Class current : ClassWalker.walk(clazz)) { - try { - return current.getDeclaredField(name); - } catch (Throwable ex) { - } - } - - throw new NoSuchFieldException(name); - } - - /** - * @param classOfEnum The class containing the enum constants - * @return The first enum found by the given names - */ - @Nonnull - public static > E getFirstEnumByNames(@Nonnull Class classOfEnum, @Nonnull String... names) { - for (String name : names) { - try { - return Enum.valueOf(classOfEnum, name); - } catch (IllegalArgumentException | NoSuchFieldError ex) { } - } - throw new IllegalArgumentException("No enum found in " + classOfEnum.getName() + " for " + Arrays.toString(names)); - } - - /** - * Iterates through an array which may contain primitive data types or non primitive data types and performs the given action on each element. - * Because we can't just cast such an array to {@code Object[]}, we have to use some reflections. - * - * @param array The target array, as {@link Object}; Can't use an array type here. - * @param The type of data we will cast the content to. Use {@link Object} if the it's unknown. - * - * @throws IllegalArgumentException - * If the {@code array} is not an actual array - * - * @see Array - * @see Array#getLength(Object) - * @see Array#get(Object, int) - */ - public static void forEachInArray(@Nonnull Object array, @Nonnull Consumer action) { - ReflectionUtils.iterableArray(array).forEach(action); - } - - @Nonnull - @CheckReturnValue - public static Iterable iterableArray(@Nonnull Object array) { - return ArrayWalker.walk(array); - } + private ReflectionUtils() { + } + + @Nonnull + public static Collection getPublicMethodsAnnotatedWith(@Nonnull Class clazz, @Nonnull Class classOfAnnotation) { + List annotatedMethods = new ArrayList<>(); + for (Method method : clazz.getMethods()) { + if (!method.isAnnotationPresent(classOfAnnotation)) continue; + annotatedMethods.add(method); + } + return annotatedMethods; + } + + @Nonnull + public static Collection getMethodsAnnotatedWith(@Nonnull Class clazz, @Nonnull Class classOfAnnotation) { + List annotatedMethods = new ArrayList<>(); + for (Class currentClass : ClassWalker.walk(clazz)) { + for (Method method : currentClass.getDeclaredMethods()) { + if (!method.isAnnotationPresent(classOfAnnotation)) continue; + annotatedMethods.add(method); + } + } + return annotatedMethods; + } + + @Nonnull + public static Method getInheritedPrivateMethod(@Nonnull Class clazz, @Nonnull String name, @Nonnull Class... parameterTypes) throws NoSuchMethodException { + for (Class current : ClassWalker.walk(clazz)) { + try { + return current.getDeclaredMethod(name, parameterTypes); + } catch (Throwable ex) { + } + } + + throw new NoSuchMethodException(name); + } + + @Nonnull + public static Field getInheritedPrivateField(@Nonnull Class clazz, @Nonnull String name) throws NoSuchFieldException { + for (Class current : ClassWalker.walk(clazz)) { + try { + return current.getDeclaredField(name); + } catch (Throwable ex) { + } + } + + throw new NoSuchFieldException(name); + } + + /** + * @param classOfEnum The class containing the enum constants + * @return The first enum found by the given names + */ + @Nonnull + public static > E getFirstEnumByNames(@Nonnull Class classOfEnum, @Nonnull String... names) { + for (String name : names) { + try { + return Enum.valueOf(classOfEnum, name); + } catch (IllegalArgumentException | NoSuchFieldError ex) { + } + } + throw new IllegalArgumentException("No enum found in " + classOfEnum.getName() + " for " + Arrays.toString(names)); + } + + /** + * Iterates through an array which may contain primitive data types or non primitive data types and performs the given action on each element. + * Because we can't just cast such an array to {@code Object[]}, we have to use some reflections. + * + * @param array The target array, as {@link Object}; Can't use an array type here. + * @param The type of data we will cast the content to. Use {@link Object} if the it's unknown. + * @throws IllegalArgumentException If the {@code array} is not an actual array + * @see Array + * @see Array#getLength(Object) + * @see Array#get(Object, int) + */ + public static void forEachInArray(@Nonnull Object array, @Nonnull Consumer action) { + ReflectionUtils.iterableArray(array).forEach(action); + } + + @Nonnull + @CheckReturnValue + public static Iterable iterableArray(@Nonnull Object array) { + return ArrayWalker.walk(array); + } @CheckReturnValue public static Class getCaller() { @@ -116,139 +115,138 @@ public static Class getCaller() { ); } - @Nonnull - public static String getCallerName() { - StackTraceElement[] trace = Thread.currentThread().getStackTrace(); - StackTraceElement element = trace[3]; - - String className = StringUtils.getAfterLastIndex(element.getClassName(), "."); - return className + "." + element.getMethodName(); - } - - /** - * Takes a {@link Enum} and returns the corresponding {@link Field} using {@link Class#getField(String)} - * - * @see Class#getField(String) - */ - @Nonnull - public static Field getEnumAsField(@Nonnull Enum enun) { - Class classOfEnum = enun.getClass(); - - try { - return classOfEnum.getField(enun.name()); - } catch (NoSuchFieldException ex) { - throw new WrappedException(ex); - } - } - - /** - * @see Field#getAnnotations() - */ - @Nonnull - public static > Annotation[] getEnumAnnotations(@Nonnull E enun) { - Field field = getEnumAsField(enun); - return field.getAnnotations(); - } - - /** - * @return Returns {@code null} if no annotation of this class is present - * - * @see Field#getAnnotation(Class) - */ - public static , A extends Annotation> A getEnumAnnotation(@Nonnull E enun, Class classOfAnnotation) { - Field field = getEnumAsField(enun); - return field.getAnnotation(classOfAnnotation); - } - - @Nullable - public static > E getEnumOrNull(@Nullable String name, @Nonnull Class classOfEnum) { - try { - if (name == null) return null; - return Enum.valueOf(classOfEnum, name); - } catch (Exception ex) { - return null; - } - } - - @Nullable - @SuppressWarnings("unchecked") - public static Class getClassOrNull(@Nullable String name) { - try { - if (name == null) return null; - return (Class) Class.forName(name); - } catch (Exception ex) { - return null; - } - } - - @Nullable - @SuppressWarnings("unchecked") - public static Class getClassOrNull(@Nullable String name, boolean initialize, @Nonnull ClassLoader classLoader) { - try { - if (name == null) return null; - return (Class) Class.forName(name, initialize, classLoader); - } catch (Exception ex) { - return null; - } - } - - @Nullable - @SuppressWarnings("unchecked") - public static T invokeMethodOrNull(@Nullable Object instance, @Nonnull Method method) { - try { - if (!method.isAccessible()) method.setAccessible(true); - return (T) method.invoke(instance); - } catch (Throwable ex) { - return null; - } - } - - @Nullable - public static T invokeStaticMethodOrNull(@Nonnull Class clazz, @Nonnull String method) { - try { - return invokeMethodOrNull(null, clazz.getMethod(method)); - } catch (NoSuchMethodException ex) { - return null; - } - } - - @Nullable - public static T invokeMethodOrNull(@Nonnull Object instance, @Nonnull String method) { - try { - return invokeMethodOrNull(instance, instance.getClass().getDeclaredMethod(method)); - } catch (NoSuchMethodException ex) { - return null; - } - } - - @Nullable - public static T getAnnotationValue(@Nonnull Annotation annotation) { - return invokeMethodOrNull(annotation, "value"); - } - - @Nullable - public static > E getEnumByAlternateNames(@Nonnull Class classOfE, @Nonnull String input) { - E[] values = invokeStaticMethodOrNull(classOfE, "values"); - String[] methodNames = { "getName", "getNames", "getAlias", "getAliases", "getKey", "getKeys", "name", "toString", "ordinal", "getId", "id" }; - for (E value : values) { - for (String method : methodNames) { - if (check(input, invokeMethodOrNull(value, method))) - return value; - } - } - - return null; - } - - private static boolean check(@Nonnull String input, @Nullable Object value) { - if (value == null) return false; - if (value.getClass().isArray()) { - for (Object key : iterableArray(value)) { - if (input.equalsIgnoreCase(String.valueOf(key))) - return true; - } - } - return input.equalsIgnoreCase(String.valueOf(value)); - } + @Nonnull + public static String getCallerName() { + StackTraceElement[] trace = Thread.currentThread().getStackTrace(); + StackTraceElement element = trace[3]; + + String className = StringUtils.getAfterLastIndex(element.getClassName(), "."); + return className + "." + element.getMethodName(); + } + + /** + * Takes a {@link Enum} and returns the corresponding {@link Field} using {@link Class#getField(String)} + * + * @see Class#getField(String) + */ + @Nonnull + public static Field getEnumAsField(@Nonnull Enum enun) { + Class classOfEnum = enun.getClass(); + + try { + return classOfEnum.getField(enun.name()); + } catch (NoSuchFieldException ex) { + throw new WrappedException(ex); + } + } + + /** + * @see Field#getAnnotations() + */ + @Nonnull + public static > Annotation[] getEnumAnnotations(@Nonnull E enun) { + Field field = getEnumAsField(enun); + return field.getAnnotations(); + } + + /** + * @return Returns {@code null} if no annotation of this class is present + * @see Field#getAnnotation(Class) + */ + public static , A extends Annotation> A getEnumAnnotation(@Nonnull E enun, Class classOfAnnotation) { + Field field = getEnumAsField(enun); + return field.getAnnotation(classOfAnnotation); + } + + @Nullable + public static > E getEnumOrNull(@Nullable String name, @Nonnull Class classOfEnum) { + try { + if (name == null) return null; + return Enum.valueOf(classOfEnum, name); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static Class getClassOrNull(@Nullable String name) { + try { + if (name == null) return null; + return (Class) Class.forName(name); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static Class getClassOrNull(@Nullable String name, boolean initialize, @Nonnull ClassLoader classLoader) { + try { + if (name == null) return null; + return (Class) Class.forName(name, initialize, classLoader); + } catch (Exception ex) { + return null; + } + } + + @Nullable + @SuppressWarnings("unchecked") + public static T invokeMethodOrNull(@Nullable Object instance, @Nonnull Method method) { + try { + if (!method.isAccessible()) method.setAccessible(true); + return (T) method.invoke(instance); + } catch (Throwable ex) { + return null; + } + } + + @Nullable + public static T invokeStaticMethodOrNull(@Nonnull Class clazz, @Nonnull String method) { + try { + return invokeMethodOrNull(null, clazz.getMethod(method)); + } catch (NoSuchMethodException ex) { + return null; + } + } + + @Nullable + public static T invokeMethodOrNull(@Nonnull Object instance, @Nonnull String method) { + try { + return invokeMethodOrNull(instance, instance.getClass().getDeclaredMethod(method)); + } catch (NoSuchMethodException ex) { + return null; + } + } + + @Nullable + public static T getAnnotationValue(@Nonnull Annotation annotation) { + return invokeMethodOrNull(annotation, "value"); + } + + @Nullable + public static > E getEnumByAlternateNames(@Nonnull Class classOfE, @Nonnull String input) { + E[] values = invokeStaticMethodOrNull(classOfE, "values"); + String[] methodNames = {"getName", "getNames", "getAlias", "getAliases", "getKey", "getKeys", "name", "toString", "ordinal", "getId", "id"}; + for (E value : values) { + for (String method : methodNames) { + if (check(input, invokeMethodOrNull(value, method))) + return value; + } + } + + return null; + } + + private static boolean check(@Nonnull String input, @Nullable Object value) { + if (value == null) return false; + if (value.getClass().isArray()) { + for (Object key : iterableArray(value)) { + if (input.equalsIgnoreCase(String.valueOf(key))) + return true; + } + } + return input.equalsIgnoreCase(String.valueOf(value)); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java index 66faae82d..e737ce0ec 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java @@ -11,133 +11,134 @@ public final class SimpleCollectionUtils { - @Deprecated - public static final String REGEX_1 = ",", - REGEX_2 = "="; - private static final ILogger logger = ILogger.forThisClass(); - private static boolean logMappingError = true; - - private SimpleCollectionUtils() {} - - public static void disableErrorLogging() { - logMappingError = false; - } - - /** - * You should not use this to serialize maps due to it's unsafe because of strings which may contain the regex chars = or , - * Use better and safer serialization strategies like json. - * - * @deprecated Unsafe because of strings containing , or = - */ - @Nonnull - @Deprecated - @CheckReturnValue - public static String convertMapToString(@Nonnull Map map, @Nonnull Function key, @Nonnull Function value) { - StringBuilder builder = new StringBuilder(); - for (Entry entry : map.entrySet()) { - if (builder.length() != 0) builder.append(REGEX_1); - builder.append(key.apply(entry.getKey())); - builder.append(REGEX_2); - builder.append(value.apply(entry.getValue())); - } - return builder.toString(); - } - - /** - * You should not use this to serialize maps due to it's unsafe because of strings which may contain the regex chars = or , - * Use better and safer serialization strategies like json. - * - * @deprecated Unsafe because of strings containing , or = - */ - @Nonnull - @Deprecated - @CheckReturnValue - public static Map convertStringToMap(@Nullable String string, @Nonnull Function key, @Nonnull Function value) { - - Map map = new HashMap<>(); - if (string == null) return map; - - String[] args = string.split(REGEX_1); - for (String arg : args) { - try { - - String[] elements = arg.split(REGEX_2); - K keyElement = key.apply(elements[0]); - V valueElement = value.apply(elements[1]); - - if (keyElement == null || valueElement == null) - throw new NullPointerException(); - - map.put(keyElement, valueElement); - - } catch (Exception ex) { - if (logMappingError) - logger.error("Cannot generate key/value: " + ex.getClass().getName() + ": " + ex.getMessage()); - } - } - - return map; - - } - - @Nonnull - @CheckReturnValue - public static Map convertMap(@Nonnull Map map, - @Nonnull Function keyMapper, - @Nonnull Function valueMapper) { - Map result = new HashMap<>(); - map.forEach((key, value) -> { - try { - result.put(keyMapper.apply(key), valueMapper.apply(value)); - } catch (Exception ex) { - if (logMappingError) - logger.error("Unable to map '{}'='{}'", key, value, ex); - } - }); - return result; - } - - @Nonnull - @CheckReturnValue - public static List convert(@Nonnull Collection collection, - @Nonnull Function mapper) { - List result = new ArrayList<>(collection.size()); - collection.forEach(value -> { - try { - result.add(mapper.apply(value)); - } catch (Exception ex) { - if (logMappingError) - logger.error("Unable map '{}'", value, ex); - } - }); - return result; - } - - public static V getMostFrequentValue(@Nonnull Map map) { - Collection values = map.values(); - List list = new ArrayList<>(values); - Set set = new HashSet<>(values); - - V valueMax = null; - int max = 0; - for (V value : set) { - int frequency = Collections.frequency(list, value); - if (frequency > max) { - max = frequency; - valueMax = value; - } - } - - return valueMax; - } - - @SafeVarargs - public static Set setOf(@Nonnull Collection... collections) { - Set set = new HashSet<>(); - for (Collection collection : collections) { - set.addAll(collection); - } - return set; - } + @Deprecated + public static final String REGEX_1 = ",", + REGEX_2 = "="; + private static final ILogger logger = ILogger.forThisClass(); + private static boolean logMappingError = true; + + private SimpleCollectionUtils() { + } + + public static void disableErrorLogging() { + logMappingError = false; + } + + /** + * You should not use this to serialize maps due to it's unsafe because of strings which may contain the regex chars = or , + * Use better and safer serialization strategies like json. + * + * @deprecated Unsafe because of strings containing , or = + */ + @Nonnull + @Deprecated + @CheckReturnValue + public static String convertMapToString(@Nonnull Map map, @Nonnull Function key, @Nonnull Function value) { + StringBuilder builder = new StringBuilder(); + for (Entry entry : map.entrySet()) { + if (builder.length() != 0) builder.append(REGEX_1); + builder.append(key.apply(entry.getKey())); + builder.append(REGEX_2); + builder.append(value.apply(entry.getValue())); + } + return builder.toString(); + } + + /** + * You should not use this to serialize maps due to it's unsafe because of strings which may contain the regex chars = or , + * Use better and safer serialization strategies like json. + * + * @deprecated Unsafe because of strings containing , or = + */ + @Nonnull + @Deprecated + @CheckReturnValue + public static Map convertStringToMap(@Nullable String string, @Nonnull Function key, @Nonnull Function value) { + + Map map = new HashMap<>(); + if (string == null) return map; + + String[] args = string.split(REGEX_1); + for (String arg : args) { + try { + + String[] elements = arg.split(REGEX_2); + K keyElement = key.apply(elements[0]); + V valueElement = value.apply(elements[1]); + + if (keyElement == null || valueElement == null) + throw new NullPointerException(); + + map.put(keyElement, valueElement); + + } catch (Exception ex) { + if (logMappingError) + logger.error("Cannot generate key/value: " + ex.getClass().getName() + ": " + ex.getMessage()); + } + } + + return map; + + } + + @Nonnull + @CheckReturnValue + public static Map convertMap(@Nonnull Map map, + @Nonnull Function keyMapper, + @Nonnull Function valueMapper) { + Map result = new HashMap<>(); + map.forEach((key, value) -> { + try { + result.put(keyMapper.apply(key), valueMapper.apply(value)); + } catch (Exception ex) { + if (logMappingError) + logger.error("Unable to map '{}'='{}'", key, value, ex); + } + }); + return result; + } + + @Nonnull + @CheckReturnValue + public static List convert(@Nonnull Collection collection, + @Nonnull Function mapper) { + List result = new ArrayList<>(collection.size()); + collection.forEach(value -> { + try { + result.add(mapper.apply(value)); + } catch (Exception ex) { + if (logMappingError) + logger.error("Unable map '{}'", value, ex); + } + }); + return result; + } + + public static V getMostFrequentValue(@Nonnull Map map) { + Collection values = map.values(); + List list = new ArrayList<>(values); + Set set = new HashSet<>(values); + + V valueMax = null; + int max = 0; + for (V value : set) { + int frequency = Collections.frequency(list, value); + if (frequency > max) { + max = frequency; + valueMax = value; + } + } + + return valueMax; + } + + @SafeVarargs + public static Set setOf(@Nonnull Collection... collections) { + Set set = new HashSet<>(); + for (Collection collection : collections) { + set.addAll(collection); + } + return set; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java index fdae424a0..3ad7f7e18 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java @@ -12,170 +12,177 @@ public final class StringUtils { - private static final ILogger logger = ILogger.forThisClass(); - - private StringUtils() {} - - @Nonnull - public static String getEnumName(@Nonnull Enum enun) { - return getEnumName(enun.name()); - } - - @Nonnull - public static String getEnumName(@Nonnull String name) { - StringBuilder builder = new StringBuilder(); - boolean nextUpperCase = true; - for (char letter : name.toCharArray()) { - // Replace _ with space - if (letter == '_') { - builder.append(' '); - nextUpperCase = true; - continue; - } - builder.append(nextUpperCase ? Character.toUpperCase(letter) : Character.toLowerCase(letter)); - nextUpperCase = false; - } - return builder.toString(); - } - - @Nonnull - public static String format(@Nonnull String sequence, @Nonnull Object... args) { - char start = '{', end = '}'; - boolean inArgument = false; - StringBuilder argument = new StringBuilder(); - StringBuilder builder = new StringBuilder(); - for (char c : sequence.toCharArray()) { - if (c == end && inArgument) { - inArgument = false; - try { - int arg = Integer.parseInt(argument.toString()); - Object current = args[arg]; - Object replacement = - current instanceof Supplier ? ((Supplier)current).get() : - current instanceof Callable ? ((Callable)current).call() : - current; - builder.append(replacement); - } catch (NumberFormatException | IndexOutOfBoundsException ex) { - logger.warn("Invalid argument index '{}'", argument); - builder.append(start).append(argument).append(end); - } catch (Exception ex) { - throw new WrappedException(ex); - } - argument = new StringBuilder(); - continue; - } - if (c == start && !inArgument) { - inArgument = true; - continue; - } - if (inArgument) { - argument.append(c); - continue; - } - builder.append(c); - } - if (argument.length() > 0) builder.append(start).append(argument); - return builder.toString(); - } - - @Nonnull - public static String getAfterLastIndex(@Nonnull String input, @Nonnull String separator) { - return Optional.of(input) - .filter(name -> name.contains(separator)) - .map(name -> name.substring(name.lastIndexOf(separator) + separator.length())) - .orElse(""); - } - - @Nonnull - public static String[] format(@Nonnull String[] array, @Nonnull Object... args) { - String[] result = new String[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = format(array[i], args); - } - return result; - } - - @Nonnull - public static String getArrayAsString(@Nonnull String[] array, @Nonnull String separator) { - StringBuilder builder = new StringBuilder(); - for (String string : array) { - if (builder.length() != 0) builder.append(separator); - builder.append(string); - } - return builder.toString(); - } - - @Nonnull - public static String[] getStringAsArray(@Nonnull String string) { - return string.split("\n"); - } - - @Nonnull - public static String getIterableAsString(@Nonnull Iterable iterable, @Nonnull String separator, @Nonnull Function mapper) { - StringBuilder builder = new StringBuilder(); - for (T t : iterable) { - if (builder.length() > 0) builder.append(separator); - String string = mapper.apply(t); - builder.append(string); - } - return builder.toString(); - } - - @Nonnull - public static String repeat(@Nullable Object sequence, int amount) { - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < amount; i++) builder.append(sequence); - return builder.toString(); - } - - private static int getMultiplier(char c) { - switch (Character.toLowerCase(c)) { - default: return 1; - case 'm': return 60; - case 'h': return 60*60; - case 'd': return 24*60*60; - case 'w': return 7*24*60*60; - case 'y': return 365*24*60*60; - } - } - - public static long parseSeconds(@Nonnull String input) { - if (input.toLowerCase().startsWith("perm")) return -1; - long current = 0; - long seconds = 0; - for (char c : input.toCharArray()) { - try { - long i = Long.parseUnsignedLong(String.valueOf(c)); - current *= 10; - current += i; - } catch (Exception ignored) { - int multiplier = getMultiplier(c); - seconds += current * multiplier; - current = 0; - } - } - seconds += current; - return seconds; - } - - public static boolean isNumber(@Nonnull String sequence) { - try { - Double.parseDouble(sequence); - return true; - } catch (Exception ex) { - return false; - } - } - - private static int indexOf(@Nonnull String string, @Nonnull String pattern, int occurrenceIndex) { - int lastIndex = 0; - for (int currentLayer = 0; currentLayer <= occurrenceIndex; currentLayer++) { - int index = string.indexOf(pattern, (lastIndex > 0) ? lastIndex + 1 : 0); - if (index == -1) return -1; - lastIndex = index + 1; - } - - return lastIndex; - } + private static final ILogger logger = ILogger.forThisClass(); + + private StringUtils() { + } + + @Nonnull + public static String getEnumName(@Nonnull Enum enun) { + return getEnumName(enun.name()); + } + + @Nonnull + public static String getEnumName(@Nonnull String name) { + StringBuilder builder = new StringBuilder(); + boolean nextUpperCase = true; + for (char letter : name.toCharArray()) { + // Replace _ with space + if (letter == '_') { + builder.append(' '); + nextUpperCase = true; + continue; + } + builder.append(nextUpperCase ? Character.toUpperCase(letter) : Character.toLowerCase(letter)); + nextUpperCase = false; + } + return builder.toString(); + } + + @Nonnull + public static String format(@Nonnull String sequence, @Nonnull Object... args) { + char start = '{', end = '}'; + boolean inArgument = false; + StringBuilder argument = new StringBuilder(); + StringBuilder builder = new StringBuilder(); + for (char c : sequence.toCharArray()) { + if (c == end && inArgument) { + inArgument = false; + try { + int arg = Integer.parseInt(argument.toString()); + Object current = args[arg]; + Object replacement = + current instanceof Supplier ? ((Supplier) current).get() : + current instanceof Callable ? ((Callable) current).call() : + current; + builder.append(replacement); + } catch (NumberFormatException | IndexOutOfBoundsException ex) { + logger.warn("Invalid argument index '{}'", argument); + builder.append(start).append(argument).append(end); + } catch (Exception ex) { + throw new WrappedException(ex); + } + argument = new StringBuilder(); + continue; + } + if (c == start && !inArgument) { + inArgument = true; + continue; + } + if (inArgument) { + argument.append(c); + continue; + } + builder.append(c); + } + if (argument.length() > 0) builder.append(start).append(argument); + return builder.toString(); + } + + @Nonnull + public static String getAfterLastIndex(@Nonnull String input, @Nonnull String separator) { + return Optional.of(input) + .filter(name -> name.contains(separator)) + .map(name -> name.substring(name.lastIndexOf(separator) + separator.length())) + .orElse(""); + } + + @Nonnull + public static String[] format(@Nonnull String[] array, @Nonnull Object... args) { + String[] result = new String[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = format(array[i], args); + } + return result; + } + + @Nonnull + public static String getArrayAsString(@Nonnull String[] array, @Nonnull String separator) { + StringBuilder builder = new StringBuilder(); + for (String string : array) { + if (builder.length() != 0) builder.append(separator); + builder.append(string); + } + return builder.toString(); + } + + @Nonnull + public static String[] getStringAsArray(@Nonnull String string) { + return string.split("\n"); + } + + @Nonnull + public static String getIterableAsString(@Nonnull Iterable iterable, @Nonnull String separator, @Nonnull Function mapper) { + StringBuilder builder = new StringBuilder(); + for (T t : iterable) { + if (builder.length() > 0) builder.append(separator); + String string = mapper.apply(t); + builder.append(string); + } + return builder.toString(); + } + + @Nonnull + public static String repeat(@Nullable Object sequence, int amount) { + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < amount; i++) builder.append(sequence); + return builder.toString(); + } + + private static int getMultiplier(char c) { + switch (Character.toLowerCase(c)) { + default: + return 1; + case 'm': + return 60; + case 'h': + return 60 * 60; + case 'd': + return 24 * 60 * 60; + case 'w': + return 7 * 24 * 60 * 60; + case 'y': + return 365 * 24 * 60 * 60; + } + } + + public static long parseSeconds(@Nonnull String input) { + if (input.toLowerCase().startsWith("perm")) return -1; + long current = 0; + long seconds = 0; + for (char c : input.toCharArray()) { + try { + long i = Long.parseUnsignedLong(String.valueOf(c)); + current *= 10; + current += i; + } catch (Exception ignored) { + int multiplier = getMultiplier(c); + seconds += current * multiplier; + current = 0; + } + } + seconds += current; + return seconds; + } + + public static boolean isNumber(@Nonnull String sequence) { + try { + Double.parseDouble(sequence); + return true; + } catch (Exception ex) { + return false; + } + } + + private static int indexOf(@Nonnull String string, @Nonnull String pattern, int occurrenceIndex) { + int lastIndex = 0; + for (int currentLayer = 0; currentLayer <= occurrenceIndex; currentLayer++) { + int index = string.indexOf(pattern, (lastIndex > 0) ? lastIndex + 1 : 0); + if (index == -1) return -1; + lastIndex = index + 1; + } + + return lastIndex; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/Version.java b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java index d9e31fedd..a8cd6c818 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/Version.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java @@ -10,96 +10,96 @@ public interface Version { - @Nonnegative - int getMajor(); - - @Nonnegative - int getMinor(); - - @Nonnegative - int getRevision(); - - default boolean isNewerThan(@Nonnull Version other) { - return this.intValue() > other.intValue(); - } - - default boolean isNewerOrEqualThan(@Nonnull Version other) { - return this.intValue() >= other.intValue(); - } - - default boolean isOlderThan(@Nonnull Version other) { - return this.intValue() < other.intValue(); - } - - default boolean isOlderOrEqualThan(@Nonnull Version other) { - return this.intValue() <= other.intValue(); - } - - default boolean equals(@Nonnull Version other) { - return this.intValue() == other.intValue(); - } - - @Nonnull - default String format() { - int revision = getRevision(); - return revision > 0 ? String.format("%s.%s.%s", getMajor(), getMinor(), revision) - : String.format("%s.%s", getMajor(), getMinor()); - } - - default int intValue() { - int major = getMajor(); - int minor = getMinor(); - int revision = getRevision(); - - if (major > 99) throw new IllegalStateException("Malformed version: major is greater than 99"); - if (minor > 99) throw new IllegalStateException("Malformed version: minor is greater than 99"); - if (revision > 99) throw new IllegalStateException("Malformed version: revision is greater than 99"); - - return revision - + minor * 100 - + major * 10000; - } - - @Nonnull - @CheckReturnValue - static Version parse(@Nullable String input) { - return parse(input, new VersionInfo(1, 0, 0)); - } - - @CheckReturnValue - static Version parse(@Nullable String input, Version def) { - return VersionInfo.parse(input, def); - } - - @Nonnull - @CheckReturnValue - static Version parseExceptionally(@Nullable String input) { - return VersionInfo.parseExceptionally(input); - } - - @Nonnull - @CheckReturnValue - static Version getAnnotatedSince(@Nonnull Object object) { - if (!object.getClass().isAnnotationPresent(Since.class)) return new VersionInfo(1, 0, 0); - return parse(object.getClass().getAnnotation(Since.class).value()); - } - - @Nonnull - @CheckReturnValue - static V findNearest(@Nonnull Version target, @Nonnull V[] sortedVersionsArray) { - List versions = new ArrayList<>(Arrays.asList(sortedVersionsArray)); - Collections.reverse(versions); - for (V version : versions) { - if (version.isNewerThan(target)) continue; - return version; - } - throw new IllegalArgumentException("No version found for '" + target + "'"); - } - - @Nonnull - @CheckReturnValue - static Comparator comparator() { - return new VersionComparator(); - } + @Nonnegative + int getMajor(); + + @Nonnegative + int getMinor(); + + @Nonnegative + int getRevision(); + + default boolean isNewerThan(@Nonnull Version other) { + return this.intValue() > other.intValue(); + } + + default boolean isNewerOrEqualThan(@Nonnull Version other) { + return this.intValue() >= other.intValue(); + } + + default boolean isOlderThan(@Nonnull Version other) { + return this.intValue() < other.intValue(); + } + + default boolean isOlderOrEqualThan(@Nonnull Version other) { + return this.intValue() <= other.intValue(); + } + + default boolean equals(@Nonnull Version other) { + return this.intValue() == other.intValue(); + } + + @Nonnull + default String format() { + int revision = getRevision(); + return revision > 0 ? String.format("%s.%s.%s", getMajor(), getMinor(), revision) + : String.format("%s.%s", getMajor(), getMinor()); + } + + default int intValue() { + int major = getMajor(); + int minor = getMinor(); + int revision = getRevision(); + + if (major > 99) throw new IllegalStateException("Malformed version: major is greater than 99"); + if (minor > 99) throw new IllegalStateException("Malformed version: minor is greater than 99"); + if (revision > 99) throw new IllegalStateException("Malformed version: revision is greater than 99"); + + return revision + + minor * 100 + + major * 10000; + } + + @Nonnull + @CheckReturnValue + static Version parse(@Nullable String input) { + return parse(input, new VersionInfo(1, 0, 0)); + } + + @CheckReturnValue + static Version parse(@Nullable String input, Version def) { + return VersionInfo.parse(input, def); + } + + @Nonnull + @CheckReturnValue + static Version parseExceptionally(@Nullable String input) { + return VersionInfo.parseExceptionally(input); + } + + @Nonnull + @CheckReturnValue + static Version getAnnotatedSince(@Nonnull Object object) { + if (!object.getClass().isAnnotationPresent(Since.class)) return new VersionInfo(1, 0, 0); + return parse(object.getClass().getAnnotation(Since.class).value()); + } + + @Nonnull + @CheckReturnValue + static V findNearest(@Nonnull Version target, @Nonnull V[] sortedVersionsArray) { + List versions = new ArrayList<>(Arrays.asList(sortedVersionsArray)); + Collections.reverse(versions); + for (V version : versions) { + if (version.isNewerThan(target)) continue; + return version; + } + throw new IllegalArgumentException("No version found for '" + target + "'"); + } + + @Nonnull + @CheckReturnValue + static Comparator comparator() { + return new VersionComparator(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java index 14a6a89c7..7027fbf7c 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java @@ -5,9 +5,9 @@ public class VersionComparator implements Comparator { - @Override - public int compare(@Nonnull Version v1, @Nonnull Version v2) { - return v1.equals(v2) ? 0 : v1.isNewerThan(v2) ? 1 : -1; - } + @Override + public int compare(@Nonnull Version v1, @Nonnull Version v2) { + return v1.equals(v2) ? 0 : v1.isNewerThan(v2) ? 1 : -1; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java index 29dbac10b..aeb0d88a6 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java @@ -7,74 +7,73 @@ public class VersionInfo implements Version { - protected static final ILogger logger = ILogger.forThisClass(); - - private final int major, minor, revision; - - public VersionInfo() { - this(1, 0, 0); - } - - public VersionInfo(int major, int minor, int revision) { - this.major = major; - this.minor = minor; - this.revision = revision; - } - - public int getMajor() { - return major; - } - - public int getMinor() { - return minor; - } - - public int getRevision() { - return revision; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - if (!(other instanceof Version)) return false; - return this.equals((Version) other); - } - - @Override - public int hashCode() { - return Objects.hash(major, minor, revision); - } - - @Override - public String toString() { - return this.format(); - } - - /** - * @throws IllegalArgumentException - * If the version could not be parsed - */ - public static Version parseExceptionally(@Nullable String input) { - if (input == null) throw new IllegalArgumentException("Version cannot be null"); - String[] array = input.split("\\."); - if (array.length == 0) throw new IllegalArgumentException("Version cannot be empty"); - try { - int major = Integer.parseInt(array[0]); - int minor = array.length >= 2 ? Integer.parseInt(array[1]) : 0; - int revision = array.length >= 3 ? Integer.parseInt(array[2]) : 0; - return new VersionInfo(major, minor, revision); - } catch (Exception ex) { - throw new IllegalArgumentException("Cannot parse Version: " + input + " (" + ex.getMessage() + ")"); - } - } - - public static Version parse(@Nullable String input, Version def) { - try { - return parseExceptionally(input); - } catch (Exception ex) { - logger.error("Could not parse version for input {}", ex.getMessage()); - return def; - } - } + protected static final ILogger logger = ILogger.forThisClass(); + + private final int major, minor, revision; + + public VersionInfo() { + this(1, 0, 0); + } + + public VersionInfo(int major, int minor, int revision) { + this.major = major; + this.minor = minor; + this.revision = revision; + } + + public int getMajor() { + return major; + } + + public int getMinor() { + return minor; + } + + public int getRevision() { + return revision; + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (!(other instanceof Version)) return false; + return this.equals((Version) other); + } + + @Override + public int hashCode() { + return Objects.hash(major, minor, revision); + } + + @Override + public String toString() { + return this.format(); + } + + /** + * @throws IllegalArgumentException If the version could not be parsed + */ + public static Version parseExceptionally(@Nullable String input) { + if (input == null) throw new IllegalArgumentException("Version cannot be null"); + String[] array = input.split("\\."); + if (array.length == 0) throw new IllegalArgumentException("Version cannot be empty"); + try { + int major = Integer.parseInt(array[0]); + int minor = array.length >= 2 ? Integer.parseInt(array[1]) : 0; + int revision = array.length >= 3 ? Integer.parseInt(array[2]) : 0; + return new VersionInfo(major, minor, revision); + } catch (Exception ex) { + throw new IllegalArgumentException("Cannot parse Version: " + input + " (" + ex.getMessage() + ")"); + } + } + + public static Version parse(@Nullable String input, Version def) { + try { + return parseExceptionally(input); + } catch (Exception ex) { + logger.error("Could not parse version for input {}", ex.getMessage()); + return def; + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/Database.java b/plugin/src/main/java/net/codingarea/commons/database/Database.java index 9092f3c1f..067656d59 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/Database.java +++ b/plugin/src/main/java/net/codingarea/commons/database/Database.java @@ -12,99 +12,96 @@ public interface Database { - ILogger LOGGER = ILogger.forThisClass(); - - @Nonnull - @CheckReturnValue - static Database empty() { - return new EmptyDatabase(true); - } - - @Nonnull - @CheckReturnValue - static Database unsupported() { - return new EmptyDatabase(false); - } - - boolean isConnected(); - - /** - * Creates the connection to the database synchronously. - * - * @throws DatabaseException - * If the connection could not be established - * @throws DatabaseAlreadyConnectedException - * If this database is already {@link #isConnected() connected} - */ - void connect() throws DatabaseException; - - /** - * Creates the connection to the database synchronously. - * No exceptions will be thrown if the process fails. - * - * @return {@code true} if the connection was established successfully - */ - boolean connectSafely(); - - /** - * Closes the connection to the database synchronously. - * - * @throws DatabaseException - * If something went wrong while closing the connection to the database - * @throws DatabaseConnectionClosedException - * If this database is not {@link #isConnected() connected} - */ - void disconnect() throws DatabaseException; - - /** - * Closes the connection to the database synchronously. - * No exceptions will be thrown if the process fails. - * - * @return {@code true} if the connection was closed without errors - */ - boolean disconnectSafely(); - - void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException; - void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns); - - @Nonnull - default Task createTableAsync(@Nonnull String name, @Nonnull SQLColumn... columns) { - return Task.asyncRunExceptionally(() -> createTable(name, columns)); - } - - @Nonnull - @CheckReturnValue - DatabaseListTables listTables(); - - @Nonnull - @CheckReturnValue - DatabaseCountEntries countEntries(@Nonnull String table); - - @Nonnull - @CheckReturnValue - DatabaseQuery query(@Nonnull String table); - - @Nonnull - @CheckReturnValue - DatabaseUpdate update(@Nonnull String table); - - @Nonnull - @CheckReturnValue - DatabaseInsertion insert(@Nonnull String table); - - @Nonnull - @CheckReturnValue - DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table); - - @Nonnull - @CheckReturnValue - DatabaseDeletion delete(@Nonnull String table); - - @Nonnull - @CheckReturnValue - SpecificDatabase getSpecificDatabase(@Nonnull String name); - - @Nonnull - DatabaseConfig getConfig(); + ILogger LOGGER = ILogger.forThisClass(); + + @Nonnull + @CheckReturnValue + static Database empty() { + return new EmptyDatabase(true); + } + + @Nonnull + @CheckReturnValue + static Database unsupported() { + return new EmptyDatabase(false); + } + + boolean isConnected(); + + /** + * Creates the connection to the database synchronously. + * + * @throws DatabaseException If the connection could not be established + * @throws DatabaseAlreadyConnectedException If this database is already {@link #isConnected() connected} + */ + void connect() throws DatabaseException; + + /** + * Creates the connection to the database synchronously. + * No exceptions will be thrown if the process fails. + * + * @return {@code true} if the connection was established successfully + */ + boolean connectSafely(); + + /** + * Closes the connection to the database synchronously. + * + * @throws DatabaseException If something went wrong while closing the connection to the database + * @throws DatabaseConnectionClosedException If this database is not {@link #isConnected() connected} + */ + void disconnect() throws DatabaseException; + + /** + * Closes the connection to the database synchronously. + * No exceptions will be thrown if the process fails. + * + * @return {@code true} if the connection was closed without errors + */ + boolean disconnectSafely(); + + void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException; + + void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns); + + @Nonnull + default Task createTableAsync(@Nonnull String name, @Nonnull SQLColumn... columns) { + return Task.asyncRunExceptionally(() -> createTable(name, columns)); + } + + @Nonnull + @CheckReturnValue + DatabaseListTables listTables(); + + @Nonnull + @CheckReturnValue + DatabaseCountEntries countEntries(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseQuery query(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseUpdate update(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseInsertion insert(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table); + + @Nonnull + @CheckReturnValue + DatabaseDeletion delete(@Nonnull String table); + + @Nonnull + @CheckReturnValue + SpecificDatabase getSpecificDatabase(@Nonnull String name); + + @Nonnull + DatabaseConfig getConfig(); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java index 8c67b2b87..57e1e3498 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java +++ b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java @@ -6,100 +6,102 @@ public final class DatabaseConfig { - private final String host; - private final String database; - private final String authDatabase; - private final String password; - private final String user; - private final String file; - private final int port; - private final boolean portIsSet; - - public DatabaseConfig(String host, String database, String password, String user, int port) { - this(host, database, null, password, user, port, true, null); - } - public DatabaseConfig(String host, String database, String password, String user) { - this(host, database, null, password, user, 0, false, null); - } - - public DatabaseConfig(String host, String database, String authDatabase, String password, String user, int port) { - this(host, database, authDatabase, password, user, port, true, null); - } - public DatabaseConfig(String host, String database, String authDatabase, String password, String user) { - this(host, database, authDatabase, password, user, 0, false, null); - } - - public DatabaseConfig(String database, String file) { - this(null, database, null, null, null, 0, false, file); - } - - public DatabaseConfig(String host, String database, String authDatabase, String password, String user, int port, boolean portIsSet, String file) { - this.host = host; - this.database = database; - this.authDatabase = authDatabase; - this.password = password; - this.user = user; - this.port = port; - this.portIsSet = portIsSet; - this.file = file; - } - - public DatabaseConfig(@Nonnull Propertyable config) { - this( - config.getString("host"), - config.getString("database"), - config.getString("auth-database"), - config.getString("password"), - config.getString("user"), - config.getInt("port"), - config.contains("port"), - config.getString("file") - ); - } - - public int getPort() { - return port; - } - - public String getAuthDatabase() { - return authDatabase; - } - - public String getDatabase() { - return database; - } - - public String getHost() { - return host; - } - - public String getPassword() { - return password; - } - - public String getUser() { - return user; - } - - public boolean isPortSet() { - return portIsSet; - } - - public String getFile() { - return file; - } - - @Override - public String toString() { - return "DatabaseConfig{" + - "host='" + host + '\'' + - ", database='" + database + '\'' + - ", authDatabase='" + authDatabase + '\'' + - ", user='" + user + '\'' + - ", file='" + file + '\'' + - ", port=" + port + - ", portIsSet=" + portIsSet + - '}'; - } + private final String host; + private final String database; + private final String authDatabase; + private final String password; + private final String user; + private final String file; + private final int port; + private final boolean portIsSet; + + public DatabaseConfig(String host, String database, String password, String user, int port) { + this(host, database, null, password, user, port, true, null); + } + + public DatabaseConfig(String host, String database, String password, String user) { + this(host, database, null, password, user, 0, false, null); + } + + public DatabaseConfig(String host, String database, String authDatabase, String password, String user, int port) { + this(host, database, authDatabase, password, user, port, true, null); + } + + public DatabaseConfig(String host, String database, String authDatabase, String password, String user) { + this(host, database, authDatabase, password, user, 0, false, null); + } + + public DatabaseConfig(String database, String file) { + this(null, database, null, null, null, 0, false, file); + } + + public DatabaseConfig(String host, String database, String authDatabase, String password, String user, int port, boolean portIsSet, String file) { + this.host = host; + this.database = database; + this.authDatabase = authDatabase; + this.password = password; + this.user = user; + this.port = port; + this.portIsSet = portIsSet; + this.file = file; + } + + public DatabaseConfig(@Nonnull Propertyable config) { + this( + config.getString("host"), + config.getString("database"), + config.getString("auth-database"), + config.getString("password"), + config.getString("user"), + config.getInt("port"), + config.contains("port"), + config.getString("file") + ); + } + + public int getPort() { + return port; + } + + public String getAuthDatabase() { + return authDatabase; + } + + public String getDatabase() { + return database; + } + + public String getHost() { + return host; + } + + public String getPassword() { + return password; + } + + public String getUser() { + return user; + } + + public boolean isPortSet() { + return portIsSet; + } + + public String getFile() { + return file; + } + + @Override + public String toString() { + return "DatabaseConfig{" + + "host='" + host + '\'' + + ", database='" + database + '\'' + + ", authDatabase='" + authDatabase + '\'' + + ", user='" + user + '\'' + + ", file='" + file + '\'' + + ", port=" + port + + ", portIsSet=" + portIsSet + + '}'; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java index 0770c8b67..9f0095658 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java @@ -1,10 +1,10 @@ package net.codingarea.commons.database; import net.codingarea.commons.common.concurrent.task.Task; -import net.codingarea.commons.database.action.*; -import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.commons.database.abstraction.DefaultExecutedQuery; import net.codingarea.commons.database.abstraction.DefaultSpecificDatabase; +import net.codingarea.commons.database.action.*; +import net.codingarea.commons.database.exceptions.DatabaseException; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -13,276 +13,276 @@ public class EmptyDatabase implements Database { - private final boolean silent; - - public EmptyDatabase(boolean silent) { - this.silent = silent; - } - - public boolean isSilent() { - return silent; - } - - protected void exception(@Nonnull String message) { - throw new UnsupportedOperationException(message); - } - - @Override - public boolean isConnected() { - return false; - } - - @Override - public void connect() throws DatabaseException { - if (!silent) - exception("Cannot connect with a NOP Database"); - } - - @Override - public boolean connectSafely() { - return false; - } - - @Override - public void disconnect() throws DatabaseException { - if (!silent) - exception("Cannot disconnect from a NOP Database"); - } - - @Override - public boolean disconnectSafely() { - return false; - } - - @Override - public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { - if (!silent) - exception("Cannot create tables from a NOP Database"); - } - - @Override - public void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns) { - } - - @Nonnull - @Override - public DatabaseListTables listTables() { - if (!silent) - exception("Cannot list tables of a NOP Database"); - - return new EmptyListTables(); - } - - @Nonnull - @Override - public DatabaseCountEntries countEntries(@Nonnull String table) { - if (!silent) - exception("Cannot count entries of a NOP Database"); - - return new EmptyCountEntries(); - } - - @Nonnull - @Override - public DatabaseQuery query(@Nonnull String table) { - if (!silent) - exception("Cannot query in a NOP Database"); - - return new EmptyDatabaseQuery(); - } - - @Nonnull - @Override - public DatabaseUpdate update(@Nonnull String table) { - if (!silent) - exception("Cannot update in a NOP Database"); - - return new EmptyVoidAction(); - } - - @Nonnull - @Override - public DatabaseInsertion insert(@Nonnull String table) { - if (!silent) - exception("Cannot insert into a NOP Database"); - - return new EmptyVoidAction(); - } - - @Nonnull - @Override - public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { - if (!silent) - exception("Cannot inset or update into a NOP Database"); - - return new EmptyVoidAction(); - } - - @Nonnull - @Override - public DatabaseDeletion delete(@Nonnull String table) { - if (!silent) - exception("Cannot delete from a NOP Database"); - - return new EmptyVoidAction(); - } - - @Nonnull - @Override - public SpecificDatabase getSpecificDatabase(@Nonnull String name) { - return new DefaultSpecificDatabase(this, name); - } - - @Nonnull - @Override - public DatabaseConfig getConfig() { - throw new UnsupportedOperationException(); - } - - @Override - public String toString() { - return "EmptyDatabase[silent=" + silent + "]"; - } - - public static class EmptyDatabaseQuery implements DatabaseQuery { - - @Nonnull - @Override - public DatabaseQuery where(@Nonnull String field, @Nullable Object object) { - return this; - } - - @Nonnull - @Override - public DatabaseQuery where(@Nonnull String field, @Nullable Number value) { - return this; - } - - @Nonnull - @Override - public DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { - return this; - } - - @Nonnull - @Override - public DatabaseQuery where(@Nonnull String field, @Nullable String value) { - return this; - } - - @Nonnull - @Override - public DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value) { - return this; - } - - @Nonnull - @Override - public DatabaseQuery select(@Nonnull String... selection) { - return this; - } - - @Nonnull - @Override - public DatabaseQuery orderBy(@Nonnull String field, @Nonnull Order order) { - return this; - } - - @Nonnull - @Override - public ExecutedQuery execute() throws DatabaseException { - return new DefaultExecutedQuery(Collections.emptyList()); - } - - @Nonnull - @Override - public Task executeAsync() { - return Task.syncCall(this::execute); - } - - } - - public static class EmptyVoidAction implements DatabaseDeletion, DatabaseInsertion, DatabaseUpdate, DatabaseInsertionOrUpdate { - - @Nonnull - @Override - public EmptyVoidAction where(@Nonnull String field, @Nullable Object value) { - return this; - } - - @Nonnull - @Override - public EmptyVoidAction where(@Nonnull String field, @Nullable Number value) { - return this; - } - - @Nonnull - @Override - public EmptyVoidAction where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { - return this; - } - - @Nonnull - @Override - public EmptyVoidAction where(@Nonnull String field, @Nullable String value) { - return this; - } - - @Nonnull - @Override - public EmptyVoidAction whereNot(@Nonnull String field, @Nullable Object value) { - return this; - } - - @Nonnull - @Override - public EmptyVoidAction set(@Nonnull String field, @Nullable Object value) { - return this; - } - - @Override - public Void execute() throws DatabaseException { - return null; - } - - @Nonnull - @Override - public Task executeAsync() { - return Task.completedVoid(); - } - - } - - public static class EmptyCountEntries implements DatabaseCountEntries { - - @Nonnull - @Override - public Long execute() throws DatabaseException { - return 0L; - } - - @Nonnull - @Override - public Task executeAsync() { - return Task.completed(0L); - } - - } - - public static class EmptyListTables implements DatabaseListTables { - - @Nonnull - @Override - public List execute() throws DatabaseException { - return Collections.emptyList(); - } - - @Nonnull - @Override - public Task> executeAsync() { - return Task.completed(Collections.emptyList()); - } - - } + private final boolean silent; + + public EmptyDatabase(boolean silent) { + this.silent = silent; + } + + public boolean isSilent() { + return silent; + } + + protected void exception(@Nonnull String message) { + throw new UnsupportedOperationException(message); + } + + @Override + public boolean isConnected() { + return false; + } + + @Override + public void connect() throws DatabaseException { + if (!silent) + exception("Cannot connect with a NOP Database"); + } + + @Override + public boolean connectSafely() { + return false; + } + + @Override + public void disconnect() throws DatabaseException { + if (!silent) + exception("Cannot disconnect from a NOP Database"); + } + + @Override + public boolean disconnectSafely() { + return false; + } + + @Override + public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { + if (!silent) + exception("Cannot create tables from a NOP Database"); + } + + @Override + public void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns) { + } + + @Nonnull + @Override + public DatabaseListTables listTables() { + if (!silent) + exception("Cannot list tables of a NOP Database"); + + return new EmptyListTables(); + } + + @Nonnull + @Override + public DatabaseCountEntries countEntries(@Nonnull String table) { + if (!silent) + exception("Cannot count entries of a NOP Database"); + + return new EmptyCountEntries(); + } + + @Nonnull + @Override + public DatabaseQuery query(@Nonnull String table) { + if (!silent) + exception("Cannot query in a NOP Database"); + + return new EmptyDatabaseQuery(); + } + + @Nonnull + @Override + public DatabaseUpdate update(@Nonnull String table) { + if (!silent) + exception("Cannot update in a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public DatabaseInsertion insert(@Nonnull String table) { + if (!silent) + exception("Cannot insert into a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { + if (!silent) + exception("Cannot inset or update into a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public DatabaseDeletion delete(@Nonnull String table) { + if (!silent) + exception("Cannot delete from a NOP Database"); + + return new EmptyVoidAction(); + } + + @Nonnull + @Override + public SpecificDatabase getSpecificDatabase(@Nonnull String name) { + return new DefaultSpecificDatabase(this, name); + } + + @Nonnull + @Override + public DatabaseConfig getConfig() { + throw new UnsupportedOperationException(); + } + + @Override + public String toString() { + return "EmptyDatabase[silent=" + silent + "]"; + } + + public static class EmptyDatabaseQuery implements DatabaseQuery { + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable Object object) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable Number value) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String field, @Nullable String value) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery select(@Nonnull String... selection) { + return this; + } + + @Nonnull + @Override + public DatabaseQuery orderBy(@Nonnull String field, @Nonnull Order order) { + return this; + } + + @Nonnull + @Override + public ExecutedQuery execute() throws DatabaseException { + return new DefaultExecutedQuery(Collections.emptyList()); + } + + @Nonnull + @Override + public Task executeAsync() { + return Task.syncCall(this::execute); + } + + } + + public static class EmptyVoidAction implements DatabaseDeletion, DatabaseInsertion, DatabaseUpdate, DatabaseInsertionOrUpdate { + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable Number value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction where(@Nonnull String field, @Nullable String value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction whereNot(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Nonnull + @Override + public EmptyVoidAction set(@Nonnull String field, @Nullable Object value) { + return this; + } + + @Override + public Void execute() throws DatabaseException { + return null; + } + + @Nonnull + @Override + public Task executeAsync() { + return Task.completedVoid(); + } + + } + + public static class EmptyCountEntries implements DatabaseCountEntries { + + @Nonnull + @Override + public Long execute() throws DatabaseException { + return 0L; + } + + @Nonnull + @Override + public Task executeAsync() { + return Task.completed(0L); + } + + } + + public static class EmptyListTables implements DatabaseListTables { + + @Nonnull + @Override + public List execute() throws DatabaseException { + return Collections.emptyList(); + } + + @Nonnull + @Override + public Task> executeAsync() { + return Task.completed(Collections.emptyList()); + } + + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/Order.java b/plugin/src/main/java/net/codingarea/commons/database/Order.java index 8165ecb8e..90cabdf1e 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/Order.java +++ b/plugin/src/main/java/net/codingarea/commons/database/Order.java @@ -7,7 +7,7 @@ */ public enum Order { - HIGHEST, - LOWEST + HIGHEST, + LOWEST } diff --git a/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java b/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java index f58d9d0aa..07987b629 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java +++ b/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java @@ -10,125 +10,173 @@ public final class SQLColumn { - public enum Type { - /** A FIXED length string (can contain letters, numbers, and special characters). The size parameter specifies the column length in characters - can be from 0 to 255. Default is 1 */ - CHAR, - /** A VARIABLE length string (can contain letters, numbers, and special characters). The size parameter specifies the maximum column length in characters - can be from 0 to 65535 */ - VARCHAR, - /** Equal to {@link #CHAR}, but stores binary byte strings. The size parameter specifies the column length in bytes. Default is 1 */ - BINARY, - /** Equal to {@link #VARCHAR}, but stores binary byte strings. The size parameter specifies the maximum column length in bytes. */ - VARBINARY, - /** For BLOBs (Binary Large OBjects). Max length: 255 bytes */ - TINYBLOB, - /** Holds a string with a maximum length of 255 characters */ - TINYTEXT, - /** Holds a string with a maximum length of 65,535 bytes */ - TEXT, - /** For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data */ - BLOB, - /** For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data */ - MEDIUMTEXT, - /** For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data */ - MEDIUMBLOB, - /** Holds a string with a maximum length of 4,294,967,295 characters */ - LONGTEXT, - /** For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data */ - LONGBLOB, - /** A string object that can have only one value, chosen from a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. The values are sorted in the order you enter them */ - ENUM, - /** A string object that can have 0 or more values, chosen from a list of possible values. You can list up to 64 values in a SET list */ - SET, - /** A bit-value type. The number of bits per value is specified in size. The size parameter can hold a value from 1 to 64. The default value for size is 1. */ - BIT, - /** A very small integer. Signed range is from -128 to 127. Unsigned range is from 0 to 255. The size parameter specifies the maximum display width (which is 255) */ - TINYINT, - /** Zero is considered as false, nonzero values are considered as true. */ - BOOLEAN, - /** A small integer. Signed range is from -32768 to 32767. Unsigned range is from 0 to 65535. The size parameter specifies the maximum display width (which is 255) */ - SMALLINT, - /** A medium integer. Signed range is from -8388608 to 8388607. Unsigned range is from 0 to 16777215. The size parameter specifies the maximum display width (which is 255) */ - MEDIUMINT, - /** A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range is from 0 to 4294967295. The size parameter specifies the maximum display width (which is 255) */ - INT, - /** A large integer. Signed range is from -9223372036854775808 to 9223372036854775807. Unsigned range is from 0 to 18446744073709551615. The size parameter specifies the maximum display width (which is 255) */ - BIGINT, - /** A floating point number. MySQL uses the p value to determine whether to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to 24, the data type becomes FLOAT(). If p is from 25 to 53, the data type becomes DOUBLE() */ - FLOAT, - /** A normal-size floating point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter */ - DOUBLE, - /** An exact fixed-point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter. The maximum number for size is 65. The maximum number for d is 30. The default value for size is 10. The default value for d is 0.*/ - DECIMAL - } - - private final String name; - private final String type; - private final String param; - - public SQLColumn(@Nonnull String name, @Nonnull String type, @Nullable String param) { - if (name.contains(" ")) throw new IllegalArgumentException("Column name cannot contain spaces"); - if (type.contains(" ")) throw new IllegalArgumentException("Column type cannot contain spaces"); - - this.name = name; - this.type = type; - this.param = param; - } - - public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnegative int size) { - this(name, type, String.valueOf(size)); - } - - public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnegative int size, @Nonnegative int d) { - this(name, type, String.valueOf(size), String.valueOf(d)); - } - - public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnull String... params) { - this(name, type, StringUtils.getArrayAsString(params, ", ")); - } - - public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nullable String param) { - this(name, type.name(), param); - } - - public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnegative int size) { - this(name, type.name(), size); - } - - public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnegative int size, @Nonnegative int d) { - this(name, type.name(), size, d); - } - - public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnull String... params) { - this(name, type.name(), params); - } - - public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnull Type... types) { - this(name, type, Arrays.stream(types).map(Type::name).toArray(String[]::new)); - } - - @Nonnull - public String getName() { - return name; - } - - @Nonnull - public String getType() { - return type; - } - - @Nullable - public Type findType() { - return ReflectionUtils.getEnumOrNull(type.toUpperCase(), Type.class); - } - - @Nullable - public String getParam() { - return param; - } - - @Override - public String toString() { - return name + " " + type + (param == null ? "" : "(" + param + ")"); - } + public enum Type { + /** + * A FIXED length string (can contain letters, numbers, and special characters). The size parameter specifies the column length in characters - can be from 0 to 255. Default is 1 + */ + CHAR, + /** + * A VARIABLE length string (can contain letters, numbers, and special characters). The size parameter specifies the maximum column length in characters - can be from 0 to 65535 + */ + VARCHAR, + /** + * Equal to {@link #CHAR}, but stores binary byte strings. The size parameter specifies the column length in bytes. Default is 1 + */ + BINARY, + /** + * Equal to {@link #VARCHAR}, but stores binary byte strings. The size parameter specifies the maximum column length in bytes. + */ + VARBINARY, + /** + * For BLOBs (Binary Large OBjects). Max length: 255 bytes + */ + TINYBLOB, + /** + * Holds a string with a maximum length of 255 characters + */ + TINYTEXT, + /** + * Holds a string with a maximum length of 65,535 bytes + */ + TEXT, + /** + * For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data + */ + BLOB, + /** + * For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data + */ + MEDIUMTEXT, + /** + * For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data + */ + MEDIUMBLOB, + /** + * Holds a string with a maximum length of 4,294,967,295 characters + */ + LONGTEXT, + /** + * For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data + */ + LONGBLOB, + /** + * A string object that can have only one value, chosen from a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. The values are sorted in the order you enter them + */ + ENUM, + /** + * A string object that can have 0 or more values, chosen from a list of possible values. You can list up to 64 values in a SET list + */ + SET, + /** + * A bit-value type. The number of bits per value is specified in size. The size parameter can hold a value from 1 to 64. The default value for size is 1. + */ + BIT, + /** + * A very small integer. Signed range is from -128 to 127. Unsigned range is from 0 to 255. The size parameter specifies the maximum display width (which is 255) + */ + TINYINT, + /** + * Zero is considered as false, nonzero values are considered as true. + */ + BOOLEAN, + /** + * A small integer. Signed range is from -32768 to 32767. Unsigned range is from 0 to 65535. The size parameter specifies the maximum display width (which is 255) + */ + SMALLINT, + /** + * A medium integer. Signed range is from -8388608 to 8388607. Unsigned range is from 0 to 16777215. The size parameter specifies the maximum display width (which is 255) + */ + MEDIUMINT, + /** + * A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range is from 0 to 4294967295. The size parameter specifies the maximum display width (which is 255) + */ + INT, + /** + * A large integer. Signed range is from -9223372036854775808 to 9223372036854775807. Unsigned range is from 0 to 18446744073709551615. The size parameter specifies the maximum display width (which is 255) + */ + BIGINT, + /** + * A floating point number. MySQL uses the p value to determine whether to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to 24, the data type becomes FLOAT(). If p is from 25 to 53, the data type becomes DOUBLE() + */ + FLOAT, + /** + * A normal-size floating point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter + */ + DOUBLE, + /** + * An exact fixed-point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter. The maximum number for size is 65. The maximum number for d is 30. The default value for size is 10. The default value for d is 0. + */ + DECIMAL + } + + private final String name; + private final String type; + private final String param; + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nullable String param) { + if (name.contains(" ")) throw new IllegalArgumentException("Column name cannot contain spaces"); + if (type.contains(" ")) throw new IllegalArgumentException("Column type cannot contain spaces"); + + this.name = name; + this.type = type; + this.param = param; + } + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnegative int size) { + this(name, type, String.valueOf(size)); + } + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnegative int size, @Nonnegative int d) { + this(name, type, String.valueOf(size), String.valueOf(d)); + } + + public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnull String... params) { + this(name, type, StringUtils.getArrayAsString(params, ", ")); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nullable String param) { + this(name, type.name(), param); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnegative int size) { + this(name, type.name(), size); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnegative int size, @Nonnegative int d) { + this(name, type.name(), size, d); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnull String... params) { + this(name, type.name(), params); + } + + public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnull Type... types) { + this(name, type, Arrays.stream(types).map(Type::name).toArray(String[]::new)); + } + + @Nonnull + public String getName() { + return name; + } + + @Nonnull + public String getType() { + return type; + } + + @Nullable + public Type findType() { + return ReflectionUtils.getEnumOrNull(type.toUpperCase(), Type.class); + } + + @Nullable + public String getParam() { + return param; + } + + @Override + public String toString() { + return name + " " + type + (param == null ? "" : "(" + param + ")"); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java b/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java index 56ae16184..6889f896a 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java +++ b/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java @@ -9,31 +9,33 @@ public final class SimpleDatabaseTypeResolver { - private SimpleDatabaseTypeResolver() {} - - private static final Map registry = new HashMap<>(); - static { - registerType("mongodb", "net.codingarea.commons.database.mongodb.MongoDBDatabase"); - registerType("mysql", "net.codingarea.commons.database.sql.mysql.MySQLDatabase"); - registerType("sqlite", "net.codingarea.commons.database.sql.sqlite.SQLiteDatabase"); - } - - @Nullable - public static Class findDatabaseType(@Nonnull String name) { - return ReflectionUtils.getClassOrNull(registry.get(name)); - } - - @Nullable - public static Class findDatabaseType(@Nonnull String name, boolean initialize, @Nonnull ClassLoader classLoader) { - return ReflectionUtils.getClassOrNull(registry.get(name), initialize, classLoader); - } - - public static void registerType(@Nonnull String name, @Nonnull String className) { - registry.put(name, className); - } - - public static void registerType(@Nonnull String name, @Nonnull Class databaseClass) { - registerType(name, databaseClass.getName()); - } + private SimpleDatabaseTypeResolver() { + } + + private static final Map registry = new HashMap<>(); + + static { + registerType("mongodb", "net.codingarea.commons.database.mongodb.MongoDBDatabase"); + registerType("mysql", "net.codingarea.commons.database.sql.mysql.MySQLDatabase"); + registerType("sqlite", "net.codingarea.commons.database.sql.sqlite.SQLiteDatabase"); + } + + @Nullable + public static Class findDatabaseType(@Nonnull String name) { + return ReflectionUtils.getClassOrNull(registry.get(name)); + } + + @Nullable + public static Class findDatabaseType(@Nonnull String name, boolean initialize, @Nonnull ClassLoader classLoader) { + return ReflectionUtils.getClassOrNull(registry.get(name), initialize, classLoader); + } + + public static void registerType(@Nonnull String name, @Nonnull String className) { + registry.put(name, className); + } + + public static void registerType(@Nonnull String name, @Nonnull Class databaseClass) { + registerType(name, databaseClass.getName()); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java index 3ef75df74..f65f869cc 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java @@ -13,54 +13,54 @@ */ public interface SpecificDatabase { - boolean isConnected(); + boolean isConnected(); - @Nonnull - String getName(); + @Nonnull + String getName(); - /** - * @see Database#countEntries(String) - */ - @Nonnull - @CheckReturnValue - DatabaseCountEntries countEntries(); + /** + * @see Database#countEntries(String) + */ + @Nonnull + @CheckReturnValue + DatabaseCountEntries countEntries(); - /** - * @see Database#query(String) - */ - @Nonnull - @CheckReturnValue - DatabaseQuery query(); + /** + * @see Database#query(String) + */ + @Nonnull + @CheckReturnValue + DatabaseQuery query(); - /** - * @see Database#update(String) - */ - @Nonnull - @CheckReturnValue - DatabaseUpdate update(); + /** + * @see Database#update(String) + */ + @Nonnull + @CheckReturnValue + DatabaseUpdate update(); - /** - * @see Database#insert(String) - */ - @Nonnull - @CheckReturnValue - DatabaseInsertion insert(); + /** + * @see Database#insert(String) + */ + @Nonnull + @CheckReturnValue + DatabaseInsertion insert(); - /** - * @see Database#insertOrUpdate(String) - */ - @Nonnull - @CheckReturnValue - DatabaseInsertionOrUpdate insertOrUpdate(); + /** + * @see Database#insertOrUpdate(String) + */ + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate insertOrUpdate(); - /** - * @see Database#delete(String) - */ - @Nonnull - @CheckReturnValue - DatabaseDeletion delete(); + /** + * @see Database#delete(String) + */ + @Nonnull + @CheckReturnValue + DatabaseDeletion delete(); - @Nonnull - Database getParent(); + @Nonnull + Database getParent(); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java index 755ddeedd..62aa6846b 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java @@ -12,89 +12,89 @@ public abstract class AbstractDatabase implements Database { - protected final DatabaseConfig config; - - public AbstractDatabase(@Nonnull DatabaseConfig config) { - this.config = config; - } - - @Override - public boolean disconnectSafely() { - try { - disconnect(); - LOGGER.info("Successfully closed connection to database of type " + this.getClass().getSimpleName()); - return true; - } catch (DatabaseException ex) { - LOGGER.error("Could not disconnect from database (" + this.getClass().getSimpleName() + ")", ex); - return false; - } - } - - @Override - public void disconnect() throws DatabaseException { - checkConnection(); - try { - disconnect0(); - } catch (Exception ex) { - throw new DatabaseException(ex); - } - } - - protected abstract void disconnect0() throws Exception; - - @Override - public boolean connectSafely() { - try { - connect(); - LOGGER.status("Successfully created connection to database of type " + this.getClass().getSimpleName()); - return true; - } catch (DatabaseException ex) { - LOGGER.error("Could not connect to database (" + this.getClass().getSimpleName() + ")", ex); - return false; - } - } - - @Override - public void connect() throws DatabaseException { - if (isConnected()) throw new DatabaseAlreadyConnectedException(); - try { - connect0(); - } catch (Exception ex) { - if (ex instanceof DatabaseException) throw (DatabaseException) ex; - throw new DatabaseException(ex); - } - } - - protected abstract void connect0() throws Exception; - - @Override - public void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns) { - try { - createTable(name, columns); - } catch (DatabaseException ex) { - LOGGER.error("Could not create table (" + this.getClass().getSimpleName() + ")", ex); - } - } - - @Nonnull - @Override - public SpecificDatabase getSpecificDatabase(@Nonnull String name) { - return new DefaultSpecificDatabase(this, name); - } - - @Nonnull - @Override - public DatabaseConfig getConfig() { - return config; - } - - protected final void checkConnection() throws DatabaseConnectionClosedException { - if (!isConnected()) - throw new DatabaseConnectionClosedException(); - } - - @Override - public String toString() { - return this.getClass().getSimpleName() + "[connected=" + isConnected() + "]"; - } + protected final DatabaseConfig config; + + public AbstractDatabase(@Nonnull DatabaseConfig config) { + this.config = config; + } + + @Override + public boolean disconnectSafely() { + try { + disconnect(); + LOGGER.info("Successfully closed connection to database of type " + this.getClass().getSimpleName()); + return true; + } catch (DatabaseException ex) { + LOGGER.error("Could not disconnect from database (" + this.getClass().getSimpleName() + ")", ex); + return false; + } + } + + @Override + public void disconnect() throws DatabaseException { + checkConnection(); + try { + disconnect0(); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + protected abstract void disconnect0() throws Exception; + + @Override + public boolean connectSafely() { + try { + connect(); + LOGGER.status("Successfully created connection to database of type " + this.getClass().getSimpleName()); + return true; + } catch (DatabaseException ex) { + LOGGER.error("Could not connect to database (" + this.getClass().getSimpleName() + ")", ex); + return false; + } + } + + @Override + public void connect() throws DatabaseException { + if (isConnected()) throw new DatabaseAlreadyConnectedException(); + try { + connect0(); + } catch (Exception ex) { + if (ex instanceof DatabaseException) throw (DatabaseException) ex; + throw new DatabaseException(ex); + } + } + + protected abstract void connect0() throws Exception; + + @Override + public void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns) { + try { + createTable(name, columns); + } catch (DatabaseException ex) { + LOGGER.error("Could not create table (" + this.getClass().getSimpleName() + ")", ex); + } + } + + @Nonnull + @Override + public SpecificDatabase getSpecificDatabase(@Nonnull String name) { + return new DefaultSpecificDatabase(this, name); + } + + @Nonnull + @Override + public DatabaseConfig getConfig() { + return config; + } + + protected final void checkConnection() throws DatabaseConnectionClosedException { + if (!isConnected()) + throw new DatabaseConnectionClosedException(); + } + + @Override + public String toString() { + return this.getClass().getSimpleName() + "[connected=" + isConnected() + "]"; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java index dd437cfb5..01f649efd 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java @@ -12,113 +12,113 @@ public class DefaultExecutedQuery implements ExecutedQuery { - protected final List results; - - public DefaultExecutedQuery(@Nonnull List results) { - this.results = results; - } - - @Nonnull - @Override - public Optional first() { - if (results.isEmpty()) return Optional.empty(); - return Optional.ofNullable(results.get(0)); - } - - @Nonnull - @Override - public Optional get(int index) { - if (index >= results.size()) return Optional.empty(); - return Optional.ofNullable(results.get(index)); - } - - @Nonnull - @Override - public Stream all() { - return results.stream(); - } - - @Nonnull - @Override - public > C toCollection(@Nonnull C collection) { - collection.addAll(results); - return collection; - } - - @Nonnull - @Override - public Document[] toArray(@Nonnull IntFunction arraySupplier) { - Document[] array = arraySupplier.apply(size()); - for (int i = 0; i < size(); i++) { - array[i] = results.get(i); - } - return array; - } - - @Override - public int index(@Nonnull Predicate filter) { - int index = 0; - for (Document result : results) { - if (filter.test(result)) - return index; - index++; - } - return -1; - } - - @Override - public boolean isEmpty() { - return results.isEmpty(); - } - - @Override - public boolean isSet() { - return !results.isEmpty(); - } - - @Override - public int size() { - return results.size(); - } - - @Override - public void print(@Nonnull PrintStream out) { - if (results.isEmpty()) { - out.println(""); - return; - } - - int index = 0; - for (Document result : results) { - out.print(index + " | "); - result.forEach((key, value) -> { - out.print(key + " = '" + value + "' "); - }); - out.println(); - index++; - } - } - - @Override - public Iterator iterator() { - return Collections.unmodifiableCollection(results).iterator(); - } - - @Override - public String toString() { - return "ExecutedQuery[size=" + size() + "]"; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - DefaultExecutedQuery documents = (DefaultExecutedQuery) o; - return Objects.equals(results, documents.results); - } - - @Override - public int hashCode() { - return Objects.hash(results); - } + protected final List results; + + public DefaultExecutedQuery(@Nonnull List results) { + this.results = results; + } + + @Nonnull + @Override + public Optional first() { + if (results.isEmpty()) return Optional.empty(); + return Optional.ofNullable(results.get(0)); + } + + @Nonnull + @Override + public Optional get(int index) { + if (index >= results.size()) return Optional.empty(); + return Optional.ofNullable(results.get(index)); + } + + @Nonnull + @Override + public Stream all() { + return results.stream(); + } + + @Nonnull + @Override + public > C toCollection(@Nonnull C collection) { + collection.addAll(results); + return collection; + } + + @Nonnull + @Override + public Document[] toArray(@Nonnull IntFunction arraySupplier) { + Document[] array = arraySupplier.apply(size()); + for (int i = 0; i < size(); i++) { + array[i] = results.get(i); + } + return array; + } + + @Override + public int index(@Nonnull Predicate filter) { + int index = 0; + for (Document result : results) { + if (filter.test(result)) + return index; + index++; + } + return -1; + } + + @Override + public boolean isEmpty() { + return results.isEmpty(); + } + + @Override + public boolean isSet() { + return !results.isEmpty(); + } + + @Override + public int size() { + return results.size(); + } + + @Override + public void print(@Nonnull PrintStream out) { + if (results.isEmpty()) { + out.println(""); + return; + } + + int index = 0; + for (Document result : results) { + out.print(index + " | "); + result.forEach((key, value) -> { + out.print(key + " = '" + value + "' "); + }); + out.println(); + index++; + } + } + + @Override + public Iterator iterator() { + return Collections.unmodifiableCollection(results).iterator(); + } + + @Override + public String toString() { + return "ExecutedQuery[size=" + size() + "]"; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DefaultExecutedQuery documents = (DefaultExecutedQuery) o; + return Objects.equals(results, documents.results); + } + + @Override + public int hashCode() { + return Objects.hash(results); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java index 52496f6c6..bd5c88b58 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java @@ -9,82 +9,82 @@ public class DefaultSpecificDatabase implements SpecificDatabase { - protected final Database parent; - protected final String name; - - public DefaultSpecificDatabase(@Nonnull Database parent, @Nonnull String name) { - this.parent = parent; - this.name = name; - } - - @Override - public boolean isConnected() { - return parent.isConnected(); - } - - @Nonnull - @Override - public String getName() { - return name; - } - - @Nonnull - @Override - public DatabaseCountEntries countEntries() { - return parent.countEntries(name); - } - - @Nonnull - @Override - public DatabaseQuery query() { - return parent.query(name); - } - - @Nonnull - @Override - public DatabaseUpdate update() { - return parent.update(name); - } - - @Nonnull - @Override - public DatabaseInsertion insert() { - return parent.insert(name); - } - - @Nonnull - @Override - public DatabaseInsertionOrUpdate insertOrUpdate() { - return parent.insertOrUpdate(name); - } - - @Nonnull - @Override - public DatabaseDeletion delete() { - return parent.delete(name); - } - - @Nonnull - @Override - public Database getParent() { - return parent; - } - - @Override - public String toString() { - return "SpecificDatabase[" + name + "]"; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - DefaultSpecificDatabase that = (DefaultSpecificDatabase) o; - return Objects.equals(parent, that.parent) && Objects.equals(name, that.name); - } - - @Override - public int hashCode() { - return Objects.hash(parent, name); - } + protected final Database parent; + protected final String name; + + public DefaultSpecificDatabase(@Nonnull Database parent, @Nonnull String name) { + this.parent = parent; + this.name = name; + } + + @Override + public boolean isConnected() { + return parent.isConnected(); + } + + @Nonnull + @Override + public String getName() { + return name; + } + + @Nonnull + @Override + public DatabaseCountEntries countEntries() { + return parent.countEntries(name); + } + + @Nonnull + @Override + public DatabaseQuery query() { + return parent.query(name); + } + + @Nonnull + @Override + public DatabaseUpdate update() { + return parent.update(name); + } + + @Nonnull + @Override + public DatabaseInsertion insert() { + return parent.insert(name); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate() { + return parent.insertOrUpdate(name); + } + + @Nonnull + @Override + public DatabaseDeletion delete() { + return parent.delete(name); + } + + @Nonnull + @Override + public Database getParent() { + return parent; + } + + @Override + public String toString() { + return "SpecificDatabase[" + name + "]"; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DefaultSpecificDatabase that = (DefaultSpecificDatabase) o; + return Objects.equals(parent, that.parent) && Objects.equals(name, that.name); + } + + @Override + public int hashCode() { + return Objects.hash(parent, name); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java b/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java index 118141f4e..638b0d965 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java +++ b/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java @@ -14,72 +14,72 @@ public class CachedDatabaseAccess extends DirectDatabaseAccess { - protected final Map cache = new ConcurrentHashMap<>(); - - public CachedDatabaseAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config, @Nonnull BiFunction mapper) { - super(database, config, mapper); - } - - @Nullable - @Override - public V getValue(@Nonnull String key) throws DatabaseException { - V value = cache.get(key); - if (value != null) return value; - - value = super.getValue(key); - cache.put(key, value); - return value; - } - - @Nonnull - @Override - public V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException { - V value = cache.get(key); - if (value != null) return value; - - value = super.getValue(key, def); - cache.put(key, value); - return value; - } - - @Nonnull - @Override - public Optional getValueOptional(@Nonnull String key) throws DatabaseException { - V cached = cache.get(key); - if (cached != null) return Optional.of(cached); - - return super.getValueOptional(key); - } - - @Override - public void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException { - cache.put(key, value); - super.setValue(key, value); - } - - @Nonnull - public static CachedDatabaseAccess newStringAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { - return new CachedDatabaseAccess<>(database, config, Propertyable::getString); - } - - @Nonnull - public static CachedDatabaseAccess newIntAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { - return new CachedDatabaseAccess<>(database, config, Propertyable::getInt); - } - - @Nonnull - public static CachedDatabaseAccess newLongAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { - return new CachedDatabaseAccess<>(database, config, Propertyable::getLong); - } - - @Nonnull - public static CachedDatabaseAccess newDoubleAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { - return new CachedDatabaseAccess<>(database, config, Propertyable::getDouble); - } - - @Nonnull - public static CachedDatabaseAccess newDocumentAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { - return new CachedDatabaseAccess<>(database, config, Document::getDocument); - } + protected final Map cache = new ConcurrentHashMap<>(); + + public CachedDatabaseAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config, @Nonnull BiFunction mapper) { + super(database, config, mapper); + } + + @Nullable + @Override + public V getValue(@Nonnull String key) throws DatabaseException { + V value = cache.get(key); + if (value != null) return value; + + value = super.getValue(key); + cache.put(key, value); + return value; + } + + @Nonnull + @Override + public V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException { + V value = cache.get(key); + if (value != null) return value; + + value = super.getValue(key, def); + cache.put(key, value); + return value; + } + + @Nonnull + @Override + public Optional getValueOptional(@Nonnull String key) throws DatabaseException { + V cached = cache.get(key); + if (cached != null) return Optional.of(cached); + + return super.getValueOptional(key); + } + + @Override + public void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException { + cache.put(key, value); + super.setValue(key, value); + } + + @Nonnull + public static CachedDatabaseAccess newStringAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getString); + } + + @Nonnull + public static CachedDatabaseAccess newIntAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getInt); + } + + @Nonnull + public static CachedDatabaseAccess newLongAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getLong); + } + + @Nonnull + public static CachedDatabaseAccess newDoubleAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Propertyable::getDouble); + } + + @Nonnull + public static CachedDatabaseAccess newDocumentAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + return new CachedDatabaseAccess<>(database, config, Document::getDocument); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java index 9215c50cd..0870dfb8d 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java +++ b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java @@ -9,25 +9,25 @@ public interface DatabaseAccess { - @Nullable - V getValue(@Nonnull String key) throws DatabaseException; + @Nullable + V getValue(@Nonnull String key) throws DatabaseException; - @Nonnull - V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException; + @Nonnull + V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException; - @Nonnull - Optional getValueOptional(@Nonnull String key) throws DatabaseException; + @Nonnull + Optional getValueOptional(@Nonnull String key) throws DatabaseException; - void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException; + void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException; - default boolean hasValue(@Nonnull String key) throws DatabaseException { - return getValueOptional(key).isPresent(); - } + default boolean hasValue(@Nonnull String key) throws DatabaseException { + return getValueOptional(key).isPresent(); + } - @Nonnull - Database getDatabase(); + @Nonnull + Database getDatabase(); - @Nonnull - DatabaseAccessConfig getConfig(); + @Nonnull + DatabaseAccessConfig getConfig(); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java index 824b8bbdd..edbaae624 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java +++ b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java @@ -4,29 +4,29 @@ public final class DatabaseAccessConfig { - private final String table; - private final String keyField; - private final String valueField; - - public DatabaseAccessConfig(@Nonnull String table, @Nonnull String keyField, @Nonnull String valueField) { - this.table = table; - this.keyField = keyField; - this.valueField = valueField; - } - - @Nonnull - public String getTable() { - return table; - } - - @Nonnull - public String getKeyField() { - return keyField; - } - - @Nonnull - public String getValueField() { - return valueField; - } + private final String table; + private final String keyField; + private final String valueField; + + public DatabaseAccessConfig(@Nonnull String table, @Nonnull String keyField, @Nonnull String valueField) { + this.table = table; + this.keyField = keyField; + this.valueField = valueField; + } + + @Nonnull + public String getTable() { + return table; + } + + @Nonnull + public String getKeyField() { + return keyField; + } + + @Nonnull + public String getValueField() { + return valueField; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java b/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java index e2213d1bc..902b1b6e3 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java +++ b/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java @@ -11,59 +11,59 @@ public class DirectDatabaseAccess implements DatabaseAccess { - protected final Database database; - protected final DatabaseAccessConfig config; - protected final BiFunction mapper; + protected final Database database; + protected final DatabaseAccessConfig config; + protected final BiFunction mapper; - public DirectDatabaseAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config, @Nonnull BiFunction mapper) { - this.database = database; - this.config = config; - this.mapper = mapper; - } + public DirectDatabaseAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config, @Nonnull BiFunction mapper) { + this.database = database; + this.config = config; + this.mapper = mapper; + } - @Nullable - @Override - public V getValue(@Nonnull String key) throws DatabaseException { - return getValue0(key).orElse(null); - } + @Nullable + @Override + public V getValue(@Nonnull String key) throws DatabaseException { + return getValue0(key).orElse(null); + } - @Nonnull - @Override - public V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException { - return getValue0(key).orElse(def); - } + @Nonnull + @Override + public V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException { + return getValue0(key).orElse(def); + } - @Nonnull - @Override - public Optional getValueOptional(@Nonnull String key) throws DatabaseException { - return getValue0(key); - } + @Nonnull + @Override + public Optional getValueOptional(@Nonnull String key) throws DatabaseException { + return getValue0(key); + } - @Nonnull - protected Optional getValue0(@Nonnull String key) throws DatabaseException { - return database.query(config.getTable()) - .where(config.getKeyField(), key) - .execute().first() - .map(document -> mapper.apply(document, config.getValueField())); - } + @Nonnull + protected Optional getValue0(@Nonnull String key) throws DatabaseException { + return database.query(config.getTable()) + .where(config.getKeyField(), key) + .execute().first() + .map(document -> mapper.apply(document, config.getValueField())); + } - @Override - public void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException { - database.insertOrUpdate(config.getTable()) - .set(config.getValueField(), value) - .where(config.getKeyField(), key) - .execute(); - } + @Override + public void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException { + database.insertOrUpdate(config.getTable()) + .set(config.getValueField(), value) + .where(config.getKeyField(), key) + .execute(); + } - @Nonnull - @Override - public Database getDatabase() { - return database; - } + @Nonnull + @Override + public Database getDatabase() { + return database; + } - @Nonnull - @Override - public DatabaseAccessConfig getConfig() { - return config; - } + @Nonnull + @Override + public DatabaseAccessConfig getConfig() { + return config; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java index da7a8ee61..b2f0fde7f 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java @@ -12,25 +12,23 @@ /** * Some action which will be executed on a database. - * + *

* This action is only prepared. - * + *

* It will be executed synchronously by calling {@link #execute()}, * a {@link DatabaseException} will be thrown when something goes from or * a {@link DatabaseConnectionClosedException} will be thrown * when the connection to the database is already closed. - * + *

* It will also be executed synchronously by calling {@link #executeUnsigned()} but this method has no signed exceptions ({@code throws} declaration), * so when an exception occurs it will be rethrown as a {@link UnsignedDatabaseException}. - * + *

* Calling {@link #executeAsync()} will return a new {@link Task} which will complete when the action is done or fail if something went wrong (a {@link DatabaseException} was thrown). * * @param The type of the result this action will return - * * @see WhereAction * @see SetAction * @see OrderedAction - * * @see DatabaseListTables * @see DatabaseCountEntries * @see DatabaseDeletion @@ -41,42 +39,37 @@ */ public interface DatabaseAction { - /** - * Executes this action synchronously - * - * @return the result of type {@link R} returned by the database - * - * @throws DatabaseException - * If a database error occurs - * @throws DatabaseConnectionClosedException - * If the database is no longer connected - */ - R execute() throws DatabaseException; + /** + * Executes this action synchronously + * + * @return the result of type {@link R} returned by the database + * @throws DatabaseException If a database error occurs + * @throws DatabaseConnectionClosedException If the database is no longer connected + */ + R execute() throws DatabaseException; - /** - * Executes this action synchronously without any signed exceptions - * - * @return the result of type {@link R} returned by the database - * - * @throws UnsignedDatabaseException - * If a database error occurs - */ - default R executeUnsigned() { - try { - return execute(); - } catch (DatabaseException ex) { - throw new UnsignedDatabaseException(ex); - } - } + /** + * Executes this action synchronously without any signed exceptions + * + * @return the result of type {@link R} returned by the database + * @throws UnsignedDatabaseException If a database error occurs + */ + default R executeUnsigned() { + try { + return execute(); + } catch (DatabaseException ex) { + throw new UnsignedDatabaseException(ex); + } + } - /** - * Executes this action asynchronous - * - * @return a new {@link Task} which will be completed when the action was executed - */ - @Nonnull - default Task executeAsync() { - return Task.asyncCall(this::execute); - } + /** + * Executes this action asynchronous + * + * @return a new {@link Task} which will be completed when the action was executed + */ + @Nonnull + default Task executeAsync() { + return Task.asyncCall(this::execute); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java index 70bedb389..67206e3be 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java @@ -13,9 +13,9 @@ */ public interface DatabaseCountEntries extends DatabaseAction { - @Nonnull - @Override - @Nonnegative - Long execute() throws DatabaseException; + @Nonnull + @Override + @Nonnegative + Long execute() throws DatabaseException; } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java index 3c3b20fe1..1f02e8392 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java @@ -15,28 +15,28 @@ */ public interface DatabaseDeletion extends DatabaseAction, WhereAction { - @Nonnull - @CheckReturnValue - DatabaseDeletion where(@Nonnull String field, @Nullable Object value); + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable Object value); - @Nonnull - @CheckReturnValue - DatabaseDeletion where(@Nonnull String field, @Nullable Number value); + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable Number value); - @Nonnull - @CheckReturnValue - DatabaseDeletion where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable String value, boolean ignoreCase); - @Nonnull - @CheckReturnValue - DatabaseDeletion where(@Nonnull String field, @Nullable String value); + @Nonnull + @CheckReturnValue + DatabaseDeletion where(@Nonnull String field, @Nullable String value); - @Nonnull - @CheckReturnValue - DatabaseDeletion whereNot(@Nonnull String field, @Nullable Object value); + @Nonnull + @CheckReturnValue + DatabaseDeletion whereNot(@Nonnull String field, @Nullable Object value); - @Nullable - @Override - Void execute() throws DatabaseException; + @Nullable + @Override + Void execute() throws DatabaseException; } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java index ef0d7b8ca..2feb77399 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java @@ -15,12 +15,12 @@ */ public interface DatabaseInsertion extends DatabaseAction, SetAction { - @Nonnull - @CheckReturnValue - DatabaseInsertion set(@Nonnull String field, @Nullable Object value); + @Nonnull + @CheckReturnValue + DatabaseInsertion set(@Nonnull String field, @Nullable Object value); - @Nullable - @Override - Void execute() throws DatabaseException; + @Nullable + @Override + Void execute() throws DatabaseException; } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java index 000f76a09..c97385028 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java @@ -14,32 +14,32 @@ */ public interface DatabaseInsertionOrUpdate extends DatabaseUpdate, DatabaseInsertion { - @Nonnull - @CheckReturnValue - DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Object value); + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Object value); - @Nonnull - @CheckReturnValue - DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Number value); + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Number value); - @Nonnull - @CheckReturnValue - DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase); - @Nonnull - @CheckReturnValue - DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value); + @Nonnull + @CheckReturnValue + DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value); - @Nonnull - @Override - DatabaseInsertionOrUpdate whereNot(@Nonnull String field, @Nullable Object value); + @Nonnull + @Override + DatabaseInsertionOrUpdate whereNot(@Nonnull String field, @Nullable Object value); - @Nonnull - @Override - DatabaseInsertionOrUpdate set(@Nonnull String field, @Nullable Object value); + @Nonnull + @Override + DatabaseInsertionOrUpdate set(@Nonnull String field, @Nullable Object value); - @Nullable - @Override - Void execute() throws DatabaseException; + @Nullable + @Override + Void execute() throws DatabaseException; } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java index be7173659..27ac72e78 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java @@ -11,8 +11,8 @@ */ public interface DatabaseListTables extends DatabaseAction> { - @Nonnull - @Override - List execute() throws DatabaseException; + @Nonnull + @Override + List execute() throws DatabaseException; } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java index 770b8b542..8cf667d39 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java @@ -17,37 +17,37 @@ */ public interface DatabaseQuery extends DatabaseAction, WhereAction, OrderedAction { - @Nonnull - @CheckReturnValue - DatabaseQuery where(@Nonnull String field, @Nullable Object object); - - @Nonnull - @CheckReturnValue - DatabaseQuery where(@Nonnull String field, @Nullable Number value); - - @Nonnull - @CheckReturnValue - DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase); - - @Nonnull - @CheckReturnValue - DatabaseQuery where(@Nonnull String field, @Nullable String value); - - @Nonnull - @CheckReturnValue - DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value); - - @Nonnull - @CheckReturnValue - DatabaseQuery select(@Nonnull String... selection); - - @Nonnull - @CheckReturnValue - DatabaseQuery orderBy(@Nonnull String field, @Nonnull Order order); - - @Nonnull - @Override - @CheckReturnValue - ExecutedQuery execute() throws DatabaseException; + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable Object object); + + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable Number value); + + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + + @Nonnull + @CheckReturnValue + DatabaseQuery where(@Nonnull String field, @Nullable String value); + + @Nonnull + @CheckReturnValue + DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value); + + @Nonnull + @CheckReturnValue + DatabaseQuery select(@Nonnull String... selection); + + @Nonnull + @CheckReturnValue + DatabaseQuery orderBy(@Nonnull String field, @Nonnull Order order); + + @Nonnull + @Override + @CheckReturnValue + ExecutedQuery execute() throws DatabaseException; } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java index 83073b113..d39831207 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java @@ -16,32 +16,32 @@ */ public interface DatabaseUpdate extends DatabaseAction, WhereAction, SetAction { - @Nonnull - @CheckReturnValue - DatabaseUpdate where(@Nonnull String field, @Nullable Object value); + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable Object value); - @Nonnull - @CheckReturnValue - DatabaseUpdate where(@Nonnull String field, @Nullable Number value); + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable Number value); - @Nonnull - @CheckReturnValue - DatabaseUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase); - @Nonnull - @CheckReturnValue - DatabaseUpdate where(@Nonnull String field, @Nullable String value); + @Nonnull + @CheckReturnValue + DatabaseUpdate where(@Nonnull String field, @Nullable String value); - @Nonnull - @CheckReturnValue - DatabaseUpdate whereNot(@Nonnull String field, @Nullable Object value); + @Nonnull + @CheckReturnValue + DatabaseUpdate whereNot(@Nonnull String field, @Nullable Object value); - @Nonnull - @CheckReturnValue - DatabaseUpdate set(@Nonnull String field, @Nullable Object value); + @Nonnull + @CheckReturnValue + DatabaseUpdate set(@Nonnull String field, @Nullable Object value); - @Nullable - @Override - Void execute() throws DatabaseException; + @Nullable + @Override + Void execute() throws DatabaseException; } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java b/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java index 37cf98630..70520483c 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java @@ -17,70 +17,70 @@ */ public interface ExecutedQuery extends Iterable { - @Nonnull - @CheckReturnValue - Optional first(); + @Nonnull + @CheckReturnValue + Optional first(); - @Nonnull - @CheckReturnValue - default Document firstOrEmpty() { - return first().orElse(Document.empty()); - } + @Nonnull + @CheckReturnValue + default Document firstOrEmpty() { + return first().orElse(Document.empty()); + } - @Nonnull - @CheckReturnValue - Optional get(int index); + @Nonnull + @CheckReturnValue + Optional get(int index); - @Nonnull - @CheckReturnValue - default Document getOrEmpty(int index) { - return get(index).orElse(Document.empty()); - } + @Nonnull + @CheckReturnValue + default Document getOrEmpty(int index) { + return get(index).orElse(Document.empty()); + } - @Nonnull - @CheckReturnValue - Stream all(); + @Nonnull + @CheckReturnValue + Stream all(); - @Nonnull - @CheckReturnValue - default List toList() { - return toCollection((IntFunction>) ArrayList::new); - } + @Nonnull + @CheckReturnValue + default List toList() { + return toCollection((IntFunction>) ArrayList::new); + } - @Nonnull - @CheckReturnValue - default Set toSet() { - return toCollection((IntFunction>) HashSet::new); - } + @Nonnull + @CheckReturnValue + default Set toSet() { + return toCollection((IntFunction>) HashSet::new); + } - @Nonnull - > C toCollection(@Nonnull C collection); + @Nonnull + > C toCollection(@Nonnull C collection); - @Nonnull - @CheckReturnValue - default > C toCollection(@Nonnull IntFunction collectionSupplier) { - return toCollection(collectionSupplier.apply(size())); - } + @Nonnull + @CheckReturnValue + default > C toCollection(@Nonnull IntFunction collectionSupplier) { + return toCollection(collectionSupplier.apply(size())); + } - @Nonnull - Document[] toArray(@Nonnull IntFunction arraySupplier); + @Nonnull + Document[] toArray(@Nonnull IntFunction arraySupplier); - int index(@Nonnull Predicate filter); + int index(@Nonnull Predicate filter); - boolean isEmpty(); + boolean isEmpty(); - boolean isSet(); + boolean isSet(); - int size(); + int size(); - void print(@Nonnull PrintStream out); + void print(@Nonnull PrintStream out); - default void print(@Nonnull ILogger logger) { - print(logger.asPrintStream(LogLevel.INFO)); - } + default void print(@Nonnull ILogger logger) { + print(logger.asPrintStream(LogLevel.INFO)); + } - default void print() { - print(System.out); - } + default void print() { + print(System.out); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java index edfdc29b1..7f7446830 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java @@ -7,7 +7,7 @@ public interface OrderedAction { - @Nullable - OrderedAction orderBy(@Nonnull String field, @Nonnull Order order); + @Nullable + OrderedAction orderBy(@Nonnull String field, @Nonnull Order order); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java index cb395773b..c22e7970f 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java @@ -5,7 +5,7 @@ public interface SetAction { - @Nonnull - SetAction set(@Nonnull String field, @Nullable Object value); + @Nonnull + SetAction set(@Nonnull String field, @Nullable Object value); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java index 5e5d69c9d..6df5c791b 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java @@ -6,24 +6,24 @@ public interface WhereAction { - @Nonnull - @CheckReturnValue - WhereAction where(@Nonnull String field, @Nullable Object value); + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable Object value); - @Nonnull - @CheckReturnValue - WhereAction where(@Nonnull String field, @Nullable Number value); + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable Number value); - @Nonnull - @CheckReturnValue - WhereAction where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable String value, boolean ignoreCase); - @Nonnull - @CheckReturnValue - WhereAction where(@Nonnull String field, @Nullable String value); + @Nonnull + @CheckReturnValue + WhereAction where(@Nonnull String field, @Nullable String value); - @Nonnull - @CheckReturnValue - WhereAction whereNot(@Nonnull String field, @Nullable Object value); + @Nonnull + @CheckReturnValue + WhereAction whereNot(@Nonnull String field, @Nullable Object value); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseAlreadyConnectedException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseAlreadyConnectedException.java index 192f891f6..2e9f28e0f 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseAlreadyConnectedException.java +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseAlreadyConnectedException.java @@ -5,8 +5,8 @@ */ public class DatabaseAlreadyConnectedException extends DatabaseException { - public DatabaseAlreadyConnectedException() { - super("Database already connected"); - } + public DatabaseAlreadyConnectedException() { + super("Database already connected"); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseConnectionClosedException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseConnectionClosedException.java index f3563f241..603bf2223 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseConnectionClosedException.java +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseConnectionClosedException.java @@ -5,8 +5,8 @@ */ public class DatabaseConnectionClosedException extends DatabaseException { - public DatabaseConnectionClosedException() { - super("Database connection closed"); - } + public DatabaseConnectionClosedException() { + super("Database connection closed"); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java index d42805661..49722e7e7 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java @@ -8,24 +8,23 @@ * @see DatabaseAlreadyConnectedException * @see DatabaseConnectionClosedException * @see DatabaseUnsupportedFeatureException - * * @see DatabaseAction#execute() */ public class DatabaseException extends Exception { - protected DatabaseException() { - super(); - } + protected DatabaseException() { + super(); + } - public DatabaseException(@Nonnull String message) { - super(message); - } + public DatabaseException(@Nonnull String message) { + super(message); + } - public DatabaseException(@Nonnull Throwable cause) { - super(cause); - } + public DatabaseException(@Nonnull Throwable cause) { + super(cause); + } - public DatabaseException(@Nonnull String message, @Nonnull Throwable cause) { - super(message, cause); - } + public DatabaseException(@Nonnull String message, @Nonnull Throwable cause) { + super(message, cause); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java index 0f57f6827..5aa24fd12 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java @@ -4,11 +4,11 @@ public class DatabaseUnsupportedFeatureException extends DatabaseException { - public DatabaseUnsupportedFeatureException() { - } + public DatabaseUnsupportedFeatureException() { + } - public DatabaseUnsupportedFeatureException(@Nonnull String message) { - super(message); - } + public DatabaseUnsupportedFeatureException(@Nonnull String message) { + super(message); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java index a5f96d5f9..c9137b8b5 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java @@ -7,18 +7,17 @@ /** * @see DatabaseException - * * @see DatabaseAction#executeUnsigned() */ public class UnsignedDatabaseException extends WrappedException { - public UnsignedDatabaseException(@Nonnull DatabaseException cause) { - super(cause); - } + public UnsignedDatabaseException(@Nonnull DatabaseException cause) { + super(cause); + } - @Nonnull - @Override - public DatabaseException getCause() { - return (DatabaseException) super.getCause(); - } + @Nonnull + @Override + public DatabaseException getCause() { + return (DatabaseException) super.getCause(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java index 10887b6c3..19551869f 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java @@ -2,9 +2,9 @@ import net.codingarea.commons.database.DatabaseConfig; import net.codingarea.commons.database.SQLColumn; +import net.codingarea.commons.database.abstraction.AbstractDatabase; import net.codingarea.commons.database.action.*; import net.codingarea.commons.database.exceptions.DatabaseException; -import net.codingarea.commons.database.abstraction.AbstractDatabase; import net.codingarea.commons.database.sql.abstraction.count.SQLCountEntries; import net.codingarea.commons.database.sql.abstraction.deletion.SQLDeletion; import net.codingarea.commons.database.sql.abstraction.insertion.SQLInsertion; @@ -22,113 +22,113 @@ public abstract class AbstractSQLDatabase extends AbstractDatabase { - protected Connection connection; - - public AbstractSQLDatabase(@Nonnull DatabaseConfig config) { - super(config); - } - - @Override - public void disconnect0() throws Exception { - connection.close(); - connection = null; - } - - @Override - public void connect0() throws Exception { - connection = DriverManager.getConnection(createUrl(), config.getUser(), config.getPassword()); - } - - protected abstract String createUrl(); - - @Override - public boolean isConnected() { - try { - if (connection == null) return false; - connection.isClosed(); - return true; - } catch (SQLException ex) { - LOGGER.error("Could not check connection state: " + ex.getMessage()); - return false; - } - } - - @Override - public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { - try { - StringBuilder command = new StringBuilder(); - command.append("CREATE TABLE IF NOT EXISTS `"); - command.append(name); - command.append("` ("); - { - int index = 0; - for (SQLColumn column : columns) { - if (index > 0) command.append(", "); - command.append(column); - index++; - } - } - command.append(")"); - - PreparedStatement statement = prepare(command.toString()); - statement.execute(); - } catch (Exception ex) { - throw new DatabaseException(ex); - } - } - - @Nonnull - @Override - public DatabaseCountEntries countEntries(@Nonnull String table) { - return new SQLCountEntries(this, table); - } - - @Nonnull - @Override - public DatabaseQuery query(@Nonnull String table) { - return new SQLQuery(this, table); - } - - @Nonnull - public DatabaseQuery query(@Nonnull String table, @Nonnull Map where) { - return new SQLQuery(this, table, where); - } - - @Nonnull - @Override - public DatabaseUpdate update(@Nonnull String table) { - return new SQLUpdate(this, table); - } - - @Nonnull - @Override - public DatabaseInsertion insert(@Nonnull String table) { - return new SQLInsertion(this, table); - } - - @Nonnull - public DatabaseInsertion insert(@Nonnull String table, @Nonnull Map values) { - return new SQLInsertion(this, table, values); - } - - @Nonnull - @Override - public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { - return new SQLInsertionOrUpdate(this, table); - } - - @Nonnull - @Override - public DatabaseDeletion delete(@Nonnull String table) { - return new SQLDeletion(this, table); - } - - @Nonnull - public PreparedStatement prepare(@Nonnull CharSequence command, @Nonnull Object... args) throws SQLException, DatabaseException { - checkConnection(); - PreparedStatement statement = connection.prepareStatement(command.toString()); - SQLHelper.fillParams(statement, args); - return statement; - } + protected Connection connection; + + public AbstractSQLDatabase(@Nonnull DatabaseConfig config) { + super(config); + } + + @Override + public void disconnect0() throws Exception { + connection.close(); + connection = null; + } + + @Override + public void connect0() throws Exception { + connection = DriverManager.getConnection(createUrl(), config.getUser(), config.getPassword()); + } + + protected abstract String createUrl(); + + @Override + public boolean isConnected() { + try { + if (connection == null) return false; + connection.isClosed(); + return true; + } catch (SQLException ex) { + LOGGER.error("Could not check connection state: " + ex.getMessage()); + return false; + } + } + + @Override + public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { + try { + StringBuilder command = new StringBuilder(); + command.append("CREATE TABLE IF NOT EXISTS `"); + command.append(name); + command.append("` ("); + { + int index = 0; + for (SQLColumn column : columns) { + if (index > 0) command.append(", "); + command.append(column); + index++; + } + } + command.append(")"); + + PreparedStatement statement = prepare(command.toString()); + statement.execute(); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Nonnull + @Override + public DatabaseCountEntries countEntries(@Nonnull String table) { + return new SQLCountEntries(this, table); + } + + @Nonnull + @Override + public DatabaseQuery query(@Nonnull String table) { + return new SQLQuery(this, table); + } + + @Nonnull + public DatabaseQuery query(@Nonnull String table, @Nonnull Map where) { + return new SQLQuery(this, table, where); + } + + @Nonnull + @Override + public DatabaseUpdate update(@Nonnull String table) { + return new SQLUpdate(this, table); + } + + @Nonnull + @Override + public DatabaseInsertion insert(@Nonnull String table) { + return new SQLInsertion(this, table); + } + + @Nonnull + public DatabaseInsertion insert(@Nonnull String table, @Nonnull Map values) { + return new SQLInsertion(this, table, values); + } + + @Nonnull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { + return new SQLInsertionOrUpdate(this, table); + } + + @Nonnull + @Override + public DatabaseDeletion delete(@Nonnull String table) { + return new SQLDeletion(this, table); + } + + @Nonnull + public PreparedStatement prepare(@Nonnull CharSequence command, @Nonnull Object... args) throws SQLException, DatabaseException { + checkConnection(); + PreparedStatement statement = connection.prepareStatement(command.toString()); + SQLHelper.fillParams(statement, args); + return statement; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java index 9fdf86b6c..e53c76cbd 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java @@ -12,26 +12,28 @@ public final class SQLHelper { - private SQLHelper() {} + private SQLHelper() { + } - public static void fillParams(@Nonnull PreparedStatement statement, @Nonnull Object... params) throws SQLException { - for (int i = 0; i < params.length; i++) { - Object param = serializeObject(params[i]); - statement.setObject(i + 1 /* in sql we count from 1 */, param); - } - } + public static void fillParams(@Nonnull PreparedStatement statement, @Nonnull Object... params) throws SQLException { + for (int i = 0; i < params.length; i++) { + Object param = serializeObject(params[i]); + statement.setObject(i + 1 /* in sql we count from 1 */, param); + } + } - @Nullable - public static Object serializeObject(@Nullable Object object) { - if (object == null) return null; - if (object instanceof Number) return object; - if (object instanceof Boolean) return object; - if (object instanceof Enum) return ((Enum)object).name(); - if (object instanceof Json) return ((Json)object).toJson(); - if (object instanceof Map) return new GsonDocument((Map) object).toJson(); - if (object instanceof Iterable) return GsonUtils.convertIterableToJsonArray(GsonDocument.GSON, (Iterable) object).toString(); - if (object.getClass().isArray()) return GsonUtils.convertArrayToJsonArray(GsonDocument.GSON, object).toString(); - return object.toString(); - } + @Nullable + public static Object serializeObject(@Nullable Object object) { + if (object == null) return null; + if (object instanceof Number) return object; + if (object instanceof Boolean) return object; + if (object instanceof Enum) return ((Enum) object).name(); + if (object instanceof Json) return ((Json) object).toJson(); + if (object instanceof Map) return new GsonDocument((Map) object).toJson(); + if (object instanceof Iterable) + return GsonUtils.convertIterableToJsonArray(GsonDocument.GSON, (Iterable) object).toString(); + if (object.getClass().isArray()) return GsonUtils.convertArrayToJsonArray(GsonDocument.GSON, object).toString(); + return object.toString(); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java index dbf6aa821..a0100ab1e 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java @@ -11,44 +11,44 @@ public class SQLCountEntries implements DatabaseCountEntries { - protected final AbstractSQLDatabase database; - protected final String table; - - public SQLCountEntries(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { - this.database = database; - this.table = table; - } - - @Nonnull - @Override - public Long execute() throws DatabaseException { - try { - PreparedStatement statement = database.prepare("SELECT COUNT(*) FROM `" + table + "`"); - ResultSet result = statement.executeQuery(); - - if (!result.next()) { - result.close(); - return 0L; - } - - long count = result.getLong(1); - result.close(); - return count; - } catch (Exception ex) { - throw new DatabaseException(ex); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - SQLCountEntries that = (SQLCountEntries) o; - return Objects.equals(database, that.database) && Objects.equals(table, that.table); - } - - @Override - public int hashCode() { - return Objects.hash(database, table); - } + protected final AbstractSQLDatabase database; + protected final String table; + + public SQLCountEntries(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + } + + @Nonnull + @Override + public Long execute() throws DatabaseException { + try { + PreparedStatement statement = database.prepare("SELECT COUNT(*) FROM `" + table + "`"); + ResultSet result = statement.executeQuery(); + + if (!result.next()) { + result.close(); + return 0L; + } + + long count = result.getLong(1); + result.close(); + return count; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLCountEntries that = (SQLCountEntries) o; + return Objects.equals(database, that.database) && Objects.equals(table, that.table); + } + + @Override + public int hashCode() { + return Objects.hash(database, table); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java index d1dfeaf9b..14a3239c5 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java @@ -16,95 +16,95 @@ public class SQLDeletion implements DatabaseDeletion { - protected final AbstractSQLDatabase database; - protected final String table; - protected final Map where = new HashMap<>(); - - public SQLDeletion(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { - this.database = database; - this.table = table; - } - - @Nonnull - @Override - public DatabaseDeletion where(@Nonnull String column, @Nullable Object value) { - where.put(column, new ObjectWhere(column, value, "=")); - return this; - } - - @Nonnull - @Override - public DatabaseDeletion where(@Nonnull String column, @Nullable Number value) { - return where(column, (Object) value); - } - - @Nonnull - @Override - public DatabaseDeletion where(@Nonnull String column, @Nullable String value) { - return where(column, (Object) value); - } - - @Nonnull - @Override - public DatabaseDeletion where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { - if (!ignoreCase) return where(column, value); - if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); - where.put(column, new StringIgnoreCaseWhere(column, value)); - return this; - } - - @Nonnull - @Override - public DatabaseDeletion whereNot(@Nonnull String column, @Nullable Object value) { - where.put(column, new ObjectWhere(column, value, "!=")); - return this; - } - - @Nonnull - protected PreparedStatement prepare() throws SQLException, DatabaseException { - StringBuilder command = new StringBuilder(); - List args = new ArrayList<>(); - - command.append("DELETE FROM "); - command.append(table); - - if (!where.isEmpty()) { - command.append(" WHERE "); - int index = 0; - for (Entry entry : where.entrySet()) { - SQLWhere where = entry.getValue(); - if (index > 0) command.append(" AND "); - command.append(where.getAsSQLString()); - args.addAll(Arrays.asList(where.getArgs())); - index++; - } - } - - return database.prepare(command.toString(),args.toArray()); - } - - @Override - public Void execute() throws DatabaseException { - try { - PreparedStatement statement = prepare(); - statement.execute(); - return null; - } catch (Exception ex) { - throw new DatabaseException(ex); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - SQLDeletion that = (SQLDeletion) o; - return database.equals(that.database) && table.equals(that.table) && where.equals(that.where); - } - - @Override - public int hashCode() { - return Objects.hash(database, table, where); - } + protected final AbstractSQLDatabase database; + protected final String table; + protected final Map where = new HashMap<>(); + + public SQLDeletion(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "=")); + return this; + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseDeletion where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @Nonnull + @Override + public DatabaseDeletion whereNot(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "!=")); + return this; + } + + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + StringBuilder command = new StringBuilder(); + List args = new ArrayList<>(); + + command.append("DELETE FROM "); + command.append(table); + + if (!where.isEmpty()) { + command.append(" WHERE "); + int index = 0; + for (Entry entry : where.entrySet()) { + SQLWhere where = entry.getValue(); + if (index > 0) command.append(" AND "); + command.append(where.getAsSQLString()); + args.addAll(Arrays.asList(where.getArgs())); + index++; + } + } + + return database.prepare(command.toString(), args.toArray()); + } + + @Override + public Void execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + statement.execute(); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLDeletion that = (SQLDeletion) o; + return database.equals(that.database) && table.equals(that.table) && where.equals(that.where); + } + + @Override + public int hashCode() { + return Objects.hash(database, table, where); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java index 6af25eaa4..a2b397b48 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java @@ -12,84 +12,84 @@ public class SQLInsertion implements DatabaseInsertion { - protected final Map values; - protected final AbstractSQLDatabase database; - protected final String table; + protected final Map values; + protected final AbstractSQLDatabase database; + protected final String table; - public SQLInsertion(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { - this.database = database; - this.table = table; - this.values = new HashMap<>(); - } + public SQLInsertion(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + this.values = new HashMap<>(); + } - public SQLInsertion(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map values) { - this.database = database; - this.table = table; - this.values = values; - } + public SQLInsertion(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map values) { + this.database = database; + this.table = table; + this.values = values; + } - @Nonnull - @Override - public DatabaseInsertion set(@Nonnull String field, @Nullable Object value) { - values.put(field, value); - return this; - } + @Nonnull + @Override + public DatabaseInsertion set(@Nonnull String field, @Nullable Object value) { + values.put(field, value); + return this; + } - @Nonnull - protected PreparedStatement prepare() throws SQLException, DatabaseException { - if (values.isEmpty()) throw new IllegalArgumentException("Cannot insert nothing"); + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + if (values.isEmpty()) throw new IllegalArgumentException("Cannot insert nothing"); - StringBuilder command = new StringBuilder(); - List args = new ArrayList<>(values.size()); + StringBuilder command = new StringBuilder(); + List args = new ArrayList<>(values.size()); - command.append("INSERT INTO "); - command.append(table); - command.append(" ("); - { - int index = 0; - for (String column : values.keySet()) { - if (index > 0) command.append(", "); - command.append(column); - index++; - } - } - command.append(") VALUES ("); - { - int index = 0; - for (Object value : values.values()) { - if (index > 0) command.append(", "); - command.append("?"); - args.add(value); - index++; - } - } - command.append(")"); + command.append("INSERT INTO "); + command.append(table); + command.append(" ("); + { + int index = 0; + for (String column : values.keySet()) { + if (index > 0) command.append(", "); + command.append(column); + index++; + } + } + command.append(") VALUES ("); + { + int index = 0; + for (Object value : values.values()) { + if (index > 0) command.append(", "); + command.append("?"); + args.add(value); + index++; + } + } + command.append(")"); - return database.prepare(command.toString(), args.toArray()); - } + return database.prepare(command.toString(), args.toArray()); + } - @Override - public Void execute() throws DatabaseException { - try { - PreparedStatement statement = prepare(); - statement.execute(); - return null; - } catch (Exception ex) { - throw new DatabaseException(ex); - } - } + @Override + public Void execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + statement.execute(); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - SQLInsertion that = (SQLInsertion) o; - return values.equals(that.values) && database.equals(that.database) && table.equals(that.table); - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLInsertion that = (SQLInsertion) o; + return values.equals(that.values) && database.equals(that.database) && table.equals(that.table); + } - @Override - public int hashCode() { - return Objects.hash(values, database, table); - } + @Override + public int hashCode() { + return Objects.hash(values, database, table); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java index f89cbc135..348a51d3d 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java @@ -14,72 +14,72 @@ public class SQLInsertionOrUpdate extends SQLUpdate implements DatabaseInsertionOrUpdate { - public SQLInsertionOrUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { - super(database, table); - } + public SQLInsertionOrUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + super(database, table); + } - @Nonnull - @Override - public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable Object value) { - super.where(column, value); - return this; - } + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable Object value) { + super.where(column, value); + return this; + } - @Nonnull - @Override - public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable Number value) { - super.where(column, value); - return this; - } + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable Number value) { + super.where(column, value); + return this; + } - @Nonnull - @Override - public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { - super.where(column, value); - return this; - } + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + super.where(column, value); + return this; + } - @Nonnull - @Override - public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable String value) { - super.where(column, value); - return this; - } + @Nonnull + @Override + public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable String value) { + super.where(column, value); + return this; + } - @Nonnull - @Override - public DatabaseInsertionOrUpdate whereNot(@Nonnull String column, @Nullable Object value) { - super.whereNot(column, value); - return this; - } + @Nonnull + @Override + public DatabaseInsertionOrUpdate whereNot(@Nonnull String column, @Nullable Object value) { + super.whereNot(column, value); + return this; + } - @Nonnull - @Override - public DatabaseInsertionOrUpdate set(@Nonnull String column, @Nullable Object value) { - super.set(column, value); - return this; - } + @Nonnull + @Override + public DatabaseInsertionOrUpdate set(@Nonnull String column, @Nullable Object value) { + super.set(column, value); + return this; + } - @Override - public Void execute() throws DatabaseException { - if (database.query(table, where).execute().isSet()) { - return super.execute(); - } else { - Map insert = new HashMap<>(values); - for (Entry entry : where.entrySet()) { - Object[] args = entry.getValue().getArgs(); - if (args.length == 0) continue; - insert.put(entry.getKey(), args[0]); - } + @Override + public Void execute() throws DatabaseException { + if (database.query(table, where).execute().isSet()) { + return super.execute(); + } else { + Map insert = new HashMap<>(values); + for (Entry entry : where.entrySet()) { + Object[] args = entry.getValue().getArgs(); + if (args.length == 0) continue; + insert.put(entry.getKey(), args[0]); + } - database.insert(table, insert).execute(); - return null; - } - } + database.insert(table, insert).execute(); + return null; + } + } - @Override - public boolean equals(Object o) { - return super.equals(o); - } + @Override + public boolean equals(Object o) { + return super.equals(o); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java index 75536fe81..814a05b7f 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java @@ -2,10 +2,10 @@ import net.codingarea.commons.common.config.Document; import net.codingarea.commons.database.Order; +import net.codingarea.commons.database.abstraction.DefaultExecutedQuery; import net.codingarea.commons.database.action.DatabaseQuery; import net.codingarea.commons.database.action.ExecutedQuery; import net.codingarea.commons.database.exceptions.DatabaseException; -import net.codingarea.commons.database.abstraction.DefaultExecutedQuery; import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; import net.codingarea.commons.database.sql.abstraction.where.ObjectWhere; import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; @@ -22,155 +22,155 @@ public class SQLQuery implements DatabaseQuery { - protected final AbstractSQLDatabase database; - protected final String table; - protected final Map where; - protected String[] selection = { "*" }; - protected String orderBy; - protected Order order; - - public SQLQuery(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { - this.database = database; - this.table = table; - this.where = new HashMap<>(); - } - - public SQLQuery(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map where) { - this.database = database; - this.table = table; - this.where = where; - } - - @Nonnull - @Override - public DatabaseQuery where(@Nonnull String column, @Nullable Object object) { - where.put(column, new ObjectWhere(column, object, "=")); - return this; - } - - @Nonnull - @Override - public DatabaseQuery where(@Nonnull String column, @Nullable Number value) { - return where(column, (Object) value); - } - - @Nonnull - @Override - public DatabaseQuery where(@Nonnull String column, @Nullable String value) { - return where(column, (Object) value); - } - - @Nonnull - @Override - public DatabaseQuery where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { - if (!ignoreCase) return where(column, value); - if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); - where.put(column, new StringIgnoreCaseWhere(column, value)); - return this; - } - - @Nonnull - @Override - public DatabaseQuery whereNot(@Nonnull String column, @Nullable Object object) { - where.put(column, new ObjectWhere(column, object, "!=")); - return this; - } - - @Nonnull - @Override - public DatabaseQuery orderBy(@Nonnull String column, @Nonnull Order order) { - this.orderBy = column; - this.order = order; - return this; - } - - @Nonnull - @Override - public DatabaseQuery select(@Nonnull String... selection) { - if (selection.length == 0) throw new IllegalArgumentException("Cannot select noting"); - this.selection = selection; - return this; - } - - @Nonnull - protected PreparedStatement prepare() throws SQLException, DatabaseException { - StringBuilder command = new StringBuilder(); - List args = new LinkedList<>(); - - command.append("SELECT "); - for (int i = 0; i < selection.length; i++) { - if (i > 0) command.append(", "); - command.append(selection[i]); - } - command.append(" FROM "); - command.append(table); - - if (!where.isEmpty()) { - command.append(" WHERE "); - int index = 0; - for (Entry entry : where.entrySet()) { - SQLWhere where = entry.getValue(); - if (index > 0) command.append(" AND "); - command.append(where.getAsSQLString()); - args.addAll(Arrays.asList(where.getArgs())); - index++; - } - } - - if (orderBy != null) { - command.append(" ORDER BY "); - command.append(orderBy); - if (order != null) - command.append(" " + (order == Order.HIGHEST ? "DESC" : "ASC")); - command.append(" "); - } - - return database.prepare(command.toString(), args.toArray()); - } - - @Nonnull - @Override - public ExecutedQuery execute() throws DatabaseException { - try { - PreparedStatement statement = prepare(); - ResultSet result = statement.executeQuery(); - return createExecutedQuery(result); - } catch (Exception ex) { - throw new DatabaseException(ex); - } - } - - @Nonnull - private ExecutedQuery createExecutedQuery(@Nonnull ResultSet result) throws SQLException { - List results = new ArrayList<>(); - ResultSetMetaData data = result.getMetaData(); - while (result.next()) { - Map map = new HashMap<>(); - for (int i = 1; i <= data.getColumnCount(); i++) { - Object value = result.getObject(i); - map.put(data.getColumnLabel(i), value); - } - Document row = new SQLResult(map); - results.add(row); - } - result.close(); - - return new DefaultExecutedQuery(results); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - SQLQuery sqlQuery = (SQLQuery) o; - return database.equals(sqlQuery.database) && table.equals(sqlQuery.table) && where.equals(sqlQuery.where) && Arrays.equals(selection, sqlQuery.selection) && Objects.equals(orderBy, sqlQuery.orderBy) && order == sqlQuery.order; - } - - @Override - public int hashCode() { - int result = Objects.hash(database, table, where, orderBy, order); - result = 31 * result + Arrays.hashCode(selection); - return result; - } + protected final AbstractSQLDatabase database; + protected final String table; + protected final Map where; + protected String[] selection = {"*"}; + protected String orderBy; + protected Order order; + + public SQLQuery(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + this.where = new HashMap<>(); + } + + public SQLQuery(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map where) { + this.database = database; + this.table = table; + this.where = where; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, "=")); + return this; + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseQuery where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @Nonnull + @Override + public DatabaseQuery whereNot(@Nonnull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, "!=")); + return this; + } + + @Nonnull + @Override + public DatabaseQuery orderBy(@Nonnull String column, @Nonnull Order order) { + this.orderBy = column; + this.order = order; + return this; + } + + @Nonnull + @Override + public DatabaseQuery select(@Nonnull String... selection) { + if (selection.length == 0) throw new IllegalArgumentException("Cannot select noting"); + this.selection = selection; + return this; + } + + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + StringBuilder command = new StringBuilder(); + List args = new LinkedList<>(); + + command.append("SELECT "); + for (int i = 0; i < selection.length; i++) { + if (i > 0) command.append(", "); + command.append(selection[i]); + } + command.append(" FROM "); + command.append(table); + + if (!where.isEmpty()) { + command.append(" WHERE "); + int index = 0; + for (Entry entry : where.entrySet()) { + SQLWhere where = entry.getValue(); + if (index > 0) command.append(" AND "); + command.append(where.getAsSQLString()); + args.addAll(Arrays.asList(where.getArgs())); + index++; + } + } + + if (orderBy != null) { + command.append(" ORDER BY "); + command.append(orderBy); + if (order != null) + command.append(" " + (order == Order.HIGHEST ? "DESC" : "ASC")); + command.append(" "); + } + + return database.prepare(command.toString(), args.toArray()); + } + + @Nonnull + @Override + public ExecutedQuery execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + ResultSet result = statement.executeQuery(); + return createExecutedQuery(result); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Nonnull + private ExecutedQuery createExecutedQuery(@Nonnull ResultSet result) throws SQLException { + List results = new ArrayList<>(); + ResultSetMetaData data = result.getMetaData(); + while (result.next()) { + Map map = new HashMap<>(); + for (int i = 1; i <= data.getColumnCount(); i++) { + Object value = result.getObject(i); + map.put(data.getColumnLabel(i), value); + } + Document row = new SQLResult(map); + results.add(row); + } + result.close(); + + return new DefaultExecutedQuery(results); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLQuery sqlQuery = (SQLQuery) o; + return database.equals(sqlQuery.database) && table.equals(sqlQuery.table) && where.equals(sqlQuery.where) && Arrays.equals(selection, sqlQuery.selection) && Objects.equals(orderBy, sqlQuery.orderBy) && order == sqlQuery.order; + } + + @Override + public int hashCode() { + int result = Objects.hash(database, table, where, orderBy, order); + result = 31 * result + Arrays.hashCode(selection); + return result; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java index 2d6536855..9077b8a92 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java @@ -11,23 +11,23 @@ public final class SQLResult extends MapDocument { - public SQLResult(@Nonnull Map values) { - super(values); - } + public SQLResult(@Nonnull Map values) { + super(values); + } - @Nonnull - @Override - public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { - try { - return new GsonDocument(getString(path), this, this).readonly(); - } catch (Exception ex) { - return new EmptyDocument(this, null); - } - } + @Nonnull + @Override + public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + try { + return new GsonDocument(getString(path), this, this).readonly(); + } catch (Exception ex) { + return new EmptyDocument(this, null); + } + } - @Override - public boolean isReadonly() { - return true; - } + @Override + public boolean isReadonly() { + return true; + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java index d3b4cd844..7f2326334 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java @@ -16,125 +16,125 @@ public class SQLUpdate implements DatabaseUpdate { - protected final AbstractSQLDatabase database; - protected final String table; - protected final Map where; - protected final Map values; - - public SQLUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { - this.database = database; - this.table = table; - this.where = new HashMap<>(); - this.values = new HashMap<>(); - } - - public SQLUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map where, @Nonnull Map values) { - this.database = database; - this.table = table; - this.where = where; - this.values = values; - } - - @Nonnull - @Override - public DatabaseUpdate where(@Nonnull String column, @Nullable Object value) { - where.put(column, new ObjectWhere(column, value, "=")); - return this; - } - - @Nonnull - @Override - public DatabaseUpdate where(@Nonnull String column, @Nullable Number value) { - return where(column, (Object) value); - } - - @Nonnull - @Override - public DatabaseUpdate where(@Nonnull String column, @Nullable String value) { - return where(column, (Object) value); - } - - @Nonnull - @Override - public DatabaseUpdate where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { - if (!ignoreCase) return where(column, value); - if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); - where.put(column, new StringIgnoreCaseWhere(column, value)); - return this; - } - - @Nonnull - @Override - public DatabaseUpdate whereNot(@Nonnull String column, @Nullable Object value) { - where.put(column, new ObjectWhere(column, value, "!=")); - return this; - } - - @Nonnull - @Override - public DatabaseUpdate set(@Nonnull String column, @Nullable Object value) { - values.put(column, value); - return this; - } - - @Nonnull - protected PreparedStatement prepare() throws SQLException, DatabaseException { - if (values.isEmpty()) throw new IllegalArgumentException("Can't update nothing"); - - StringBuilder command = new StringBuilder(); - List args = new ArrayList<>(); - - command.append("UPDATE "); - command.append(table); - command.append(" SET "); - - { - int index = 0; - for (Entry entry : values.entrySet()) { - if (index > 0) command.append(", "); - command.append("`" + entry.getKey() + "` = ?"); - args.add(entry.getValue()); - index++; - } - } - - if (!where.isEmpty()) { - command.append(" WHERE "); - int index = 0; - for (Entry entry : where.entrySet()) { - SQLWhere where = entry.getValue(); - if (index > 0) command.append(" AND "); - command.append(where.getAsSQLString()); - args.addAll(Arrays.asList(where.getArgs())); - index++; - } - } - - return database.prepare(command.toString(), args.toArray()); - } - - @Override - public Void execute() throws DatabaseException { - try { - PreparedStatement statement = prepare(); - statement.executeUpdate(); - return null; - } catch (SQLException ex) { - throw new DatabaseException(ex); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - SQLUpdate sqlUpdate = (SQLUpdate) o; - return database.equals(sqlUpdate.database) && table.equals(sqlUpdate.table) && where.equals(sqlUpdate.where) && values.equals(sqlUpdate.values); - } - - @Override - public int hashCode() { - return Objects.hash(database, table, where, values); - } + protected final AbstractSQLDatabase database; + protected final String table; + protected final Map where; + protected final Map values; + + public SQLUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + this.database = database; + this.table = table; + this.where = new HashMap<>(); + this.values = new HashMap<>(); + } + + public SQLUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map where, @Nonnull Map values) { + this.database = database; + this.table = table; + this.where = where; + this.values = values; + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "=")); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @Nonnull + @Override + public DatabaseUpdate where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate whereNot(@Nonnull String column, @Nullable Object value) { + where.put(column, new ObjectWhere(column, value, "!=")); + return this; + } + + @Nonnull + @Override + public DatabaseUpdate set(@Nonnull String column, @Nullable Object value) { + values.put(column, value); + return this; + } + + @Nonnull + protected PreparedStatement prepare() throws SQLException, DatabaseException { + if (values.isEmpty()) throw new IllegalArgumentException("Can't update nothing"); + + StringBuilder command = new StringBuilder(); + List args = new ArrayList<>(); + + command.append("UPDATE "); + command.append(table); + command.append(" SET "); + + { + int index = 0; + for (Entry entry : values.entrySet()) { + if (index > 0) command.append(", "); + command.append("`" + entry.getKey() + "` = ?"); + args.add(entry.getValue()); + index++; + } + } + + if (!where.isEmpty()) { + command.append(" WHERE "); + int index = 0; + for (Entry entry : where.entrySet()) { + SQLWhere where = entry.getValue(); + if (index > 0) command.append(" AND "); + command.append(where.getAsSQLString()); + args.addAll(Arrays.asList(where.getArgs())); + index++; + } + } + + return database.prepare(command.toString(), args.toArray()); + } + + @Override + public Void execute() throws DatabaseException { + try { + PreparedStatement statement = prepare(); + statement.executeUpdate(); + return null; + } catch (SQLException ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SQLUpdate sqlUpdate = (SQLUpdate) o; + return database.equals(sqlUpdate.database) && table.equals(sqlUpdate.table) && where.equals(sqlUpdate.where) && values.equals(sqlUpdate.values); + } + + @Override + public int hashCode() { + return Objects.hash(database, table, where, values); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java index f398190fc..3ea51faf7 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java @@ -6,39 +6,39 @@ public class ObjectWhere implements SQLWhere { - protected final String column; - protected final Object value; - protected final String comparator; - - public ObjectWhere(@Nonnull String column, @Nullable Object value, @Nonnull String comparator) { - this.column = column; - this.value = value; - this.comparator = comparator; - } - - @Nonnull - @Override - public Object[] getArgs() { - return new Object[] { value }; - } - - @Nonnull - @Override - public String getAsSQLString() { - return String.format("`%s` %s ?", column, comparator); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ObjectWhere that = (ObjectWhere) o; - return column.equals(that.column) && Objects.equals(value, that.value); - } - - @Override - public int hashCode() { - return Objects.hash(column, value); - } + protected final String column; + protected final Object value; + protected final String comparator; + + public ObjectWhere(@Nonnull String column, @Nullable Object value, @Nonnull String comparator) { + this.column = column; + this.value = value; + this.comparator = comparator; + } + + @Nonnull + @Override + public Object[] getArgs() { + return new Object[]{value}; + } + + @Nonnull + @Override + public String getAsSQLString() { + return String.format("`%s` %s ?", column, comparator); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ObjectWhere that = (ObjectWhere) o; + return column.equals(that.column) && Objects.equals(value, that.value); + } + + @Override + public int hashCode() { + return Objects.hash(column, value); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java index a16075f93..f1ad961e9 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java @@ -4,10 +4,10 @@ public interface SQLWhere { - @Nonnull - Object[] getArgs(); + @Nonnull + Object[] getArgs(); - @Nonnull - String getAsSQLString(); + @Nonnull + String getAsSQLString(); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java index 7a3fe07b6..efe4efe88 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java @@ -5,37 +5,37 @@ public class StringIgnoreCaseWhere implements SQLWhere { - protected final String column; - protected final String value; - - public StringIgnoreCaseWhere(@Nonnull String column, @Nonnull String value) { - this.column = column; - this.value = value; - } - - @Nonnull - @Override - public Object[] getArgs() { - return new Object[] { value }; - } - - @Nonnull - @Override - public String getAsSQLString() { - return String.format("LOWER(%s) = LOWER(?)", column); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - StringIgnoreCaseWhere that = (StringIgnoreCaseWhere) o; - return column.equals(that.column) && value.equals(that.value); - } - - @Override - public int hashCode() { - return Objects.hash(column, value); - } + protected final String column; + protected final String value; + + public StringIgnoreCaseWhere(@Nonnull String column, @Nonnull String value) { + this.column = column; + this.value = value; + } + + @Nonnull + @Override + public Object[] getArgs() { + return new Object[]{value}; + } + + @Nonnull + @Override + public String getAsSQLString() { + return String.format("LOWER(%s) = LOWER(?)", column); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + StringIgnoreCaseWhere that = (StringIgnoreCaseWhere) o; + return column.equals(that.column) && value.equals(that.value); + } + + @Override + public int hashCode() { + return Objects.hash(column, value); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java index 627b39e20..4f4ee4c54 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java @@ -9,28 +9,28 @@ public class MySQLDatabase extends AbstractSQLDatabase { - static { - try { - Class.forName("com.mysql.cj.jdbc.Driver"); - } catch (ClassNotFoundException ex) { - LOGGER.error("Could not load mysql driver"); - } - } - - public MySQLDatabase(@Nonnull DatabaseConfig config) { - super(config); - } - - @Nonnull - @Override - protected String createUrl() { - return "jdbc:mysql://" + config.getHost() + (config.isPortSet() ? ":" + config.getPort() : "") + "/" + config.getDatabase(); - } - - @Nonnull - @Override - public DatabaseListTables listTables() { - return new MySQLListTables(this); - } + static { + try { + Class.forName("com.mysql.cj.jdbc.Driver"); + } catch (ClassNotFoundException ex) { + LOGGER.error("Could not load mysql driver"); + } + } + + public MySQLDatabase(@Nonnull DatabaseConfig config) { + super(config); + } + + @Nonnull + @Override + protected String createUrl() { + return "jdbc:mysql://" + config.getHost() + (config.isPortSet() ? ":" + config.getPort() : "") + "/" + config.getDatabase(); + } + + @Nonnull + @Override + public DatabaseListTables listTables() { + return new MySQLListTables(this); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java index 2d60ee58b..23a77bcc9 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java @@ -12,27 +12,27 @@ public class MySQLListTables implements DatabaseListTables { - protected final AbstractSQLDatabase database; - - public MySQLListTables(@Nonnull AbstractSQLDatabase database) { - this.database = database; - } - - @Nonnull - @Override - public List execute() throws DatabaseException { - try { - PreparedStatement statement = database.prepare("SHOW TABLES"); - ResultSet result = statement.executeQuery(); - - List tables = new ArrayList<>(); - while (result.next()) { - tables.add(result.getString(1)); - } - return tables; - } catch (Exception ex) { - throw new DatabaseException(ex); - } - } + protected final AbstractSQLDatabase database; + + public MySQLListTables(@Nonnull AbstractSQLDatabase database) { + this.database = database; + } + + @Nonnull + @Override + public List execute() throws DatabaseException { + try { + PreparedStatement statement = database.prepare("SHOW TABLES"); + ResultSet result = statement.executeQuery(); + + List tables = new ArrayList<>(); + while (result.next()) { + tables.add(result.getString(1)); + } + return tables; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java index 70fbe6953..183e8da35 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java @@ -13,41 +13,41 @@ public class SQLiteDatabase extends AbstractSQLDatabase { - static { - try { - Class.forName("org.sqlite.JDBC"); - } catch (ClassNotFoundException ex) { - LOGGER.error("Could not load sqlite driver"); - } - } - - protected final File file; - - public SQLiteDatabase(@Nonnull DatabaseConfig config) { - super(config); - file = new File(config.getFile()); - } - - @Override - public void connect() throws DatabaseException { - try { - FileUtils.createFilesIfNecessary(file); - } catch (IOException ex) { - throw new DatabaseException(ex); - } - - super.connect(); - } - - @Override - protected String createUrl() { - return "jdbc:sqlite:" + file; - } - - @Nonnull - @Override - public DatabaseListTables listTables() { - return new SQLiteListTables(this); - } + static { + try { + Class.forName("org.sqlite.JDBC"); + } catch (ClassNotFoundException ex) { + LOGGER.error("Could not load sqlite driver"); + } + } + + protected final File file; + + public SQLiteDatabase(@Nonnull DatabaseConfig config) { + super(config); + file = new File(config.getFile()); + } + + @Override + public void connect() throws DatabaseException { + try { + FileUtils.createFilesIfNecessary(file); + } catch (IOException ex) { + throw new DatabaseException(ex); + } + + super.connect(); + } + + @Override + protected String createUrl() { + return "jdbc:sqlite:" + file; + } + + @Nonnull + @Override + public DatabaseListTables listTables() { + return new SQLiteListTables(this); + } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java index f7a4c48d6..1ac41caf8 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java @@ -12,27 +12,27 @@ public class SQLiteListTables implements DatabaseListTables { - protected final AbstractSQLDatabase database; - - public SQLiteListTables(@Nonnull AbstractSQLDatabase database) { - this.database = database; - } - - @Nonnull - @Override - public List execute() throws DatabaseException { - try { - PreparedStatement statement = database.prepare("SELECT name FROM sqlite_master WHERE type = 'table'"); - ResultSet result = statement.executeQuery(); - - List tables = new ArrayList<>(); - while (result.next()) { - tables.add(result.getString(1)); - } - return tables; - } catch (Exception ex) { - throw new DatabaseException(ex); - } - } + protected final AbstractSQLDatabase database; + + public SQLiteListTables(@Nonnull AbstractSQLDatabase database) { + this.database = database; + } + + @Nonnull + @Override + public List execute() throws DatabaseException { + try { + PreparedStatement statement = database.prepare("SELECT name FROM sqlite_master WHERE type = 'table'"); + ResultSet result = statement.executeQuery(); + + List tables = new ArrayList<>(); + while (result.next()) { + tables.add(result.getString(1)); + } + return tables; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } } From 7cbac8d9f342046ce745118ad12be8fb634e0dd8 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Wed, 27 May 2026 00:17:55 +0200 Subject: [PATCH 072/119] refactor: extract cloud support modules --- cloud-support/cloudnet2/build.gradle.kts | 19 +++++++++++++++++++ .../cloud/support/CloudNet2Support.java | 0 cloud-support/cloudnet3/build.gradle.kts | 15 +++++++++++++++ .../cloud/support/CloudNet3Support.java | 0 gradle/libs.versions.toml | 5 ----- plugin/build.gradle.kts | 9 +++++---- settings.gradle.kts | 7 ++++++- 7 files changed, 45 insertions(+), 10 deletions(-) create mode 100644 cloud-support/cloudnet2/build.gradle.kts rename {plugin => cloud-support/cloudnet2}/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java (100%) create mode 100644 cloud-support/cloudnet3/build.gradle.kts rename {plugin => cloud-support/cloudnet3}/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java (100%) diff --git a/cloud-support/cloudnet2/build.gradle.kts b/cloud-support/cloudnet2/build.gradle.kts new file mode 100644 index 000000000..77db5a975 --- /dev/null +++ b/cloud-support/cloudnet2/build.gradle.kts @@ -0,0 +1,19 @@ +plugins { + `java-library` +} + +dependencies { + compileOnly(libs.spigot.api) + compileOnly(libs.cloudnet2.bridge) + compileOnly(project(":plugin")) +} + +tasks { + jar { + archiveClassifier = "plain" + } + + build { + dependsOn(shadowJar) + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java b/cloud-support/cloudnet2/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java similarity index 100% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java rename to cloud-support/cloudnet2/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java diff --git a/cloud-support/cloudnet3/build.gradle.kts b/cloud-support/cloudnet3/build.gradle.kts new file mode 100644 index 000000000..c544ba506 --- /dev/null +++ b/cloud-support/cloudnet3/build.gradle.kts @@ -0,0 +1,15 @@ +plugins { + `java-library` +} + +dependencies { + compileOnly(libs.spigot.api) + compileOnly(libs.cloudnet3.bridge) + compileOnly(project(":plugin")) +} + +tasks { + jar { + archiveClassifier = "plain" + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java b/cloud-support/cloudnet3/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java similarity index 100% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java rename to cloud-support/cloudnet3/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 447342029..99ecb951d 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -41,8 +41,3 @@ mongodb-driver = { group = "org.mongodb", name = "mongodb-driver", version.ref = cloudnet3-driver = { group = "de.dytanic.cloudnet", name = "cloudnet-driver", version.ref = "cloudnet3" } cloudnet3-bridge = { group = "de.dytanic.cloudnet", name = "cloudnet-bridge", version.ref = "cloudnet3" } cloudnet2-bridge = { group = "de.dytanic.cloudnet", name = "cloudnet-api-bridge", version.ref = "cloudnet2" } - - -[bundles] - -cloudnet = ["cloudnet3-driver", "cloudnet3-bridge", "cloudnet2-bridge"] diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index 00c6e2ece..af8da6a1f 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -16,11 +16,12 @@ dependencies { // consider bundling relocated impl if version compatibility becomes unmanageable compileOnly(libs.gson) - compileOnly(libs.cloudnet3.driver) - compileOnly(libs.cloudnet3.bridge) - compileOnly(libs.cloudnet2.bridge) - annotationProcessor(libs.lombok) + + // bundle cloud impl modules + // TODO abstract to register dynamically + implementation(project(":cloud-support:cloudnet2")) + implementation(project(":cloud-support:cloudnet3")) } tasks { diff --git a/settings.gradle.kts b/settings.gradle.kts index 531a13a12..1e76ea914 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,3 +1,8 @@ rootProject.name = "Challenges" -include("plugin", "mongo-connector") +include( + "plugin", + "mongo-connector", + "cloud-support:cloudnet2", + "cloud-support:cloudnet3", +) From 439e2631e72176046fee944df6a5ca7bca894a2e Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Wed, 27 May 2026 00:25:44 +0200 Subject: [PATCH 073/119] chore: cloud support impl build config --- cloud-support/cloudnet2/build.gradle.kts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/cloud-support/cloudnet2/build.gradle.kts b/cloud-support/cloudnet2/build.gradle.kts index 77db5a975..05823c555 100644 --- a/cloud-support/cloudnet2/build.gradle.kts +++ b/cloud-support/cloudnet2/build.gradle.kts @@ -12,8 +12,4 @@ tasks { jar { archiveClassifier = "plain" } - - build { - dependsOn(shadowJar) - } } From 6550ebf2c1aef55a2660e51ede625ab588ead9e4 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Wed, 27 May 2026 01:19:45 +0200 Subject: [PATCH 074/119] refactor: extract cloud api module - provisional step, considering extracting plugin api entirely and registering cloud impl indirectly --- cloud-support/api/build.gradle.kts | 13 +++++++++++++ .../plugin/management/cloud/CloudSupport.java | 0 cloud-support/cloudnet2/build.gradle.kts | 2 +- cloud-support/cloudnet3/build.gradle.kts | 3 ++- plugin/build.gradle.kts | 1 + settings.gradle.kts | 1 + 6 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 cloud-support/api/build.gradle.kts rename {plugin => cloud-support/api}/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java (100%) diff --git a/cloud-support/api/build.gradle.kts b/cloud-support/api/build.gradle.kts new file mode 100644 index 000000000..4e547c495 --- /dev/null +++ b/cloud-support/api/build.gradle.kts @@ -0,0 +1,13 @@ +plugins { + `java-library` +} + +dependencies { + compileOnly(libs.spigot.api) +} + +tasks { + jar { + archiveClassifier = "plain" + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java b/cloud-support/api/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java similarity index 100% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java rename to cloud-support/api/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java diff --git a/cloud-support/cloudnet2/build.gradle.kts b/cloud-support/cloudnet2/build.gradle.kts index 05823c555..487ef394e 100644 --- a/cloud-support/cloudnet2/build.gradle.kts +++ b/cloud-support/cloudnet2/build.gradle.kts @@ -5,7 +5,7 @@ plugins { dependencies { compileOnly(libs.spigot.api) compileOnly(libs.cloudnet2.bridge) - compileOnly(project(":plugin")) + compileOnly(project(":cloud-support:api")) } tasks { diff --git a/cloud-support/cloudnet3/build.gradle.kts b/cloud-support/cloudnet3/build.gradle.kts index c544ba506..915680d7f 100644 --- a/cloud-support/cloudnet3/build.gradle.kts +++ b/cloud-support/cloudnet3/build.gradle.kts @@ -4,8 +4,9 @@ plugins { dependencies { compileOnly(libs.spigot.api) + compileOnly(libs.cloudnet3.driver) compileOnly(libs.cloudnet3.bridge) - compileOnly(project(":plugin")) + compileOnly(project(":cloud-support:api")) } tasks { diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index af8da6a1f..9a528f157 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -20,6 +20,7 @@ dependencies { // bundle cloud impl modules // TODO abstract to register dynamically + implementation(project(":cloud-support:api")) implementation(project(":cloud-support:cloudnet2")) implementation(project(":cloud-support:cloudnet3")) } diff --git a/settings.gradle.kts b/settings.gradle.kts index 1e76ea914..27b097582 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -3,6 +3,7 @@ rootProject.name = "Challenges" include( "plugin", "mongo-connector", + "cloud-support:api", "cloud-support:cloudnet2", "cloud-support:cloudnet3", ) From f4c17b29a9c40ad23ef1983a98e77412c6f7d98d Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Wed, 27 May 2026 14:55:37 +0200 Subject: [PATCH 075/119] refactor: migrate from jsr (javax.*) to jetbrains annotations - before: mix of javax.* annotations and jetbrains annotations - replaced all references to jsr (javax.*) annotations with jetbrains annotations - as jsr becomes stale, it's considered best practice to use jetbrains annotations, esp. in combination with intellij and qodana --- .../plugin/management/cloud/CloudSupport.java | 12 +- .../cloud/support/CloudNet2Support.java | 12 +- .../cloud/support/CloudNet3Support.java | 12 +- gradle/libs.versions.toml | 4 +- mongo-connector/build.gradle.kts | 3 +- .../mongoconnector/MongoConnector.java | 2 +- .../common/config/document/BsonDocument.java | 568 +++++++++--------- .../commons/common/misc/BsonUtils.java | 216 +++---- .../commons/common/misc/MongoUtils.java | 86 +-- .../database/mongodb/MongoDBDatabase.java | 232 +++---- .../mongodb/count/MongoDBCountEntries.java | 62 +- .../mongodb/deletion/MongoDBDeletion.java | 166 ++--- .../mongodb/insertion/MongoDBInsertion.java | 94 +-- .../MongoDBInsertionOrUpdate.java | 118 ++-- .../mongodb/list/MongoDBListTables.java | 28 +- .../database/mongodb/query/MongoDBQuery.java | 214 +++---- .../database/mongodb/query/MongoDBResult.java | 17 +- .../mongodb/update/MongoDBUpdate.java | 222 +++---- .../database/mongodb/where/MongoDBWhere.java | 13 +- .../database/mongodb/where/ObjectWhere.java | 72 +-- .../mongodb/where/StringIgnoreCaseWhere.java | 68 +-- plugin/build.gradle.kts | 2 +- .../challenges/plugin/ChallengeAPI.java | 24 +- .../challenges/plugin/Challenges.java | 6 +- .../challenges/custom/CustomChallenge.java | 11 +- .../custom/settings/CustomSettingsLoader.java | 2 +- .../custom/settings/FallbackNames.java | 5 +- .../action/impl/RandomItemAction.java | 4 +- .../impl/EntityDamageByPlayerTrigger.java | 5 +- .../trigger/impl/EntityDamageTrigger.java | 4 +- .../trigger/impl/EntityDeathTrigger.java | 5 +- .../trigger/impl/PlayerJumpTrigger.java | 5 +- .../trigger/impl/PlayerSneakTrigger.java | 5 +- .../challenge/DamageTeleportChallenge.java | 10 +- .../challenge/ZeroHeartsChallenge.java | 7 +- .../damage/AdvancementDamageChallenge.java | 9 +- .../damage/BlockBreakDamageChallenge.java | 7 +- .../damage/BlockPlaceDamageChallenge.java | 7 +- .../damage/DamagePerBlockChallenge.java | 9 +- .../damage/DamagePerItemChallenge.java | 11 +- .../damage/DeathOnFallChallenge.java | 7 +- .../damage/DelayDamageChallenge.java | 5 +- .../challenge/damage/FreezeChallenge.java | 11 +- .../challenge/damage/JumpDamageChallenge.java | 9 +- .../damage/ReversedDamageChallenge.java | 7 +- .../damage/SneakDamageChallenge.java | 9 +- .../damage/WaterAllergyChallenge.java | 7 +- .../challenge/effect/InfectionChallenge.java | 10 +- .../PermanentEffectOnDamageChallenge.java | 30 +- .../effect/RandomPotionEffectChallenge.java | 12 +- .../entities/AllMobsToDeathPoint.java | 8 +- .../entities/DupedSpawningChallenge.java | 7 +- .../entities/HydraNormalChallenge.java | 7 +- .../entities/HydraPlusChallenge.java | 7 +- .../entities/InvisibleMobsChallenge.java | 9 +- .../entities/MobSightDamageChallenge.java | 7 +- .../entities/MobTransformationChallenge.java | 11 +- .../entities/NewEntityOnJumpChallenge.java | 9 +- .../entities/StoneSightChallenge.java | 6 +- .../extraworld/JumpAndRunChallenge.java | 18 +- .../extraworld/WaterMLGChallenge.java | 11 +- .../challenge/force/ForceBiomeChallenge.java | 13 +- .../challenge/force/ForceBlockChallenge.java | 11 +- .../challenge/force/ForceHeightChallenge.java | 11 +- .../challenge/force/ForceItemChallenge.java | 15 +- .../challenge/force/ForceMobChallenge.java | 11 +- .../DamageInventoryClearChallenge.java | 9 +- .../inventory/MissingItemsChallenge.java | 20 +- .../MovementItemRemovingChallenge.java | 9 +- .../inventory/NoDupedItemsChallenge.java | 12 +- .../inventory/PermanentItemChallenge.java | 9 +- .../inventory/PickupItemLaunchChallenge.java | 6 +- .../inventory/UncraftItemsChallenge.java | 10 +- .../miscellaneous/EnderGamesChallenge.java | 8 +- .../miscellaneous/FoodLaunchChallenge.java | 6 +- .../miscellaneous/FoodOnceChallenge.java | 16 +- .../miscellaneous/InvertHealthChallenge.java | 7 +- .../miscellaneous/LowDropRateChallenge.java | 6 +- .../miscellaneous/NoExpChallenge.java | 5 +- .../miscellaneous/NoTradingChallenge.java | 9 +- .../miscellaneous/OneDurabilityChallenge.java | 9 +- .../movement/AlwaysRunningChallenge.java | 5 +- .../movement/DontStopRunningChallenge.java | 6 +- .../movement/FiveHundredBlocksChallenge.java | 3 +- .../movement/HigherJumpsChallenge.java | 7 +- .../movement/HungerPerBlockChallenge.java | 7 +- .../challenge/movement/MoveMouseDamage.java | 6 +- .../challenge/movement/OnlyDirtChallenge.java | 11 +- .../challenge/movement/OnlyDownChallenge.java | 7 +- .../movement/TrafficLightChallenge.java | 9 +- .../challenge/quiz/QuizChallenge.java | 52 +- .../randomizer/BlockRandomizerChallenge.java | 4 +- .../CraftingRandomizerChallenge.java | 6 +- .../EntityLootRandomizerChallenge.java | 7 +- .../randomizer/HotBarRandomizerChallenge.java | 8 +- .../randomizer/MobRandomizerChallenge.java | 14 +- .../randomizer/RandomChallengeChallenge.java | 8 +- .../randomizer/RandomEventChallenge.java | 39 +- .../randomizer/RandomItemChallenge.java | 7 +- .../RandomItemDroppingChallenge.java | 9 +- .../RandomItemRemovingChallenge.java | 7 +- .../RandomItemSwappingChallenge.java | 9 +- .../randomizer/RandomizedHPChallenge.java | 14 +- .../challenge/time/MaxBiomeTimeChallenge.java | 15 +- .../time/MaxHeightTimeChallenge.java | 13 +- .../world/AllBlocksDisappearChallenge.java | 16 +- .../challenge/world/AnvilRainChallenge.java | 18 +- .../challenge/world/BedrockPathChallenge.java | 7 +- .../challenge/world/BedrockWallChallenge.java | 8 +- .../BlocksDisappearAfterTimeChallenge.java | 12 +- .../world/ChunkDeconstructionChallenge.java | 14 +- .../challenge/world/FloorIsLavaChallenge.java | 13 +- .../challenge/world/IceFloorChallenge.java | 14 +- .../challenge/world/LevelBorderChallenge.java | 17 +- .../challenge/world/LoopChallenge.java | 22 +- .../challenge/world/SnakeChallenge.java | 10 +- .../challenge/world/SurfaceHoleChallenge.java | 8 +- .../challenge/world/TsunamiChallenge.java | 22 +- .../damage/DamageRuleSetting.java | 7 +- .../goal/AllAdvancementGoal.java | 5 +- .../goal/CollectAllItemsGoal.java | 22 +- .../goal/CollectMostDeathsGoal.java | 7 +- .../goal/CollectMostExpGoal.java | 9 +- .../goal/CollectMostItemsGoal.java | 11 +- .../implementation/goal/CollectWoodGoal.java | 23 +- .../implementation/goal/FinishRaidGoal.java | 8 +- .../goal/FirstOneToDieGoal.java | 8 +- .../goal/GetFullHealthGoal.java | 2 +- .../goal/KillAllBossesGoal.java | 4 +- .../goal/KillAllBossesNewGoal.java | 4 +- .../goal/KillElderGuardianGoal.java | 7 +- .../goal/KillEnderDragonGoal.java | 7 +- .../goal/KillIronGolemGoal.java | 7 +- .../goal/KillSnowGolemGoal.java | 7 +- .../implementation/goal/KillWardenGoal.java | 7 +- .../implementation/goal/KillWitherGoal.java | 7 +- .../goal/LastManStandingGoal.java | 10 +- .../goal/MineMostBlocksGoal.java | 7 +- .../implementation/goal/MostEmeraldsGoal.java | 15 +- .../implementation/goal/MostOresGoal.java | 6 +- .../forcebattle/ExtremeForceBattleGoal.java | 5 +- .../forcebattle/ForceDamageBattleGoal.java | 3 +- .../goal/forcebattle/ForceMobBattleGoal.java | 3 +- .../material/BlockMaterialSetting.java | 13 +- .../setting/BackpackSetting.java | 26 +- .../setting/BastionSpawnSetting.java | 4 +- .../setting/CutCleanSetting.java | 28 +- .../setting/DamageDisplaySetting.java | 9 +- .../setting/DamageMultiplierModifier.java | 9 +- .../setting/DeathMessageSetting.java | 9 +- .../setting/DeathPositionSetting.java | 7 +- .../setting/DifficultySetting.java | 18 +- .../setting/EnderChestCommandSetting.java | 7 +- .../setting/FortressSpawnSetting.java | 5 +- .../setting/HealthDisplaySetting.java | 11 +- .../setting/ImmediateRespawnSetting.java | 7 +- .../setting/KeepInventorySetting.java | 5 +- .../setting/LanguageSetting.java | 6 +- .../setting/MaxHealthSetting.java | 9 +- .../setting/MobGriefingSetting.java | 5 +- .../setting/NoHitDelaySetting.java | 7 +- .../setting/NoHungerSetting.java | 9 +- .../setting/NoItemDamageSetting.java | 5 +- .../setting/NoOffhandSetting.java | 5 +- .../implementation/setting/OldPvPSetting.java | 15 +- .../setting/OneTeamLifeSetting.java | 7 +- .../setting/PlayerGlowSetting.java | 7 +- .../setting/PositionSetting.java | 21 +- .../setting/PregameMovementSetting.java | 9 +- .../implementation/setting/PvPSetting.java | 7 +- .../setting/RegenerationSetting.java | 7 +- .../setting/RespawnSetting.java | 8 +- .../setting/SlotLimitSetting.java | 21 +- .../implementation/setting/SoupSetting.java | 5 +- .../setting/SplitHealthSetting.java | 13 +- .../implementation/setting/TimberSetting.java | 14 +- .../setting/TopCommandSetting.java | 7 +- .../setting/TotemSaveDeathSetting.java | 7 +- .../challenges/type/EmptyChallenge.java | 4 +- .../plugin/challenges/type/IChallenge.java | 19 +- .../plugin/challenges/type/IGoal.java | 8 +- .../plugin/challenges/type/IModifier.java | 5 - .../type/abstraction/AbstractChallenge.java | 60 +- .../abstraction/AbstractForceChallenge.java | 11 +- .../type/abstraction/CollectionGoal.java | 28 +- .../CompletableForceChallenge.java | 15 +- .../abstraction/EndingForceChallenge.java | 16 +- .../type/abstraction/FindItemGoal.java | 3 +- .../type/abstraction/HydraChallenge.java | 11 +- .../type/abstraction/ItemCollectionGoal.java | 7 +- .../type/abstraction/KillEntityGoal.java | 10 +- .../type/abstraction/KillMobsGoal.java | 7 +- .../challenges/type/abstraction/MenuGoal.java | 6 +- .../type/abstraction/MenuSetting.java | 124 ++-- .../challenges/type/abstraction/Modifier.java | 23 +- .../abstraction/ModifierCollectionGoal.java | 17 +- .../abstraction/NetherPortalSpawnSetting.java | 22 +- .../type/abstraction/OneEnabledSetting.java | 7 +- .../type/abstraction/PointsGoal.java | 27 +- .../type/abstraction/RandomizerSetting.java | 11 +- .../challenges/type/abstraction/Setting.java | 15 +- .../type/abstraction/SettingGoal.java | 7 +- .../type/abstraction/SettingModifier.java | 21 +- .../SettingModifierCollectionGoal.java | 17 +- .../type/abstraction/SettingModifierGoal.java | 17 +- .../type/abstraction/TimedChallenge.java | 21 +- .../abstraction/WorldDependentChallenge.java | 34 +- .../type/helper/ChallengeConfigHelper.java | 7 +- .../type/helper/ChallengeHelper.java | 63 +- .../challenges/type/helper/GoalHelper.java | 24 +- .../plugin/content/ItemDescription.java | 18 +- .../challenges/plugin/content/Message.java | 66 +- .../challenges/plugin/content/Prefix.java | 29 +- .../plugin/content/impl/MessageImpl.java | 72 +-- .../plugin/content/impl/MessageManager.java | 11 +- .../plugin/content/loader/ContentLoader.java | 12 +- .../plugin/content/loader/LanguageLoader.java | 8 +- .../plugin/content/loader/LoaderRegistry.java | 14 +- .../management/blocks/BlockDropManager.java | 34 +- .../challenges/ChallengeManager.java | 30 +- .../challenges/CustomChallengesLoader.java | 12 +- .../challenges/ModuleChallengeLoader.java | 28 +- .../annotations/RequireVersion.java | 4 +- .../entities/GamestateSaveable.java | 7 +- .../management/cloud/CloudSupportManager.java | 20 +- .../management/database/DatabaseManager.java | 10 +- .../management/files/ConfigManager.java | 8 +- .../inventory/PlayerInventoryManager.java | 42 +- .../menu/InventoryTitleManager.java | 37 +- .../plugin/management/menu/MenuManager.java | 13 +- .../plugin/management/menu/MenuType.java | 10 +- .../generator/ChallengeMenuGenerator.java | 31 +- .../menu/generator/ChooseItemGenerator.java | 13 +- .../ChooseMultipleItemGenerator.java | 13 +- .../menu/generator/MenuGenerator.java | 7 +- .../generator/MultiPageMenuGenerator.java | 13 +- .../menu/generator/ValueMenuGenerator.java | 6 +- .../implementation/SettingsMenuGenerator.java | 5 +- .../implementation/TimerMenuGenerator.java | 23 +- .../custom/InfoMenuGenerator.java | 6 +- .../custom/MainCustomMenuGenerator.java | 11 +- .../menu/info/ChallengeMenuClickInfo.java | 8 +- .../scheduler/AbstractTaskExecutor.java | 8 +- .../scheduler/PoliciesContainer.java | 10 +- .../management/scheduler/ScheduleManager.java | 18 +- .../scheduler/ScheduledFunction.java | 6 +- .../scheduler/ScheduledTaskConfig.java | 8 +- .../scheduler/ScheduledTaskExecutor.java | 7 +- .../management/scheduler/TimerTaskConfig.java | 10 +- .../scheduler/TimerTaskExecutor.java | 7 +- .../policy/ChallengeStatusPolicy.java | 8 +- .../scheduler/policy/ExtraWorldPolicy.java | 6 +- .../scheduler/policy/FreshnessPolicy.java | 6 +- .../management/scheduler/policy/IPolicy.java | 6 +- .../scheduler/policy/PlayerCountPolicy.java | 6 +- .../scheduler/policy/TimerPolicy.java | 6 +- .../scheduler/task/ScheduledTask.java | 14 +- .../management/scheduler/task/TimerTask.java | 12 +- .../scheduler/timer/ChallengeTimer.java | 9 +- .../scheduler/timer/TimerFormat.java | 13 +- .../management/server/ChallengeEndCause.java | 9 +- .../management/server/GameWorldStorage.java | 5 +- .../server/GeneratorWorldPortalManager.java | 9 +- .../management/server/ScoreboardManager.java | 16 +- .../management/server/ServerManager.java | 8 +- .../management/server/TitleManager.java | 11 +- .../management/server/WorldManager.java | 28 +- .../server/scoreboard/ChallengeBossBar.java | 32 +- .../scoreboard/ChallengeScoreboard.java | 20 +- .../management/stats/LeaderboardInfo.java | 8 +- .../plugin/management/stats/PlayerStats.java | 16 +- .../plugin/management/stats/Statistic.java | 10 +- .../plugin/management/stats/StatsManager.java | 38 +- .../spigot/command/ChallengesCommand.java | 3 +- .../spigot/command/DatabaseCommand.java | 3 +- .../plugin/spigot/command/FeedCommand.java | 6 +- .../plugin/spigot/command/FlyCommand.java | 6 +- .../spigot/command/GamemodeCommand.java | 3 +- .../spigot/command/GamestateCommand.java | 8 +- .../plugin/spigot/command/GodModeCommand.java | 6 +- .../plugin/spigot/command/HealCommand.java | 6 +- .../plugin/spigot/command/HelpCommand.java | 5 +- .../plugin/spigot/command/InvseeCommand.java | 18 +- .../spigot/command/LeaderboardCommand.java | 14 +- .../plugin/spigot/command/ResetCommand.java | 6 +- .../plugin/spigot/command/SearchCommand.java | 8 +- .../plugin/spigot/command/StatsCommand.java | 12 +- .../plugin/spigot/command/TimeCommand.java | 12 +- .../plugin/spigot/command/TimerCommand.java | 6 +- .../plugin/spigot/command/VillageCommand.java | 5 +- .../plugin/spigot/command/WeatherCommand.java | 6 +- .../plugin/spigot/command/WorldCommand.java | 5 +- .../events/InventoryClickEventWrapper.java | 26 +- .../events/PlayerInventoryClickEvent.java | 9 +- .../plugin/spigot/events/PlayerJumpEvent.java | 9 +- .../spigot/events/PlayerPickupItemEvent.java | 9 +- .../spigot/generator/VoidMapGenerator.java | 8 +- .../spigot/listener/BlockDropListener.java | 12 +- .../plugin/spigot/listener/CheatListener.java | 11 +- .../spigot/listener/CustomEventListener.java | 9 +- .../ExtraWorldRestrictionListener.java | 15 +- .../plugin/spigot/listener/HelpListener.java | 4 +- .../listener/PlayerConnectionListener.java | 6 +- .../spigot/listener/RestrictionListener.java | 41 +- .../plugin/spigot/listener/StatsListener.java | 20 +- .../utils/bukkit/command/Completer.java | 8 +- .../bukkit/command/ForwardingCommand.java | 10 +- .../utils/bukkit/command/PlayerCommand.java | 7 +- .../utils/bukkit/command/SenderCommand.java | 7 +- .../utils/bukkit/container/PlayerData.java | 16 +- .../bukkit/jumpgeneration/IJumpGenerator.java | 9 +- .../jumpgeneration/RandomJumpGenerator.java | 15 +- .../utils/bukkit/misc/BukkitStringUtils.java | 36 +- .../plugin/utils/item/DefaultItem.java | 41 +- .../plugin/utils/item/ItemBuilder.java | 191 +++--- .../plugin/utils/logging/ConsolePrint.java | 7 +- .../plugin/utils/misc/BlockUtils.java | 30 +- .../plugin/utils/misc/ColorConversions.java | 26 +- .../plugin/utils/misc/CommandHelper.java | 10 +- .../plugin/utils/misc/DatabaseHelper.java | 12 +- .../plugin/utils/misc/EntityUtils.java | 9 +- .../plugin/utils/misc/ImageUtils.java | 10 +- .../plugin/utils/misc/InventoryUtils.java | 46 +- .../utils/misc/MinecraftNameWrapper.java | 26 +- .../plugin/utils/misc/NameHelper.java | 7 +- .../plugin/utils/misc/ParticleUtils.java | 22 +- .../plugin/utils/misc/StatsHelper.java | 15 +- .../challenges/plugin/utils/misc/Utils.java | 17 +- .../commons/bukkit/core/BukkitModule.java | 56 +- .../bukkit/core/RequirementsChecker.java | 13 +- .../bukkit/core/SimpleConfigManager.java | 14 +- .../utils/animation/AnimatedInventory.java | 42 +- .../utils/animation/AnimationFrame.java | 26 +- .../bukkit/utils/animation/SoundSample.java | 32 +- .../bukkit/utils/item/BannerPattern.java | 9 +- .../bukkit/utils/item/ItemBuilder.java | 184 +++--- .../commons/bukkit/utils/item/ItemUtils.java | 15 +- .../commons/bukkit/utils/logging/Logger.java | 17 +- .../bukkit/utils/menu/MenuClickInfo.java | 14 +- .../bukkit/utils/menu/MenuPosition.java | 14 +- .../bukkit/utils/menu/MenuPositionHolder.java | 5 +- .../utils/menu/MenuPositionListener.java | 5 +- .../menu/positions/EmptyMenuPosition.java | 5 +- .../menu/positions/SlottedMenuPosition.java | 16 +- .../utils/misc/BukkitReflectionUtils.java | 16 +- .../bukkit/utils/misc/CompatibilityUtils.java | 6 +- .../bukkit/utils/misc/GameProfileUtils.java | 16 +- .../bukkit/utils/misc/MinecraftVersion.java | 88 ++- .../bukkit/utils/wrapper/ActionListener.java | 10 +- .../bukkit/utils/wrapper/MaterialWrapper.java | 7 +- .../utils/wrapper/SimpleEventExecutor.java | 6 +- .../common/annotations/AlsoKnownAs.java | 5 +- .../common/annotations/DeprecatedSince.java | 5 +- .../common/annotations/ReplaceWith.java | 5 +- .../commons/common/annotations/Since.java | 5 +- .../common/collection/ArrayWalker.java | 9 +- .../common/collection/ClassWalker.java | 13 +- .../commons/common/collection/Colors.java | 9 +- .../common/collection/FontBuilder.java | 35 +- .../commons/common/collection/IOUtils.java | 15 +- .../commons/common/collection/IRandom.java | 82 ++- .../common/collection/NamedThreadFactory.java | 9 +- .../common/collection/NumberFormatter.java | 45 +- .../common/collection/RandomWrapper.java | 33 +- .../common/collection/RomanNumerals.java | 5 +- .../common/collection/RunnableTimerTask.java | 5 +- .../collection/StringBuilderPrintWriter.java | 5 +- .../collection/StringBuilderWriter.java | 10 +- .../commons/common/collection/Triple.java | 2 +- .../commons/common/collection/Tuple.java | 2 +- .../common/collection/WrappedException.java | 26 +- .../commons/common/collection/pair/Pair.java | 6 +- .../common/collection/pair/Quadro.java | 31 +- .../common/collection/pair/Triple.java | 27 +- .../commons/common/collection/pair/Tuple.java | 23 +- .../cache/CleanAndWriteDatabaseCache.java | 23 +- .../concurrent/cache/CleanWriteableCache.java | 15 +- .../concurrent/cache/CoolDownCache.java | 19 +- .../concurrent/cache/DatabaseCache.java | 7 +- .../common/concurrent/cache/ICache.java | 8 +- .../concurrent/cache/WriteableCache.java | 9 +- .../concurrent/task/CompletableTask.java | 26 +- .../common/concurrent/task/CompletedTask.java | 19 +- .../commons/common/concurrent/task/Task.java | 120 ++-- .../common/concurrent/task/TaskListener.java | 8 +- .../commons/common/config/Config.java | 46 +- .../commons/common/config/Document.java | 154 ++--- .../commons/common/config/FileDocument.java | 78 +-- .../commons/common/config/Json.java | 23 +- .../commons/common/config/PropertyHelper.java | 3 +- .../commons/common/config/Propertyable.java | 176 +++--- .../config/document/AbstractConfig.java | 130 ++-- .../config/document/AbstractDocument.java | 63 +- .../common/config/document/EmptyDocument.java | 232 +++---- .../common/config/document/GsonDocument.java | 130 ++-- .../common/config/document/MapDocument.java | 74 +-- .../config/document/PropertiesDocument.java | 78 +-- .../common/config/document/YamlDocument.java | 106 ++-- ...kkitReflectionSerializableTypeAdapter.java | 8 +- .../document/gson/ClassTypeAdapter.java | 6 +- .../document/gson/ColorTypeAdapter.java | 6 +- .../document/gson/DocumentTypeAdapter.java | 6 +- .../config/document/gson/GsonTypeAdapter.java | 16 +- .../config/document/gson/PairTypeAdapter.java | 6 +- .../readonly/ReadOnlyDocumentWrapper.java | 5 +- .../document/wrapper/FileDocumentWrapper.java | 24 +- .../document/wrapper/WrappedDocument.java | 228 +++---- .../exceptions/ConfigReadOnlyException.java | 4 +- .../commons/common/debug/TimingsHelper.java | 8 +- .../common/discord/DiscordWebhook.java | 54 +- .../function/ExceptionallyFunction.java | 6 +- .../commons/common/logging/ILogger.java | 88 +-- .../common/logging/ILoggerFactory.java | 10 +- .../commons/common/logging/LogLevel.java | 23 +- .../common/logging/LogOutputStream.java | 5 +- .../common/logging/LoggingApiUser.java | 20 +- .../common/logging/WrappedILogger.java | 54 +- .../logging/handler/HandledAsyncLogger.java | 6 +- .../common/logging/handler/HandledLogger.java | 24 +- .../logging/handler/HandledSyncLogger.java | 7 +- .../common/logging/handler/LogEntry.java | 14 +- .../common/logging/handler/LogHandler.java | 5 +- .../logging/internal/BukkitLoggerWrapper.java | 9 +- .../logging/internal/FallbackLogger.java | 18 +- .../logging/internal/JavaLoggerWrapper.java | 42 +- .../common/logging/internal/SimpleLogger.java | 31 +- .../logging/internal/Slf4jILoggerWrapper.java | 7 +- .../logging/internal/Slf4jLoggerWrapper.java | 15 +- .../factory/ConstantLoggerFactory.java | 11 +- .../factory/DefaultLoggerFactory.java | 12 +- .../internal/factory/Slf4jLoggerFactory.java | 9 +- .../common/logging/lib/JavaILogger.java | 6 +- .../common/logging/lib/Slf4jILogger.java | 15 +- .../BukkitReflectionSerializationUtils.java | 14 +- .../commons/common/misc/FileUtils.java | 95 ++- .../commons/common/misc/GsonUtils.java | 30 +- .../commons/common/misc/ImageUtils.java | 30 +- .../commons/common/misc/PropertiesUtils.java | 5 +- .../commons/common/misc/ReflectionUtils.java | 61 +- .../common/misc/SimpleCollectionUtils.java | 35 +- .../commons/common/misc/StringUtils.java | 44 +- .../commons/common/version/Version.java | 41 +- .../common/version/VersionComparator.java | 5 +- .../commons/common/version/VersionInfo.java | 2 +- .../codingarea/commons/database/Database.java | 49 +- .../commons/database/DatabaseConfig.java | 5 +- .../commons/database/EmptyDatabase.java | 108 ++-- .../commons/database/SQLColumn.java | 27 +- .../database/SimpleDatabaseTypeResolver.java | 12 +- .../commons/database/SpecificDatabase.java | 21 +- .../abstraction/AbstractDatabase.java | 13 +- .../abstraction/DefaultExecutedQuery.java | 22 +- .../abstraction/DefaultSpecificDatabase.java | 20 +- .../database/access/CachedDatabaseAccess.java | 38 +- .../database/access/DatabaseAccess.java | 22 +- .../database/access/DatabaseAccessConfig.java | 10 +- .../database/access/DirectDatabaseAccess.java | 26 +- .../database/action/DatabaseAction.java | 5 +- .../database/action/DatabaseCountEntries.java | 7 +- .../database/action/DatabaseDeletion.java | 27 +- .../database/action/DatabaseInsertion.java | 11 +- .../action/DatabaseInsertionOrUpdate.java | 31 +- .../database/action/DatabaseListTables.java | 4 +- .../database/action/DatabaseQuery.java | 38 +- .../database/action/DatabaseUpdate.java | 31 +- .../database/action/ExecutedQuery.java | 36 +- .../action/hierarchy/OrderedAction.java | 7 +- .../database/action/hierarchy/SetAction.java | 8 +- .../action/hierarchy/WhereAction.java | 26 +- .../exceptions/DatabaseException.java | 9 +- .../DatabaseUnsupportedFeatureException.java | 4 +- .../exceptions/UnsignedDatabaseException.java | 7 +- .../sql/abstraction/AbstractSQLDatabase.java | 42 +- .../database/sql/abstraction/SQLHelper.java | 6 +- .../abstraction/count/SQLCountEntries.java | 6 +- .../sql/abstraction/deletion/SQLDeletion.java | 28 +- .../abstraction/insertion/SQLInsertion.java | 14 +- .../insertorupdate/SQLInsertionOrUpdate.java | 30 +- .../sql/abstraction/query/SQLQuery.java | 44 +- .../sql/abstraction/query/SQLResult.java | 10 +- .../sql/abstraction/update/SQLUpdate.java | 34 +- .../sql/abstraction/where/ObjectWhere.java | 11 +- .../sql/abstraction/where/SQLWhere.java | 6 +- .../where/StringIgnoreCaseWhere.java | 9 +- .../database/sql/mysql/MySQLDatabase.java | 9 +- .../sql/mysql/list/MySQLListTables.java | 6 +- .../database/sql/sqlite/SQLiteDatabase.java | 6 +- .../sql/sqlite/list/SQLiteListTables.java | 6 +- 488 files changed, 5331 insertions(+), 5632 deletions(-) diff --git a/cloud-support/api/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java b/cloud-support/api/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java index d916ae229..31f697bed 100644 --- a/cloud-support/api/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java +++ b/cloud-support/api/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupport.java @@ -1,19 +1,19 @@ package net.codingarea.challenges.plugin.management.cloud; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.UUID; public interface CloudSupport { - @Nonnull - String getColoredName(@Nonnull Player player); + @NotNull + String getColoredName(@NotNull Player player); - @Nonnull - String getColoredName(@Nonnull UUID uuid); + @NotNull + String getColoredName(@NotNull UUID uuid); - boolean hasNameFor(@Nonnull UUID uuid); + boolean hasNameFor(@NotNull UUID uuid); void setIngame(); diff --git a/cloud-support/cloudnet2/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java b/cloud-support/cloudnet2/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java index 8fcd02f28..64395f203 100644 --- a/cloud-support/cloudnet2/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java +++ b/cloud-support/cloudnet2/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet2Support.java @@ -7,21 +7,21 @@ import de.dytanic.cloudnet.lib.server.ServerState; import net.codingarea.challenges.plugin.management.cloud.CloudSupport; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.UUID; public final class CloudNet2Support implements CloudSupport { - @Nonnull + @NotNull @Override - public String getColoredName(@Nonnull Player player) { + public String getColoredName(@NotNull Player player) { return getColoredName(player.getUniqueId()); } - @Nonnull + @NotNull @Override - public String getColoredName(@Nonnull UUID uuid) { + public String getColoredName(@NotNull UUID uuid) { OfflinePlayer offlinePlayer = CloudAPI.getInstance().getOfflinePlayer(uuid); PermissionGroup permissionGroup = offlinePlayer.getPermissionEntity().getHighestPermissionGroup(CloudAPI.getInstance().getPermissionPool()); String color = permissionGroup.getColor(); @@ -29,7 +29,7 @@ public String getColoredName(@Nonnull UUID uuid) { } @Override - public boolean hasNameFor(@Nonnull UUID uuid) { + public boolean hasNameFor(@NotNull UUID uuid) { return CloudAPI.getInstance().getOfflinePlayer(uuid) != null; } diff --git a/cloud-support/cloudnet3/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java b/cloud-support/cloudnet3/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java index 7c2e60f52..42b4c9d14 100644 --- a/cloud-support/cloudnet3/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java +++ b/cloud-support/cloudnet3/src/main/java/net/codingarea/challenges/plugin/management/cloud/support/CloudNet3Support.java @@ -8,21 +8,21 @@ import de.dytanic.cloudnet.ext.bridge.bukkit.BukkitCloudNetHelper; import net.codingarea.challenges.plugin.management.cloud.CloudSupport; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.UUID; public final class CloudNet3Support implements CloudSupport { - @Nonnull + @NotNull @Override - public String getColoredName(@Nonnull Player player) { + public String getColoredName(@NotNull Player player) { return getColoredName(player.getUniqueId()); } - @Nonnull + @NotNull @Override - public String getColoredName(@Nonnull UUID uuid) { + public String getColoredName(@NotNull UUID uuid) { IPermissionManagement management = CloudNetDriver.getInstance().getPermissionManagement(); IPermissionUser user = management.getUser(uuid); if (user == null) return "Unknown CloudPlayer"; @@ -32,7 +32,7 @@ public String getColoredName(@Nonnull UUID uuid) { } @Override - public boolean hasNameFor(@Nonnull UUID uuid) { + public boolean hasNameFor(@NotNull UUID uuid) { return CloudNetDriver.getInstance().getPermissionManagement().getUser(uuid) != null; } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 99ecb951d..089a524e3 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -10,7 +10,7 @@ gson = "2.13.2" # annotations, compile time processing lombok = "1.18.38" -jsr305 = "3.0.2" # TODO replace with jetbrains annotations +jetbrains-annotations = "26.1.0" # database mongodb = "3.12.14" @@ -32,7 +32,7 @@ gson = { group = "com.google.code.gson", name = "gson", version.ref = "gson" } # annotations, compile time processing lombok = { group = "org.projectlombok", name = "lombok", version.ref = "lombok" } -jsr305 = { group = "com.google.code.findbugs", name = "jsr305", version.ref = "jsr305" } +jetbrains-annotations = { group = "org.jetbrains", name = "annotations", version.ref = "jetbrains-annotations" } # database mongodb-driver = { group = "org.mongodb", name = "mongodb-driver", version.ref = "mongodb" } diff --git a/mongo-connector/build.gradle.kts b/mongo-connector/build.gradle.kts index ea795fbde..f9d4300f3 100644 --- a/mongo-connector/build.gradle.kts +++ b/mongo-connector/build.gradle.kts @@ -6,9 +6,10 @@ plugins { dependencies { implementation(libs.slf4j.api) implementation(libs.mongodb.driver) - implementation(libs.jsr305) compileOnly(libs.spigot.api) + + compileOnly(libs.jetbrains.annotations) compileOnly(libs.lombok) implementation(project(":plugin")) diff --git a/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java b/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java index ee9999e4d..d0ae1c6f2 100644 --- a/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java +++ b/mongo-connector/src/main/java/net/codingarea/challenges/mongoconnector/MongoConnector.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.mongoconnector; -import net.codingarea.commons.database.mongodb.MongoDBDatabase; import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.commons.database.mongodb.MongoDBDatabase; import org.bukkit.plugin.java.JavaPlugin; diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java index f801ab556..62b403284 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/config/document/BsonDocument.java @@ -5,9 +5,9 @@ import org.bson.BsonArray; import org.bson.BsonValue; import org.bson.json.JsonWriterSettings; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.awt.*; import java.io.*; import java.time.OffsetDateTime; @@ -18,287 +18,287 @@ public class BsonDocument extends AbstractDocument { - protected org.bson.Document bsonDocument; - - public BsonDocument(@Nonnull File file) throws IOException { - this(FileUtils.newBufferedReader(file)); - } - - public BsonDocument(@Nonnull Reader reader) { - BufferedReader buffered = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); - StringBuilder content = new StringBuilder(); - buffered.lines().forEach(content::append); - bsonDocument = org.bson.Document.parse(content.toString()); - } - - public BsonDocument(@Nonnull org.bson.Document bsonDocument) { - this.bsonDocument = bsonDocument; - } - - public BsonDocument(@Nonnull org.bson.Document bsonDocument, @Nonnull Document root, @Nullable Document parent) { - super(root, parent); - this.bsonDocument = bsonDocument; - } - - public BsonDocument() { - this(new org.bson.Document()); - } - - @Nonnull - @Override - public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { - org.bson.Document document = bsonDocument.get(path, org.bson.Document.class); - if (document == null) { - bsonDocument.put(path, document = new org.bson.Document()); - } - - return new BsonDocument(document, root, parent); - } - - @Nonnull - @Override - public List getDocumentList(@Nonnull String path) { - BsonArray array = bsonDocument.get(path, BsonArray.class); - if (array == null) return new ArrayList<>(); - List documents = new ArrayList<>(array.size()); - for (BsonValue value : array) { - if (!value.isDocument()) continue; - String json = value.asDocument().toJson(); - org.bson.Document document = org.bson.Document.parse(json); - documents.add(new BsonDocument(document, root, this)); - } - return documents; - } - - @Nullable - @Override - public String getString(@Nonnull String path) { - Object value = getObject(path); - return value == null ? null : value.toString(); - } - - @Override - public long getLong(@Nonnull String path, long def) { - try { - return Long.parseLong(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public int getInt(@Nonnull String path, int def) { - try { - return Integer.parseInt(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public short getShort(@Nonnull String path, short def) { - try { - return Short.parseShort(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public byte getByte(@Nonnull String path, byte def) { - try { - return Byte.parseByte(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public double getDouble(@Nonnull String path, double def) { - try { - return Double.parseDouble(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public float getFloat(@Nonnull String path, float def) { - try { - return Float.parseFloat(getString(path)); - } catch (Exception ex) { - return def; - } - } - - @Override - public boolean getBoolean(@Nonnull String path, boolean def) { - try { - Object value = bsonDocument.get(path); - if (value instanceof Boolean) return (Boolean) value; - if (value instanceof String) return Boolean.parseBoolean((String) value); - } catch (Exception ex) { - } - return def; - } - - @Nullable - @Override - public Object getObject(@Nonnull String path) { - return bsonDocument.get(path); - } - - @Nonnull - @Override - public List getStringList(@Nonnull String path) { - return bsonDocument.getList(path, String.class); - } - - @Nullable - @Override - public UUID getUUID(@Nonnull String path) { - try { - Object value = bsonDocument.get(path); - if (value instanceof UUID) return (UUID) value; - if (value instanceof String) return UUID.fromString((String) value); - } catch (Exception ex) { - } - return null; - } - - @Nullable - @Override - public Date getDate(@Nonnull String path) { - return bsonDocument.getDate(path); - } - - @Nullable - @Override - public OffsetDateTime getDateTime(@Nonnull String path) { - Object value = getObject(path); - - if (value == null) - return null; - if (value instanceof OffsetDateTime) - return (OffsetDateTime) value; - if (value instanceof Date) - return ((Date)value).toInstant().atOffset(ZoneOffset.UTC); - if (value instanceof String) - return OffsetDateTime.parse((CharSequence) value); - - throw new IllegalStateException(value.getClass().getName() + " cannot be converted to java.time.OffsetDateTime"); - } - - @Nullable - @Override - public Color getColor(@Nonnull String path) { - Object value = getObject(path); - - if (value == null) - return null; - if (value instanceof Color) - return (Color) value; - if (value instanceof String) - return Color.decode((String) value); - - throw new IllegalStateException(value.getClass().getName() + " cannot be converted to java.awt.Color"); - } - - @Override - public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { - return copyJson().getInstance(path, classOfT); - } - - @Override - public T toInstanceOf(@Nonnull Class classOfT) { - return copyJson().toInstanceOf(classOfT); - } - - @Override - public boolean contains(@Nonnull String path) { - return bsonDocument.containsKey(path); - } - - @Override - public boolean isList(@Nonnull String path) { - Object value = bsonDocument.get(path); - return value instanceof Iterable || (value != null && value.getClass().isArray()); - } - - @Override - public boolean isDocument(@Nonnull String path) { - Object value = bsonDocument.get(path); - return value instanceof org.bson.Document; - } - - @Override - public boolean isObject(@Nonnull String path) { - return !isList(path) && !isDocument(path); - } - - @Override - public int size() { - return bsonDocument.size(); - } - - @Override - public void clear0() { - bsonDocument.clear(); - } - - @Override - public void set0(@Nonnull String path, @Nullable Object value) { - bsonDocument.put(path, value); - } - - @Override - public void remove0(@Nonnull String path) { - bsonDocument.remove(path); - } - - @Override - public void write(@Nonnull Writer writer) throws IOException { - String json = bsonDocument.toString(); - writer.write(json); - } - - @Nonnull - @Override - public Map values() { - return Collections.unmodifiableMap(bsonDocument); - } - - @Nonnull - @Override - public Collection keys() { - return bsonDocument.keySet(); - } - - @Override - public void forEach(@Nonnull BiConsumer action) { - bsonDocument.forEach(action); - } - - @Nonnull - @Override - public String toJson() { - return bsonDocument.toJson(); - } - - @Nonnull - @Override - public String toPrettyJson() { - return bsonDocument.toJson(JsonWriterSettings.builder().indent(true).build()); - } - - @Override - public String toString() { - return toJson(); - } - - @Override - public boolean isReadonly() { - return false; - } + protected org.bson.Document bsonDocument; + + public BsonDocument(@NotNull File file) throws IOException { + this(FileUtils.newBufferedReader(file)); + } + + public BsonDocument(@NotNull Reader reader) { + BufferedReader buffered = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); + StringBuilder content = new StringBuilder(); + buffered.lines().forEach(content::append); + bsonDocument = org.bson.Document.parse(content.toString()); + } + + public BsonDocument(@NotNull org.bson.Document bsonDocument) { + this.bsonDocument = bsonDocument; + } + + public BsonDocument(@NotNull org.bson.Document bsonDocument, @NotNull Document root, @Nullable Document parent) { + super(root, parent); + this.bsonDocument = bsonDocument; + } + + public BsonDocument() { + this(new org.bson.Document()); + } + + @NotNull + @Override + public Document getDocument0(@NotNull String path, @NotNull Document root, @Nullable Document parent) { + org.bson.Document document = bsonDocument.get(path, org.bson.Document.class); + if (document == null) { + bsonDocument.put(path, document = new org.bson.Document()); + } + + return new BsonDocument(document, root, parent); + } + + @NotNull + @Override + public List getDocumentList(@NotNull String path) { + BsonArray array = bsonDocument.get(path, BsonArray.class); + if (array == null) return new ArrayList<>(); + List documents = new ArrayList<>(array.size()); + for (BsonValue value : array) { + if (!value.isDocument()) continue; + String json = value.asDocument().toJson(); + org.bson.Document document = org.bson.Document.parse(json); + documents.add(new BsonDocument(document, root, this)); + } + return documents; + } + + @Nullable + @Override + public String getString(@NotNull String path) { + Object value = getObject(path); + return value == null ? null : value.toString(); + } + + @Override + public long getLong(@NotNull String path, long def) { + try { + return Long.parseLong(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public int getInt(@NotNull String path, int def) { + try { + return Integer.parseInt(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public short getShort(@NotNull String path, short def) { + try { + return Short.parseShort(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public byte getByte(@NotNull String path, byte def) { + try { + return Byte.parseByte(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public double getDouble(@NotNull String path, double def) { + try { + return Double.parseDouble(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public float getFloat(@NotNull String path, float def) { + try { + return Float.parseFloat(getString(path)); + } catch (Exception ex) { + return def; + } + } + + @Override + public boolean getBoolean(@NotNull String path, boolean def) { + try { + Object value = bsonDocument.get(path); + if (value instanceof Boolean) return (Boolean) value; + if (value instanceof String) return Boolean.parseBoolean((String) value); + } catch (Exception ex) { + } + return def; + } + + @Nullable + @Override + public Object getObject(@NotNull String path) { + return bsonDocument.get(path); + } + + @NotNull + @Override + public List getStringList(@NotNull String path) { + return bsonDocument.getList(path, String.class); + } + + @Nullable + @Override + public UUID getUUID(@NotNull String path) { + try { + Object value = bsonDocument.get(path); + if (value instanceof UUID) return (UUID) value; + if (value instanceof String) return UUID.fromString((String) value); + } catch (Exception ex) { + } + return null; + } + + @Nullable + @Override + public Date getDate(@NotNull String path) { + return bsonDocument.getDate(path); + } + + @Nullable + @Override + public OffsetDateTime getDateTime(@NotNull String path) { + Object value = getObject(path); + + if (value == null) + return null; + if (value instanceof OffsetDateTime) + return (OffsetDateTime) value; + if (value instanceof Date) + return ((Date) value).toInstant().atOffset(ZoneOffset.UTC); + if (value instanceof String) + return OffsetDateTime.parse((CharSequence) value); + + throw new IllegalStateException(value.getClass().getName() + " cannot be converted to java.time.OffsetDateTime"); + } + + @Nullable + @Override + public Color getColor(@NotNull String path) { + Object value = getObject(path); + + if (value == null) + return null; + if (value instanceof Color) + return (Color) value; + if (value instanceof String) + return Color.decode((String) value); + + throw new IllegalStateException(value.getClass().getName() + " cannot be converted to java.awt.Color"); + } + + @Override + public T getInstance(@NotNull String path, @NotNull Class classOfT) { + return copyJson().getInstance(path, classOfT); + } + + @Override + public T toInstanceOf(@NotNull Class classOfT) { + return copyJson().toInstanceOf(classOfT); + } + + @Override + public boolean contains(@NotNull String path) { + return bsonDocument.containsKey(path); + } + + @Override + public boolean isList(@NotNull String path) { + Object value = bsonDocument.get(path); + return value instanceof Iterable || (value != null && value.getClass().isArray()); + } + + @Override + public boolean isDocument(@NotNull String path) { + Object value = bsonDocument.get(path); + return value instanceof org.bson.Document; + } + + @Override + public boolean isObject(@NotNull String path) { + return !isList(path) && !isDocument(path); + } + + @Override + public int size() { + return bsonDocument.size(); + } + + @Override + public void clear0() { + bsonDocument.clear(); + } + + @Override + public void set0(@NotNull String path, @Nullable Object value) { + bsonDocument.put(path, value); + } + + @Override + public void remove0(@NotNull String path) { + bsonDocument.remove(path); + } + + @Override + public void write(@NotNull Writer writer) throws IOException { + String json = bsonDocument.toString(); + writer.write(json); + } + + @NotNull + @Override + public Map values() { + return Collections.unmodifiableMap(bsonDocument); + } + + @NotNull + @Override + public Collection keys() { + return bsonDocument.keySet(); + } + + @Override + public void forEach(@NotNull BiConsumer action) { + bsonDocument.forEach(action); + } + + @NotNull + @Override + public String toJson() { + return bsonDocument.toJson(); + } + + @NotNull + @Override + public String toPrettyJson() { + return bsonDocument.toJson(JsonWriterSettings.builder().indent(true).build()); + } + + @Override + public String toString() { + return toJson(); + } + + @Override + public boolean isReadonly() { + return false; + } } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java index 05611a0b0..d99183002 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/BsonUtils.java @@ -5,9 +5,9 @@ import org.bson.*; import org.bson.conversions.Bson; import org.bson.types.ObjectId; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -16,120 +16,120 @@ public final class BsonUtils { - protected static final ILogger logger = ILogger.forThisClass(); + protected static final ILogger logger = ILogger.forThisClass(); - private BsonUtils() { - } + private BsonUtils() { + } - @Nonnull - public static BsonDocument convertBsonToBsonDocument(@Nonnull Bson bson) { - return bson.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry()); - } + @NotNull + public static BsonDocument convertBsonToBsonDocument(@NotNull Bson bson) { + return bson.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry()); + } - @Nullable - public static Object unpackBsonElement(@Nullable Object value) { - if (value == null || value instanceof BsonNull) { - return null; - } else if (value instanceof BsonString) { - return ((BsonString) value).getValue(); - } else if (value instanceof BsonDouble) { - return ((BsonDouble) value).getValue(); - } else if (value instanceof BsonInt32) { - return ((BsonInt32) value).getValue(); - } else if (value instanceof BsonInt64) { - return ((BsonInt64) value).getValue(); - } else if (value instanceof BsonBinary) { - return ((BsonBinary) value).getData(); - } else if (value instanceof BsonObjectId) { - return ((BsonObjectId) value).getValue(); - } else if (value instanceof BsonArray) { - return convertBsonArrayToList((BsonArray) value); - } else if (value instanceof BsonDocument) { - return convertBsonDocumentToMap((BsonDocument) value); - } else if (value instanceof Document) { - return value; - } else { - return value; - } - } + @Nullable + public static Object unpackBsonElement(@Nullable Object value) { + if (value == null || value instanceof BsonNull) { + return null; + } else if (value instanceof BsonString) { + return ((BsonString) value).getValue(); + } else if (value instanceof BsonDouble) { + return ((BsonDouble) value).getValue(); + } else if (value instanceof BsonInt32) { + return ((BsonInt32) value).getValue(); + } else if (value instanceof BsonInt64) { + return ((BsonInt64) value).getValue(); + } else if (value instanceof BsonBinary) { + return ((BsonBinary) value).getData(); + } else if (value instanceof BsonObjectId) { + return ((BsonObjectId) value).getValue(); + } else if (value instanceof BsonArray) { + return convertBsonArrayToList((BsonArray) value); + } else if (value instanceof BsonDocument) { + return convertBsonDocumentToMap((BsonDocument) value); + } else if (value instanceof Document) { + return value; + } else { + return value; + } + } - @Nonnull - public static List convertBsonArrayToList(@Nonnull BsonArray array) { - List list = new ArrayList<>(array.size()); - for (BsonValue value : array) { - list.add(unpackBsonElement(value)); - } - return list; - } + @NotNull + public static List convertBsonArrayToList(@NotNull BsonArray array) { + List list = new ArrayList<>(array.size()); + for (BsonValue value : array) { + list.add(unpackBsonElement(value)); + } + return list; + } - @Nonnull - public static Map convertBsonDocumentToMap(@Nonnull BsonDocument document) { - Map map = new HashMap<>(); - for (Entry entry : document.entrySet()) { - map.put(entry.getKey(), unpackBsonElement(entry.getValue())); - } - return map; - } + @NotNull + public static Map convertBsonDocumentToMap(@NotNull BsonDocument document) { + Map map = new HashMap<>(); + for (Entry entry : document.entrySet()) { + map.put(entry.getKey(), unpackBsonElement(entry.getValue())); + } + return map; + } - @Nonnull - public static BsonValue convertObjectToBsonElement(@Nullable Object value) { - if (value == null) { - return BsonNull.VALUE; - } else if (value instanceof BsonValue) { - return (BsonValue) value; - } else if (value instanceof Bson) { - return convertBsonToBsonDocument((Bson) value); - } else if (value instanceof String) { - return new BsonString((String) value); - } else if (value instanceof Boolean) { - return new BsonBoolean((Boolean) value); - } else if (value instanceof ObjectId) { - return new BsonObjectId((ObjectId) value); - } else if (value instanceof Double) { - return new BsonDouble((Double) value); - } else if (value instanceof Float) { - return new BsonDouble((Float) value); - } else if (value instanceof Long) { - return new BsonInt64((Long) value); - } else if (value instanceof Integer) { - return new BsonInt32((Integer) value); - } else if (value instanceof Number) { - return new BsonInt32(((Number) value).intValue()); - } else if (value instanceof byte[]) { - return new BsonBinary((byte[]) value); - } else if (value instanceof Iterable) { - return convertIterableToBsonArray((Iterable) value); - } else if (value.getClass().isArray()) { - return convertArrayToBsonArray(value); - } else if (value instanceof Map) { - BsonDocument document = new BsonDocument(); - setDocumentProperties(document, (Map) value); - return document; - } else { - logger.error("Could not serialize " + value.getClass().getName() + " to BsonValue"); - return BsonNull.VALUE; - } - } + @NotNull + public static BsonValue convertObjectToBsonElement(@Nullable Object value) { + if (value == null) { + return BsonNull.VALUE; + } else if (value instanceof BsonValue) { + return (BsonValue) value; + } else if (value instanceof Bson) { + return convertBsonToBsonDocument((Bson) value); + } else if (value instanceof String) { + return new BsonString((String) value); + } else if (value instanceof Boolean) { + return new BsonBoolean((Boolean) value); + } else if (value instanceof ObjectId) { + return new BsonObjectId((ObjectId) value); + } else if (value instanceof Double) { + return new BsonDouble((Double) value); + } else if (value instanceof Float) { + return new BsonDouble((Float) value); + } else if (value instanceof Long) { + return new BsonInt64((Long) value); + } else if (value instanceof Integer) { + return new BsonInt32((Integer) value); + } else if (value instanceof Number) { + return new BsonInt32(((Number) value).intValue()); + } else if (value instanceof byte[]) { + return new BsonBinary((byte[]) value); + } else if (value instanceof Iterable) { + return convertIterableToBsonArray((Iterable) value); + } else if (value.getClass().isArray()) { + return convertArrayToBsonArray(value); + } else if (value instanceof Map) { + BsonDocument document = new BsonDocument(); + setDocumentProperties(document, (Map) value); + return document; + } else { + logger.error("Could not serialize " + value.getClass().getName() + " to BsonValue"); + return BsonNull.VALUE; + } + } - public static void setDocumentProperties(@Nonnull BsonDocument document, @Nonnull Map values) { - for (Entry entry : values.entrySet()) { - Object value = entry.getValue(); - document.put(entry.getKey(), convertObjectToBsonElement(value)); - } - } + public static void setDocumentProperties(@NotNull BsonDocument document, @NotNull Map values) { + for (Entry entry : values.entrySet()) { + Object value = entry.getValue(); + document.put(entry.getKey(), convertObjectToBsonElement(value)); + } + } - @Nonnull - public static BsonArray convertIterableToBsonArray(@Nonnull Iterable iterable) { - BsonArray bsonArray = new BsonArray(); - iterable.forEach(object -> bsonArray.add(convertObjectToBsonElement(object))); - return bsonArray; - } + @NotNull + public static BsonArray convertIterableToBsonArray(@NotNull Iterable iterable) { + BsonArray bsonArray = new BsonArray(); + iterable.forEach(object -> bsonArray.add(convertObjectToBsonElement(object))); + return bsonArray; + } - @Nonnull - public static BsonArray convertArrayToBsonArray(@Nonnull Object array) { - BsonArray bsonArray = new BsonArray(); - ReflectionUtils.forEachInArray(array, object -> bsonArray.add(convertObjectToBsonElement(object))); - return bsonArray; - } + @NotNull + public static BsonArray convertArrayToBsonArray(@NotNull Object array) { + BsonArray bsonArray = new BsonArray(); + ReflectionUtils.forEachInArray(array, object -> bsonArray.add(convertObjectToBsonElement(object))); + return bsonArray; + } } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java index d0c2c4a37..71bf9570b 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/common/misc/MongoUtils.java @@ -8,59 +8,59 @@ import net.codingarea.commons.database.mongodb.where.MongoDBWhere; import org.bson.BsonDocument; import org.bson.Document; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; public final class MongoUtils { - private MongoUtils() { - } + private MongoUtils() { + } - public static void applyWhere(@Nonnull FindIterable iterable, @Nonnull Map where) { - for (Entry entry : where.entrySet()) { - MongoDBWhere value = entry.getValue(); - iterable.filter(value.toBson()); + public static void applyWhere(@NotNull FindIterable iterable, @NotNull Map where) { + for (Entry entry : where.entrySet()) { + MongoDBWhere value = entry.getValue(); + iterable.filter(value.toBson()); - Collation collation = value.getCollation(); - if (collation != null) - iterable.collation(collation); - } - } + Collation collation = value.getCollation(); + if (collation != null) + iterable.collation(collation); + } + } - public static void applyOrder(@Nonnull FindIterable iterable, @Nullable String orderBy, @Nullable Order order) { - if (order == null || orderBy == null) return; - switch (order) { - case HIGHEST: - iterable.sort(Sorts.descending(orderBy)); - break; - case LOWEST: - iterable.sort(Sorts.ascending(orderBy)); - break; - } - } + public static void applyOrder(@NotNull FindIterable iterable, @Nullable String orderBy, @Nullable Order order) { + if (order == null || orderBy == null) return; + switch (order) { + case HIGHEST: + iterable.sort(Sorts.descending(orderBy)); + break; + case LOWEST: + iterable.sort(Sorts.ascending(orderBy)); + break; + } + } - @Nullable - public static Object packObject(@Nullable Object value) { - if (value == null) { - return null; - } else if (value instanceof Json) { - String json = ((Json) value).toJson(); - return Document.parse(json); - } else if (BukkitReflectionSerializationUtils.isSerializable(value.getClass())) { - Map values = BukkitReflectionSerializationUtils.serializeObject(value); - if (values == null) return null; - BsonDocument bson = new BsonDocument(); - BsonUtils.setDocumentProperties(bson, values); - return bson; - } else if (value instanceof UUID) { - return ((UUID) value).toString(); - } else { - return value; - } - } + @Nullable + public static Object packObject(@Nullable Object value) { + if (value == null) { + return null; + } else if (value instanceof Json) { + String json = ((Json) value).toJson(); + return Document.parse(json); + } else if (BukkitReflectionSerializationUtils.isSerializable(value.getClass())) { + Map values = BukkitReflectionSerializationUtils.serializeObject(value); + if (values == null) return null; + BsonDocument bson = new BsonDocument(); + BsonUtils.setDocumentProperties(bson, values); + return bson; + } else if (value instanceof UUID) { + return ((UUID) value).toString(); + } else { + return value; + } + } } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/MongoDBDatabase.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/MongoDBDatabase.java index e6789feda..74779e451 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/MongoDBDatabase.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/MongoDBDatabase.java @@ -9,9 +9,9 @@ import com.mongodb.client.MongoDatabase; import net.codingarea.commons.database.DatabaseConfig; import net.codingarea.commons.database.SQLColumn; +import net.codingarea.commons.database.abstraction.AbstractDatabase; import net.codingarea.commons.database.action.*; import net.codingarea.commons.database.exceptions.DatabaseException; -import net.codingarea.commons.database.abstraction.AbstractDatabase; import net.codingarea.commons.database.mongodb.count.MongoDBCountEntries; import net.codingarea.commons.database.mongodb.deletion.MongoDBDeletion; import net.codingarea.commons.database.mongodb.insertion.MongoDBInsertion; @@ -21,8 +21,8 @@ import net.codingarea.commons.database.mongodb.update.MongoDBUpdate; import net.codingarea.commons.database.mongodb.where.MongoDBWhere; import org.bson.Document; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Collections; import java.util.Map; import java.util.logging.Level; @@ -30,119 +30,119 @@ public class MongoDBDatabase extends AbstractDatabase { - static { - Logger.getLogger("org.mongodb").setLevel(Level.SEVERE); - } - - protected MongoClient client; - protected MongoDatabase database; - - public MongoDBDatabase(@Nonnull DatabaseConfig config) { - super(config); - } - - @Override - public void connect0() throws Exception { - MongoCredential credential = MongoCredential.createCredential(config.getUser(), config.getAuthDatabase(), config.getPassword().toCharArray()); - MongoClientSettings settings = MongoClientSettings.builder() - .retryReads(false).retryReads(false) - .credential(credential) - .applyToClusterSettings(builder -> builder.hosts(Collections.singletonList(new ServerAddress(config.getHost(), config.isPortSet() ? config.getPort() : ServerAddress.defaultPort())))) - .build(); - client = MongoClients.create(settings); - database = client.getDatabase(config.getDatabase()); - } - - @Override - public void disconnect0() throws Exception { - client.close(); - client = null; - } - - @Override - public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { - checkConnection(); - - boolean collectionExists = listTables().execute().contains(name); - if (collectionExists) return; - - try { - database.createCollection(name); - } catch (Exception ex) { - throw new DatabaseException(ex); - } - } - - @Nonnull - @Override - public DatabaseListTables listTables() { - return new MongoDBListTables(this); - } - - @Nonnull - @Override - public DatabaseCountEntries countEntries(@Nonnull String table) { - return new MongoDBCountEntries(this, table); - } - - @Nonnull - @Override - public DatabaseQuery query(@Nonnull String table) { - return new MongoDBQuery(this, table); - } - - @Nonnull - public DatabaseQuery query(@Nonnull String table, @Nonnull Map where) { - return new MongoDBQuery(this, table, where); - } - - @Nonnull - @Override - public DatabaseUpdate update(@Nonnull String table) { - return new MongoDBUpdate(this, table); - } - - @Nonnull - @Override - public DatabaseInsertion insert(@Nonnull String table) { - return new MongoDBInsertion(this, table); - } - - @Nonnull - public DatabaseInsertion insert(@Nonnull String table, @Nonnull Map values) { - return new MongoDBInsertion(this, table, new Document(values)); - } - - @Nonnull - public DatabaseInsertion insert(@Nonnull String table, @Nonnull Document document) { - return new MongoDBInsertion(this, table, document); - } - - @Nonnull - @Override - public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { - return new MongoDBInsertionOrUpdate(this, table); - } - - @Nonnull - @Override - public DatabaseDeletion delete(@Nonnull String table) { - return new MongoDBDeletion(this, table); - } - - @Nonnull - public MongoCollection getCollection(@Nonnull String collection) { - return database.getCollection(collection); - } - - @Nonnull - public MongoDatabase getDatabase() { - return database; - } - - @Override - public boolean isConnected() { - return client != null && database != null; - } + static { + Logger.getLogger("org.mongodb").setLevel(Level.SEVERE); + } + + protected MongoClient client; + protected MongoDatabase database; + + public MongoDBDatabase(@NotNull DatabaseConfig config) { + super(config); + } + + @Override + public void connect0() throws Exception { + MongoCredential credential = MongoCredential.createCredential(config.getUser(), config.getAuthDatabase(), config.getPassword().toCharArray()); + MongoClientSettings settings = MongoClientSettings.builder() + .retryReads(false).retryReads(false) + .credential(credential) + .applyToClusterSettings(builder -> builder.hosts(Collections.singletonList(new ServerAddress(config.getHost(), config.isPortSet() ? config.getPort() : ServerAddress.defaultPort())))) + .build(); + client = MongoClients.create(settings); + database = client.getDatabase(config.getDatabase()); + } + + @Override + public void disconnect0() throws Exception { + client.close(); + client = null; + } + + @Override + public void createTable(@NotNull String name, @NotNull SQLColumn... columns) throws DatabaseException { + checkConnection(); + + boolean collectionExists = listTables().execute().contains(name); + if (collectionExists) return; + + try { + database.createCollection(name); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @NotNull + @Override + public DatabaseListTables listTables() { + return new MongoDBListTables(this); + } + + @NotNull + @Override + public DatabaseCountEntries countEntries(@NotNull String table) { + return new MongoDBCountEntries(this, table); + } + + @NotNull + @Override + public DatabaseQuery query(@NotNull String table) { + return new MongoDBQuery(this, table); + } + + @NotNull + public DatabaseQuery query(@NotNull String table, @NotNull Map where) { + return new MongoDBQuery(this, table, where); + } + + @NotNull + @Override + public DatabaseUpdate update(@NotNull String table) { + return new MongoDBUpdate(this, table); + } + + @NotNull + @Override + public DatabaseInsertion insert(@NotNull String table) { + return new MongoDBInsertion(this, table); + } + + @NotNull + public DatabaseInsertion insert(@NotNull String table, @NotNull Map values) { + return new MongoDBInsertion(this, table, new Document(values)); + } + + @NotNull + public DatabaseInsertion insert(@NotNull String table, @NotNull Document document) { + return new MongoDBInsertion(this, table, document); + } + + @NotNull + @Override + public DatabaseInsertionOrUpdate insertOrUpdate(@NotNull String table) { + return new MongoDBInsertionOrUpdate(this, table); + } + + @NotNull + @Override + public DatabaseDeletion delete(@NotNull String table) { + return new MongoDBDeletion(this, table); + } + + @NotNull + public MongoCollection getCollection(@NotNull String collection) { + return database.getCollection(collection); + } + + @NotNull + public MongoDatabase getDatabase() { + return database; + } + + @Override + public boolean isConnected() { + return client != null && database != null; + } } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/count/MongoDBCountEntries.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/count/MongoDBCountEntries.java index e1b185de5..983606185 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/count/MongoDBCountEntries.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/count/MongoDBCountEntries.java @@ -3,40 +3,40 @@ import net.codingarea.commons.database.action.DatabaseCountEntries; import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Objects; public class MongoDBCountEntries implements DatabaseCountEntries { - protected final MongoDBDatabase database; - protected final String table; - - public MongoDBCountEntries(@Nonnull MongoDBDatabase database, @Nonnull String table) { - this.database = database; - this.table = table; - } - - @Nonnull - @Override - public Long execute() throws DatabaseException { - try { - return database.getCollection(table).countDocuments(); - } catch (Exception ex) { - throw new DatabaseException(ex); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - MongoDBCountEntries that = (MongoDBCountEntries) o; - return Objects.equals(database, that.database) && Objects.equals(table, that.table); - } - - @Override - public int hashCode() { - return Objects.hash(database, table); - } + protected final MongoDBDatabase database; + protected final String table; + + public MongoDBCountEntries(@NotNull MongoDBDatabase database, @NotNull String table) { + this.database = database; + this.table = table; + } + + @NotNull + @Override + public Long execute() throws DatabaseException { + try { + return database.getCollection(table).countDocuments(); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBCountEntries that = (MongoDBCountEntries) o; + return Objects.equals(database, that.database) && Objects.equals(table, that.table); + } + + @Override + public int hashCode() { + return Objects.hash(database, table); + } } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/deletion/MongoDBDeletion.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/deletion/MongoDBDeletion.java index 3073dbb40..34a7cd275 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/deletion/MongoDBDeletion.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/deletion/MongoDBDeletion.java @@ -14,95 +14,95 @@ import org.bson.BsonDocument; import org.bson.Document; import org.bson.conversions.Bson; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class MongoDBDeletion implements DatabaseDeletion { - protected final MongoDBDatabase database; - protected final String collection; - protected final Map where = new HashMap<>(); - - public MongoDBDeletion(@Nonnull MongoDBDatabase database, @Nonnull String collection) { - this.database = database; - this.collection = collection; - } - - @Nonnull - @Override - public DatabaseDeletion where(@Nonnull String column, @Nullable Object object) { - where.put(column, new ObjectWhere(column, object, Filters::eq)); - return this; - } - - @Nonnull - @Override - public DatabaseDeletion where(@Nonnull String column, @Nullable Number value) { - return where(column, (Object) value); - } - - @Nonnull - @Override - public DatabaseDeletion where(@Nonnull String column, @Nullable String value) { - return where(column, (Object) value); - } - - @Nonnull - @Override - public DatabaseDeletion where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { - if (!ignoreCase) return where(column, value); - if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); - where.put(column, new StringIgnoreCaseWhere(column, value)); - return this; - } - - @Nonnull - @Override - public DatabaseDeletion whereNot(@Nonnull String column, @Nullable Object object) { - where.put(column, new ObjectWhere(column, object, Filters::ne)); - return this; - } - - @Override - public Void execute() throws DatabaseException { - try { - MongoCollection collection = database.getCollection(this.collection); - - Document filter = new Document(); - DeleteOptions options = new DeleteOptions(); - - for (MongoDBWhere where : where.values()) { - Bson whereBson = where.toBson(); - BsonDocument asBsonDocument = BsonUtils.convertBsonToBsonDocument(whereBson); - filter.putAll(asBsonDocument); - - Collation collation = where.getCollation(); - if (collation != null) - options.collation(collation); - } - - collection.deleteMany(filter, options); - return null; - } catch (Exception ex) { - throw new DatabaseException(ex); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - MongoDBDeletion that = (MongoDBDeletion) o; - return database.equals(that.database) && collection.equals(that.collection) && where.equals(that.where); - } - - @Override - public int hashCode() { - return Objects.hash(database, collection, where); - } + protected final MongoDBDatabase database; + protected final String collection; + protected final Map where = new HashMap<>(); + + public MongoDBDeletion(@NotNull MongoDBDatabase database, @NotNull String collection) { + this.database = database; + this.collection = collection; + } + + @NotNull + @Override + public DatabaseDeletion where(@NotNull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, Filters::eq)); + return this; + } + + @NotNull + @Override + public DatabaseDeletion where(@NotNull String column, @Nullable Number value) { + return where(column, (Object) value); + } + + @NotNull + @Override + public DatabaseDeletion where(@NotNull String column, @Nullable String value) { + return where(column, (Object) value); + } + + @NotNull + @Override + public DatabaseDeletion where(@NotNull String column, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(column, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(column, new StringIgnoreCaseWhere(column, value)); + return this; + } + + @NotNull + @Override + public DatabaseDeletion whereNot(@NotNull String column, @Nullable Object object) { + where.put(column, new ObjectWhere(column, object, Filters::ne)); + return this; + } + + @Override + public Void execute() throws DatabaseException { + try { + MongoCollection collection = database.getCollection(this.collection); + + Document filter = new Document(); + DeleteOptions options = new DeleteOptions(); + + for (MongoDBWhere where : where.values()) { + Bson whereBson = where.toBson(); + BsonDocument asBsonDocument = BsonUtils.convertBsonToBsonDocument(whereBson); + filter.putAll(asBsonDocument); + + Collation collation = where.getCollation(); + if (collation != null) + options.collation(collation); + } + + collection.deleteMany(filter, options); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBDeletion that = (MongoDBDeletion) o; + return database.equals(that.database) && collection.equals(that.collection) && where.equals(that.where); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, where); + } } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertion/MongoDBInsertion.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertion/MongoDBInsertion.java index 10e38cfc6..9e7424110 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertion/MongoDBInsertion.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertion/MongoDBInsertion.java @@ -5,57 +5,57 @@ import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.commons.database.mongodb.MongoDBDatabase; import org.bson.Document; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Objects; public class MongoDBInsertion implements DatabaseInsertion { - protected final MongoDBDatabase database; - protected final String collection; - protected final Document values; - - public MongoDBInsertion(@Nonnull MongoDBDatabase database, @Nonnull String collection) { - this.database = database; - this.collection = collection; - this.values = new Document(); - } - - public MongoDBInsertion(@Nonnull MongoDBDatabase database, @Nonnull String collection, @Nonnull Document values) { - this.database = database; - this.collection = collection; - this.values = values; - } - - @Nonnull - @Override - public DatabaseInsertion set(@Nonnull String field, @Nullable Object value) { - values.put(field, MongoUtils.packObject(value)); - return this; - } - - @Override - public Void execute() throws DatabaseException { - try { - database.getCollection(collection).insertOne(values); - return null; - } catch (Exception ex) { - throw new DatabaseException(ex); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - MongoDBInsertion that = (MongoDBInsertion) o; - return database.equals(that.database) && collection.equals(that.collection) && values.equals(that.values); - } - - @Override - public int hashCode() { - return Objects.hash(database, collection, values); - } + protected final MongoDBDatabase database; + protected final String collection; + protected final Document values; + + public MongoDBInsertion(@NotNull MongoDBDatabase database, @NotNull String collection) { + this.database = database; + this.collection = collection; + this.values = new Document(); + } + + public MongoDBInsertion(@NotNull MongoDBDatabase database, @NotNull String collection, @NotNull Document values) { + this.database = database; + this.collection = collection; + this.values = values; + } + + @NotNull + @Override + public DatabaseInsertion set(@NotNull String field, @Nullable Object value) { + values.put(field, MongoUtils.packObject(value)); + return this; + } + + @Override + public Void execute() throws DatabaseException { + try { + database.getCollection(collection).insertOne(values); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBInsertion that = (MongoDBInsertion) o; + return database.equals(that.database) && collection.equals(that.collection) && values.equals(that.values); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, values); + } } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertorupdate/MongoDBInsertionOrUpdate.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertorupdate/MongoDBInsertionOrUpdate.java index 295751f3d..ad8d19c18 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertorupdate/MongoDBInsertionOrUpdate.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/insertorupdate/MongoDBInsertionOrUpdate.java @@ -8,78 +8,78 @@ import net.codingarea.commons.database.mongodb.where.MongoDBWhere; import org.bson.BsonDocument; import org.bson.Document; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Map.Entry; public class MongoDBInsertionOrUpdate extends MongoDBUpdate implements DatabaseInsertionOrUpdate { - public MongoDBInsertionOrUpdate(@Nonnull MongoDBDatabase database, @Nonnull String collection) { - super(database, collection); - } + public MongoDBInsertionOrUpdate(@NotNull MongoDBDatabase database, @NotNull String collection) { + super(database, collection); + } - @Nonnull - @Override - public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { - super.where(field, value, ignoreCase); - return this; - } + @NotNull + @Override + public DatabaseInsertionOrUpdate where(@NotNull String field, @Nullable String value, boolean ignoreCase) { + super.where(field, value, ignoreCase); + return this; + } - @Nonnull - @Override - public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Object value) { - super.where(field, value); - return this; - } + @NotNull + @Override + public DatabaseInsertionOrUpdate where(@NotNull String field, @Nullable Object value) { + super.where(field, value); + return this; + } - @Nonnull - @Override - public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value) { - super.where(field, value); - return this; - } + @NotNull + @Override + public DatabaseInsertionOrUpdate where(@NotNull String field, @Nullable String value) { + super.where(field, value); + return this; + } - @Nonnull - @Override - public DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Number value) { - super.where(field, value); - return this; - } + @NotNull + @Override + public DatabaseInsertionOrUpdate where(@NotNull String field, @Nullable Number value) { + super.where(field, value); + return this; + } - @Nonnull - @Override - public DatabaseInsertionOrUpdate whereNot(@Nonnull String field, @Nullable Object value) { - super.whereNot(field, value); - return this; - } + @NotNull + @Override + public DatabaseInsertionOrUpdate whereNot(@NotNull String field, @Nullable Object value) { + super.whereNot(field, value); + return this; + } - @Nonnull - @Override - public DatabaseInsertionOrUpdate set(@Nonnull String field, @Nullable Object value) { - super.set(field, value); - return this; - } + @NotNull + @Override + public DatabaseInsertionOrUpdate set(@NotNull String field, @Nullable Object value) { + super.set(field, value); + return this; + } - @Override - public Void execute() throws DatabaseException { - if (database.query(collection, where).execute().isSet()) { - return super.execute(); - } else { - Document document = new Document(values); - for (Entry entry : where.entrySet()) { - BsonDocument bson = BsonUtils.convertBsonToBsonDocument(entry.getValue().toBson()); - document.putAll(bson); - } + @Override + public Void execute() throws DatabaseException { + if (database.query(collection, where).execute().isSet()) { + return super.execute(); + } else { + Document document = new Document(values); + for (Entry entry : where.entrySet()) { + BsonDocument bson = BsonUtils.convertBsonToBsonDocument(entry.getValue().toBson()); + document.putAll(bson); + } - database.insert(collection, document).execute(); - return null; - } - } + database.insert(collection, document).execute(); + return null; + } + } - @Override - public boolean equals(Object o) { - return super.equals(o); - } + @Override + public boolean equals(Object o) { + return super.equals(o); + } } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/list/MongoDBListTables.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/list/MongoDBListTables.java index 987eba440..8521ca01c 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/list/MongoDBListTables.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/list/MongoDBListTables.java @@ -3,27 +3,27 @@ import net.codingarea.commons.database.action.DatabaseListTables; import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.commons.database.mongodb.MongoDBDatabase; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; public class MongoDBListTables implements DatabaseListTables { - protected final MongoDBDatabase database; + protected final MongoDBDatabase database; - public MongoDBListTables(@Nonnull MongoDBDatabase database) { - this.database = database; - } + public MongoDBListTables(@NotNull MongoDBDatabase database) { + this.database = database; + } - @Nonnull - @Override - public List execute() throws DatabaseException { - try { - return database.getDatabase().listCollectionNames().into(new ArrayList<>()); - } catch (Exception ex) { - throw new DatabaseException(ex); - } - } + @NotNull + @Override + public List execute() throws DatabaseException { + try { + return database.getDatabase().listCollectionNames().into(new ArrayList<>()); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBQuery.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBQuery.java index e1e11832b..7851356c8 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBQuery.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBQuery.java @@ -4,125 +4,125 @@ import com.mongodb.client.model.Filters; import net.codingarea.commons.common.misc.MongoUtils; import net.codingarea.commons.database.Order; +import net.codingarea.commons.database.abstraction.DefaultExecutedQuery; import net.codingarea.commons.database.action.DatabaseQuery; import net.codingarea.commons.database.action.ExecutedQuery; import net.codingarea.commons.database.exceptions.DatabaseException; -import net.codingarea.commons.database.abstraction.DefaultExecutedQuery; import net.codingarea.commons.database.mongodb.MongoDBDatabase; import net.codingarea.commons.database.mongodb.where.MongoDBWhere; import net.codingarea.commons.database.mongodb.where.ObjectWhere; import net.codingarea.commons.database.mongodb.where.StringIgnoreCaseWhere; import org.bson.Document; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.*; public class MongoDBQuery implements DatabaseQuery { - protected final MongoDBDatabase database; - protected final String collection; - protected final Map where; - protected Order order; - protected String orderBy; - - public MongoDBQuery(@Nonnull MongoDBDatabase database, @Nonnull String collection) { - this.database = database; - this.collection = collection; - this.where = new HashMap<>(); - } - - public MongoDBQuery(@Nonnull MongoDBDatabase database, @Nonnull String collection, @Nonnull Map where) { - this.database = database; - this.collection = collection; - this.where = where; - } - - @Nonnull - @Override - public DatabaseQuery where(@Nonnull String field, @Nullable Object value) { - where.put(field, new ObjectWhere(field, value, Filters::eq)); - return this; - } - - @Nonnull - @Override - public DatabaseQuery where(@Nonnull String field, @Nullable Number value) { - return where(field, (Object) value); - } - - @Nonnull - @Override - public DatabaseQuery where(@Nonnull String field, @Nullable String value) { - return where(field, (Object) value); - } - - @Nonnull - @Override - public DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { - if (!ignoreCase) return where(field, value); - if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); - where.put(field, new StringIgnoreCaseWhere(field, value)); - return this; - } - - @Nonnull - @Override - public DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value) { - where.put(field, new ObjectWhere(field, value, Filters::ne)); - return this; - } - - @Nonnull - @Override - public DatabaseQuery orderBy(@Nonnull String column, @Nonnull Order order) { - this.orderBy = column; - this.order = order; - return this; - } - - @Nonnull - @Override - public DatabaseQuery select(@Nonnull String... selection) { - return this; - } - - @Nonnull - @Override - public ExecutedQuery execute() throws DatabaseException { - try { - FindIterable iterable = database.getCollection(collection).find(); - MongoUtils.applyWhere(iterable, where); - MongoUtils.applyOrder(iterable, orderBy, order); - - List documents = iterable.into(new ArrayList<>()); - return createExecutedQuery(documents); - } catch (Exception ex) { - throw new DatabaseException(ex); - } - } - - @Nonnull - private ExecutedQuery createExecutedQuery(@Nonnull List documents) { - List results = new ArrayList<>(documents.size()); - for (Document document : documents) { - results.add(new MongoDBResult(document)); - } - - return new DefaultExecutedQuery(results); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - MongoDBQuery that = (MongoDBQuery) o; - return database.equals(that.database) && collection.equals(that.collection) && where.equals(that.where) && order == that.order && Objects.equals(orderBy, that.orderBy); - } - - @Override - public int hashCode() { - return Objects.hash(database, collection, where, order, orderBy); - } + protected final MongoDBDatabase database; + protected final String collection; + protected final Map where; + protected Order order; + protected String orderBy; + + public MongoDBQuery(@NotNull MongoDBDatabase database, @NotNull String collection) { + this.database = database; + this.collection = collection; + this.where = new HashMap<>(); + } + + public MongoDBQuery(@NotNull MongoDBDatabase database, @NotNull String collection, @NotNull Map where) { + this.database = database; + this.collection = collection; + this.where = where; + } + + @NotNull + @Override + public DatabaseQuery where(@NotNull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::eq)); + return this; + } + + @NotNull + @Override + public DatabaseQuery where(@NotNull String field, @Nullable Number value) { + return where(field, (Object) value); + } + + @NotNull + @Override + public DatabaseQuery where(@NotNull String field, @Nullable String value) { + return where(field, (Object) value); + } + + @NotNull + @Override + public DatabaseQuery where(@NotNull String field, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(field, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(field, new StringIgnoreCaseWhere(field, value)); + return this; + } + + @NotNull + @Override + public DatabaseQuery whereNot(@NotNull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::ne)); + return this; + } + + @NotNull + @Override + public DatabaseQuery orderBy(@NotNull String column, @NotNull Order order) { + this.orderBy = column; + this.order = order; + return this; + } + + @NotNull + @Override + public DatabaseQuery select(@NotNull String... selection) { + return this; + } + + @NotNull + @Override + public ExecutedQuery execute() throws DatabaseException { + try { + FindIterable iterable = database.getCollection(collection).find(); + MongoUtils.applyWhere(iterable, where); + MongoUtils.applyOrder(iterable, orderBy, order); + + List documents = iterable.into(new ArrayList<>()); + return createExecutedQuery(documents); + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @NotNull + private ExecutedQuery createExecutedQuery(@NotNull List documents) { + List results = new ArrayList<>(documents.size()); + for (Document document : documents) { + results.add(new MongoDBResult(document)); + } + + return new DefaultExecutedQuery(results); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBQuery that = (MongoDBQuery) o; + return database.equals(that.database) && collection.equals(that.collection) && where.equals(that.where) && order == that.order && Objects.equals(orderBy, that.orderBy); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, where, order, orderBy); + } } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBResult.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBResult.java index c65457f05..5f1ecaded 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBResult.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/query/MongoDBResult.java @@ -1,18 +1,17 @@ package net.codingarea.commons.database.mongodb.query; import net.codingarea.commons.common.config.document.BsonDocument; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public final class MongoDBResult extends BsonDocument { - public MongoDBResult(@Nonnull org.bson.Document bsonDocument) { - super(bsonDocument); - } + public MongoDBResult(@NotNull org.bson.Document bsonDocument) { + super(bsonDocument); + } - @Override - public boolean isReadonly() { - return true; - } + @Override + public boolean isReadonly() { + return true; + } } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/update/MongoDBUpdate.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/update/MongoDBUpdate.java index 6e30f14f4..6f44634bf 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/update/MongoDBUpdate.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/update/MongoDBUpdate.java @@ -16,9 +16,9 @@ import org.bson.BsonDocument; import org.bson.Document; import org.bson.conversions.Bson; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; @@ -26,114 +26,114 @@ public class MongoDBUpdate implements DatabaseUpdate { - protected final MongoDBDatabase database; - protected final String collection; - protected final Map where; - protected final Map values; - - public MongoDBUpdate(@Nonnull MongoDBDatabase database, @Nonnull String collection) { - this.database = database; - this.collection = collection; - this.where = new HashMap<>(); - this.values = new HashMap<>(); - } - - public MongoDBUpdate(@Nonnull MongoDBDatabase database, @Nonnull String collection, @Nonnull Map where, @Nonnull Map values) { - this.database = database; - this.collection = collection; - this.where = where; - this.values = values; - } - - @Nonnull - @Override - public DatabaseUpdate where(@Nonnull String field, @Nullable Object value) { - where.put(field, new ObjectWhere(field, value, Filters::eq)); - return this; - } - - @Nonnull - @Override - public DatabaseUpdate where(@Nonnull String field, @Nullable Number value) { - return where(field, (Object) value); - } - - @Nonnull - @Override - public DatabaseUpdate where(@Nonnull String field, @Nullable String value) { - return where(field, (Object) value); - } - - @Nonnull - @Override - public DatabaseUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { - if (!ignoreCase) return where(field, value); - if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); - where.put(field, new StringIgnoreCaseWhere(field, value)); - return this; - } - - @Nonnull - @Override - public DatabaseUpdate whereNot(@Nonnull String field, @Nullable Object value) { - where.put(field, new ObjectWhere(field, value, Filters::ne)); - return this; - } - - @Nonnull - @Override - public DatabaseUpdate set(@Nonnull String field, @Nullable Object value) { - values.put(field, MongoUtils.packObject(value)); - return this; - } - - @Override - public Void execute() throws DatabaseException { - try { - MongoCollection collection = database.getCollection(this.collection); - - Document filter = new Document(); - UpdateOptions options = new UpdateOptions(); - - for (MongoDBWhere where : where.values()) { - Bson whereBson = where.toBson(); - BsonDocument asBsonDocument = BsonUtils.convertBsonToBsonDocument(whereBson); - filter.putAll(asBsonDocument); - - Collation collation = where.getCollation(); - if (collation != null) - options.collation(collation); - } - - Document newDocument = new Document(); - for (Entry entry : values.entrySet()) { - newDocument.put(entry.getKey(), MongoUtils.packObject(entry.getValue())); - } - - BasicDBObject update = new BasicDBObject(); - update.put("$set", newDocument); - - collection.updateMany(filter, update, options); - return null; - } catch (Exception ex) { - throw new DatabaseException(ex); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - MongoDBUpdate that = (MongoDBUpdate) o; - return database.equals(that.database) - && collection.equals(that.collection) - && where.equals(that.where) - && values.equals(that.values); - } - - @Override - public int hashCode() { - return Objects.hash(database, collection, where, values); - } + protected final MongoDBDatabase database; + protected final String collection; + protected final Map where; + protected final Map values; + + public MongoDBUpdate(@NotNull MongoDBDatabase database, @NotNull String collection) { + this.database = database; + this.collection = collection; + this.where = new HashMap<>(); + this.values = new HashMap<>(); + } + + public MongoDBUpdate(@NotNull MongoDBDatabase database, @NotNull String collection, @NotNull Map where, @NotNull Map values) { + this.database = database; + this.collection = collection; + this.where = where; + this.values = values; + } + + @NotNull + @Override + public DatabaseUpdate where(@NotNull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::eq)); + return this; + } + + @NotNull + @Override + public DatabaseUpdate where(@NotNull String field, @Nullable Number value) { + return where(field, (Object) value); + } + + @NotNull + @Override + public DatabaseUpdate where(@NotNull String field, @Nullable String value) { + return where(field, (Object) value); + } + + @NotNull + @Override + public DatabaseUpdate where(@NotNull String field, @Nullable String value, boolean ignoreCase) { + if (!ignoreCase) return where(field, value); + if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); + where.put(field, new StringIgnoreCaseWhere(field, value)); + return this; + } + + @NotNull + @Override + public DatabaseUpdate whereNot(@NotNull String field, @Nullable Object value) { + where.put(field, new ObjectWhere(field, value, Filters::ne)); + return this; + } + + @NotNull + @Override + public DatabaseUpdate set(@NotNull String field, @Nullable Object value) { + values.put(field, MongoUtils.packObject(value)); + return this; + } + + @Override + public Void execute() throws DatabaseException { + try { + MongoCollection collection = database.getCollection(this.collection); + + Document filter = new Document(); + UpdateOptions options = new UpdateOptions(); + + for (MongoDBWhere where : where.values()) { + Bson whereBson = where.toBson(); + BsonDocument asBsonDocument = BsonUtils.convertBsonToBsonDocument(whereBson); + filter.putAll(asBsonDocument); + + Collation collation = where.getCollation(); + if (collation != null) + options.collation(collation); + } + + Document newDocument = new Document(); + for (Entry entry : values.entrySet()) { + newDocument.put(entry.getKey(), MongoUtils.packObject(entry.getValue())); + } + + BasicDBObject update = new BasicDBObject(); + update.put("$set", newDocument); + + collection.updateMany(filter, update, options); + return null; + } catch (Exception ex) { + throw new DatabaseException(ex); + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MongoDBUpdate that = (MongoDBUpdate) o; + return database.equals(that.database) + && collection.equals(that.collection) + && where.equals(that.where) + && values.equals(that.values); + } + + @Override + public int hashCode() { + return Objects.hash(database, collection, where, values); + } } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/MongoDBWhere.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/MongoDBWhere.java index 64a41b89e..483401f3f 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/MongoDBWhere.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/MongoDBWhere.java @@ -2,16 +2,15 @@ import com.mongodb.client.model.Collation; import org.bson.conversions.Bson; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public interface MongoDBWhere { - @Nonnull - Bson toBson(); + @NotNull + Bson toBson(); - @Nullable - Collation getCollation(); + @Nullable + Collation getCollation(); } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/ObjectWhere.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/ObjectWhere.java index 84852ffb2..86b8e7c31 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/ObjectWhere.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/ObjectWhere.java @@ -3,47 +3,47 @@ import com.mongodb.client.model.Collation; import net.codingarea.commons.common.misc.MongoUtils; import org.bson.conversions.Bson; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Objects; import java.util.function.BiFunction; public class ObjectWhere implements MongoDBWhere { - protected final String field; - protected final Object value; - protected final BiFunction creator; - - public ObjectWhere(@Nonnull String field, @Nullable Object value, @Nonnull BiFunction creator) { - this.field = field; - this.value = MongoUtils.packObject(value); - this.creator = creator; - } - - @Nonnull - @Override - public Bson toBson() { - return creator.apply(field, value); - } - - @Nullable - @Override - public Collation getCollation() { - return null; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ObjectWhere that = (ObjectWhere) o; - return field.equals(that.field) && Objects.equals(value, that.value); - } - - @Override - public int hashCode() { - return Objects.hash(field, value); - } + protected final String field; + protected final Object value; + protected final BiFunction creator; + + public ObjectWhere(@NotNull String field, @Nullable Object value, @NotNull BiFunction creator) { + this.field = field; + this.value = MongoUtils.packObject(value); + this.creator = creator; + } + + @NotNull + @Override + public Bson toBson() { + return creator.apply(field, value); + } + + @Nullable + @Override + public Collation getCollation() { + return null; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ObjectWhere that = (ObjectWhere) o; + return field.equals(that.field) && Objects.equals(value, that.value); + } + + @Override + public int hashCode() { + return Objects.hash(field, value); + } } diff --git a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/StringIgnoreCaseWhere.java b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/StringIgnoreCaseWhere.java index d7e875f8e..da68a884f 100644 --- a/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/StringIgnoreCaseWhere.java +++ b/mongo-connector/src/main/java/net/codingarea/commons/database/mongodb/where/StringIgnoreCaseWhere.java @@ -4,44 +4,44 @@ import com.mongodb.client.model.CollationStrength; import com.mongodb.client.model.Filters; import org.bson.conversions.Bson; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Objects; public class StringIgnoreCaseWhere implements MongoDBWhere { - protected final String field; - protected final String value; - - public StringIgnoreCaseWhere(@Nonnull String field, @Nonnull String value) { - this.field = field; - this.value = value; - } - - @Nonnull - @Override - public Bson toBson() { - return Filters.eq(field, value); - } - - @Nullable - @Override - public Collation getCollation() { - return Collation.builder().collationStrength(CollationStrength.SECONDARY).locale("en").build(); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - StringIgnoreCaseWhere that = (StringIgnoreCaseWhere) o; - return field.equals(that.field) && value.equals(that.value); - } - - @Override - public int hashCode() { - return Objects.hash(field, value); - } + protected final String field; + protected final String value; + + public StringIgnoreCaseWhere(@NotNull String field, @NotNull String value) { + this.field = field; + this.value = value; + } + + @NotNull + @Override + public Bson toBson() { + return Filters.eq(field, value); + } + + @Nullable + @Override + public Collation getCollation() { + return Collation.builder().collationStrength(CollationStrength.SECONDARY).locale("en").build(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + StringIgnoreCaseWhere that = (StringIgnoreCaseWhere) o; + return field.equals(that.field) && value.equals(that.value); + } + + @Override + public int hashCode() { + return Objects.hash(field, value); + } } diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index 9a528f157..4d8c10bf2 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -5,11 +5,11 @@ plugins { dependencies { implementation(libs.slf4j.api) - implementation(libs.jsr305) compileOnly(libs.spigot.api) compileOnly(libs.authlib) + compileOnly(libs.jetbrains.annotations) compileOnly(libs.lombok) // gson is already bundled by mojang, accessing it saves on artifact size but might cause compatibilty issues diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java b/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java index c4323fb08..f09a08ea5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java @@ -9,9 +9,9 @@ import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; @@ -49,11 +49,11 @@ public static void resetTimer() { Challenges.getInstance().getChallengeTimer().reset(); } - public static void endChallenge(@Nonnull ChallengeEndCause endCause) { + public static void endChallenge(@NotNull ChallengeEndCause endCause) { Challenges.getInstance().getServerManager().endChallenge(endCause, null); } - public static void endChallenge(@Nonnull ChallengeEndCause endCause, Supplier> winnerGetter) { + public static void endChallenge(@NotNull ChallengeEndCause endCause, Supplier> winnerGetter) { Challenges.getInstance().getServerManager().endChallenge(endCause, winnerGetter); } @@ -66,20 +66,20 @@ public static boolean isFresh() { return Challenges.getInstance().getServerManager().isFresh(); } - public static void registerScheduler(@Nonnull Object... scheduler) { + public static void registerScheduler(@NotNull Object... scheduler) { Challenges.getInstance().getScheduler().register(scheduler); } - public static void subscribeLoader(@Nonnull Class classOfLoader, @Nonnull Runnable action) { + public static void subscribeLoader(@NotNull Class classOfLoader, @NotNull Runnable action) { Challenges.getInstance().getLoaderRegistry().subscribe(classOfLoader, action); } - @Nonnull - public static List getCustomDrops(@Nonnull Material block) { + @NotNull + public static List getCustomDrops(@NotNull Material block) { return Challenges.getInstance().getBlockDropManager().getCustomDrops(block); } - public static boolean getDropChance(@Nonnull Material block) { + public static boolean getDropChance(@NotNull Material block) { return Challenges.getInstance().getBlockDropManager().getDropChance(block).getAsBoolean(); } @@ -87,7 +87,7 @@ public static boolean getItemsDirectIntoInventory() { return Challenges.getInstance().getBlockDropManager().isItemsDirectIntoInventory(); } - @Nonnull + @NotNull public static String formatTime(long seconds) { return Challenges.getInstance().getChallengeTimer().getFormat().format(seconds); } @@ -95,7 +95,7 @@ public static String formatTime(long seconds) { /** * @return all players that aren't ignored by the plugin */ - @Nonnull + @NotNull public static List getIngamePlayers() { List list = new ArrayList<>(); for (Player player : Bukkit.getOnlinePlayers()) { @@ -114,7 +114,7 @@ public static World getGameWorld(@Nullable Environment environment) { return Challenges.getInstance().getGameWorldStorage().getWorld(environment); } - public static boolean isPlayerInGameWorld(@Nonnull Environment environment) { + public static boolean isPlayerInGameWorld(@NotNull Environment environment) { World world = getGameWorld(environment); for (Player player : world.getPlayers()) { if (!AbstractChallenge.ignorePlayer(player)) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java index 4ffa641df..1f2c22ed6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java @@ -26,8 +26,7 @@ import net.codingarea.challenges.plugin.utils.bukkit.command.ForwardingCommand; import net.codingarea.commons.bukkit.core.BukkitModule; import net.codingarea.commons.common.version.Version; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Getter public final class Challenges extends BukkitModule { @@ -56,7 +55,7 @@ public final class Challenges extends BukkitModule { private GeneratorWorldPortalManager generatorWorldPortalManager; private TeamProvider teamProvider; - @Nonnull + @NotNull public static Challenges getInstance() { return instance; } @@ -86,7 +85,6 @@ protected void handleEnable() { } private void createManagers() { - configManager = new ConfigManager(); configManager.loadConfigs(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index 99f35dacf..2e315fb3a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -16,9 +16,8 @@ import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -88,7 +87,7 @@ public ItemStack getDisplayItem() { return builder.build(); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.BARRIER); @@ -100,7 +99,7 @@ public void playStatusUpdateTitle() { } @Override - public void writeSettings(@Nonnull Document document) { + public void writeSettings(@NotNull Document document) { super.writeSettings(document); document.set("material", material == null ? null : material.name()); @@ -167,7 +166,7 @@ public void executeAction(ChallengeExecutionData challengeExecutionData) { action.execute(challengeExecutionData, subActions); } - public void applySettings(@Nonnull Material material, @Nonnull String name, @Nonnull ChallengeTrigger trigger, + public void applySettings(@NotNull Material material, @NotNull String name, @NotNull ChallengeTrigger trigger, Map subTriggers, ChallengeAction action, Map subActions) { this.material = material; this.name = name; @@ -181,7 +180,7 @@ public UUID getUniqueId() { return uuid; } - @Nonnull + @NotNull public String getDisplayName() { return name; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java index e2ec9446a..520cd32b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java @@ -10,8 +10,8 @@ import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Bukkit; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; import java.util.LinkedHashMap; import java.util.Map; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java index dc64e015f..4b7a09a17 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/FallbackNames.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.custom.settings; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -10,7 +11,7 @@ @Retention(RetentionPolicy.RUNTIME) public @interface FallbackNames { - @Nonnull + @NotNull String[] value(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java index 17b682f2b..fab3c99d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java @@ -8,8 +8,8 @@ import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Map; public class RandomItemAction extends ChallengeAction { @@ -18,7 +18,7 @@ public RandomItemAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); } - public static void giveRandomItemToPlayer(@Nonnull Player player) { + public static void giveRandomItemToPlayer(@NotNull Player player) { InventoryUtils.giveItem(player.getInventory(), player.getLocation(), InventoryUtils.getRandomItem(true, false)); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java index 37f1ccab3..055e3129d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageByPlayerTrigger.java @@ -6,8 +6,7 @@ import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class EntityDamageByPlayerTrigger extends ChallengeTrigger { @@ -21,7 +20,7 @@ public Material getMaterial() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDeath(@Nonnull EntityDamageByPlayerEvent event) { + public void onDeath(@NotNull EntityDamageByPlayerEvent event) { createData() .entity(event.getDamager()) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java index 80d8ff77c..0fc9a7789 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java @@ -13,8 +13,8 @@ import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.potion.PotionEffectType; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.*; public class EntityDamageTrigger extends ChallengeTrigger { @@ -50,7 +50,7 @@ public Material getMaterial() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDeath(@Nonnull EntityDamageEvent event) { + public void onDeath(@NotNull EntityDamageEvent event) { createData() .entity(event.getEntity()) .event(event) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java index 7cdb06121..4816b4fa5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDeathTrigger.java @@ -6,8 +6,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDeathEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class EntityDeathTrigger extends ChallengeTrigger { @@ -21,7 +20,7 @@ public Material getMaterial() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDeath(@Nonnull EntityDeathEvent event) { + public void onDeath(@NotNull EntityDeathEvent event) { createData() .entity(event.getEntity()) .entityType(event.getEntityType()) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java index 440a0bcb1..9c2af1abe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerJumpTrigger.java @@ -5,8 +5,7 @@ import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class PlayerJumpTrigger extends ChallengeTrigger { @@ -20,7 +19,7 @@ public Material getMaterial() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onJump(@Nonnull PlayerJumpEvent event) { + public void onJump(@NotNull PlayerJumpEvent event) { createData().entity(event.getPlayer()).execute(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java index 75b19ba32..3d436896d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/PlayerSneakTrigger.java @@ -5,8 +5,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerToggleSneakEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class PlayerSneakTrigger extends ChallengeTrigger { @@ -20,7 +19,7 @@ public Material getMaterial() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onJump(@Nonnull PlayerToggleSneakEvent event) { + public void onJump(@NotNull PlayerToggleSneakEvent event) { if (event.isSneaking()) { createData().entity(event.getPlayer()).execute(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java index fdaedc626..ef256edb9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java @@ -14,8 +14,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.concurrent.ThreadLocalRandom; @Since("2.0.2") @@ -27,13 +27,13 @@ public DamageTeleportChallenge() { super(MenuType.CHALLENGES, 1, 2); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.SHULKER_SHELL, Message.forName("item-damage-teleport-challenge")); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { if (getValue() == 1) { @@ -49,7 +49,7 @@ public void playValueChangeTitle() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { + public void onDamage(@NotNull EntityDamageEvent event) { if (!(event.getEntity() instanceof Player)) return; if (!shouldExecuteEffect()) return; if (ChallengeHelper.finalDamageIsNull(event)) return; @@ -57,7 +57,7 @@ public void onDamage(@Nonnull EntityDamageEvent event) { handleDamage(((Player) event.getEntity())); } - private void handleDamage(@Nonnull Player player) { + private void handleDamage(@NotNull Player player) { Location location = player.getWorld().getHighestBlockAt(getRandomLocation(player.getWorld())).getLocation(); location.setY(location.getY() + 1); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index 4aed4f536..96288f85f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -22,8 +22,7 @@ import org.bukkit.event.entity.EntityPotionEffectEvent.Action; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class ZeroHeartsChallenge extends SettingModifier { @@ -55,7 +54,7 @@ protected void onDisable() { AbstractChallenge.getFirstInstance(MaxHealthSetting.class).onValueChange(); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.ENCHANTED_GOLDEN_APPLE, Message.forName("item-zero-hearts-challenge")); @@ -99,7 +98,7 @@ private void removeAbsorptionEffect() { } @EventHandler(priority = EventPriority.HIGH) - public void onEntityPotionEffect(@Nonnull EntityPotionEffectEvent event) { + public void onEntityPotionEffect(@NotNull EntityPotionEffectEvent event) { if (event.getAction() != Action.REMOVED) return; if (!(event.getEntity() instanceof Player)) return; if (!shouldExecuteEffect()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java index 827616b35..0a9a3d78d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java @@ -10,9 +10,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerAdvancementDoneEvent; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class AdvancementDamageChallenge extends SettingModifier { @@ -26,7 +25,7 @@ public void playValueChangeTitle() { ChallengeHelper.playChallengeHeartsValueChangeTitle(this); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.BOOK, Message.forName("item-advancement-damage-challenge")); @@ -39,7 +38,7 @@ protected String[] getSettingsDescription() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerAdvancementDone(@Nonnull PlayerAdvancementDoneEvent event) { + public void onPlayerAdvancementDone(@NotNull PlayerAdvancementDoneEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java index aa70429fa..17e7bad7d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java @@ -9,9 +9,8 @@ import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.block.BlockBreakEvent; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class BlockBreakDamageChallenge extends SettingModifier { @@ -32,7 +31,7 @@ public void playValueChangeTitle() { ChallengeHelper.playChallengeHeartsValueChangeTitle(this); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-block-break-damage-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java index 1bfef2206..df833d52c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java @@ -10,9 +10,8 @@ import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.block.BlockPlaceEvent; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Since("2.0") public class BlockPlaceDamageChallenge extends SettingModifier { @@ -34,7 +33,7 @@ public void playValueChangeTitle() { ChallengeHelper.playChallengeHeartsValueChangeTitle(this); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.GOLD_BLOCK, Message.forName("item-block-place-damage-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java index ca487586a..aede1febc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java @@ -13,9 +13,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class DamagePerBlockChallenge extends SettingModifier { @@ -25,7 +24,7 @@ public DamagePerBlockChallenge() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { + public void onMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), event.getFrom())) return; @@ -39,7 +38,7 @@ public void playValueChangeTitle() { ChallengeHelper.playChallengeHeartsValueChangeTitle(this); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-damage-block-challenge")).setColor(Color.RED); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java index 196888b2a..4a5fbf391 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java @@ -12,8 +12,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.inventory.InventoryAction; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class DamagePerItemChallenge extends Setting { @@ -23,14 +22,14 @@ public DamagePerItemChallenge() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPickup(@Nonnull PlayerPickupItemEvent event) { + public void onPickup(@NotNull PlayerPickupItemEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; applyDamage(event.getPlayer(), event.getItem().getItemStack().getAmount()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onClick(@Nonnull PlayerInventoryClickEvent event) { + public void onClick(@NotNull PlayerInventoryClickEvent event) { if (event.isCancelled()) return; // ignoreCancelled not working on own event if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; @@ -39,12 +38,12 @@ public void onClick(@Nonnull PlayerInventoryClickEvent event) { applyDamage(event.getPlayer(), event.getCurrentItem().getAmount()); } - private void applyDamage(@Nonnull Player player, int amount) { + private void applyDamage(@NotNull Player player, int amount) { player.setNoDamageTicks(0); player.damage(amount); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.SHEARS, Message.forName("item-damage-item-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java index 963f0126c..7f0a0fea8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java @@ -12,8 +12,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class DeathOnFallChallenge extends Setting { @@ -23,14 +22,14 @@ public DeathOnFallChallenge() { setCategory(SettingCategory.DAMAGE); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.FEATHER, Message.forName("item-death-on-fall-challenge")); } @EventHandler(priority = EventPriority.HIGH) - public void onEntityDamage(@Nonnull EntityDamageEvent event) { + public void onEntityDamage(@NotNull EntityDamageEvent event) { if (!(event.getEntity() instanceof Player)) return; if (!shouldExecuteEffect()) return; Player player = (Player) event.getEntity(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java index a85704c62..4385ef78f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java @@ -14,9 +14,8 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; @@ -70,7 +69,7 @@ protected String[] getSettingsDescription() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerDamage(@Nonnull EntityDamageEvent event) { + public void onPlayerDamage(@NotNull EntityDamageEvent event) { if (!shouldExecuteEffect()) return; if (!(event.getEntity() instanceof Player)) return; if (ignorePlayer((Player) event.getEntity())) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java index 0d93ac66d..ecc6ece2b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java @@ -16,9 +16,8 @@ import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.potion.PotionEffect; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Since("2.0.2") public class FreezeChallenge extends SettingModifier { @@ -28,7 +27,7 @@ public FreezeChallenge() { setCategory(SettingCategory.DAMAGE); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.BLUE_ICE, Message.forName("item-freeze-challenge")); @@ -41,7 +40,7 @@ protected String[] getSettingsDescription() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { + public void onDamage(@NotNull EntityDamageEvent event) { if (!shouldExecuteEffect()) return; if (!(event.getEntity() instanceof Player)) return; Player player = (Player) event.getEntity(); @@ -53,7 +52,7 @@ public void onDamage(@Nonnull EntityDamageEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { + public void onMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (event.getTo() == null) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java index 375f55d66..d96a2c4d9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java @@ -15,9 +15,8 @@ import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Since("2.0") public class JumpDamageChallenge extends SettingModifier { @@ -27,7 +26,7 @@ public JumpDamageChallenge() { setCategory(SettingCategory.DAMAGE); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-jump-damage-challenge")).setColor(Color.ORANGE); @@ -45,7 +44,7 @@ public void playValueChangeTitle() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSneak(@Nonnull PlayerJumpEvent event) { + public void onSneak(@NotNull PlayerJumpEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; Message.forName("jump-damage-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java index babb068e9..8d0d6c171 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java @@ -9,8 +9,7 @@ import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class ReversedDamageChallenge extends Setting { @@ -19,14 +18,14 @@ public ReversedDamageChallenge() { setCategory(SettingCategory.DAMAGE); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.GOLDEN_SWORD, Message.forName("item-reversed-damage-challenge")); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDamageByPlayer(@Nonnull EntityDamageByPlayerEvent event) { + public void onDamageByPlayer(@NotNull EntityDamageByPlayerEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getDamager())) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java index 86f1b627d..e7f327172 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java @@ -14,9 +14,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerToggleSneakEvent; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class SneakDamageChallenge extends SettingModifier { @@ -25,7 +24,7 @@ public SneakDamageChallenge() { setCategory(SettingCategory.DAMAGE); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-sneak-damage-challenge")).setColor(Color.YELLOW); @@ -43,7 +42,7 @@ public void playValueChangeTitle() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSneak(@Nonnull PlayerToggleSneakEvent event) { + public void onSneak(@NotNull PlayerToggleSneakEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (!event.isSneaking()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java index ea80f79be..95674e6ef 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java @@ -11,9 +11,8 @@ import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Since("2.0") public class WaterAllergyChallenge extends SettingModifier { @@ -34,7 +33,7 @@ public void onFifthTick() { } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.CYAN_GLAZED_TERRACOTTA, Message.forName("item-water-allergy-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java index 67ec37da2..83cb7fefa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java @@ -15,8 +15,8 @@ import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.List; import java.util.stream.Collectors; @@ -27,7 +27,7 @@ public InfectionChallenge() { setCategory(SettingCategory.EFFECT); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.SLIME_BALL, Message.forName("item-infection-challenge")); @@ -47,7 +47,7 @@ public void onHalfSecond() { Bukkit.getOnlinePlayers().forEach(this::updateSickness); } - private void updateSickness(@Nonnull Player player) { + private void updateSickness(@NotNull Player player) { if (ignorePlayer(player)) { removeEffects(player); return; @@ -76,13 +76,13 @@ private void updateSickness(@Nonnull Player player) { } - private void removeEffects(@Nonnull Player player) { + private void removeEffects(@NotNull Player player) { player.removePotionEffect(MinecraftNameWrapper.NAUSEA); player.removePotionEffect(PotionEffectType.POISON); player.removePotionEffect(PotionEffectType.WITHER); } - private List getNearbyTargets(@Nonnull Player player, double range) { + private List getNearbyTargets(@NotNull Player player, double range) { return player.getNearbyEntities(range, range, range).stream() .filter(entity -> entity != player) .filter(entity -> entity instanceof LivingEntity) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java index ae02128f1..a1a36e792 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java @@ -29,9 +29,9 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.*; @Since("2.0") @@ -45,7 +45,7 @@ public PermanentEffectOnDamageChallenge() { setCategory(SettingCategory.EFFECT); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.MAGMA_CREAM, Message.forName("item-permanent-effect-on-damage-challenge")); @@ -78,7 +78,7 @@ public void onTimerPause() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onConsume(@Nonnull PlayerItemConsumeEvent event) { + public void onConsume(@NotNull PlayerItemConsumeEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (event.getItem().getType() != Material.MILK_BUCKET) return; @@ -86,21 +86,21 @@ public void onConsume(@Nonnull PlayerItemConsumeEvent event) { } @EventHandler(priority = EventPriority.HIGH) - public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { + public void onPlayerJoin(@NotNull PlayerJoinEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; updateEffects(); } @EventHandler(priority = EventPriority.HIGH) - public void onPlayerItemConsume(@Nonnull PlayerItemConsumeEvent event) { + public void onPlayerItemConsume(@NotNull PlayerItemConsumeEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; updateEffects(); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { + public void onPlayerGameModeChange(@NotNull PlayerGameModeChangeEvent event) { if (!shouldExecuteEffect()) return; Bukkit.getScheduler().runTask(plugin, () -> { clearEffects(); @@ -109,7 +109,7 @@ public void onPlayerGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerDamage(@Nonnull EntityDamageEvent event) { + public void onPlayerDamage(@NotNull EntityDamageEvent event) { if (!shouldExecuteEffect()) return; if (event.getFinalDamage() <= 0 && event.getDamage(DamageModifier.ABSORPTION) >= 0) return; if (!(event.getEntity() instanceof Player)) return; @@ -122,13 +122,13 @@ public void onPlayerDamage(@Nonnull EntityDamageEvent event) { updateEffects(); } - public void addRandomEffect(@Nonnull Player eventPlayer) { + public void addRandomEffect(@NotNull Player eventPlayer) { PotionEffectType randomEffect = getNewRandomEffect(); if (randomEffect == null) return; applyNewEffect(eventPlayer, randomEffect); } - private void applyNewEffect(@Nonnull Player player, @Nonnull PotionEffectType potionEffectType) { + private void applyNewEffect(@NotNull Player player, @NotNull PotionEffectType potionEffectType) { String path = player.getUniqueId().toString(); Document effects = getGameStateData().getDocument(path); @@ -171,7 +171,7 @@ public void updateEffects() { }); } - private void addEffect(@Nonnull Player player, @Nonnull PotionEffectType effectType, int amplifier) { + private void addEffect(@NotNull Player player, @NotNull PotionEffectType effectType, int amplifier) { if (player.hasPotionEffect(effectType)) { PotionEffect effect = player.getPotionEffect(effectType); @@ -192,7 +192,7 @@ private void clearEffects() { }); } - private void forEachEffect(@Nonnull TriConsumer action) { + private void forEachEffect(@NotNull TriConsumer action) { List> effects = new ArrayList<>(); for (String uuid : getGameStateData().keys()) { @@ -224,7 +224,7 @@ private void forEachEffect(@Nonnull TriConsumer> effectsList, @Nonnull PotionEffectType effectType, int amplifier) { + private void addEffectToList(@NotNull List> effectsList, @NotNull PotionEffectType effectType, int amplifier) { Tuple effectTuple = effectsList.stream().filter(tuple -> tuple.getFirst() == effectType).findFirst() .orElse(new Tuple<>(effectType, 0)); effectTuple.setSecond(effectTuple.getSecond() + amplifier); @@ -243,7 +243,7 @@ protected void onValueChange() { updateEffects(); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { if (!isEnabled()) return DefaultItem.disabled(); @@ -262,7 +262,7 @@ public void playValueChangeTitle() { } @Override - public void loadGameState(@Nonnull Document document) { + public void loadGameState(@NotNull Document document) { super.loadGameState(document); broadcast(player -> { for (PotionEffect potionEffect : player.getActivePotionEffects()) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index ce4f1bae5..125dbfac2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -15,9 +15,9 @@ import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -64,7 +64,7 @@ public RandomPotionEffectChallenge() { } @Nullable - public static PotionEffectType getNewRandomEffect(@Nonnull LivingEntity entity) { + public static PotionEffectType getNewRandomEffect(@NotNull LivingEntity entity) { List activeEffects = entity.getActivePotionEffects().stream().map(PotionEffect::getType).collect(Collectors.toList()); ArrayList possibleEffects = new ArrayList<>(Arrays.asList(PotionEffectType.values())); @@ -74,7 +74,7 @@ public static PotionEffectType getNewRandomEffect(@Nonnull LivingEntity entity) return possibleEffects.get(IRandom.threadLocal().nextInt(possibleEffects.size())); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.BREWING_STAND, Message.forName("item-random-effect-challenge")); @@ -95,13 +95,13 @@ private void applyRandomEffect() { Bukkit.getOnlinePlayers().forEach(this::applyRandomEffect); } - private void applyRandomEffect(@Nonnull Player entity) { + private void applyRandomEffect(@NotNull Player entity) { PotionEffectType effect = getNewRandomEffect(entity); if (effect == null) return; applyEffect(entity, effect); } - private void applyEffect(@Nonnull Player player, @Nonnull PotionEffectType effectType) { + private void applyEffect(@NotNull Player player, @NotNull PotionEffectType effectType) { PotionEffect potionEffect = new PotionEffect(effectType, (getSetting("length").getAsInt() + 1) * 20, getSetting("amplifier").getAsInt() - 1); player.addPotionEffect(potionEffect); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java index 5a7361d9e..0c3bc4351 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java @@ -11,8 +11,8 @@ import org.bukkit.Material; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Collection; @Since("2.0") @@ -24,7 +24,7 @@ public AllMobsToDeathPoint() { } @EventHandler - public void onEntityDeath(@Nonnull EntityDeathByPlayerEvent event) { + public void onEntityDeath(@NotNull EntityDeathByPlayerEvent event) { if (!shouldExecuteEffect()) return; if (event.getEntity() instanceof EnderDragon || event.getEntity() instanceof Player) return; if (!(event.getEntity() instanceof LivingEntity)) return; @@ -33,7 +33,7 @@ public void onEntityDeath(@Nonnull EntityDeathByPlayerEvent event) { teleportAllMobsOfType(event.getEntityType(), event.getEntity().getLocation()); } - private void teleportAllMobsOfType(@Nonnull EntityType entityType, @Nonnull Location location) { + private void teleportAllMobsOfType(@NotNull EntityType entityType, @NotNull Location location) { if (location.getWorld() == null) return; Collection entities = location.getWorld().getEntitiesByClasses(entityType.getEntityClass()); for (Entity entity : entities) { @@ -44,7 +44,7 @@ private void teleportAllMobsOfType(@Nonnull EntityType entityType, @Nonnull Loca } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.SPAWNER, Message.forName("item-all-mobs-to-death-position-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java index 7cd6d145e..338e46a69 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java @@ -10,8 +10,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntitySpawnEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class DupedSpawningChallenge extends Setting { @@ -22,14 +21,14 @@ public DupedSpawningChallenge() { setCategory(SettingCategory.ENTITIES); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.ELDER_GUARDIAN_SPAWN_EGG, Message.forName("item-duped-spawning-challenge")); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSpawn(@Nonnull EntitySpawnEvent event) { + public void onSpawn(@NotNull EntitySpawnEvent event) { if (!shouldExecuteEffect()) return; if (!(event.getEntity() instanceof LivingEntity) || event.getEntity() instanceof Player diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java index 37d82eb9f..8baa720ad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java @@ -7,8 +7,7 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.entity.EntityType; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class HydraNormalChallenge extends HydraChallenge { @@ -17,14 +16,14 @@ public HydraNormalChallenge() { setCategory(SettingCategory.ENTITIES); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.WITCH_SPAWN_EGG, Message.forName("item-hydra-challenge")); } @Override - public int getNewMobsCount(@Nonnull EntityType entityType) { + public int getNewMobsCount(@NotNull EntityType entityType) { return 2; } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java index 399cd242e..421cc89f2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java @@ -8,8 +8,7 @@ import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.EntityType; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class HydraPlusChallenge extends HydraChallenge { @@ -21,14 +20,14 @@ public HydraPlusChallenge() { setCategory(SettingCategory.ENTITIES); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.BAT_SPAWN_EGG, Message.forName("item-hydra-plus-challenge")); } @Override - public int getNewMobsCount(@Nonnull EntityType entityType) { + public int getNewMobsCount(@NotNull EntityType entityType) { int currentCount = getGameStateData().getInt(entityType.name()); if (currentCount == 0) { currentCount = 2; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java index 75131b7bf..63d76e871 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java @@ -20,8 +20,7 @@ import org.bukkit.event.entity.EntitySpawnEvent; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class InvisibleMobsChallenge extends Setting { @@ -36,14 +35,14 @@ protected void onEnable() { addEffectForEveryEntity(); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new PotionBuilder(Material.POTION, Message.forName("item-invisible-mobs-challenge")).setColor(Color.WHITE); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSpawn(@Nonnull EntitySpawnEvent event) { + public void onSpawn(@NotNull EntitySpawnEvent event) { if (!shouldExecuteEffect()) return; if (!(event.getEntity() instanceof LivingEntity)) return; addEffect(((LivingEntity) event.getEntity())); @@ -64,7 +63,7 @@ private void addEffectForEveryEntity() { } } - private void addEffect(@Nonnull LivingEntity entity) { + private void addEffect(@NotNull LivingEntity entity) { entity.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 40, 1, true, false, false)); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java index beb3f0121..964b968ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java @@ -15,9 +15,8 @@ import org.bukkit.entity.Player; import org.bukkit.util.BoundingBox; import org.bukkit.util.RayTraceResult; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Since("2.0") public class MobSightDamageChallenge extends SettingModifier { @@ -27,7 +26,7 @@ public MobSightDamageChallenge() { setCategory(SettingCategory.ENTITIES); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.SPIDER_EYE, Message.forName("item-no-mob-sight-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java index 85207883c..e320aa2f4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java @@ -15,9 +15,8 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Since("2.0") public class MobTransformationChallenge extends Setting { @@ -43,14 +42,14 @@ protected void onDisable() { bossbar.hide(); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-mob-transformation-challenge")); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityDamageByPlayer(@Nonnull EntityDamageByPlayerEvent event) { + public void onEntityDamageByPlayer(@NotNull EntityDamageByPlayerEvent event) { if (!shouldExecuteEffect()) return; if (event.getEntity() instanceof Player || !(event.getEntity() instanceof LivingEntity) || event.getEntity() instanceof EnderDragon) return; @@ -68,7 +67,7 @@ public void onEntityDamageByPlayer(@Nonnull EntityDamageByPlayerEvent event) { bossbar.update(player); } - private EntityType getType(@Nonnull Player player, @Nullable EntityType defaultType) { + private EntityType getType(@NotNull Player player, @Nullable EntityType defaultType) { EntityType type = getPlayerData(player).getEnum("type", EntityType.class); if (type == null) return defaultType; return type; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java index 8f855b4fb..d8053d8ab 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java @@ -15,8 +15,7 @@ import org.bukkit.entity.EntityType; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class NewEntityOnJumpChallenge extends Setting { @@ -26,20 +25,20 @@ public NewEntityOnJumpChallenge() { setCategory(SettingCategory.ENTITIES); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-jump-entity-challenge")).setColor(Color.GREEN); } @EventHandler(priority = EventPriority.HIGH) - public void onJump(@Nonnull PlayerJumpEvent event) { + public void onJump(@NotNull PlayerJumpEvent event) { if (ignorePlayer(event.getPlayer())) return; if (!shouldExecuteEffect()) return; spawnRandomEntity(event.getPlayer().getLocation()); } - private void spawnRandomEntity(@Nonnull Location location) { + private void spawnRandomEntity(@NotNull Location location) { if (location.getWorld() == null) return; EntityType type = globalRandom.choose(RandomMobAction.getSpawnableMobs()); location.getWorld().spawnEntity(location, type); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java index 85df80778..5e3ca563e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java @@ -16,8 +16,8 @@ import org.bukkit.entity.Player; import org.bukkit.util.BoundingBox; import org.bukkit.util.RayTraceResult; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Random; @Since("2.0") @@ -30,7 +30,7 @@ public StoneSightChallenge() { setCategory(SettingCategory.ENTITIES); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.COBBLESTONE, Message.forName("item-stone-sight-challenge")); @@ -69,7 +69,7 @@ public void onTick() { } - @Nonnull + @NotNull private Material getRandomStone() { Material[] materials = { Material.STONE, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java index 805956ebc..13a71d792 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java @@ -30,9 +30,9 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -56,7 +56,7 @@ public JumpAndRunChallenge() { setCategory(SettingCategory.EXTRA_WORLD); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.ACACIA_STAIRS, Message.forName("item-jump-and-run-challenge")); @@ -96,7 +96,7 @@ protected void handleCountdown() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onQuit(@Nonnull PlayerQuitEvent event) { + public void onQuit(@NotNull PlayerQuitEvent event) { if (currentPlayer == null) return; if (!currentPlayer.equals(event.getPlayer().getUniqueId())) return; exitJumpAndRun(); @@ -137,7 +137,7 @@ protected void buildNextJump() { } - @Nonnull + @NotNull protected Material getRandomBlockType() { if (currentJump == jumps - 1) return Material.EMERALD_BLOCK; @@ -153,7 +153,7 @@ protected Material getRandomBlockType() { return globalRandom.choose(materials); } - @Nonnull + @NotNull protected Player getNextPlayer() { List players = new ArrayList<>(Bukkit.getOnlinePlayers()); players.removeIf(AbstractChallenge::ignorePlayer); @@ -191,14 +191,14 @@ protected void breakJumpAndRun() { } @Override - public void writeGameState(@Nonnull Document document) { + public void writeGameState(@NotNull Document document) { super.writeGameState(document); document.set("jumps", jumps); document.set("jumpsDone", jumpsDone); } @Override - public void loadGameState(@Nonnull Document document) { + public void loadGameState(@NotNull Document document) { super.loadGameState(document); jumps = document.getInt("jumps", jumps); jumpsDone = document.getInt("jumpsDone", jumpsDone); @@ -212,7 +212,7 @@ public void spawnParticles() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { + public void onMove(@NotNull PlayerMoveEvent event) { if (!event.getPlayer().getUniqueId().equals(currentPlayer)) return; if (!isInExtraWorld()) return; if (targetBlock == null) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java index c5b34d165..2c871a1f1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java @@ -17,9 +17,8 @@ import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.inventory.ItemStack; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class WaterMLGChallenge extends WorldDependentChallenge { @@ -28,7 +27,7 @@ public WaterMLGChallenge() { setCategory(SettingCategory.EXTRA_WORLD); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.WATER_BUCKET, Message.forName("item-water-mlg-challenge")); @@ -68,7 +67,7 @@ public void startWorldChallenge() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerBucketEmpty(@Nonnull PlayerBucketEmptyEvent event) { + public void onPlayerBucketEmpty(@NotNull PlayerBucketEmptyEvent event) { if (!isInExtraWorld()) return; Bukkit.getScheduler().runTaskLater(plugin, () -> { @@ -81,7 +80,7 @@ public void onPlayerBucketEmpty(@Nonnull PlayerBucketEmptyEvent event) { } @EventHandler(priority = EventPriority.HIGH) - public void onEntityDamage(@Nonnull EntityDamageEvent event) { + public void onEntityDamage(@NotNull EntityDamageEvent event) { if (!(event.getEntity() instanceof Player)) return; if (!isInExtraWorld()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java index 0c71dd962..8aa7e8162 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java @@ -24,9 +24,8 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Arrays; import java.util.Objects; import java.util.function.BiConsumer; @@ -42,7 +41,7 @@ public ForceBiomeChallenge() { setCategory(SettingCategory.FORCE); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.CHAINMAIL_BOOTS, Message.forName("item-force-biome-challenge")); @@ -59,7 +58,7 @@ public void playValueChangeTitle() { ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 * 3 - 60, getValue() * 60 * 3 + 60); } - @Nonnull + @NotNull @Override protected BiConsumer setupBossbar() { return (bossbar, player) -> { @@ -80,7 +79,7 @@ protected void broadcastFailedMessage() { } @Override - protected void broadcastSuccessMessage(@Nonnull Player player) { + protected void broadcastSuccessMessage(@NotNull Player player) { Message.forName("force-biome-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), BukkitStringUtils.getBiomeName(biome)); } @@ -101,7 +100,7 @@ protected int getForcingTime() { return globalRandom.around(getRarity(biome) * 60 * 6, 60); } - private int getRarity(@Nonnull Biome biome) { + private int getRarity(@NotNull Biome biome) { Object[][] mapping = { {"BADLANDS", 5}, {"JUNGLE", 4}, @@ -125,7 +124,7 @@ protected int getSecondsUntilNextActivation() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { + public void onMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (event.getTo() == null) return; if (event.getTo().getBlock().getBiome() != biome) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java index a77dfaac2..0e3e78ab4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java @@ -19,9 +19,8 @@ import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Arrays; import java.util.function.BiConsumer; @@ -35,7 +34,7 @@ public ForceBlockChallenge() { setCategory(SettingCategory.FORCE); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.GOLDEN_BOOTS, Message.forName("item-force-block-challenge")); @@ -52,7 +51,7 @@ public void playValueChangeTitle() { ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); } - @Nonnull + @NotNull @Override protected BiConsumer setupBossbar() { return (bossbar, player) -> { @@ -68,7 +67,7 @@ protected BiConsumer setupBossbar() { } @Override - protected boolean isFailing(@Nonnull Player player) { + protected boolean isFailing(@NotNull Player player) { for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { for (int y = -1; y <= 1; y++) { @@ -81,7 +80,7 @@ protected boolean isFailing(@Nonnull Player player) { } @Override - protected void broadcastFailedMessage(@Nonnull Player player) { + protected void broadcastFailedMessage(@NotNull Player player) { Message.forName("force-block-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), player.getLocation().subtract(0, 1, 0).getBlock().getType()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java index 94b15fe80..e8502f0ec 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java @@ -19,9 +19,8 @@ import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.function.BiConsumer; @ExcludeFromRandomChallenges @@ -34,7 +33,7 @@ public ForceHeightChallenge() { setCategory(SettingCategory.FORCE); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.IRON_BOOTS, Message.forName("item-force-height-challenge")); @@ -51,7 +50,7 @@ public void playValueChangeTitle() { ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); } - @Nonnull + @NotNull @Override protected BiConsumer setupBossbar() { return (bossbar, player) -> { @@ -67,12 +66,12 @@ protected BiConsumer setupBossbar() { } @Override - protected boolean isFailing(@Nonnull Player player) { + protected boolean isFailing(@NotNull Player player) { return player.getLocation().getBlockY() != height; } @Override - protected void broadcastFailedMessage(@Nonnull Player player) { + protected void broadcastFailedMessage(@NotNull Player player) { Message.forName("force-height-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), player.getLocation().getBlockY()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java index 60bcf0cd2..b7ad48b72 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java @@ -27,9 +27,8 @@ import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -46,7 +45,7 @@ public ForceItemChallenge() { setCategory(SettingCategory.FORCE); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.LEATHER_BOOTS, Message.forName("item-force-item-challenge")); @@ -63,7 +62,7 @@ public void playValueChangeTitle() { ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); } - @Nonnull + @NotNull @Override protected BiConsumer setupBossbar() { return (bossbar, player) -> { @@ -84,7 +83,7 @@ protected void broadcastFailedMessage() { } @Override - protected void broadcastSuccessMessage(@Nonnull Player player) { + protected void broadcastSuccessMessage(@NotNull Player player) { Message.forName("force-item-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), item); } @@ -109,7 +108,7 @@ protected int getSecondsUntilNextActivation() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onClick(@Nonnull PlayerInventoryClickEvent event) { + public void onClick(@NotNull PlayerInventoryClickEvent event) { ItemStack item = event.getCurrentItem(); if (item == null) return; if (item.getType() != this.item) return; @@ -117,14 +116,14 @@ public void onClick(@Nonnull PlayerInventoryClickEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPickUp(@Nonnull PlayerPickupItemEvent event) { + public void onPickUp(@NotNull PlayerPickupItemEvent event) { Material material = event.getItem().getItemStack().getType(); if (material != item) return; completeForcing(event.getPlayer()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInteract(@Nonnull PlayerInteractEvent event) { + public void onInteract(@NotNull PlayerInteractEvent event) { Bukkit.getScheduler().runTaskLater(plugin, () -> { ItemStack item = event.getPlayer().getInventory().getItemInMainHand(); Material material = item.getType(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java index 6648251b3..3f135f0ca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java @@ -22,9 +22,8 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDeathEvent; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -40,7 +39,7 @@ public ForceMobChallenge() { setCategory(SettingCategory.FORCE); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-mob-challenge")); @@ -57,7 +56,7 @@ public void playValueChangeTitle() { ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); } - @Nonnull + @NotNull @Override protected BiConsumer setupBossbar() { return (bossbar, player) -> { @@ -78,7 +77,7 @@ protected void broadcastFailedMessage() { } @Override - protected void broadcastSuccessMessage(@Nonnull Player player) { + protected void broadcastSuccessMessage(@NotNull Player player) { Message.forName("force-mob-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), entity); } @@ -103,7 +102,7 @@ protected int getSecondsUntilNextActivation() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onKill(@Nonnull EntityDeathEvent event) { + public void onKill(@NotNull EntityDeathEvent event) { LivingEntity entity = event.getEntity(); if (entity.getType() != this.entity) return; Player killer = entity.getKiller(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java index ed7861ba1..6185ff956 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java @@ -12,8 +12,7 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.entity.EntityDamageEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class DamageInventoryClearChallenge extends SettingModifier { @@ -23,7 +22,7 @@ public DamageInventoryClearChallenge() { } @EventHandler - public void onDamage(@Nonnull EntityDamageEvent event) { + public void onDamage(@NotNull EntityDamageEvent event) { if (!(event.getEntity() instanceof Player)) return; if (!shouldExecuteEffect()) return; if (ChallengeHelper.finalDamageIsNull(event)) return; @@ -36,13 +35,13 @@ public void onDamage(@Nonnull EntityDamageEvent event) { } } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.CHEST, Message.forName("item-damage-inv-clear-challenge")); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { if (getValue() == 1) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java index 858bdb9a0..cd39a3f98 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java @@ -32,9 +32,9 @@ import org.bukkit.inventory.meta.Damageable; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.*; import java.util.function.Consumer; import java.util.stream.Collectors; @@ -66,7 +66,7 @@ protected int getSecondsUntilNextActivation() { return globalRandom.around(getValue() * 60, 10); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.FISHING_ROD, Message.forName("item-missing-items-challenge")); @@ -95,7 +95,7 @@ protected void onTimeActivation() { } - private void startGuessingGame(@Nonnull Player player) { + private void startGuessingGame(@NotNull Player player) { BukkitTask task = new BukkitRunnable() { @@ -132,7 +132,7 @@ public void run() { } - private void createMissingItemsInventory(@Nonnull Player player, Consumer onFinish) { + private void createMissingItemsInventory(@NotNull Player player, Consumer onFinish) { int targetSlot = InventoryUtils.getRandomFullSlot(player.getInventory()); if (targetSlot == -1) return; @@ -163,7 +163,7 @@ private void createMissingItemsInventory(@Nonnull Player player, Consumer } - private void sendInfoText(@Nonnull Player player) { + private void sendInfoText(@NotNull Player player) { String message = Message.forName("missing-items-inventory").asString("§7"); String openMessage = Message.forName("missing-items-inventory-open").asString(); @@ -177,7 +177,7 @@ private void sendInfoText(@Nonnull Player player) { player.spigot().sendMessage(messageComponent); } - private boolean openGameInventory(@Nonnull Player player) { + private boolean openGameInventory(@NotNull Player player) { Tuple inventoryTuple = inventories.get(player.getUniqueId()); if (inventoryTuple == null) return false; player.openInventory(inventoryTuple.getFirst()); @@ -185,7 +185,7 @@ private boolean openGameInventory(@Nonnull Player player) { return true; } - private Tuple generateMissingItemsInventory(@Nonnull ItemStack itemStack) { + private Tuple generateMissingItemsInventory(@NotNull ItemStack itemStack) { Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(Message.forName("missing-items-inventory").asString(Message.forName("inventory-color").asString()))); int targetSlot = globalRandom.nextInt(inventory.getSize()); @@ -205,7 +205,7 @@ private Tuple generateMissingItemsInventory(@Nonnull ItemSta return new Tuple<>(inventory, targetSlot); } - private ItemStack getRandomItem(@Nonnull ItemStack blacklisted) { + private ItemStack getRandomItem(@NotNull ItemStack blacklisted) { if (materials == null) onEnable(); Material material = globalRandom.choose(materials); @@ -225,7 +225,7 @@ private ItemStack getRandomItem(@Nonnull ItemStack blacklisted) { } @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (openGameInventory(player)) { SoundSample.OPEN.play(player); } else { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java index b62474076..3dac9faf3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java @@ -14,8 +14,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class MovementItemRemovingChallenge extends SettingModifier { @@ -27,13 +26,13 @@ public MovementItemRemovingChallenge() { setCategory(SettingCategory.INVENTORY); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.DETECTOR_RAIL, Message.forName("item-block-chunk-item-remove-challenge")); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { if (!isEnabled()) return DefaultItem.disabled(); @@ -51,7 +50,7 @@ public void playValueChangeTitle() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + public void onPlayerMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (event.getTo() == null) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java index b7161917e..48abf2483 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java @@ -20,8 +20,8 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -37,21 +37,21 @@ public NoDupedItemsChallenge() { setCategory(SettingCategory.INVENTORY); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.OBSERVER, Message.forName("item-no-duped-items-challenge")); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + public void onInventoryClick(@NotNull PlayerInventoryClickEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; checkInventories(); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onEntityPickUpItem(@Nonnull PlayerPickupItemEvent event) { + public void onEntityPickUpItem(@NotNull PlayerPickupItemEvent event) { Bukkit.getScheduler().runTaskLater(plugin, () -> { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; @@ -60,7 +60,7 @@ public void onEntityPickUpItem(@Nonnull PlayerPickupItemEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInteract(@Nonnull PlayerInteractEvent event) { + public void onInteract(@NotNull PlayerInteractEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (event.getClickedBlock() == null) return; @@ -87,7 +87,7 @@ private void checkInventories() { } - private Triple checkInventory(@Nonnull Player player, Map> blacklist) { + private Triple checkInventory(@NotNull Player player, Map> blacklist) { List localBlacklist = new ArrayList<>(); List playerBlacklist = blacklist.getOrDefault(player, new ArrayList<>()); blacklist.put(player, playerBlacklist); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java index 1c4a905f5..a4c14a102 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java @@ -15,8 +15,7 @@ import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.inventory.Inventory; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class PermanentItemChallenge extends Setting { @@ -26,14 +25,14 @@ public PermanentItemChallenge() { setCategory(SettingCategory.INVENTORY); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.VINE, Message.forName("item-permanent-item-challenge")); } @EventHandler(priority = EventPriority.HIGH) - public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + public void onInventoryClick(@NotNull PlayerInventoryClickEvent event) { Player player = event.getPlayer(); if (!shouldExecuteEffect()) return; if (ignorePlayer(player)) return; @@ -52,7 +51,7 @@ public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { } @EventHandler - public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { + public void onPlayerDropItem(@NotNull PlayerDropItemEvent event) { if (!shouldExecuteEffect()) return; event.setCancelled(true); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java index e67b49fac..3b66b41aa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java @@ -14,9 +14,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.Nullable; @Since("2.0") public class PickupItemLaunchChallenge extends SettingModifier { @@ -44,7 +42,7 @@ public void playValueChangeTitle() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerPickUpItem(@Nonnull PlayerPickupItemEvent event) { + public void onPlayerPickUpItem(@NotNull PlayerPickupItemEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java index ec0702a0e..ff7c92151 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java @@ -12,9 +12,9 @@ import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.*; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -27,7 +27,7 @@ public UncraftItemsChallenge() { setCategory(SettingCategory.INVENTORY); } - public static void uncraftInventory(@Nonnull Player player) { + public static void uncraftInventory(@NotNull Player player) { PlayerInventory inventory = player.getInventory(); @@ -93,7 +93,7 @@ private static boolean canCraft(List recipes, Material material) { return false; } - private static List getIngredientsOfRecipe(@Nonnull Recipe recipe) { + private static List getIngredientsOfRecipe(@NotNull Recipe recipe) { List ingredients = new ArrayList<>(); if (recipe instanceof ShapedRecipe) { ShapedRecipe shaped = (ShapedRecipe) recipe; @@ -113,7 +113,7 @@ private static List getIngredientsOfRecipe(@Nonnull Recipe recipe) { return ingredients; } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.CRAFTING_TABLE, Message.forName("item-uncraft-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index b1b4413f6..d60bb4e7e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -14,9 +14,9 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.List; import java.util.stream.Collectors; @@ -27,7 +27,7 @@ public EnderGamesChallenge() { super(MenuType.CHALLENGES, 1, 10, 5, false); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.ENDER_PEARL, Message.forName("item-ender-games-challenge")); @@ -59,7 +59,7 @@ protected void onTimeActivation() { SoundSample.TELEPORT.broadcast(); } - private void teleportRandom(@Nonnull Player player) { + private void teleportRandom(@NotNull Player player) { List list = player.getWorld().getNearbyEntities(player.getLocation(), 200, 200, 200).stream() .filter(entity -> !(entity instanceof Player)) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java index 759248d1b..9e582f278 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java @@ -13,9 +13,7 @@ import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.Nullable; @Since("2.0.2") public class FoodLaunchChallenge extends SettingModifier { @@ -42,7 +40,7 @@ public void playValueChangeTitle() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerItemConsume(@Nonnull PlayerItemConsumeEvent event) { + public void onPlayerItemConsume(@NotNull PlayerItemConsumeEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java index cf3a29206..be08e1776 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java @@ -13,8 +13,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerItemConsumeEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.List; public class FoodOnceChallenge extends SettingModifier { @@ -23,13 +23,13 @@ public FoodOnceChallenge() { super(MenuType.CHALLENGES, 2); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.COOKED_BEEF, Message.forName("item-food-once-challenge")); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { switch (getValue()) { @@ -48,7 +48,7 @@ public void playValueChangeTitle() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerItemConsume(@Nonnull PlayerItemConsumeEvent event) { + public void onPlayerItemConsume(@NotNull PlayerItemConsumeEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; @@ -76,13 +76,13 @@ private void addFood(Player player, Material type) { } } - private void addPlayerFood(@Nonnull Player player, @Nonnull Material material) { + private void addPlayerFood(@NotNull Player player, @NotNull Material material) { List foods = getPlayerData(player).getEnumList("foods", Material.class); foods.add(material); getPlayerData(player).set("foods", foods); } - private boolean hasEaten(@Nonnull Player player, @Nonnull Material material) { + private boolean hasEaten(@NotNull Player player, @NotNull Material material) { if (teamFoodsActivated()) { return hasBeenEatenByTeam(material); } @@ -90,13 +90,13 @@ private boolean hasEaten(@Nonnull Player player, @Nonnull Material material) { return getPlayerData(player).getEnumList("foods", Material.class).contains(material); } - private void addTeamFood(@Nonnull Material material) { + private void addTeamFood(@NotNull Material material) { List foods = getGameStateData().getEnumList("foods", Material.class); foods.add(material); getGameStateData().set("foods", foods); } - private boolean hasBeenEatenByTeam(@Nonnull Material material) { + private boolean hasBeenEatenByTeam(@NotNull Material material) { return getGameStateData().getEnumList("foods", Material.class).contains(material); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java index 203e34b53..f70a00886 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java @@ -12,9 +12,8 @@ import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Since("2.0") @ExcludeFromRandomChallenges @@ -33,7 +32,7 @@ public static void invertHealth(Player player) { player.setHealth(health); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.POPPY, Message.forName("item-invert-health-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java index 3d162e60c..b2d410412 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java @@ -10,9 +10,9 @@ import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Arrays; import java.util.Random; @@ -25,7 +25,7 @@ public LowDropRateChallenge() { super(MenuType.CHALLENGES, 9); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.WOODEN_AXE, Message.forName("item-low-drop-rate-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java index 60597c942..1615bd175 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java @@ -11,8 +11,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerExpChangeEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class NoExpChallenge extends Setting { @@ -29,7 +28,7 @@ public void onExp(PlayerExpChangeEvent event) { ChallengeHelper.kill(event.getPlayer()); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-no-exp-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java index aaf281b19..10a213dd4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java @@ -11,8 +11,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityPickupItemEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class NoTradingChallenge extends Setting { @@ -20,14 +19,14 @@ public NoTradingChallenge() { super(MenuType.CHALLENGES); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.EMERALD, Message.forName("item-no-trading-challenge")); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onInteract(@Nonnull PlayerInteractEntityEvent event) { + public void onInteract(@NotNull PlayerInteractEntityEvent event) { if (!shouldExecuteEffect()) return; if (event.getRightClicked() instanceof Villager) { event.getPlayer().playSound(event.getPlayer().getLocation(), Sound.ENTITY_VILLAGER_NO, 1F, 1F); @@ -39,7 +38,7 @@ public void onInteract(@Nonnull PlayerInteractEntityEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityPickupItem(@Nonnull EntityPickupItemEvent event) { + public void onEntityPickupItem(@NotNull EntityPickupItemEvent event) { if (!shouldExecuteEffect()) return; if (event.getEntityType().name().equals("PIGLIN")) { event.setCancelled(true); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java index e2783a952..70d7d50ca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java @@ -14,8 +14,7 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.ItemMeta; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class OneDurabilityChallenge extends Setting { @@ -23,14 +22,14 @@ public OneDurabilityChallenge() { super(MenuType.CHALLENGES); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.WOODEN_HOE, Message.forName("item-one-durability-challenge")); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onInventoryClick(@Nonnull InventoryClickEvent event) { + public void onInventoryClick(@NotNull InventoryClickEvent event) { if (!shouldExecuteEffect()) return; if (event.getWhoClicked() instanceof Player && ignorePlayer((Player) event.getWhoClicked())) return; @@ -55,7 +54,7 @@ public void onInteract(EntityPickupItemEvent event) { setDurability(event.getItem().getItemStack()); } - private void setDurability(@Nonnull ItemStack item) { + private void setDurability(@NotNull ItemStack item) { ItemMeta meta = item.getItemMeta(); if (meta instanceof Damageable) { meta.setUnbreakable(false); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java index 2c30ec4cc..9a3429152 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java @@ -11,8 +11,7 @@ import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.util.Vector; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class AlwaysRunningChallenge extends Setting { @@ -22,7 +21,7 @@ public AlwaysRunningChallenge() { setCategory(SettingCategory.MOVEMENT); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.CARROT_ON_A_STICK, Message.forName("item-always-running-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java index 4be9cb7ab..7c6dacd6c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java @@ -15,8 +15,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @@ -55,7 +55,7 @@ protected void onDisable() { bossbar.hide(); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.SADDLE, Message.forName("item-dont-stop-running-challenge")); @@ -91,7 +91,7 @@ private void countUpOrKillEveryone() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + public void onPlayerMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (event.getTo() == null) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java index 4fc5a6a4a..3b4fdc3fe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java @@ -28,7 +28,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; @@ -144,7 +143,7 @@ public void onBlockExplosion(BlockExplodeEvent event) { /** * @return if 500 blocks were reached */ - private boolean updateOrReset(@Nonnull Player player) { + private boolean updateOrReset(@NotNull Player player) { UUID uuid = player.getUniqueId(); int blocksWalked = this.blocksWalked.getOrDefault(uuid, 0); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java index 0047eacc9..637b633da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java @@ -10,8 +10,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.util.Vector; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class HigherJumpsChallenge extends Setting { @@ -20,14 +19,14 @@ public HigherJumpsChallenge() { setCategory(SettingCategory.MOVEMENT); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.RABBIT_FOOT, Message.forName("item-higher-jumps-challenge")); } @EventHandler(priority = EventPriority.NORMAL) - public void onJump(@Nonnull PlayerJumpEvent event) { + public void onJump(@NotNull PlayerJumpEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java index 40713305b..93d9cc583 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java @@ -11,8 +11,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class HungerPerBlockChallenge extends SettingModifier { @@ -22,14 +21,14 @@ public HungerPerBlockChallenge() { setCategory(SettingCategory.MOVEMENT); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.ROTTEN_FLESH, Message.forName("item-hunger-block-challenge")); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + public void onPlayerMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getFrom(), event.getTo())) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java index 1abfdcb3b..55cc26801 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java @@ -14,9 +14,9 @@ import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.AbstractMap.SimpleEntry; import java.util.HashMap; import java.util.Map; @@ -33,7 +33,7 @@ public MoveMouseDamage() { setCategory(SettingCategory.MOVEMENT); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.COMPASS, Message.forName("item-no-mouse-move-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java index b332c98e2..e720c1f77 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java @@ -17,8 +17,7 @@ import org.bukkit.event.block.BlockSpreadEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @CanInstaKillOnEnable public class OnlyDirtChallenge extends Setting { @@ -28,20 +27,20 @@ public OnlyDirtChallenge() { setCategory(SettingCategory.MOVEMENT); } - @Nonnull + @NotNull @Override public ItemStack getSettingsItem() { return super.getSettingsItem(); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.DIRT, Message.forName("item-only-dirt-challenge")); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + public void onPlayerMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (event.getTo() == null) return; @@ -56,7 +55,7 @@ public void onPlayerMove(@Nonnull PlayerMoveEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockSpread(@Nonnull BlockSpreadEvent event) { + public void onBlockSpread(@NotNull BlockSpreadEvent event) { if (!shouldExecuteEffect()) return; if (event.getNewState().getType() == Material.GRASS_BLOCK) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java index 39c551b80..325c059d2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java @@ -12,8 +12,7 @@ import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class OnlyDownChallenge extends Setting { @@ -23,14 +22,14 @@ public OnlyDownChallenge() { setCategory(SettingCategory.MOVEMENT); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.ACACIA_SLAB, Message.forName("item-only-down-challenge")); } @EventHandler - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + public void onPlayerMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (event.getTo() == null) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java index c783eeed8..7e17c62b0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java @@ -17,9 +17,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Since("1.3") public class TrafficLightChallenge extends TimedChallenge { @@ -33,7 +32,7 @@ public TrafficLightChallenge() { setCategory(SettingCategory.MOVEMENT); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.LIME_STAINED_GLASS, Message.forName("item-traffic-light-challenge")); @@ -106,7 +105,7 @@ protected void onTimeActivation() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + public void onPlayerMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (state != RED) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index 3427176da..b4387bd8c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -37,9 +37,9 @@ import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerToggleSneakEvent; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.*; import java.util.Map.Entry; import java.util.stream.Collectors; @@ -60,7 +60,7 @@ public QuizChallenge() { instance = this; } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.BARRIER); @@ -107,7 +107,7 @@ protected int getSecondsUntilNextActivation() { return random.around(getValue() * 60 * 3, 60); } - private void broadcastMessage(@Nonnull String questionedPlayerMessage, @Nonnull String othersMessage, Object... args) { + private void broadcastMessage(@NotNull String questionedPlayerMessage, @NotNull String othersMessage, Object... args) { broadcast(player1 -> { if (currentQuestionedPlayer == player1) { Message.forName(questionedPlayerMessage).send(player1, prefix, args); @@ -178,7 +178,7 @@ private void cancelQuestion() { } @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (currentQuestion == null || currentQuestionedPlayer != player) { // TODO: REMOVE RESTART TIMER HERE @@ -208,19 +208,19 @@ public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exc } @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String s, @Nonnull String[] strings) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] strings) { return new ArrayList<>(); } interface IQuestion { - List createAnswers(@Nonnull SavedStatistic statistic, @Nonnull Player player); + List createAnswers(@NotNull SavedStatistic statistic, @NotNull Player player); List getRightAnswers(); - boolean isRightAnswer(@Nonnull String answer); + boolean isRightAnswer(@NotNull String answer); - static void sendMessage(@Nonnull String question, @Nonnull List answers) { + static void sendMessage(@NotNull String question, @NotNull List answers) { Player player = instance.currentQuestionedPlayer; player.sendMessage(" "); @@ -244,14 +244,14 @@ public Question(TriFunction, List> } @Override - public List createAnswers(@Nonnull SavedStatistic statistic, @Nonnull Player player) { + public List createAnswers(@NotNull SavedStatistic statistic, @NotNull Player player) { ArrayList answers = new ArrayList<>(); currentRightAnswers = questionCreator.apply(statistic, player, answers); return answers; } @Override - public boolean isRightAnswer(@Nonnull String answer) { + public boolean isRightAnswer(@NotNull String answer) { if (currentRightAnswers == null) return false; for (String currentRightAnswer : currentRightAnswers) { @@ -353,15 +353,15 @@ public IQuestion[] getQuestions() { return new Question[]{INTEGER_QUESTION}; } - public void increaseStatistic(@Nonnull Player player) { + public void increaseStatistic(@NotNull Player player) { increaseStatistic(player, 1); } - public void increaseStatistic(@Nonnull Player player, int amount) { + public void increaseStatistic(@NotNull Player player, int amount) { instance.getPlayerData(player).set(key, getStatistic(player) + amount); } - public int getStatistic(@Nonnull Player player) { + public int getStatistic(@NotNull Player player) { return instance.getPlayerData(player).getInt(key); } @@ -380,7 +380,7 @@ public String getKey() { return key; } - public Document getDocument(@Nonnull Player player) { + public Document getDocument(@NotNull Player player) { return instance.getPlayerData(player).getDocument(key); } @@ -466,15 +466,15 @@ public DocumentCountStatistic(String key, String verbMessage, String questionSuf this.questionVerb = questionVerb; } - public void increaseStatistic(@Nonnull Player player, @Nonnull String key) { + public void increaseStatistic(@NotNull Player player, @NotNull String key) { increaseStatistic(player, key, 1); } - public void increaseStatistic(@Nonnull Player player, @Nonnull String key, double amount) { + public void increaseStatistic(@NotNull Player player, @NotNull String key, double amount) { getDocument(player).set(key, getStatistic(player, key) + amount); } - public double getStatistic(@Nonnull Player player, @Nonnull String key) { + public double getStatistic(@NotNull Player player, @NotNull String key) { return getDocument(player).getDouble(key); } @@ -503,14 +503,14 @@ public IQuestion[] getQuestions() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onJump(@Nonnull PlayerJumpEvent event) { + public void onJump(@NotNull PlayerJumpEvent event) { if (!shouldExecuteEffect()) return; if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; SavedStatistic.JUMPED.increaseStatistic(event.getPlayer()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onJump(@Nonnull PlayerToggleSneakEvent event) { + public void onJump(@NotNull PlayerToggleSneakEvent event) { if (!shouldExecuteEffect()) return; if (!event.isSneaking()) return; if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; @@ -518,7 +518,7 @@ public void onJump(@Nonnull PlayerToggleSneakEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onEntityKill(@Nonnull EntityDamageByEntityEvent event) { + public void onEntityKill(@NotNull EntityDamageByEntityEvent event) { if (!shouldExecuteEffect()) return; if (!(event.getDamager() instanceof Player)) return; @@ -536,14 +536,14 @@ public void onEntityKill(@Nonnull EntityDamageByEntityEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + public void onBlockPlace(@NotNull BlockPlaceEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; SavedStatistic.BLOCKS_PLACED.increaseStatistic(event.getPlayer(), event.getBlockPlaced().getType().name()); } @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { + public void onBlockBreak(@NotNull BlockBreakEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (BukkitReflectionUtils.isAir(event.getBlock().getType())) return; @@ -551,7 +551,7 @@ public void onBlockBreak(@Nonnull BlockBreakEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { + public void onMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (event.getTo() == null) return; @@ -560,14 +560,14 @@ public void onMove(@Nonnull PlayerMoveEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(@Nonnull PlayerDropItemEvent event) { + public void onMove(@NotNull PlayerDropItemEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; SavedStatistic.ITEMS_DROPPED.increaseStatistic(event.getPlayer(), event.getItemDrop().getItemStack().getType().name()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(@Nonnull EntityDamageEvent event) { + public void onMove(@NotNull EntityDamageEvent event) { if (!shouldExecuteEffect()) return; if (!(event.getEntity() instanceof Player)) return; Player player = (Player) event.getEntity(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java index ad6e77487..fc63d250a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java @@ -11,8 +11,8 @@ import net.codingarea.commons.bukkit.utils.item.ItemUtils; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.Material; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -23,7 +23,7 @@ public BlockRandomizerChallenge() { super(MenuType.CHALLENGES); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.MINECART, Message.forName("item-block-randomizer-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java index 72628c416..c5ba7842b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java @@ -11,8 +11,8 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.*; public class CraftingRandomizerChallenge extends RandomizerSetting { @@ -23,7 +23,7 @@ public CraftingRandomizerChallenge() { super(MenuType.CHALLENGES); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.CHEST_MINECART, Message.forName("item-crafting-randomizer-challenge")); @@ -55,7 +55,7 @@ protected void onDisable() { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onCraftItem(@Nonnull CraftItemEvent event) { + public void onCraftItem(@NotNull CraftItemEvent event) { if (!isEnabled()) return; ItemStack item = event.getCurrentItem(); if (item == null) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java index df0d4f0ad..1cf2f7058 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java @@ -24,9 +24,8 @@ import org.bukkit.loot.LootTable; import org.bukkit.loot.LootTables; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.*; import java.util.stream.Collectors; @@ -126,7 +125,7 @@ public Optional getEntityForLootTable(LootTable lootTable) { } @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (!isEnabled()) { Message.forName("command-searchloot-disabled").send(sender, Prefix.CHALLENGES); @@ -171,7 +170,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) thr @Nullable @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { EntityLootRandomizerChallenge instance = AbstractChallenge.getFirstInstance(EntityLootRandomizerChallenge.class); return args.length != 1 ? null : instance.getLootableEntities().stream() diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 4005ed489..76c07e790 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -26,9 +26,7 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.inventory.Inventory; import org.jetbrains.annotations.NotNull; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.Nullable; @Since("2.1.2") public class HotBarRandomizerChallenge extends TimedChallenge { @@ -110,7 +108,7 @@ public void onBreak(BlockBreakEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + public void onInventoryClick(@NotNull PlayerInventoryClickEvent event) { Player player = event.getPlayer(); if (!shouldExecuteEffect()) return; if (ignorePlayer(player)) return; @@ -129,7 +127,7 @@ public void onInventoryClick(@Nonnull PlayerInventoryClickEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { + public void onPlayerDropItem(@NotNull PlayerDropItemEvent event) { if (!shouldExecuteEffect()) return; event.setCancelled(true); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java index 6384de216..d3268e059 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java @@ -20,8 +20,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntitySpawnEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -91,7 +91,7 @@ private void unLoadAllEntities() { } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.COMMAND_BLOCK_MINECART, Message.forName("item-mob-randomizer-challenge")); @@ -125,7 +125,7 @@ public List getSpawnAbleEntities() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntitySpawn(@Nonnull EntitySpawnEvent event) { + public void onEntitySpawn(@NotNull EntitySpawnEvent event) { if (!shouldExecuteEffect()) return; if (!entityRandomizer.containsKey(event.getEntityType())) return; if (inSpawn) return; @@ -141,14 +141,14 @@ public void onEntitySpawn(@Nonnull EntitySpawnEvent event) { inSpawn = false; } - private boolean maySpawn(@Nonnull EntityType newType, @Nonnull World world) { + private boolean maySpawn(@NotNull EntityType newType, @NotNull World world) { EntityCategory category = getEntityCategory(newType); int currentMobCount = getCurrentMobCount(category, world); int spawnLimit = getEntityCategory(newType).getSpawnLimit(world); return currentMobCount < spawnLimit; } - private int getCurrentMobCount(@Nonnull EntityCategory entityState, @Nonnull World world) { + private int getCurrentMobCount(@NotNull EntityCategory entityState, @NotNull World world) { int mobCount = 0; @@ -164,7 +164,7 @@ private int getCurrentMobCount(@Nonnull EntityCategory entityState, @Nonnull Wor return mobCount; } - private EntityCategory getEntityCategory(@Nonnull EntityType type) { + private EntityCategory getEntityCategory(@NotNull EntityType type) { Class entity = type.getEntityClass(); if (entity == null) return EntityCategory.OTHER; @@ -193,7 +193,7 @@ public enum EntityCategory { WATER_AMBIENT, OTHER; - private int getSpawnLimit(@Nonnull World world) { + private int getSpawnLimit(@NotNull World world) { boolean useSpawnCategories = MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_19); // World#getSpawnLimit was added in 1.19 switch (this) { case AMBIENT: diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java index b62eb3380..e28be1f94 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java @@ -14,9 +14,9 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; @@ -30,7 +30,7 @@ public RandomChallengeChallenge() { setCategory(SettingCategory.RANDOMIZER); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.REDSTONE, Message.forName("item-random-challenge-challenge")); @@ -107,7 +107,7 @@ protected void onTimeActivation() { } - private void setEnabled(@Nonnull IChallenge challenge, boolean enabled) { + private void setEnabled(@NotNull IChallenge challenge, boolean enabled) { if (challenge instanceof Setting) { Setting setting = (Setting) challenge; setting.setEnabled(enabled); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java index 69eab970a..83876e781 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java @@ -20,9 +20,8 @@ import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Since("2.0") public class RandomEventChallenge extends TimedChallenge { @@ -43,7 +42,7 @@ public RandomEventChallenge() { }; } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.CLOCK, Message.forName("item-random-event-challenge").asItemDescription(events.length)); @@ -76,23 +75,23 @@ protected void onTimeActivation() { public interface Event { - @Nonnull + @NotNull Message getActivationMessage(); - void run(@Nonnull Player player); + void run(@NotNull Player player); } public static class SpeedEvent implements Event { - @Nonnull + @NotNull @Override public Message getActivationMessage() { return Message.forName("random-event-speed"); } @Override - public void run(@Nonnull Player player) { + public void run(@NotNull Player player) { player.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 10 * 20, 99)); } @@ -100,14 +99,14 @@ public void run(@Nonnull Player player) { public static class HoleEvent implements Event { - @Nonnull + @NotNull @Override public Message getActivationMessage() { return Message.forName("random-event-hole"); } @Override - public void run(@Nonnull Player player) { + public void run(@NotNull Player player) { Location location = player.getLocation().getBlock().getLocation(); for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { @@ -122,14 +121,14 @@ public void run(@Nonnull Player player) { public static class FlyEvent implements Event { - @Nonnull + @NotNull @Override public Message getActivationMessage() { return Message.forName("random-event-fly"); } @Override - public void run(@Nonnull Player player) { + public void run(@NotNull Player player) { player.addPotionEffect(new PotionEffect(PotionEffectType.LEVITATION, 3 * 20, 5)); } @@ -137,14 +136,14 @@ public void run(@Nonnull Player player) { public static class ReplaceOresEvent implements Event { - @Nonnull + @NotNull @Override public Message getActivationMessage() { return Message.forName("random-event-ores"); } @Override - public void run(@Nonnull Player player) { + public void run(@NotNull Player player) { Location location = player.getLocation(); Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { for (int x = -100; x <= 100; x++) { @@ -172,14 +171,14 @@ public void run(@Nonnull Player player) { public static class SicknessEvent implements Event { - @Nonnull + @NotNull @Override public Message getActivationMessage() { return Message.forName("random-event-sickness"); } @Override - public void run(@Nonnull Player player) { + public void run(@NotNull Player player) { player.addPotionEffect(new PotionEffect(MinecraftNameWrapper.NAUSEA, 7 * 20, 0)); player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 3 * 20, 1)); player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 5 * 20, 1)); @@ -188,14 +187,14 @@ public void run(@Nonnull Player player) { public static class SpawnEntitiesEvent implements Event { - @Nonnull + @NotNull @Override public Message getActivationMessage() { return Message.forName("random-event-entities"); } @Override - public void run(@Nonnull Player player) { + public void run(@NotNull Player player) { EntityType type = globalRandom.choose(EntityType.PIG, EntityType.CHICKEN, EntityType.CAT, EntityType.SILVERFISH, EntityType.WOLF); for (int i = 0; i < globalRandom.nextInt(5) + 5; i++) { @@ -212,14 +211,14 @@ public void run(@Nonnull Player player) { public static class CobWebEvent implements Event { - @Nonnull + @NotNull @Override public Message getActivationMessage() { return Message.forName("random-event-webs"); } @Override - public void run(@Nonnull Player player) { + public void run(@NotNull Player player) { for (int i = 0; i < 13; i++) { Location randomLocation = player.getLocation().add(globalRandom.nextInt(10) - 5, -20, globalRandom.nextInt(10 - 5)); if (randomLocation.getWorld() == null) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java index 521532871..1ecd498ba 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java @@ -9,9 +9,8 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Since("2.0") public class RandomItemChallenge extends TimedChallenge { @@ -21,7 +20,7 @@ public RandomItemChallenge() { setCategory(SettingCategory.RANDOMIZER); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.BEACON, Message.forName("item-random-item-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java index 3fad92fd6..03ca11d88 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java @@ -14,9 +14,8 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Since("2.0") public class RandomItemDroppingChallenge extends TimedChallenge { @@ -31,7 +30,7 @@ public static void dropRandomItem(Player player) { dropRandomItem(player.getLocation(), player.getInventory()); } - public static void dropRandomItem(@Nonnull Location location, @Nonnull Inventory inventory) { + public static void dropRandomItem(@NotNull Location location, @NotNull Inventory inventory) { if (location.getWorld() == null) return; int slot = InventoryUtils.getRandomFullSlot(inventory); if (slot == -1) return; @@ -41,7 +40,7 @@ public static void dropRandomItem(@Nonnull Location location, @Nonnull Inventory InventoryUtils.dropItemByPlayer(location, item); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.DISPENSER, Message.forName("item-random-dropping-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java index 3e23a4503..6bc569cc9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java @@ -11,9 +11,8 @@ import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Since("2.0") public class RandomItemRemovingChallenge extends TimedChallenge { @@ -23,7 +22,7 @@ public RandomItemRemovingChallenge() { setCategory(SettingCategory.RANDOMIZER); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.DROPPER, Message.forName("item-random-removing-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java index 079e2261d..8fc8c9743 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java @@ -13,9 +13,8 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Since("2.0") public class RandomItemSwappingChallenge extends TimedChallenge { @@ -36,7 +35,7 @@ public static void swapRandomItems(Player player) { ); } - private static void swapItemToRandomSlot(@Nonnull Inventory inventory, int slot1, int slot2) { + private static void swapItemToRandomSlot(@NotNull Inventory inventory, int slot1, int slot2) { if (slot1 == -1 || slot2 == -1) return; ItemStack item1 = inventory.getItem(slot1); ItemStack item2 = inventory.getItem(slot2); @@ -44,7 +43,7 @@ private static void swapItemToRandomSlot(@Nonnull Inventory inventory, int slot1 inventory.setItem(slot2, item1); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.HOPPER, Message.forName("item-random-swapping-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java index c475ceca6..17365b36f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java @@ -22,9 +22,9 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntitySpawnEvent; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; import java.util.Random; @@ -55,14 +55,14 @@ protected void onValueChange() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSpawn(@Nonnull EntitySpawnEvent event) { + public void onSpawn(@NotNull EntitySpawnEvent event) { if (!shouldExecuteEffect()) return; if (!(event.getEntity() instanceof LivingEntity)) return; LivingEntity entity = (LivingEntity) event.getEntity(); randomizeEntityHealth(entity); } - private void randomizeEntityHealth(@Nonnull LivingEntity entity) { + private void randomizeEntityHealth(@NotNull LivingEntity entity) { if (entity instanceof Player) return; if (!isEnabled()) { entity.resetMaxHealth(); @@ -101,7 +101,7 @@ private void resetExistingEntityHealth() { } } - private double getDefaultHealth(@Nonnull EntityType entityType) { + private double getDefaultHealth(@NotNull EntityType entityType) { World world = ChallengeAPI.getGameWorld(Environment.NORMAL); Entity entity = world.spawnEntity(new Location(world, 0, 0, 0), entityType); entity.remove(); @@ -111,13 +111,13 @@ private double getDefaultHealth(@Nonnull EntityType entityType) { return attribute.getBaseValue(); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new PotionBuilder(Material.POTION, Message.forName("item-randomized-hp-challenge")).setColor(Color.RED); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { return super.createSettingsItem().amount(isEnabled() ? getValue() * 5 : 1); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java index f384b6fa6..d74e42fd4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java @@ -14,9 +14,8 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Since("2.0") public class MaxBiomeTimeChallenge extends SettingModifier { @@ -48,7 +47,7 @@ protected void onValueChange() { bossbar.update(); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.SPRUCE_SAPLING, Message.forName("item-max-biome-time-challenge")); @@ -66,7 +65,7 @@ public void playValueChangeTitle() { } @EventHandler - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + public void onPlayerMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (event.getTo() == null) return; @@ -79,7 +78,7 @@ public void onSecond() { broadcast(this::updateBiomeTime); } - private void updateBiomeTime(@Nonnull Player player) { + private void updateBiomeTime(@NotNull Player player) { if (ignorePlayer(player)) { bossbar.update(player); return; @@ -96,11 +95,11 @@ private void updateBiomeTime(@Nonnull Player player) { bossbar.update(player); } - private int getCurrentTime(@Nonnull Player player) { + private int getCurrentTime(@NotNull Player player) { return getPlayerData(player).getInt(getBiome(player).name(), 0); } - private Biome getBiome(@Nonnull Player player) { + private Biome getBiome(@NotNull Player player) { return player.getLocation().getBlock().getBiome(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java index 31fad03db..d873baec3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java @@ -14,9 +14,8 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Since("2.0") public class MaxHeightTimeChallenge extends SettingModifier { @@ -48,7 +47,7 @@ protected void onValueChange() { bossbar.update(); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.PARROT_SPAWN_EGG, Message.forName("item-max-height-time-challenge")); @@ -66,7 +65,7 @@ public void playValueChangeTitle() { } @EventHandler - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + public void onPlayerMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (event.getTo() == null) return; @@ -79,7 +78,7 @@ public void onSecond() { broadcast(this::updateHeightTime); } - private void updateHeightTime(@Nonnull Player player) { + private void updateHeightTime(@NotNull Player player) { if (ignorePlayer(player)) { bossbar.update(player); return; @@ -95,7 +94,7 @@ private void updateHeightTime(@Nonnull Player player) { bossbar.update(player); } - private int getCurrentTime(@Nonnull Player player) { + private int getCurrentTime(@NotNull Player player) { return getPlayerData(player).getInt(String.valueOf(player.getLocation().getBlockY()), 0); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java index 1052de3c1..3065a48a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java @@ -23,9 +23,9 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.*; @Since("2.0") @@ -48,14 +48,14 @@ public AllBlocksDisappearChallenge() { stackDropLimit = document.contains("all-block-disappear-stack-drop-limit") ? document.getInt("all-block-disappear-stack-drop-limit") : 50; } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.TNT, Message.forName("item-all-blocks-disappear-challenge")); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { + public void onBlockBreak(@NotNull BlockBreakEvent event) { if (!shouldExecuteEffect()) return; if (!getSetting("break").getAsBoolean()) return; if (ignorePlayer(event.getPlayer())) return; @@ -65,7 +65,7 @@ public void onBlockBreak(@Nonnull BlockBreakEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + public void onBlockPlace(@NotNull BlockPlaceEvent event) { if (!shouldExecuteEffect()) return; if (!getSetting("place").getAsBoolean()) return; if (ignorePlayer(event.getPlayer())) return; @@ -74,7 +74,7 @@ public void onBlockPlace(@Nonnull BlockPlaceEvent event) { breakBlocks(event.getBlockAgainst(), null, event.getPlayer().getInventory()); } - private void breakBlocks(@Nonnull Block block, @Nullable ItemStack tool, @Nonnull Inventory inventory) { + private void breakBlocks(@NotNull Block block, @Nullable ItemStack tool, @NotNull Inventory inventory) { Chunk chunk = block.getChunk(); List blocks = getAllBlocksToBreak(chunk, block.getType()); @@ -105,7 +105,7 @@ private void breakBlocks(@Nonnull Block block, @Nullable ItemStack tool, @Nonnul dropList(allDrops, block.getLocation(), inventory); } - private void dropList(@Nonnull Collection itemStacks, @Nonnull Location location, @Nonnull Inventory inventory) { + private void dropList(@NotNull Collection itemStacks, @NotNull Location location, @NotNull Inventory inventory) { if (location.getWorld() == null) return; Map stackCount = new HashMap<>(); @@ -125,7 +125,7 @@ private boolean increaseStackCount(Map map, Material material return true; } - protected List getAllBlocksToBreak(@Nonnull Chunk chunk, @Nonnull Material material) { + protected List getAllBlocksToBreak(@NotNull Chunk chunk, @NotNull Material material) { return new ListBuilder() .fill(builder -> { for (int x = 0; x < 16; x++) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java index cdd70b0be..01bdb8ac2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java @@ -17,8 +17,8 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityDropItemEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.Random; @@ -88,7 +88,7 @@ private void removeAnvils() { } } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.ANVIL, Message.forName("item-anvil-rain-challenge")); @@ -120,7 +120,7 @@ private void handleTimeActivation() { } - private void spawnAnvils(@Nonnull Chunk chunk, int height) { + private void spawnAnvils(@NotNull Chunk chunk, int height) { for (int i = 0; i < getCount(); i++) { Block block = getRandomBlockInChunk(chunk, height); Location location = block.getLocation().add(0.5, 0, 0.5); @@ -128,7 +128,7 @@ private void spawnAnvils(@Nonnull Chunk chunk, int height) { } } - private List getTargetChunks(@Nonnull Chunk origin) { + private List getTargetChunks(@NotNull Chunk origin) { List chunks = new ArrayList<>(); int originX = origin.getX(); @@ -146,14 +146,14 @@ private List getTargetChunks(@Nonnull Chunk origin) { return chunks; } - private Block getRandomBlockInChunk(@Nonnull Chunk chunk, int y) { + private Block getRandomBlockInChunk(@NotNull Chunk chunk, int y) { int x = random.nextInt(16); int z = random.nextInt(16); return chunk.getBlock(x, y, z); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityChangeBlock(@Nonnull EntityChangeBlockEvent event) { + public void onEntityChangeBlock(@NotNull EntityChangeBlockEvent event) { if (!shouldExecuteEffect()) return; if (!(event.getEntity() instanceof FallingBlock)) return; @@ -171,7 +171,7 @@ public void onEntityChangeBlock(@Nonnull EntityChangeBlockEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDrop(@Nonnull EntityDropItemEvent event) { + public void onDrop(@NotNull EntityDropItemEvent event) { if (event.getItemDrop().getItemStack().getType() != Material.ANVIL) return; if (event.getEntityType() != EntityType.FALLING_BLOCK) return; String name = ((FallingBlock) event.getEntity()).getBlockData().getMaterial().name(); @@ -183,7 +183,7 @@ public void onDrop(@Nonnull EntityDropItemEvent event) { applyDamageToNearEntities(event.getEntity().getLocation().getBlock().getLocation().add(0.5, 0.5, 0.5)); } - public void destroyRandomBlocks(@Nonnull Location origin) { + public void destroyRandomBlocks(@NotNull Location origin) { int i = random.nextInt(2); if (i == 0) return; @@ -201,7 +201,7 @@ public void destroyRandomBlocks(@Nonnull Location origin) { } - public void applyDamageToNearEntities(@Nonnull Location location) { + public void applyDamageToNearEntities(@NotNull Location location) { if (location.getWorld() == null) return; for (Entity entity : location.getWorld().getNearbyEntities(location, 0.25, 0.25, 0.25)) { if (!(entity instanceof LivingEntity)) continue; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java index 20cfef5a9..2aa84e8b1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java @@ -12,8 +12,7 @@ import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class BedrockPathChallenge extends Setting { @@ -22,14 +21,14 @@ public BedrockPathChallenge() { setCategory(SettingCategory.WORLD); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-bedrock-path-challenge")).setColor(Color.GRAY); } @EventHandler - public void onMove(@Nonnull PlayerMoveEvent event) { + public void onMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java index 805ef6538..4b22248c0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java @@ -11,9 +11,9 @@ import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; @@ -25,7 +25,7 @@ public BedrockWallChallenge() { } @EventHandler - public void onMove(@Nonnull PlayerMoveEvent event) { + public void onMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) return; @@ -54,7 +54,7 @@ public void onMove(@Nonnull PlayerMoveEvent event) { } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.BEDROCK, Message.forName("item-bedrock-walls-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java index f3576ab03..9a28748d3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java @@ -14,9 +14,9 @@ import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.scheduler.BukkitTask; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; @@ -30,7 +30,7 @@ public BlocksDisappearAfterTimeChallenge() { setCategory(SettingCategory.WORLD); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.STRING, Message.forName("item-blocks-disappear-time-challenge")); @@ -43,7 +43,7 @@ protected String[] getSettingsDescription() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + public void onBlockPlace(@NotNull BlockPlaceEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; @@ -54,7 +54,7 @@ public void onBlockPlace(@Nonnull BlockPlaceEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockBreakEvent event) { + public void onBlockPlace(@NotNull BlockBreakEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; @@ -62,7 +62,7 @@ public void onBlockPlace(@Nonnull BlockBreakEvent event) { if (oldTask != null) oldTask.cancel(); } - private BukkitTask runTask(@Nonnull Block block) { + private BukkitTask runTask(@NotNull Block block) { return Bukkit.getScheduler().runTaskLater(plugin, () -> block.setType(Material.AIR), getValue() * 20L); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java index 155bed1ef..dd078d165 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java @@ -11,9 +11,9 @@ import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.*; import org.bukkit.block.Block; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.List; public class ChunkDeconstructionChallenge extends TimedChallenge { @@ -23,7 +23,7 @@ public ChunkDeconstructionChallenge() { setCategory(SettingCategory.WORLD); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.DIAMOND_PICKAXE, Message.forName("item-chunk-deconstruction-challenge")); @@ -57,7 +57,7 @@ protected void onTimeActivation() { restartTimer(); } - private void deconstructChunk(@Nonnull Chunk chunk) { + private void deconstructChunk(@NotNull Chunk chunk) { for (int x = 0; x < 16; x++) { int finalX = x; @@ -70,7 +70,7 @@ private void deconstructChunk(@Nonnull Chunk chunk) { } - private void deconstructAtLocation(@Nonnull Block block) { + private void deconstructAtLocation(@NotNull Block block) { Block lowestBreakableBlock = getLowestBreakableBlock(block); if (lowestBreakableBlock == null) return; @@ -78,7 +78,7 @@ private void deconstructAtLocation(@Nonnull Block block) { } @Nullable - private Block getLowestBreakableBlock(@Nonnull Block block) { + private Block getLowestBreakableBlock(@NotNull Block block) { Location location = block.getLocation(); location.setY(block.getWorld().getMaxHeight()); @@ -90,7 +90,7 @@ private Block getLowestBreakableBlock(@Nonnull Block block) { return currentBlock.getType() == Material.BEDROCK || currentBlock.isLiquid() ? null : location.getBlock(); } - private boolean isBreakable(@Nonnull Block block) { + private boolean isBreakable(@NotNull Block block) { return block.getType() != Material.BEDROCK && !BukkitReflectionUtils.isAir(block.getType()) && !block.isLiquid(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java index 94ec501fe..b1cd4abb8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java @@ -12,9 +12,8 @@ import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class FloorIsLavaChallenge extends SettingModifier { @@ -24,7 +23,7 @@ public FloorIsLavaChallenge() { } @EventHandler - public void onMove(@Nonnull PlayerMoveEvent event) { + public void onMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) return; @@ -36,18 +35,18 @@ public void onMove(@Nonnull PlayerMoveEvent event) { }, getValue() * 20L); } - private void createMagmaFloor(@Nonnull Location to) { + private void createMagmaFloor(@NotNull Location to) { BlockUtils.setBlockNatural(BlockUtils.getBlockBelow(to, 0.6), Material.MAGMA_BLOCK, true); Bukkit.getScheduler().runTaskLater(plugin, () -> { createLavaFloor(to); }, getValue() * 20L); } - private void createLavaFloor(@Nonnull Location to) { + private void createLavaFloor(@NotNull Location to) { BlockUtils.setBlockNatural(BlockUtils.getBlockBelow(to), Material.LAVA, true); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.MAGMA_BLOCK, Message.forName("item-floor-lava-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java index 02e222ae8..c350e1fbb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java @@ -19,8 +19,8 @@ import org.bukkit.event.player.PlayerToggleSneakEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; @@ -34,7 +34,7 @@ public IceFloorChallenge() { setCategory(SettingCategory.WORLD); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.PACKED_ICE, Message.forName("item-ice-floor-challenge")); @@ -55,7 +55,7 @@ protected void onDisable() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(@Nonnull PlayerMoveEvent event) { + public void onPlayerMove(@NotNull PlayerMoveEvent event) { Player player = event.getPlayer(); if (!shouldExecuteEffect()) return; if (ignorePlayer(player)) return; @@ -63,12 +63,12 @@ public void onPlayerMove(@Nonnull PlayerMoveEvent event) { createIceFloorForPlayer(player); } - private void createIceFloorForPlayer(@Nonnull Player player) { + private void createIceFloorForPlayer(@NotNull Player player) { Block middleBlock = player.getLocation().clone().subtract(0, 1, 0).getBlock(); createIceFloor(middleBlock); } - private void createIceFloor(@Nonnull Block middleBlock) { + private void createIceFloor(@NotNull Block middleBlock) { for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { @@ -85,7 +85,7 @@ private void createIceFloor(@Nonnull Block middleBlock) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onSneak(@Nonnull PlayerToggleSneakEvent event) { + public void onSneak(@NotNull PlayerToggleSneakEvent event) { if (!shouldExecuteEffect()) return; if (!event.isSneaking()) return; if (ignorePlayer(event.getPlayer())) return; @@ -99,7 +99,7 @@ public void onSneak(@Nonnull PlayerToggleSneakEvent event) { bossbar.update(event.getPlayer()); } - private boolean ignoreIce(@Nonnull Player player) { + private boolean ignoreIce(@NotNull Player player) { return ignoredPlayers.contains(player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java index d6ee2489a..326aca912 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java @@ -28,7 +28,6 @@ import org.bukkit.event.player.*; import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.HashMap; import java.util.Map; import java.util.UUID; @@ -173,7 +172,7 @@ private void updateBorderSize(boolean animate) { } } - private void updateBorderSize(@Nonnull World world, boolean animate) { + private void updateBorderSize(@NotNull World world, boolean animate) { Location location = worldCenters.get(world); if (location == null) return; int newSize = bestPlayerLevel + 1; @@ -199,13 +198,13 @@ public void onTimerStart() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onLevelChange(@Nonnull PlayerLevelChangeEvent event) { + public void onLevelChange(@NotNull PlayerLevelChangeEvent event) { if (!shouldExecuteEffect()) return; checkBorderSize(true); } @EventHandler(priority = EventPriority.HIGH) - public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { + public void onPlayerJoin(@NotNull PlayerJoinEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; Bukkit.getScheduler().runTaskLater(plugin, () -> checkBorderSize(false), 1); @@ -213,7 +212,7 @@ public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { } @EventHandler(priority = EventPriority.HIGH) - public void onPlayerLeave(@Nonnull PlayerQuitEvent event) { + public void onPlayerLeave(@NotNull PlayerQuitEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; Bukkit.getScheduler().runTaskLater(plugin, () -> checkBorderSize(false), 1); @@ -225,7 +224,7 @@ public void onPlayerLeave(@Nonnull PlayerQuitEvent event) { * because of the random spawning mechanic at the world spawn. */ @EventHandler(priority = EventPriority.HIGH) - public void onRespawn(@Nonnull PlayerRespawnEvent event) { + public void onRespawn(@NotNull PlayerRespawnEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; Bukkit.getScheduler().runTaskLater(plugin, () -> { @@ -238,7 +237,7 @@ public void onRespawn(@Nonnull PlayerRespawnEvent event) { * Execute level change event when dying instead of respawning like spigot does it */ @EventHandler(priority = EventPriority.HIGH) - public void onDeath(@Nonnull PlayerDeathEvent event) { + public void onDeath(@NotNull PlayerDeathEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getEntity())) return; PlayerLevelChangeEvent lvlEvent = new PlayerLevelChangeEvent( @@ -259,7 +258,7 @@ public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onTeleport(@Nonnull PlayerTeleportEvent event) { + public void onTeleport(@NotNull PlayerTeleportEvent event) { if (event.getTo() == null) return; if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; @@ -334,7 +333,7 @@ private void updateBorder(World world, Location center, int size, boolean animat } } - private void sendBorder(@Nonnull Player player) { + private void sendBorder(@NotNull Player player) { if (useAPI) { WorldBorder border = playerWorldBorders.get(player.getWorld()); player.setWorldBorder(border); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index 5c8e95f0c..0d983dcfb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -39,8 +39,8 @@ import org.bukkit.projectiles.ProjectileSource; import org.bukkit.util.RayTraceResult; import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.*; import java.util.Map.Entry; @@ -54,7 +54,7 @@ public LoopChallenge() { setCategory(SettingCategory.WORLD); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.LEAD, Message.forName("item-loop-challenge")); @@ -87,12 +87,12 @@ private void clearLoops() { loops.clear(); } - private void createLoop(@Nonnull Loop loop) { + private void createLoop(@NotNull Loop loop) { loops.put(loop, System.currentTimeMillis()); } @EventHandler(priority = EventPriority.MONITOR) - public void onSneak(@Nonnull PlayerToggleSneakEvent event) { + public void onSneak(@NotNull PlayerToggleSneakEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (!event.isSneaking()) return; @@ -101,7 +101,7 @@ public void onSneak(@Nonnull PlayerToggleSneakEvent event) { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onProjectileLaunch(@Nonnull ProjectileLaunchEvent event) { + public void onProjectileLaunch(@NotNull ProjectileLaunchEvent event) { if (!shouldExecuteEffect()) return; ProjectileSource shooter = event.getEntity().getShooter(); if (shooter == null) return; @@ -110,7 +110,7 @@ public void onProjectileLaunch(@Nonnull ProjectileLaunchEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { + public void onDamage(@NotNull EntityDamageEvent event) { if (!shouldExecuteEffect()) return; if (!(event.getEntity() instanceof LivingEntity)) return; double damage = event.getFinalDamage() + event.getDamage(DamageModifier.ABSORPTION); @@ -119,14 +119,14 @@ public void onDamage(@Nonnull EntityDamageEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + public void onBlockPlace(@NotNull BlockPlaceEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; createLoop(new BlockPlaceLoop(event.getBlock().getType(), event.getPlayer(), event.getBlockAgainst().getFace(event.getBlock()), event.getBlock())); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { + public void onBlockBreak(@NotNull BlockBreakEvent event) { if (!shouldExecuteEffect()) return; Player player = event.getPlayer(); if (ignorePlayer(player)) return; @@ -141,7 +141,7 @@ public void onBlockBreak(@Nonnull BlockBreakEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull PlayerDropItemEvent event) { + public void onBlockPlace(@NotNull PlayerDropItemEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; createLoop(new DropLoop(event.getItemDrop().getItemStack(), event.getPlayer())); @@ -312,7 +312,7 @@ private boolean decreaseDurability() { return true; } - private boolean isTool(@Nonnull ItemStack itemStack) { + private boolean isTool(@NotNull ItemStack itemStack) { if (itemStack.getItemMeta() != null) { try { Attribute attribute = AttributeWrapper.MAX_HEALTH; @@ -326,7 +326,7 @@ private boolean isTool(@Nonnull ItemStack itemStack) { return true; } - private boolean cantBeBroken(@Nonnull Block block, @Nonnull ItemStack tool) { + private boolean cantBeBroken(@NotNull Block block, @NotNull ItemStack tool) { return block.getDrops(tool).isEmpty(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index a1147e49a..e67924724 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -18,8 +18,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -33,7 +33,7 @@ public SnakeChallenge() { setCategory(SettingCategory.WORLD); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.BLUE_TERRACOTTA, Message.forName("item-snake-challenge")); @@ -45,7 +45,7 @@ protected void onDisable() { } @Override - public void writeGameState(@Nonnull Document document) { + public void writeGameState(@NotNull Document document) { super.writeGameState(document); List locations = blocks.stream().map(Block::getLocation).collect(Collectors.toList()); @@ -53,14 +53,14 @@ public void writeGameState(@Nonnull Document document) { } @Override - public void loadGameState(@Nonnull Document document) { + public void loadGameState(@NotNull Document document) { super.loadGameState(document); blocks.addAll(document.getSerializableList("blocks", Location.class).stream().map(Location::getBlock).collect(Collectors.toList())); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { + public void onMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (event.getTo() == null) return; if (event.getFrom().getBlock().equals(event.getTo().getBlock())) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java index 9c72132df..189c355e4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java @@ -11,9 +11,9 @@ import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; @@ -25,7 +25,7 @@ public SurfaceHoleChallenge() { } @EventHandler - public void onMove(@Nonnull PlayerMoveEvent event) { + public void onMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) return; @@ -56,7 +56,7 @@ public void onMove(@Nonnull PlayerMoveEvent event) { } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.BARRIER, Message.forName("item-surface-hole-challenge")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java index 7611270ac..2372aae4b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java @@ -23,9 +23,9 @@ import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.world.ChunkUnloadEvent; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -47,7 +47,7 @@ public TsunamiChallenge() { setCategory(SettingCategory.WORLD); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.ICE, Message.forName("item-tsunami-challenge")); @@ -131,7 +131,7 @@ protected void onTimeActivation() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - private void onPlayerMove(@Nonnull PlayerMoveEvent event) { + private void onPlayerMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (event.getTo() == null) return; @@ -145,7 +145,7 @@ private void onPlayerMove(@Nonnull PlayerMoveEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onTeleport(@Nonnull PlayerTeleportEvent event) { + public void onTeleport(@NotNull PlayerTeleportEvent event) { if (ignorePlayer(event.getPlayer())) return; if (!shouldExecuteEffect()) return; if (event.getTo() == null) return; @@ -161,11 +161,11 @@ public void onTeleport(@Nonnull PlayerTeleportEvent event) { } @EventHandler - public void onChunkUnload(@Nonnull ChunkUnloadEvent event) { + public void onChunkUnload(@NotNull ChunkUnloadEvent event) { floodedChunks.remove(event.getChunk()); } - private void floodChunk(@Nonnull Chunk chunk, boolean discovered) { + private void floodChunk(@NotNull Chunk chunk, boolean discovered) { if (floodedChunks.contains(chunk)) return; floodedChunks.add(chunk); if (chunk.getWorld().getEnvironment() == Environment.THE_END) return; @@ -175,7 +175,7 @@ private void floodChunk(@Nonnull Chunk chunk, boolean discovered) { floodChunk0(chunk, discovered ? null : height - 1, height, overworld, (delay, task) -> Bukkit.getScheduler().runTaskLater(plugin, task, delay)); } - private void floodChunk0(@Nonnull Chunk chunk, @Nullable Integer givenStartAt, int height, boolean overworld, @Nonnull BiConsumer executor) { + private void floodChunk0(@NotNull Chunk chunk, @Nullable Integer givenStartAt, int height, boolean overworld, @NotNull BiConsumer executor) { int startAt = givenStartAt != null ? Math.max(BukkitReflectionUtils.getMinHeight(chunk.getWorld()) + 1, givenStartAt) : BukkitReflectionUtils .getMinHeight(chunk.getWorld()) + 1; Map> blocksByDelay = new HashMap<>(); @@ -207,7 +207,7 @@ private List getChunksToFlood() { }).build(); } - private List getChunksAroundChunk(@Nonnull Chunk origin) { + private List getChunksAroundChunk(@NotNull Chunk origin) { return new ListBuilder().fill(builder -> { for (int x = -RANGE; x <= RANGE; x++) { for (int z = -RANGE; z <= RANGE; z++) { @@ -218,14 +218,14 @@ private List getChunksAroundChunk(@Nonnull Chunk origin) { } @Override - public void writeGameState(@Nonnull Document document) { + public void writeGameState(@NotNull Document document) { super.writeGameState(document); document.set("waterHeight", waterHeight); document.set("lavaHeight", lavaHeight); } @Override - public void loadGameState(@Nonnull Document document) { + public void loadGameState(@NotNull Document document) { super.loadGameState(document); waterHeight = document.getInt("waterHeight"); lavaHeight = document.getInt("lavaHeight"); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java index b8efd70c9..a3bc15578 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java @@ -12,7 +12,6 @@ import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Arrays; import java.util.List; @@ -23,7 +22,7 @@ public class DamageRuleSetting extends Setting { private final String name; private final ItemBuilder preset; - public DamageRuleSetting(@Nonnull ItemBuilder preset, @Nonnull String name, @Nonnull DamageCause... causes) { + public DamageRuleSetting(@NotNull ItemBuilder preset, @NotNull String name, @NotNull DamageCause... causes) { super(MenuType.DAMAGE, true); this.causes = Arrays.asList(causes); this.name = name; @@ -36,14 +35,14 @@ public String getUniqueName() { return super.getUniqueName() + name; } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return preset.clone().applyFormat(Message.forName("item-damage-rule-" + name).asItemDescription()); } @EventHandler(priority = EventPriority.NORMAL) - public void onDamage(@Nonnull EntityDamageEvent event) { + public void onDamage(@NotNull EntityDamageEvent event) { if (ChallengeAPI.isWorldInUse()) return; if (isEnabled()) return; if (!(event.getEntity() instanceof Player)) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java index ad6b21b80..50167e3b6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java @@ -20,7 +20,6 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Collections; import java.util.LinkedList; import java.util.List; @@ -100,7 +99,7 @@ protected void updateAdvancements() { broadcastFiltered(this::updateAdvancements); } - protected void updateAdvancements(@Nonnull Player player) { + protected void updateAdvancements(@NotNull Player player) { int done = 0; for (Advancement advancement : allAdvancements) { AdvancementProgress progress = player.getAdvancementProgress(advancement); @@ -118,7 +117,7 @@ protected void checkForWinning(Player player) { } } - protected boolean hasWon(@Nonnull Player player) { + protected boolean hasWon(@NotNull Player player) { return getPoints(player.getUniqueId()) >= advancementCount; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index 9337fceff..2cbd98394 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -25,9 +25,9 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -53,7 +53,7 @@ public CollectAllItemsGoal() { totalItemsCount = itemsToFind.size(); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-all-items-goal")); @@ -100,7 +100,7 @@ protected void onDisable() { } @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (!isEnabled()) { Message.forName("challenge-disabled").send(sender, Prefix.CHALLENGES); SoundSample.BASS_OFF.playIfPlayer(sender); @@ -120,7 +120,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) thr } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onClick(@Nonnull PlayerInventoryClickEvent event) { + public void onClick(@NotNull PlayerInventoryClickEvent event) { if (event.isCancelled()) return; ItemStack item = event.getCurrentItem(); if (item == null) return; @@ -128,13 +128,13 @@ public void onClick(@Nonnull PlayerInventoryClickEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPickUp(@Nonnull PlayerPickupItemEvent event) { + public void onPickUp(@NotNull PlayerPickupItemEvent event) { Material material = event.getItem().getItemStack().getType(); handleNewItem(material, event.getPlayer()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInteract(@Nonnull PlayerInteractEvent event) { + public void onInteract(@NotNull PlayerInteractEvent event) { Bukkit.getScheduler().runTaskLater(plugin, () -> { ItemStack item = event.getPlayer().getInventory().getItemInMainHand(); Material material = item.getType(); @@ -142,7 +142,7 @@ public void onInteract(@Nonnull PlayerInteractEvent event) { }, 1); } - protected void handleNewItem(@Nullable Material material, @Nonnull Player player) { + protected void handleNewItem(@Nullable Material material, @NotNull Player player) { if (!shouldExecuteEffect()) return; if (ignorePlayer(player)) return; if (currentItem != material) return; @@ -153,11 +153,11 @@ protected void handleNewItem(@Nullable Material material, @Nonnull Player player } @Override - public void getWinnersOnEnd(@Nonnull List winners) { + public void getWinnersOnEnd(@NotNull List winners) { } @Override - public void loadGameState(@Nonnull Document document) { + public void loadGameState(@NotNull Document document) { super.loadGameState(document); random = new SeededRandomWrapper(document.getLong("seed")); reloadItemsToFind(); @@ -167,7 +167,7 @@ public void loadGameState(@Nonnull Document document) { } @Override - public void writeGameState(@Nonnull Document document) { + public void writeGameState(@NotNull Document document) { super.writeGameState(document); document.set("seed", random.getSeed()); document.set("found", totalItemsCount - itemsToFind.size()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java index 3f95511a3..ab587345c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java @@ -12,8 +12,7 @@ import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.PlayerDeathEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class CollectMostDeathsGoal extends CollectionGoal { @@ -22,14 +21,14 @@ public CollectMostDeathsGoal() { setCategory(SettingCategory.SCORE_POINTS); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.LAVA_BUCKET, Message.forName("item-most-deaths-goal")); } @EventHandler - public void onDeath(@Nonnull PlayerDeathEvent event) { + public void onDeath(@NotNull PlayerDeathEvent event) { if (!shouldExecuteEffect()) return; EntityDamageEvent lastCause = event.getEntity().getLastDamageCause(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java index acaca9793..6e10ba9a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java @@ -10,8 +10,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerExpChangeEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class CollectMostExpGoal extends PointsGoal { @@ -21,20 +20,20 @@ public CollectMostExpGoal() { setCategory(SettingCategory.SCORE_POINTS); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-most-xp-goal")); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onExpChange(@Nonnull PlayerExpChangeEvent event) { + public void onExpChange(@NotNull PlayerExpChangeEvent event) { if (!shouldExecuteEffect()) return; collect(event.getPlayer(), event.getAmount()); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { + public void onPlayerDeath(@NotNull PlayerDeathEvent event) { if (!shouldExecuteEffect()) return; event.setKeepLevel(true); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java index 79a48eca9..d45111b83 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java @@ -15,8 +15,7 @@ import org.bukkit.event.entity.EntityPickupItemEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.ItemStack; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class CollectMostItemsGoal extends CollectionGoal { @@ -25,14 +24,14 @@ public CollectMostItemsGoal() { setCategory(SettingCategory.SCORE_POINTS); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.STICK, Message.forName("item-most-items-goal")); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPickUp(@Nonnull EntityPickupItemEvent event) { + public void onPickUp(@NotNull EntityPickupItemEvent event) { if (!isEnabled()) return; if (!(event.getEntity() instanceof Player)) return; @@ -42,7 +41,7 @@ public void onPickUp(@Nonnull EntityPickupItemEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onClick(@Nonnull InventoryClickEvent event) { + public void onClick(@NotNull InventoryClickEvent event) { if (!shouldExecuteEffect()) return; if (!(event.getWhoClicked() instanceof Player)) return; @@ -54,7 +53,7 @@ public void onClick(@Nonnull InventoryClickEvent event) { handleNewItem(item.getType(), player); } - protected void handleNewItem(@Nonnull Material material, @Nonnull Player player) { + protected void handleNewItem(@NotNull Material material, @NotNull Player player) { collect(player, material, () -> { Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); SoundSample.PLING.play(player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java index 462b7d395..489592629 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java @@ -17,8 +17,7 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class CollectWoodGoal extends SettingModifierCollectionGoal { @@ -33,13 +32,13 @@ public CollectWoodGoal() { setCategory(SettingCategory.FASTEST_TIME); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.GOLDEN_AXE, Message.forName("item-collect-wood-goal")); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { if (!newNether) return DefaultItem.enabled(); @@ -51,7 +50,7 @@ public ItemBuilder createSettingsItem() { } @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + public void handleClick(@NotNull ChallengeMenuClickInfo info) { if (!newNether && info.isLowerItemClick() && enabled) { setEnabled(false); SoundSample.playStatusSound(info.getPlayer(), enabled); @@ -74,7 +73,7 @@ protected void onValueChange() { checkCollects(); } - @Nonnull + @NotNull private Object[] getWoodMaterials() { return new ListBuilder().fill(builder -> { for (Material material : ExperimentalUtils.getMaterials()) { @@ -84,22 +83,22 @@ private Object[] getWoodMaterials() { }).build().toArray(); } - private boolean isLog(@Nonnull Material material) { + private boolean isLog(@NotNull Material material) { return material.name().contains("LOG") && !material.name().contains("STRIPPED"); } - private boolean isNetherLog(@Nonnull Material material) { + private boolean isNetherLog(@NotNull Material material) { return material == Material.WARPED_STEM || material == Material.CRIMSON_STEM; } - private boolean isSearched(@Nonnull Material material) { + private boolean isSearched(@NotNull Material material) { return getValue() == OVERWORLD && isLog(material) || getValue() == NETHER && isNetherLog(material) || getValue() == BOTH && (isLog(material) || isNetherLog(material)); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPickupItem(@Nonnull PlayerPickupItemEvent event) { + public void onPickupItem(@NotNull PlayerPickupItemEvent event) { if (!shouldExecuteEffect()) return; Material material = event.getItem().getItemStack().getType(); Player player = event.getPlayer(); @@ -107,7 +106,7 @@ public void onPickupItem(@Nonnull PlayerPickupItemEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + public void onPlayerInventoryClick(@NotNull PlayerInventoryClickEvent event) { if (!shouldExecuteEffect()) return; if (event.isCancelled()) return; if (event.getClickedInventory() == null) return; @@ -118,7 +117,7 @@ public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { handleCollect(player, material); } - private void handleCollect(@Nonnull Player player, @Nonnull Material material) { + private void handleCollect(@NotNull Player player, @NotNull Material material) { collect(player, material, () -> { Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); SoundSample.PLING.play(player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java index 970cf6ff4..be3648a6b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java @@ -15,8 +15,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.raid.RaidFinishEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.List; @Since("2.0") @@ -29,18 +29,18 @@ public FinishRaidGoal() { } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.CROSSBOW, Message.forName("item-finish-raid-goal")); } @Override - public void getWinnersOnEnd(@Nonnull List winners) { + public void getWinnersOnEnd(@NotNull List winners) { } @EventHandler(priority = EventPriority.HIGH) - public void onRaidFinish(@Nonnull RaidFinishEvent event) { + public void onRaidFinish(@NotNull RaidFinishEvent event) { if (!shouldExecuteEffect()) return; if (event.getRaid().getStatus() != RaidStatus.VICTORY) return; ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, event::getWinners); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java index cb582ec83..b237c8c54 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java @@ -12,8 +12,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.List; @Since("2.0") @@ -26,14 +26,14 @@ public FirstOneToDieGoal() { setCategory(SettingCategory.FASTEST_TIME); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-first-one-to-die-goal")); } @Override - public void getWinnersOnEnd(@Nonnull List winners) { + public void getWinnersOnEnd(@NotNull List winners) { if (winner != null) winners.add(winner); } @@ -44,7 +44,7 @@ protected void onDisable() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onDeath(@Nonnull PlayerDeathEvent event) { + public void onDeath(@NotNull PlayerDeathEvent event) { if (!shouldExecuteEffect()) return; winner = event.getEntity(); ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index eb81fb0f1..5513fd239 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -18,8 +18,8 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; import java.util.List; @Since("2.2.0") diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java index 2b6640616..e1281d49a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java @@ -7,8 +7,8 @@ import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.EntityType; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Arrays; @Since("2.0") @@ -24,7 +24,7 @@ public Message getBossbarMessage() { return Message.forName("bossbar-kill-all-bosses"); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.DIAMOND_SWORD, Message.forName("item-all-bosses-goal")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java index 4e20f659b..a466bbb5d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java @@ -9,8 +9,8 @@ import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.EntityType; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Arrays; @Since("2.2.0") @@ -27,7 +27,7 @@ public Message getBossbarMessage() { return Message.forName("bossbar-kill-all-bosses"); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.NETHERITE_SWORD, Message.forName("item-all-bosses-new-goal")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java index 311a93954..d04c79afd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java @@ -9,8 +9,7 @@ import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class KillElderGuardianGoal extends KillEntityGoal { @@ -20,13 +19,13 @@ public KillElderGuardianGoal() { setCategory(SettingCategory.KILL_ENTITY); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.PRISMARINE_SHARD, Message.forName("item-elder-guardian-goal")); } - @Nonnull + @NotNull @Override public SoundSample getStartSound() { return new SoundSample().addSound(Sound.ENTITY_ELDER_GUARDIAN_CURSE, 1); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java index e7a6a4238..36af39651 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java @@ -8,9 +8,8 @@ import org.bukkit.Material; import org.bukkit.World.Environment; import org.bukkit.entity.EntityType; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class KillEnderDragonGoal extends KillEntityGoal { @@ -26,7 +25,7 @@ public SoundSample getWinSound() { return null; } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.DRAGON_EGG, Message.forName("item-dragon-goal")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java index 56ce69182..0badc6037 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java @@ -9,8 +9,7 @@ import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class KillIronGolemGoal extends KillEntityGoal { @@ -21,13 +20,13 @@ public KillIronGolemGoal() { this.killerNeeded = true; } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.IRON_INGOT, Message.forName("item-iron-golem-goal")); } - @Nonnull + @NotNull @Override public SoundSample getStartSound() { return new SoundSample().addSound(Sound.ENTITY_IRON_GOLEM_HURT, 1); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java index 606e9d077..b070346bb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java @@ -9,8 +9,7 @@ import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.Sound; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class KillSnowGolemGoal extends KillEntityGoal { @@ -21,13 +20,13 @@ public KillSnowGolemGoal() { this.killerNeeded = true; } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.SNOWBALL, Message.forName("item-snow-golem-goal")); } - @Nonnull + @NotNull @Override public SoundSample getStartSound() { return new SoundSample().addSound(Sound.ENTITY_SNOW_GOLEM_DEATH, 1); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java index 41d975a97..f9bdd0bfe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java @@ -11,8 +11,7 @@ import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.2.0") @RequireVersion(MinecraftVersion.V1_19) @@ -23,13 +22,13 @@ public KillWardenGoal() { setCategory(SettingCategory.KILL_ENTITY); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.ECHO_SHARD, Message.forName("item-warden-goal")); } - @Nonnull + @NotNull @Override public SoundSample getStartSound() { return new SoundSample().addSound(Sound.ENTITY_WARDEN_EMERGE, 0.2f); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java index c16fdc86c..44aec66b7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java @@ -8,8 +8,7 @@ import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class KillWitherGoal extends KillEntityGoal { @@ -18,13 +17,13 @@ public KillWitherGoal() { setCategory(SettingCategory.KILL_ENTITY); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.NETHER_STAR, Message.forName("item-wither-goal")); } - @Nonnull + @NotNull @Override public SoundSample getStartSound() { return new SoundSample().addSound(Sound.ENTITY_WITHER_SPAWN, 1); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java index 4a686f4fb..a7f09c5cf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java @@ -14,8 +14,8 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.List; @Since("2.0") @@ -23,27 +23,27 @@ public class LastManStandingGoal extends SettingGoal { private Player winner; - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.IRON_HELMET, Message.forName("item-last-man-standing-goal")); } @Override - public void getWinnersOnEnd(@Nonnull List winners) { + public void getWinnersOnEnd(@NotNull List winners) { determineWinner(); if (winner != null) winners.add(winner); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { + public void onPlayerDeath(@NotNull PlayerDeathEvent event) { if (!isEnabled()) return; checkEnd(); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onLeave(@Nonnull PlayerQuitEvent event) { + public void onLeave(@NotNull PlayerQuitEvent event) { if (!isEnabled()) return; checkEnd(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java index 09cfad354..5cfcb11f9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java @@ -8,8 +8,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.block.BlockBreakEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class MineMostBlocksGoal extends PointsGoal { @@ -18,14 +17,14 @@ public MineMostBlocksGoal() { setCategory(SettingCategory.SCORE_POINTS); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-mine-most-blocks-goal")); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { + public void onBlockBreak(@NotNull BlockBreakEvent event) { if (!isEnabled()) return; if (event.getBlock().isPassable()) return; collect(event.getPlayer()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java index 74c28a5f1..b9f755bf3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java @@ -15,8 +15,7 @@ import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0.2") public class MostEmeraldsGoal extends PointsGoal { @@ -26,7 +25,7 @@ public MostEmeraldsGoal() { setCategory(SettingCategory.SCORE_POINTS); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.EMERALD, Message.forName("item-most-emeralds-goal")); @@ -38,14 +37,14 @@ protected void onEnable() { super.onEnable(); } - private void updatePoints(@Nonnull Player player) { + private void updatePoints(@NotNull Player player) { Bukkit.getScheduler().runTask(plugin, () -> { int count = getEmeraldsCount(player); setPoints(player.getUniqueId(), count); }); } - private int getEmeraldsCount(@Nonnull Player player) { + private int getEmeraldsCount(@NotNull Player player) { PlayerInventory inventory = player.getInventory(); int count = 0; for (ItemStack itemStack : inventory.getContents()) { @@ -58,7 +57,7 @@ private int getEmeraldsCount(@Nonnull Player player) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUpdate(@Nonnull InventoryClickEvent event) { + public void onUpdate(@NotNull InventoryClickEvent event) { if (!shouldExecuteEffect()) return; if (!(event.getWhoClicked() instanceof Player)) return; Player player = (Player) event.getWhoClicked(); @@ -67,14 +66,14 @@ public void onUpdate(@Nonnull InventoryClickEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUpdate(@Nonnull PlayerPickupItemEvent event) { + public void onUpdate(@NotNull PlayerPickupItemEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; updatePoints(event.getPlayer()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUpdate(@Nonnull PlayerDropItemEvent event) { + public void onUpdate(@NotNull PlayerDropItemEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; updatePoints(event.getPlayer()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java index 4a359c706..976936bfa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java @@ -14,8 +14,6 @@ import org.bukkit.event.block.BlockPlaceEvent; import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; - @Since("2.1.1") public class MostOresGoal extends PointsGoal { @@ -58,7 +56,7 @@ private int getPointsForOre(Material material) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUpdate(@Nonnull BlockBreakEvent event) { + public void onUpdate(@NotNull BlockBreakEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; int points = getPointsForOre(event.getBlock().getType()); @@ -70,7 +68,7 @@ public void onUpdate(@Nonnull BlockBreakEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUpdate(@Nonnull BlockPlaceEvent event) { + public void onUpdate(@NotNull BlockPlaceEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; int points = getPointsForOre(event.getBlock().getType()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java index 722351c55..a2078bb93 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java @@ -29,7 +29,6 @@ import org.bukkit.event.entity.EntityDeathEvent; import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.*; import java.util.function.Function; @@ -244,7 +243,7 @@ public Function> getRandomTarget() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onKill(@Nonnull EntityDeathEvent event) { + public void onKill(@NotNull EntityDeathEvent event) { if (!shouldExecuteEffect()) return; LivingEntity entity = event.getEntity(); Player killer = entity.getKiller(); @@ -259,7 +258,7 @@ public void onKill(@Nonnull EntityDeathEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { + public void onDamage(@NotNull EntityDamageEvent event) { if (!shouldExecuteEffect()) return; if (!(event.getEntity() instanceof Player)) return; Player player = (Player) event.getEntity(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java index 949179a96..93ee186b3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java @@ -13,7 +13,6 @@ import org.bukkit.event.entity.EntityDamageEvent; import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.List; import java.util.stream.Collectors; @@ -60,7 +59,7 @@ protected boolean shouldRegisterDupedTargetsSetting() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { + public void onDamage(@NotNull EntityDamageEvent event) { if (!shouldExecuteEffect()) return; if (!(event.getEntity() instanceof Player)) return; Player player = (Player) event.getEntity(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java index 8c6cc344f..4f6273580 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java @@ -15,7 +15,6 @@ import org.bukkit.event.entity.EntityDeathEvent; import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.List; import java.util.stream.Collectors; @@ -54,7 +53,7 @@ public List getListFromDocument(Document document, String path) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onKill(@Nonnull EntityDeathEvent event) { + public void onKill(@NotNull EntityDeathEvent event) { if (!shouldExecuteEffect()) return; LivingEntity entity = event.getEntity(); Player killer = entity.getKiller(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java index a09668c43..c4528c95e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java @@ -17,7 +17,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Arrays; public class BlockMaterialSetting extends Setting { @@ -27,7 +26,7 @@ public class BlockMaterialSetting extends Setting { private final Object[] replacements; private final Material[] materials; - public BlockMaterialSetting(@Nonnull String name, @Nonnull ItemBuilder preset, @Nonnull Object[] replacements, @Nonnull Material... materials) { + public BlockMaterialSetting(@NotNull String name, @NotNull ItemBuilder preset, @NotNull Object[] replacements, @NotNull Material... materials) { super(MenuType.ITEMS, true); this.name = name; this.preset = preset; @@ -35,7 +34,7 @@ public BlockMaterialSetting(@Nonnull String name, @Nonnull ItemBuilder preset, @ this.materials = materials; } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return preset.clone().applyFormat(Message.forName(name).asItemDescription(replacements)); @@ -46,7 +45,7 @@ private boolean blockMaterial(Material material) { } @EventHandler(priority = EventPriority.HIGH) - public void onPlayerInteract(@Nonnull PlayerInteractEvent event) { + public void onPlayerInteract(@NotNull PlayerInteractEvent event) { if (isEnabled()) return; if (ChallengeAPI.isWorldInUse()) return; if (ignorePlayer(event.getPlayer())) return; @@ -62,7 +61,7 @@ public void onPlayerInteract(@Nonnull PlayerInteractEvent event) { } @EventHandler(priority = EventPriority.HIGH) - public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + public void onPlayerInventoryClick(@NotNull PlayerInventoryClickEvent event) { if (isEnabled()) return; if (ignorePlayer(event.getPlayer())) return; if (ChallengeAPI.isWorldInUse()) return; @@ -76,7 +75,7 @@ public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerPickupItem(@Nonnull PlayerPickupItemEvent event) { + public void onPlayerPickupItem(@NotNull PlayerPickupItemEvent event) { if (isEnabled()) return; if (ignorePlayer(event.getPlayer())) return; if (ChallengeAPI.isWorldInUse()) return; @@ -84,7 +83,7 @@ public void onPlayerPickupItem(@Nonnull PlayerPickupItemEvent event) { event.setCancelled(true); } - public void dropMaterial(@Nonnull Location location, @Nonnull Inventory inventory) { + public void dropMaterial(@NotNull Location location, @NotNull Inventory inventory) { for (int slot = 0; slot < inventory.getSize(); slot++) { ItemStack item = inventory.getItem(slot); if (item == null) continue; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java index 3835b6613..bb39d96f5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java @@ -20,8 +20,8 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.io.IOException; import java.util.HashMap; import java.util.Map; @@ -42,13 +42,13 @@ public BackpackSetting() { sharedBackpack = createInventory("§5Team Backpack"); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.CHEST, Message.forName("item-backpack-setting")); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { if (getValue() == SHARED) @@ -72,7 +72,7 @@ public void playValueChangeTitle() { } @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) { + public void onCommand(@NotNull Player player, @NotNull String[] args) { if (ChallengeAPI.isPaused()) { Message.forName("timer-not-started").send(player, Prefix.BACKPACK); SoundSample.BASS_OFF.play(player); @@ -96,7 +96,7 @@ public void onCommand(@Nonnull Player player, @Nonnull String[] args) { } @Override - public void loadGameState(@Nonnull Document document) { + public void loadGameState(@NotNull Document document) { super.loadGameState(document); loadChecked(document, "shared", sharedBackpack); @@ -108,7 +108,7 @@ public void loadGameState(@Nonnull Document document) { } - protected void loadChecked(@Nonnull Document document, @Nonnull String key, @Nonnull Inventory inventory) { + protected void loadChecked(@NotNull Document document, @NotNull String key, @NotNull Inventory inventory) { if (document.isDocument(key)) { loadLegacy(document.getDocument(key), inventory); @@ -124,7 +124,7 @@ protected void loadChecked(@Nonnull Document document, @Nonnull String key, @Non } - protected void loadLegacy(@Nonnull Document document, @Nonnull Inventory inventory) { + protected void loadLegacy(@NotNull Document document, @NotNull Inventory inventory) { for (String key : document.keys()) { try { @@ -137,7 +137,7 @@ protected void loadLegacy(@Nonnull Document document, @Nonnull Inventory invento } @Override - public void writeGameState(@Nonnull Document document) { + public void writeGameState(@NotNull Document document) { super.writeGameState(document); write(document, "shared", sharedBackpack); @@ -148,17 +148,17 @@ public void writeGameState(@Nonnull Document document) { }); } - protected void write(@Nonnull Document document, @Nonnull String key, @Nonnull Inventory inventory) { + protected void write(@NotNull Document document, @NotNull String key, @NotNull Inventory inventory) { document.set(key, BukkitSerialization.toBase64(inventory)); } - @Nonnull - protected Inventory createInventory(@Nonnull String title) { + @NotNull + protected Inventory createInventory(@NotNull String title) { return Bukkit.createInventory(null, size, InventoryTitleManager.getTitle(title)); } - @Nonnull - protected Inventory getCurrentBackpack(@Nonnull Player player) { + @NotNull + protected Inventory getCurrentBackpack(@NotNull Player player) { return (getValue() == SHARED) ? sharedBackpack : backpacks.computeIfAbsent(player.getUniqueId(), key -> createInventory("§6Backpack")); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java index 1fcf74c13..2aca8175b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java @@ -10,8 +10,8 @@ import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.StructureType; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Arrays; import java.util.stream.Collectors; @@ -24,7 +24,7 @@ public BastionSpawnSetting() { Arrays.stream(ExperimentalUtils.getMaterials()).filter(material -> material.name().contains("BASALT")).collect(Collectors.toList())); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.POLISHED_BLACKSTONE_BRICKS, Message.forName("item-bastion-spawn-setting")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java index a56afac9c..f7a18a17b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java @@ -23,8 +23,8 @@ import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; @@ -55,7 +55,7 @@ public CutCleanSetting() { new CookFoodSubSetting(() -> new ItemBuilder(Material.COOKED_BEEF, Message.forName("item-cut-clean-food-setting")), true)); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.IRON_AXE, Message.forName("item-cut-clean-setting")); @@ -67,11 +67,11 @@ protected boolean directIntoInventory() { private class DirectIntoInventorySubSetting extends BooleanSubSetting { - public DirectIntoInventorySubSetting(@Nonnull Supplier item) { + public DirectIntoInventorySubSetting(@NotNull Supplier item) { super(item); } - @Nonnull + @NotNull @Override public BooleanSubSetting setEnabled(boolean enabled) { return super.setEnabled(enabled); @@ -84,8 +84,8 @@ private class ConvertDropSubSetting extends BooleanSubSetting { protected final Material[] from; protected final Material to; - public ConvertDropSubSetting(@Nonnull Supplier item, boolean enabledByDefault, - @Nonnull Material to, @Nonnull String... from) { + public ConvertDropSubSetting(@NotNull Supplier item, boolean enabledByDefault, + @NotNull Material to, @NotNull String... from) { super(item, enabledByDefault); List materials = new ArrayList<>(); @@ -117,7 +117,7 @@ public void onDisable() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { + public void onBlockBreak(@NotNull BlockBreakEvent event) { if (!shouldExecuteEffect()) return; if (!directIntoInventory()) return; if (!event.isDropItems()) return; @@ -137,12 +137,12 @@ public void onBlockBreak(@Nonnull BlockBreakEvent event) { private class BreakOreVeinsSubSetting extends NumberAndBooleanSubSetting { - public BreakOreVeinsSubSetting(@Nonnull Supplier item, int min, int max) { + public BreakOreVeinsSubSetting(@NotNull Supplier item, int min, int max) { super(item, min, max); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { + public void onBlockBreak(@NotNull BlockBreakEvent event) { if (!shouldExecuteEffect()) return; ItemStack itemInMainHand = event.getPlayer().getInventory().getItemInMainHand(); if (!canBeBroken(event.getBlock(), itemInMainHand)) return; @@ -151,7 +151,7 @@ public void onBlockBreak(@Nonnull BlockBreakEvent event) { breakBlockVein(event.getPlayer(), event.getBlock(), itemInMainHand); } - private void breakBlockVein(@Nonnull Player player, @Nonnull Block block, @Nonnull ItemStack tool) { + private void breakBlockVein(@NotNull Player player, @NotNull Block block, @NotNull ItemStack tool) { Material material = block.getType(); List allBlocks = new ArrayList<>(); @@ -197,11 +197,11 @@ private void breakBlockVein(@Nonnull Player player, @Nonnull Block block, @Nonnu } - private boolean canBeBroken(@Nonnull Block block, @Nonnull ItemStack tool) { + private boolean canBeBroken(@NotNull Block block, @NotNull ItemStack tool) { return !block.getDrops(tool).isEmpty(); } - @Nonnull + @NotNull @Override public ItemBuilder getSettingsItem() { return getAsBoolean() ? DefaultItem.value(getValue(), "§7Max Vein Size: §e") : DefaultItem.disabled(); @@ -211,12 +211,12 @@ public ItemBuilder getSettingsItem() { private class CookFoodSubSetting extends BooleanSubSetting { - public CookFoodSubSetting(@Nonnull Supplier item, boolean enabledByDefault) { + public CookFoodSubSetting(@NotNull Supplier item, boolean enabledByDefault) { super(item, enabledByDefault); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityKill(@Nonnull EntityDeathEvent event) { + public void onEntityKill(@NotNull EntityDeathEvent event) { if (!isEnabled()) return; event.getDrops().replaceAll(item -> new ItemBuilder(ItemUtils.convertFoodToCookedFood(item.getType())).amount(item.getAmount()).build()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java index f16116bdd..3332fbfa4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java @@ -20,8 +20,7 @@ import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.projectiles.ProjectileSource; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class DamageDisplaySetting extends Setting { @@ -29,7 +28,7 @@ public DamageDisplaySetting() { super(MenuType.SETTINGS, true); } - public static String getCause(@Nonnull EntityDamageEvent event) { + public static String getCause(@NotNull EntityDamageEvent event) { if (event.getCause() == DamageCause.CUSTOM) return Message.forName("undefined").asString(); String cause = StringUtils.getEnumName(event.getCause()); @@ -67,7 +66,7 @@ public static String getCause(@Nonnull EntityDamageEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { + public void onDamage(@NotNull EntityDamageEvent event) { if (ChallengeAPI.isPaused() || event.getCause() == DamageCause.CUSTOM || !isEnabled()) return; if (!(event.getEntity() instanceof Player)) return; @@ -78,7 +77,7 @@ public void onDamage(@Nonnull EntityDamageEvent event) { Message.forName("player-damage-display").broadcast(Prefix.DAMAGE, NameHelper.getName((Player) event.getEntity()), damageDisplay, getCause(event)); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.COMMAND_BLOCK, Message.forName("item-damage-display-setting")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java index 2841569f9..f78a94486 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java @@ -11,8 +11,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class DamageMultiplierModifier extends Modifier { @@ -20,20 +19,20 @@ public DamageMultiplierModifier() { super(MenuType.SETTINGS, 10); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-damage-setting")); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { return DefaultItem.value(getValue()).appendName("x"); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { + public void onDamage(@NotNull EntityDamageEvent event) { if (!(event.getEntity() instanceof Player)) return; event.setDamage(event.getDamage() * getValue()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java index 96feb5592..783124b1b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java @@ -17,8 +17,7 @@ import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.PlayerDeathEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class DeathMessageSetting extends Modifier { @@ -31,13 +30,13 @@ public DeathMessageSetting() { super(MenuType.SETTINGS, 1, 3, 2); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.BOW, Message.forName("item-death-message-setting")); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { switch (getValue()) { @@ -65,7 +64,7 @@ public void playValueChangeTitle() { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onDeath(@Nonnull PlayerDeathEvent event) { + public void onDeath(@NotNull PlayerDeathEvent event) { event.setDeathMessage(null); if (hide) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java index d1eca389f..a85ea9e24 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java @@ -11,8 +11,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class DeathPositionSetting extends Setting { @@ -24,7 +23,7 @@ public DeathPositionSetting() { } @EventHandler(priority = EventPriority.LOWEST) - public void onDeath(@Nonnull PlayerDeathEvent event) { + public void onDeath(@NotNull PlayerDeathEvent event) { if (!shouldExecuteEffect()) return; int index = 1; @@ -36,7 +35,7 @@ public void onDeath(@Nonnull PlayerDeathEvent event) { } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.MUSIC_DISC_11, Message.forName("item-death-position-setting")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java index 80ebdf9d4..38366644c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java @@ -23,9 +23,9 @@ import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -41,13 +41,13 @@ protected void onValueChange() { setDifficulty(getDifficultyByValue(getValue())); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.GLISTERING_MELON_SLICE, Message.forName("item-difficulty-setting")); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { switch (getValue()) { @@ -78,20 +78,20 @@ private void setDifficulty(Difficulty difficulty) { } } - @Nonnull + @NotNull private Difficulty getCurrentDifficulty() { return Bukkit.getWorlds().isEmpty() ? Difficulty.NORMAL : ChallengeAPI.getGameWorld(Environment.NORMAL) .getDifficulty(); } - @Nonnull + @NotNull private Difficulty getDifficultyByValue(int value) { Difficulty difficulty = Difficulty.values()[value]; return difficulty == null ? Difficulty.NORMAL : difficulty; } @Override - public void loadSettings(@Nonnull Document document) { + public void loadSettings(@NotNull Document document) { if (!document.contains("value")) setValue(getCurrentDifficulty().ordinal()); @@ -99,7 +99,7 @@ public void loadSettings(@Nonnull Document document) { } @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (args.length == 0) { Message.forName("command-difficulty-current").send(sender, Prefix.CHALLENGES, getDifficultyComponent()); @@ -138,12 +138,12 @@ private BaseComponent getDifficultyComponent() { @Nullable @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String alias, @Nonnull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { if (args.length > 1) return new ArrayList<>(); return Arrays.asList("peaceful", "easy", "normal", "hard"); } - private int getDifficultyValue(@Nonnull String input) { + private int getDifficultyValue(@NotNull String input) { switch (input.toLowerCase()) { case "peaceful": diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java index 9f8a5b96b..9d59a29d6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java @@ -10,8 +10,7 @@ import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.Player; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class EnderChestCommandSetting extends Setting implements PlayerCommand { @@ -20,14 +19,14 @@ public EnderChestCommandSetting() { super(MenuType.SETTINGS); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.ENDER_CHEST, Message.forName("item-enderchest-command-setting")); } @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (!isEnabled() || ChallengeAPI.isWorldInUse()) { Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java index 5fa357f75..376eb06f5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java @@ -7,8 +7,7 @@ import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.StructureType; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class FortressSpawnSetting extends NetherPortalSpawnSetting { @@ -17,7 +16,7 @@ public FortressSpawnSetting() { super(MenuType.SETTINGS, StructureType.NETHER_FORTRESS, "unable-to-find-fortress", Material.NETHER_BRICKS); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.NETHER_BRICK_STAIRS, Message.forName("item-fortress-spawn-setting")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java index 33e30529e..4a74c4998 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java @@ -13,8 +13,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.scoreboard.*; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class HealthDisplaySetting extends Setting { @@ -25,7 +24,7 @@ public HealthDisplaySetting() { super(MenuType.SETTINGS, true); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.RED_STAINED_GLASS, Message.forName("item-health-display-setting")); @@ -42,7 +41,7 @@ protected void onDisable() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onJoin(@Nonnull PlayerJoinEvent event) { + public void onJoin(@NotNull PlayerJoinEvent event) { if (isEnabled()) { show(event.getPlayer()); } else { @@ -50,7 +49,7 @@ public void onJoin(@Nonnull PlayerJoinEvent event) { } } - private void show(@Nonnull Player player) { + private void show(@NotNull Player player) { Scoreboard scoreboard = player.getScoreboard(); ScoreboardManager manager = Bukkit.getScoreboardManager(); if (manager == null) return; @@ -73,7 +72,7 @@ private void show(@Nonnull Player player) { } - private void hide(@Nonnull Player player) { + private void hide(@NotNull Player player) { Scoreboard scoreboard = player.getScoreboard(); Objective objective = scoreboard.getObjective(OBJECTIVE_NAME); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java index c5553bb88..217f6362b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java @@ -12,8 +12,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class ImmediateRespawnSetting extends Setting { @@ -24,7 +23,7 @@ public ImmediateRespawnSetting() { super(MenuType.SETTINGS); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.GOLDEN_APPLE, Message.forName("item-immediate-respawn-setting")); @@ -58,7 +57,7 @@ protected void onDisable() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { + public void onPlayerDeath(@NotNull PlayerDeathEvent event) { if (!isEnabled()) return; if (!respawnWithEvent) return; Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> event.getEntity().spigot().respawn(), 1); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java index dac4723cd..70ad1c808 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java @@ -8,8 +8,7 @@ import org.bukkit.GameRule; import org.bukkit.Material; import org.bukkit.World; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class KeepInventorySetting extends Setting { @@ -17,7 +16,7 @@ public KeepInventorySetting() { super(MenuType.SETTINGS); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.ENDER_EYE, Message.forName("item-keep-inventory-setting")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java index f91ef2290..c3b20a56d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java @@ -9,8 +9,8 @@ import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Objects; public class LanguageSetting extends Modifier { @@ -25,13 +25,13 @@ public LanguageSetting() { super(MenuType.SETTINGS, 1, 2, ENGLISH); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.KNOWLEDGE_BOOK, Message.forName("item-language-setting")); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { String texture = getValue() == GERMAN ? GERMAN_SKULL : ENGLISH_SKULL; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index 116c77d08..4d36cc1ce 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -17,8 +17,6 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; - public class MaxHealthSetting extends Modifier { /** @@ -33,13 +31,13 @@ public MaxHealthSetting() { super(MenuType.SETTINGS, 1, 200 * 2, 20); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(MaterialWrapper.RED_DYE, Message.forName("item-max-health-setting")); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { return DefaultItem.value(getValue(), "§e").appendName(" §7HP §8(§e" + (getValue() / 2f) + " §c❤§8)"); @@ -69,7 +67,7 @@ public void playValueChangeTitle() { } @EventHandler - public void onJoin(@Nonnull PlayerJoinEvent event) { + public void onJoin(@NotNull PlayerJoinEvent event) { updateHealth(event.getPlayer()); } @@ -118,4 +116,3 @@ public void addHealth(Player player, int health) { } } - diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java index 1a6180b08..2f3836178 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java @@ -8,8 +8,7 @@ import org.bukkit.GameRule; import org.bukkit.Material; import org.bukkit.World; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class MobGriefingSetting extends Setting { @@ -17,7 +16,7 @@ public MobGriefingSetting() { super(MenuType.SETTINGS); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.CREEPER_HEAD, Message.forName("item-mob-griefing-setting")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java index 7ac0f95a9..929fc27f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java @@ -11,8 +11,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class NoHitDelaySetting extends Setting { @@ -21,7 +20,7 @@ public NoHitDelaySetting() { } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onDamageByEntity(@Nonnull EntityDamageEvent event) { + public void onDamageByEntity(@NotNull EntityDamageEvent event) { if (!(event.getEntity() instanceof LivingEntity)) return; if (!shouldExecuteEffect()) return; Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { @@ -29,7 +28,7 @@ public void onDamageByEntity(@Nonnull EntityDamageEvent event) { }, 1); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.FEATHER, Message.forName("item-no-hit-delay-setting")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java index a7e2ced01..c4e4f68b1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java @@ -8,8 +8,7 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.entity.FoodLevelChangeEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class NoHungerSetting extends Setting { @@ -22,21 +21,21 @@ protected void onEnable() { broadcastFiltered(this::feedPlayer); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.BREAD, Message.forName("no-hunger-setting")); } @EventHandler(ignoreCancelled = true) - public void onHunger(@Nonnull FoodLevelChangeEvent event) { + public void onHunger(@NotNull FoodLevelChangeEvent event) { if (!(event.getEntity() instanceof Player)) return; if (!shouldExecuteEffect()) return; feedPlayer(((Player) event.getEntity())); event.setCancelled(true); } - private void feedPlayer(@Nonnull Player player) { + private void feedPlayer(@NotNull Player player) { player.setFoodLevel(20); player.setSaturation(20); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java index 3c57403c8..cd20e492d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java @@ -7,8 +7,7 @@ import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerItemDamageEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class NoItemDamageSetting extends Setting { @@ -25,7 +24,7 @@ public void onItemDamage(PlayerItemDamageEvent event) { event.getPlayer().updateInventory(); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.ANVIL, Message.forName("item-no-item-damage-setting")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java index 79fd3de5c..c5de2e8b0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java @@ -14,8 +14,7 @@ import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerSwapHandItemsEvent; import org.bukkit.inventory.ItemStack; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class NoOffhandSetting extends Setting { @@ -35,7 +34,7 @@ protected void onEnable() { } } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.SHIELD, Message.forName("item-no-offhand-setting")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java index 43b96aaa3..659f71666 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java @@ -15,8 +15,7 @@ import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class OldPvPSetting extends Setting { @@ -27,7 +26,7 @@ public OldPvPSetting() { super(MenuType.SETTINGS); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.IRON_SWORD, Message.forName("item-old-pvp-setting")); @@ -44,30 +43,30 @@ protected void onEnable() { } @EventHandler - public void onChangeWorldEvent(@Nonnull PlayerChangedWorldEvent event) { + public void onChangeWorldEvent(@NotNull PlayerChangedWorldEvent event) { if (!isEnabled()) return; setAttackSpeed(event.getPlayer(), DISABLED); } @EventHandler - public void onJoin(@Nonnull PlayerJoinEvent event) { + public void onJoin(@NotNull PlayerJoinEvent event) { if (!isEnabled()) return; setAttackSpeed(event.getPlayer(), DISABLED); } @EventHandler - public void onQuit(@Nonnull PlayerQuitEvent event) { + public void onQuit(@NotNull PlayerQuitEvent event) { setAttackSpeed(event.getPlayer(), NORMAL); } @EventHandler - public void onSweepDamage(@Nonnull EntityDamageEvent event) { + public void onSweepDamage(@NotNull EntityDamageEvent event) { if (!isEnabled()) return; if (event.getCause() != DamageCause.ENTITY_SWEEP_ATTACK) return; event.setCancelled(true); } - protected void setAttackSpeed(@Nonnull Player player, double value) { + protected void setAttackSpeed(@NotNull Player player, double value) { AttributeInstance attribute = player.getAttribute(AttributeWrapper.ATTACK_SPEED); if (attribute == null) return; attribute.setBaseValue(value); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java index 5daa22b3d..3d5f02235 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java @@ -12,8 +12,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class OneTeamLifeSetting extends Setting { @@ -23,14 +22,14 @@ public OneTeamLifeSetting() { super(MenuType.SETTINGS, true); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.FIRE_CHARGE, Message.forName("item-one-life-setting")); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDeath(@Nonnull PlayerDeathEvent event) { + public void onDeath(@NotNull PlayerDeathEvent event) { if (!shouldExecuteEffect()) return; if (isKilling) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java index 2d2a688b6..d2929f1e2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java @@ -13,8 +13,7 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class PlayerGlowSetting extends Setting { @@ -23,7 +22,7 @@ public PlayerGlowSetting() { } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.GLASS_BOTTLE, Message.forName("item-glow-setting")); @@ -50,7 +49,7 @@ public void updateEffects() { } @EventHandler - public void onPlayerJoin(@Nonnull PlayerJoinEvent event) { + public void onPlayerJoin(@NotNull PlayerJoinEvent event) { updateEffects(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java index 04770c37a..da4fef55a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java @@ -25,7 +25,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.*; import java.util.Map.Entry; @@ -41,7 +40,7 @@ public PositionSetting() { Challenges.getInstance().registerCommand(new SetPosCommand(), "setposition"); } - public static Environment getWorldEnvironment(@Nonnull String name) { + public static Environment getWorldEnvironment(@NotNull String name) { switch (name.toLowerCase()) { default: return null; @@ -54,14 +53,14 @@ public static Environment getWorldEnvironment(@Nonnull String name) { } } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.BLUE_BANNER, Message.forName("item-position-setting")); } @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) { + public void onCommand(@NotNull Player player, @NotNull String[] args) { if (!isEnabled()) { Message.forName("positions-disabled").send(player, Prefix.POSITION); SoundSample.BASS_OFF.play(player); @@ -110,12 +109,12 @@ public void onCommand(@Nonnull Player player, @Nonnull String[] args) { @Nullable @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String alias, @Nonnull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { if (args.length > 1) return new ArrayList<>(); return Utils.filterRecommendations(args[0], positions.keySet().toArray(new String[0])); } - public String getWorldName(@Nonnull Location location) { + public String getWorldName(@NotNull Location location) { if (location.getWorld() == null) return "?"; switch (location.getWorld().getEnvironment()) { default: @@ -127,15 +126,15 @@ public String getWorldName(@Nonnull Location location) { } } - public boolean containsPosition(@Nonnull String name) { + public boolean containsPosition(@NotNull String name) { return positions.containsKey(name); } - private void broadcastParticleLine(@Nonnull Location location) { + private void broadcastParticleLine(@NotNull Location location) { broadcast(player -> playParticleLine(player, location)); } - private void playParticleLine(@Nonnull Player player, @Nonnull Location position) { + private void playParticleLine(@NotNull Player player, @NotNull Location position) { if (!particleLines) return; if (player.getWorld() != position.getWorld()) return; @@ -152,7 +151,7 @@ private void playParticleLine(@Nonnull Player player, @Nonnull Location position } @Override - public void loadGameState(@Nonnull Document document) { + public void loadGameState(@NotNull Document document) { positions.clear(); for (String name : document.keys()) { positions.put(name, document.getSerializable(name, Location.class)); @@ -160,7 +159,7 @@ public void loadGameState(@Nonnull Document document) { } @Override - public void writeGameState(@Nonnull Document document) { + public void writeGameState(@NotNull Document document) { for (String key : document.keys()) { document.remove(key); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java index 16f50d30a..a2d56e67c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java @@ -11,8 +11,7 @@ import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class PregameMovementSetting extends Setting { @@ -21,7 +20,7 @@ public PregameMovementSetting() { } @EventHandler - public void onMove(@Nonnull PlayerMoveEvent event) { + public void onMove(@NotNull PlayerMoveEvent event) { if (ChallengeAPI.isStarted() || isEnabled()) return; if (event.getPlayer().getGameMode() == GameMode.SPECTATOR || event.getPlayer().getGameMode() == GameMode.CREATIVE) return; @@ -43,12 +42,12 @@ public void onMove(@Nonnull PlayerMoveEvent event) { Message.forName("title-pregame-movement-setting").sendTitleInstant(event.getPlayer()); } - private void findNearestBlock(@Nonnull Location location) { + private void findNearestBlock(@NotNull Location location) { for (; location.getBlockY() > 0 && location.getBlock().isPassable(); location.subtract(0, 1, 0)) ; } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.PISTON, Message.forName("pregame-movement-setting")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java index 5e301e89f..b43339481 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java @@ -8,8 +8,7 @@ import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class PvPSetting extends Setting { @@ -17,14 +16,14 @@ public PvPSetting() { super(MenuType.SETTINGS, true); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-pvp-setting")); } @EventHandler - public void onDamage(@Nonnull EntityDamageByPlayerEvent event) { + public void onDamage(@NotNull EntityDamageByPlayerEvent event) { if (isEnabled()) return; if (!(event.getEntity() instanceof Player)) return; event.setCancelled(true); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java index c4a3b67b0..538be7125 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java @@ -14,8 +14,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class RegenerationSetting extends Modifier { @@ -23,13 +22,13 @@ public RegenerationSetting() { super(MenuType.SETTINGS, 1, 3, 2); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new PotionBuilder(Material.POTION, Message.forName("item-regeneration-setting")).color(Color.RED); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { if (getValue() == 1) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java index 3fbd01b29..d5d80f470 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java @@ -18,8 +18,8 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerRespawnEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -31,14 +31,14 @@ public RespawnSetting() { super(MenuType.SETTINGS); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.RED_BED, Message.forName("item-respawn-setting")); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { + public void onPlayerDeath(@NotNull PlayerDeathEvent event) { Player player = event.getEntity(); if (isEnabled()) { SoundSample.DEATH.play(player); @@ -62,7 +62,7 @@ public void checkAllPlayersDead() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onRespawn(@Nonnull PlayerRespawnEvent event) { + public void onRespawn(@NotNull PlayerRespawnEvent event) { if (isEnabled()) return; Player player = event.getPlayer(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java index 56c86ecdb..b2edf6b88 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java @@ -22,8 +22,7 @@ import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerSwapHandItemsEvent; import org.bukkit.inventory.ItemStack; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class SlotLimitSetting extends Modifier { @@ -32,7 +31,7 @@ public SlotLimitSetting() { super(MenuType.SETTINGS, 1, 36, 36); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.BARRIER, Message.forName("item-slot-limit-setting")); @@ -53,7 +52,7 @@ public void update() { Bukkit.getOnlinePlayers().forEach(this::updateSlots); } - private void updateSlots(@Nonnull Player player) { + private void updateSlots(@NotNull Player player) { for (int i = 0; i < 36; i++) { if (ignorePlayer(player)) { unBlockSlot(player, i); @@ -81,7 +80,7 @@ private boolean isBlocked(int slot) { return slot > value; } - private void blockSlot(@Nonnull Player player, int slot) { + private void blockSlot(@NotNull Player player, int slot) { if (ignorePlayer(player)) return; ItemStack item = player.getInventory().getItem(slot); @@ -97,7 +96,7 @@ private void blockSlot(@Nonnull Player player, int slot) { player.getInventory().setItem(slot, ItemBuilder.BLOCKED_ITEM); } - private void unBlockSlot(@Nonnull Player player, int slot) { + private void unBlockSlot(@NotNull Player player, int slot) { ItemStack item = player.getInventory().getItem(slot); if (item != null && item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { player.getInventory().setItem(slot, null); @@ -105,7 +104,7 @@ private void unBlockSlot(@Nonnull Player player, int slot) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + public void onPlayerInventoryClick(@NotNull PlayerInventoryClickEvent event) { if (!shouldExecuteEffect()) return; if (event.getClickedInventory() == null) return; if (event.getClickedInventory().getType() != InventoryType.PLAYER) return; @@ -115,7 +114,7 @@ public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { + public void onPlayerDropItem(@NotNull PlayerDropItemEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (!event.getItemDrop().getItemStack().isSimilar(ItemBuilder.BLOCKED_ITEM)) return; @@ -123,7 +122,7 @@ public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onClick(@Nonnull BlockPlaceEvent event) { + public void onClick(@NotNull BlockPlaceEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (!event.getItemInHand().isSimilar(ItemBuilder.BLOCKED_ITEM)) return; @@ -131,7 +130,7 @@ public void onClick(@Nonnull BlockPlaceEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onSwapItem(@Nonnull PlayerSwapHandItemsEvent event) { + public void onSwapItem(@NotNull PlayerSwapHandItemsEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; @@ -143,7 +142,7 @@ public void onSwapItem(@Nonnull PlayerSwapHandItemsEvent event) { } @EventHandler(priority = EventPriority.HIGH) - public void onPlayerDeath(@Nonnull PlayerDeathEvent event) { + public void onPlayerDeath(@NotNull PlayerDeathEvent event) { event.getDrops().removeIf(itemStack -> itemStack.isSimilar(ItemBuilder.BLOCKED_ITEM)); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java index 0c4e9861a..4bc199d27 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java @@ -13,8 +13,7 @@ import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.potion.PotionEffect; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class SoupSetting extends Setting { @@ -22,7 +21,7 @@ public SoupSetting() { super(MenuType.SETTINGS); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.MUSHROOM_STEW, Message.forName("item-soup-setting")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index 95cf0c17b..2ffd61e64 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -17,9 +17,8 @@ import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.player.PlayerJoinEvent; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class SplitHealthSetting extends Setting { @@ -27,7 +26,7 @@ public SplitHealthSetting() { super(MenuType.SETTINGS); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new PotionBuilder(Material.TIPPED_ARROW, Message.forName("item-split-health-setting")).color(Color.RED); @@ -39,7 +38,7 @@ protected void onEnable() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityRegainHealth(@Nonnull EntityRegainHealthEvent event) { + public void onEntityRegainHealth(@NotNull EntityRegainHealthEvent event) { if (!shouldExecuteEffect()) return; if (!(event.getEntity() instanceof Player)) return; Player player = (Player) event.getEntity(); @@ -59,7 +58,7 @@ public void onDamage(EntityDamageEvent event) { } @EventHandler(priority = EventPriority.HIGH) - public void onJoin(@Nonnull PlayerJoinEvent event) { + public void onJoin(@NotNull PlayerJoinEvent event) { if (ignorePlayer(event.getPlayer())) return; setHealth(); } @@ -80,7 +79,7 @@ private void setHealth() { setHealth(player, null); } - public void setHealth(@Nonnull Player player, @Nullable EntityDamageEvent damageEvent) { + public void setHealth(@NotNull Player player, @Nullable EntityDamageEvent damageEvent) { if (!shouldExecuteEffect()) return; for (Player currentPlayer : Bukkit.getOnlinePlayers()) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java index df36636db..0c0f63541 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java @@ -17,8 +17,8 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -32,13 +32,13 @@ public TimberSetting() { super(MenuType.SETTINGS, 2); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.DIAMOND_AXE, Message.forName("item-timber-setting")); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { if (getValue() == LOGS_LEAVES) @@ -52,7 +52,7 @@ public void playValueChangeTitle() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBreak(@Nonnull BlockBreakEvent event) { + public void onBreak(@NotNull BlockBreakEvent event) { if (!shouldExecuteEffect()) return; if (!isLog(event.getBlock().getType())) return; @@ -78,7 +78,7 @@ public void onBreak(@Nonnull BlockBreakEvent event) { } - private void breakBlock(@Nonnull Block block, @Nonnull ItemStack item, boolean damageItem) { + private void breakBlock(@NotNull Block block, @NotNull ItemStack item, boolean damageItem) { if (isLog(block.getType())) { ChallengeHelper.breakBlock(block, item); if (damageItem) { @@ -89,7 +89,7 @@ private void breakBlock(@Nonnull Block block, @Nonnull ItemStack item, boolean d } } - private List getAllTreeBlocks(@Nonnull Block block, boolean leaves) { + private List getAllTreeBlocks(@NotNull Block block, boolean leaves) { List allBlocks = new ArrayList<>(); List currentBlocks = new ArrayList<>(); @@ -129,7 +129,7 @@ private boolean isLeaves(Material material) { return material.name().endsWith("LEAVES") || material.name().endsWith("WART_BLOCK"); } - public boolean isLeaveMaterial(@Nonnull Material logMaterial, @Nonnull Material leaveMaterial) { + public boolean isLeaveMaterial(@NotNull Material logMaterial, @NotNull Material leaveMaterial) { // Exceptions like nether wood if (logMaterial.name().equals("CRIMSON_STEM")) return leaveMaterial.name().equals("NETHER_WART_BLOCK") || leaveMaterial.name().equals("SHROOMLIGHT"); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java index d53d47855..bd3611a5c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java @@ -13,8 +13,7 @@ import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.entity.Player; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class TopCommandSetting extends Setting implements PlayerCommand { @@ -23,7 +22,7 @@ public TopCommandSetting() { } @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) { + public void onCommand(@NotNull Player player, @NotNull String[] args) { if (!isEnabled()) { Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); SoundSample.BASS_OFF.play(player); @@ -66,7 +65,7 @@ public void onCommand(@Nonnull Player player, @Nonnull String[] args) { } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.MAGENTA_GLAZED_TERRACOTTA, Message.forName("top-command-setting")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java index 1d0c39ec4..d7d05e14f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java @@ -10,8 +10,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityResurrectEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Since("2.0") public class TotemSaveDeathSetting extends Setting { @@ -20,14 +19,14 @@ public TotemSaveDeathSetting() { super(MenuType.SETTINGS); } - @Nonnull + @NotNull @Override public ItemBuilder createDisplayItem() { return new ItemBuilder(Material.TOTEM_OF_UNDYING, Message.forName("item-totem-save-setting")); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityResurrect(@Nonnull EntityResurrectEvent event) { + public void onEntityResurrect(@NotNull EntityResurrectEvent event) { if (ChallengeHelper.isInInstantKill() && !isEnabled()) { event.setCancelled(true); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java index 8b3be4c54..d51dc9156 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java @@ -11,13 +11,11 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; - public class EmptyChallenge implements IChallenge { private final MenuType menuType; - public EmptyChallenge(@Nonnull MenuType menuType) { + public EmptyChallenge(@NotNull MenuType menuType) { this.menuType = menuType; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java index 6ef245016..c540894bb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java @@ -7,9 +7,8 @@ import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.commons.common.config.Document; import org.bukkit.inventory.ItemStack; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public interface IChallenge extends GamestateSaveable { @@ -47,7 +46,7 @@ public interface IChallenge extends GamestateSaveable { * * @return the internal name of this challenge */ - @Nonnull + @NotNull String getUniqueName(); /** @@ -57,22 +56,22 @@ public interface IChallenge extends GamestateSaveable { * * @return the target menu for the challenge */ - @Nonnull + @NotNull MenuType getType(); @Nullable SettingCategory getCategory(); - @Nonnull + @NotNull ItemStack getDisplayItem(); - @Nonnull + @NotNull ItemStack getSettingsItem(); - void handleClick(@Nonnull ChallengeMenuClickInfo info); + void handleClick(@NotNull ChallengeMenuClickInfo info); - void writeSettings(@Nonnull Document document); + void writeSettings(@NotNull Document document); - void loadSettings(@Nonnull Document document); + void loadSettings(@NotNull Document document); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java index d2cc2ab81..a023037ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java @@ -5,9 +5,9 @@ import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.List; public interface IGoal extends IChallenge { @@ -27,7 +27,7 @@ public interface IGoal extends IChallenge { * * @return the sound to play */ - @Nonnull + @NotNull SoundSample getStartSound(); /** @@ -45,6 +45,6 @@ public interface IGoal extends IChallenge { * * @param winners the list to which the winners should be added */ - void getWinnersOnEnd(@Nonnull List winners); + void getWinnersOnEnd(@NotNull List winners); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java index 8f1a6be8b..988b5737b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IModifier.java @@ -1,18 +1,13 @@ package net.codingarea.challenges.plugin.challenges.type; -import javax.annotation.Nonnegative; - public interface IModifier { - @Nonnegative int getValue(); void setValue(int value); - @Nonnegative int getMinValue(); - @Nonnegative int getMaxValue(); void playValueChangeTitle(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java index f9008203f..a9ca3c100 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java @@ -19,10 +19,9 @@ import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; import java.util.UUID; @@ -53,45 +52,43 @@ public abstract class AbstractChallenge implements IChallenge, Listener { private String name; private ItemStack cachedDisplayItem; - public AbstractChallenge(@Nonnull MenuType menu) { + public AbstractChallenge(@NotNull MenuType menu) { this.menu = menu; firstInstanceByClass.put(this.getClass(), this); } - @Nonnull - public static C getFirstInstance(@Nonnull Class classOfChallenge) { + @NotNull + public static C getFirstInstance(@NotNull Class classOfChallenge) { return classOfChallenge.cast(firstInstanceByClass.get(classOfChallenge)); } - public static void broadcast(@Nonnull Consumer action) { + public static void broadcast(@NotNull Consumer action) { Bukkit.getOnlinePlayers().forEach(action); } - public static void broadcastFiltered(@Nonnull Consumer action) { + public static void broadcastFiltered(@NotNull Consumer action) { for (Player player : Bukkit.getOnlinePlayers()) { if (ignorePlayer(player)) continue; action.accept(player); } } - public static void broadcastIgnored(@Nonnull Consumer action) { + public static void broadcastIgnored(@NotNull Consumer action) { for (Player player : Bukkit.getOnlinePlayers()) { if (!ignorePlayer(player)) continue; action.accept(player); } } - @CheckReturnValue - public static boolean ignorePlayer(@Nonnull Player player) { + public static boolean ignorePlayer(@NotNull Player player) { return ignoreGameMode(player.getGameMode()); } - @CheckReturnValue - public static boolean ignoreGameMode(@Nonnull GameMode gameMode) { + public static boolean ignoreGameMode(@NotNull GameMode gameMode) { return (isIgnoreSpectatorPlayers() && gameMode == GameMode.SPECTATOR) || (isIgnoreCreativePlayers() && gameMode == GameMode.CREATIVE); } - @Nonnull + @NotNull @Override public final MenuType getType() { return menu; @@ -106,7 +103,7 @@ protected final void updateItems() { ChallengeHelper.updateItems(this); } - @Nonnull + @NotNull @Override public ItemStack getDisplayItem() { if (cachedDisplayItem != null) return cachedDisplayItem.clone(); @@ -114,7 +111,7 @@ public ItemStack getDisplayItem() { return cachedDisplayItem.clone(); } - @Nonnull + @NotNull @Override public ItemStack getSettingsItem() { ItemBuilder item = createSettingsItem(); @@ -132,19 +129,19 @@ protected String[] getSettingsDescription() { return null; } - @Nonnull + @NotNull public abstract ItemBuilder createDisplayItem(); - @Nonnull + @NotNull public abstract ItemBuilder createSettingsItem(); - @Nonnull + @NotNull @Override public String getUniqueGamestateName() { return getUniqueName(); } - @Nonnull + @NotNull @Override public String getUniqueName() { return name != null ? name : (name = getClass().getSimpleName().toLowerCase() @@ -160,22 +157,21 @@ public void handleShutdown() { } @Override - public void writeGameState(@Nonnull Document document) { + public void writeGameState(@NotNull Document document) { } @Override - public void loadGameState(@Nonnull Document document) { + public void loadGameState(@NotNull Document document) { } @Override - public void writeSettings(@Nonnull Document document) { + public void writeSettings(@NotNull Document document) { } @Override - public void loadSettings(@Nonnull Document document) { + public void loadSettings(@NotNull Document document) { } - @CheckReturnValue protected boolean shouldExecuteEffect() { return isEnabled() && ChallengeAPI.isStarted() && !ChallengeAPI.isWorldInUse(); } @@ -185,7 +181,7 @@ protected boolean shouldExecuteEffect() { */ @Deprecated @DeprecatedSince("2.1.0") - public void kill(@Nonnull Player player) { + public void kill(@NotNull Player player) { ChallengeHelper.kill(player); } @@ -194,23 +190,23 @@ public void kill(@Nonnull Player player) { */ @Deprecated @DeprecatedSince("2.1.0") - public void kill(@Nonnull Player player, int delay) { + public void kill(@NotNull Player player, int delay) { ChallengeHelper.kill(player, delay); } - @Nonnull + @NotNull protected final Document getGameStateData() { return plugin.getConfigManager().getGamestateConfig().getDocument(this.getUniqueGamestateName()); } - @Nonnull - protected final Document getPlayerData(@Nonnull UUID player) { + @NotNull + protected final Document getPlayerData(@NotNull UUID player) { return getGameStateData().getDocument("player").getDocument(player.toString()); } - @Nonnull - protected final Document getPlayerData(@Nonnull Player player) { + @NotNull + protected final Document getPlayerData(@NotNull Player player) { return getPlayerData(player.getUniqueId()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java index fd1dd34ec..21c67067b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java @@ -8,7 +8,6 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.function.BiConsumer; @Setter @@ -19,19 +18,19 @@ public abstract class AbstractForceChallenge extends TimedChallenge { private int state = WAITING; - public AbstractForceChallenge(@Nonnull MenuType menu) { + public AbstractForceChallenge(@NotNull MenuType menu) { super(menu, false); } - public AbstractForceChallenge(@Nonnull MenuType menu, int max) { + public AbstractForceChallenge(@NotNull MenuType menu, int max) { super(menu, max, false); } - public AbstractForceChallenge(@Nonnull MenuType menu, int min, int max) { + public AbstractForceChallenge(@NotNull MenuType menu, int min, int max) { super(menu, min, max, false); } - public AbstractForceChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { + public AbstractForceChallenge(@NotNull MenuType menu, int min, int max, int defaultValue) { super(menu, min, max, defaultValue, false); } @@ -90,7 +89,7 @@ public void loadGameState(@NotNull Document document) { protected abstract int getForcingTime(); - @Nonnull + @NotNull protected abstract BiConsumer setupBossbar(); public final int getState() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java index b41c1eaed..8ab7c519f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java @@ -7,9 +7,8 @@ import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicInteger; @@ -20,12 +19,12 @@ public abstract class CollectionGoal extends SettingGoal { private final Map> collections = new HashMap<>(); protected Object[] target; - public CollectionGoal(@Nonnull Object[] target) { + public CollectionGoal(@NotNull Object[] target) { super(); this.target = target; } - public CollectionGoal(boolean enabledByDefault, @Nonnull Object[] target) { + public CollectionGoal(boolean enabledByDefault, @NotNull Object[] target) { super(enabledByDefault); this.target = target; } @@ -42,7 +41,7 @@ protected void onDisable() { } @Override - public void getWinnersOnEnd(@Nonnull List winners) { + public void getWinnersOnEnd(@NotNull List winners) { AtomicInteger mostPoints = new AtomicInteger(); Map points = getPoints(mostPoints, false); if (mostPoints.get() == 0) return; // Nobody won, nobody has anything @@ -53,13 +52,12 @@ public void getWinnersOnEnd(@Nonnull List winners) { } } - @Nonnull - @CheckReturnValue - protected Map getPoints(@Nonnull AtomicInteger mostPoints, boolean zeros) { + @NotNull + protected Map getPoints(@NotNull AtomicInteger mostPoints, boolean zeros) { return GoalHelper.createPointsFromValues(mostPoints, collections, (uuid, strings) -> getCollectionFiltered(uuid).size(), zeros); } - protected void collect(@Nonnull Player player, @Nonnull Object item, @Nonnull Runnable success) { + protected void collect(@NotNull Player player, @NotNull Object item, @NotNull Runnable success) { if (ignorePlayer(player)) return; List collection = getCollectionRaw(player.getUniqueId()); if (collection.contains(item.toString())) return; @@ -69,12 +67,12 @@ protected void collect(@Nonnull Player player, @Nonnull Object item, @Nonnull Ru checkCollects(); } - protected List getCollectionFiltered(@Nonnull UUID uuid) { + protected List getCollectionFiltered(@NotNull UUID uuid) { List targetStringList = Arrays.stream(target).map(Object::toString).collect(Collectors.toList()); return collections.computeIfAbsent(uuid, key -> new ArrayList<>()).stream().filter(targetStringList::contains).collect(Collectors.toList()); } - protected List getCollectionRaw(@Nonnull UUID uuid) { + protected List getCollectionRaw(@NotNull UUID uuid) { return collections.computeIfAbsent(uuid, key -> new ArrayList<>()); } @@ -85,13 +83,13 @@ protected void checkCollects() { } } - protected void checkCollects(@Nonnull List collection) { + protected void checkCollects(@NotNull List collection) { if (collection.size() >= target.length) ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); } @Override - public void loadGameState(@Nonnull Document document) { + public void loadGameState(@NotNull Document document) { super.loadGameState(document); collections.clear(); @@ -112,7 +110,7 @@ public void loadGameState(@Nonnull Document document) { } @Override - public void writeGameState(@Nonnull Document document) { + public void writeGameState(@NotNull Document document) { super.writeGameState(document); Document scores = document.getDocument("scores"); @@ -121,7 +119,7 @@ public void writeGameState(@Nonnull Document document) { }); } - protected void setTarget(@Nonnull Object... target) { + protected void setTarget(@NotNull Object... target) { this.target = target; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java index 09e28abda..0368e524f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java @@ -5,24 +5,23 @@ import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.entity.Player; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public abstract class CompletableForceChallenge extends AbstractForceChallenge { - public CompletableForceChallenge(@Nonnull MenuType menu) { + public CompletableForceChallenge(@NotNull MenuType menu) { super(menu); } - public CompletableForceChallenge(@Nonnull MenuType menu, int max) { + public CompletableForceChallenge(@NotNull MenuType menu, int max) { super(menu, max); } - public CompletableForceChallenge(@Nonnull MenuType menu, int min, int max) { + public CompletableForceChallenge(@NotNull MenuType menu, int min, int max) { super(menu, min, max); } - public CompletableForceChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { + public CompletableForceChallenge(@NotNull MenuType menu, int min, int max, int defaultValue) { super(menu, min, max, defaultValue); } @@ -33,7 +32,7 @@ protected final void handleCountdownEnd() { ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_FAILED); } - protected final void completeForcing(@Nonnull Player player) { + protected final void completeForcing(@NotNull Player player) { if (getState() != COUNTDOWN) return; broadcastSuccessMessage(player); endForcing(); @@ -42,6 +41,6 @@ protected final void completeForcing(@Nonnull Player player) { protected abstract void broadcastFailedMessage(); - protected abstract void broadcastSuccessMessage(@Nonnull Player player); + protected abstract void broadcastSuccessMessage(@NotNull Player player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java index 53543adbe..f7d079be4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java @@ -6,26 +6,26 @@ import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; public abstract class EndingForceChallenge extends AbstractForceChallenge { - public EndingForceChallenge(@Nonnull MenuType menu) { + public EndingForceChallenge(@NotNull MenuType menu) { super(menu); } - public EndingForceChallenge(@Nonnull MenuType menu, int max) { + public EndingForceChallenge(@NotNull MenuType menu, int max) { super(menu, max); } - public EndingForceChallenge(@Nonnull MenuType menu, int min, int max) { + public EndingForceChallenge(@NotNull MenuType menu, int min, int max) { super(menu, min, max); } - public EndingForceChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { + public EndingForceChallenge(@NotNull MenuType menu, int min, int max, int defaultValue) { super(menu, min, max, defaultValue); } @@ -51,14 +51,14 @@ private void checkAllPlayers() { SoundSample.LEVEL_UP.broadcast(); } - private void killFailedPlayers(@Nonnull Iterable failed) { + private void killFailedPlayers(@NotNull Iterable failed) { if (!ChallengeAPI.isStarted()) return; failed.forEach(ChallengeHelper::kill); } - protected abstract boolean isFailing(@Nonnull Player player); + protected abstract boolean isFailing(@NotNull Player player); - protected abstract void broadcastFailedMessage(@Nonnull Player player); + protected abstract void broadcastFailedMessage(@NotNull Player player); protected abstract void broadcastSuccessMessage(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java index da5e8ffba..7cb6a5850 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java @@ -11,7 +11,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Collections; import java.util.List; @@ -28,7 +27,7 @@ public void getWinnersOnEnd(@NotNull List winners) { } - private void checkItem(ItemStack itemStack, @Nonnull Player player) { + private void checkItem(ItemStack itemStack, @NotNull Player player) { if (itemStack == null) return; if (itemStack.getType() != searchedItem) return; ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(player)); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java index 163829a2a..e14799978 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java @@ -11,23 +11,22 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public abstract class HydraChallenge extends Setting { - public HydraChallenge(@Nonnull MenuType menu) { + public HydraChallenge(@NotNull MenuType menu) { super(menu); } - public HydraChallenge(@Nonnull MenuType menu, boolean enabledByDefault) { + public HydraChallenge(@NotNull MenuType menu, boolean enabledByDefault) { super(menu, enabledByDefault); } - public abstract int getNewMobsCount(@Nonnull EntityType entityType); + public abstract int getNewMobsCount(@NotNull EntityType entityType); @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityDamageByEntity(@Nonnull EntityDeathByPlayerEvent event) { + public void onEntityDamageByEntity(@NotNull EntityDeathByPlayerEvent event) { if (!shouldExecuteEffect()) return; if (event.getEntity() instanceof EnderDragon || event.getEntity() instanceof Player) return; if (ChallengeHelper.ignoreDamager(event.getKiller())) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java index b4cb0fcae..1882175b9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java @@ -12,7 +12,6 @@ import org.bukkit.event.EventPriority; import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; @@ -26,7 +25,7 @@ public ItemCollectionGoal(boolean enabledByDefault, @NotNull Material... target) super(enabledByDefault, target); } - protected void handleCollect(@Nonnull Player player, @Nonnull Material material) { + protected void handleCollect(@NotNull Player player, @NotNull Material material) { collect(player, material, () -> { Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); SoundSample.PLING.play(player); @@ -41,7 +40,7 @@ protected void onEnable() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPickupItem(@Nonnull PlayerPickupItemEvent event) { + public void onPickupItem(@NotNull PlayerPickupItemEvent event) { if (!shouldExecuteEffect()) return; Material material = event.getItem().getItemStack().getType(); Player player = event.getPlayer(); @@ -49,7 +48,7 @@ public void onPickupItem(@Nonnull PlayerPickupItemEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + public void onPlayerInventoryClick(@NotNull PlayerInventoryClickEvent event) { if (!shouldExecuteEffect()) return; if (event.isCancelled()) return; if (event.getClickedInventory() == null) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java index 3a70470bd..bdb27f584 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java @@ -10,8 +10,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDeathEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.List; public abstract class KillEntityGoal extends SettingGoal { @@ -23,11 +23,11 @@ public abstract class KillEntityGoal extends SettingGoal { protected boolean killerNeeded = false; protected Player winner; - public KillEntityGoal(@Nonnull EntityType entity) { + public KillEntityGoal(@NotNull EntityType entity) { this(entity, false); } - public KillEntityGoal(@Nonnull EntityType entity, boolean enabledByDefault) { + public KillEntityGoal(@NotNull EntityType entity, boolean enabledByDefault) { this(entity, null, enabledByDefault); } @@ -42,12 +42,12 @@ public KillEntityGoal(EntityType entity, Environment world, boolean enabledByDef } @Override - public void getWinnersOnEnd(@Nonnull List winners) { + public void getWinnersOnEnd(@NotNull List winners) { if (oneWinner && winner != null) winners.add(winner); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onKill(@Nonnull EntityDeathEvent event) { + public void onKill(@NotNull EntityDeathEvent event) { if (!isEnabled() || !ChallengeAPI.isStarted()) return; LivingEntity entity = event.getEntity(); if (entity.getType() != this.entity) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java index 667eb7ba6..13a0e61cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java @@ -13,7 +13,6 @@ import org.bukkit.event.entity.EntityDeathEvent; import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.LinkedList; import java.util.List; @@ -56,7 +55,7 @@ protected void onDisable() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDeath(@Nonnull EntityDeathEvent event) { + public void onDeath(@NotNull EntityDeathEvent event) { if (!shouldExecuteEffect()) return; if (event.getEntityType() != EntityType.WITHER && event.getEntityType() != EntityType.ENDER_DRAGON && event.getEntityType() != EntityType.ELDER_GUARDIAN) { if (event.getEntity().getKiller() == null) return; @@ -73,14 +72,14 @@ public void onDeath(@Nonnull EntityDeathEvent event) { } @Override - public void writeGameState(@Nonnull Document document) { + public void writeGameState(@NotNull Document document) { super.writeGameState(document); document.set("entities", entitiesKilled); } @Override - public void loadGameState(@Nonnull Document document) { + public void loadGameState(@NotNull Document document) { super.loadGameState(document); entitiesKilled = document.getEnumList("entities", EntityType.class); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java index abe1efc1e..459f27c35 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java @@ -6,9 +6,7 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.jetbrains.annotations.NotNull; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.Nullable; public abstract class MenuGoal extends MenuSetting implements IGoal { public MenuGoal(@NotNull MenuType menu, @NotNull Message title) { @@ -22,7 +20,7 @@ public final void setEnabled(boolean enabled) { super.setEnabled(enabled); } - @Nonnull + @NotNull @Override public SoundSample getStartSound() { return SoundSample.DRAGON_BREATH; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java index 96eff4212..08a962e15 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java @@ -21,9 +21,9 @@ import org.bukkit.event.Listener; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.*; import java.util.Map.Entry; import java.util.function.Function; @@ -35,12 +35,12 @@ public abstract class MenuSetting extends Setting { private final List inventories = new ArrayList<>(); private final Message title; - public MenuSetting(@Nonnull MenuType menu, @Nonnull Message title) { + public MenuSetting(@NotNull MenuType menu, @NotNull Message title) { super(menu); this.title = title; } - @Nonnull + @NotNull public static int[] getSlots(int amount) { switch (amount) { default: @@ -99,7 +99,7 @@ protected final void generateInventories() { } - @Nonnull + @NotNull private Inventory createNewInventory(int page, int pagesAmount) { Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, SettingsMenuGenerator.SIZE, InventoryTitleManager.getMenuSettingTitle(getType(), title.asString(), page, pagesAmount > 1)); InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); @@ -107,18 +107,18 @@ private Inventory createNewInventory(int page, int pagesAmount) { return inventory; } - protected final void registerSetting(@Nonnull String name, @Nonnull SubSetting setting) { + protected final void registerSetting(@NotNull String name, @NotNull SubSetting setting) { if (name.equals("enabled")) throw new IllegalArgumentException(); settings.put(name, setting); Challenges.getInstance().registerListener(setting); } - public final SubSetting getSetting(@Nonnull String name) { + public final SubSetting getSetting(@NotNull String name) { return settings.get(name); } @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + public void handleClick(@NotNull ChallengeMenuClickInfo info) { if (info.isUpperItemClick()) { super.handleClick(info); } else if (isEnabled() && !info.isRightClick()) { @@ -128,7 +128,7 @@ public void handleClick(@Nonnull ChallengeMenuClickInfo info) { } } - private void openMenu(@Nonnull ChallengeMenuClickInfo event) { + private void openMenu(@NotNull ChallengeMenuClickInfo event) { MenuPosition position = MenuPosition.get(event.getPlayer()); if (position == null) position = new EmptyMenuPosition(); Inventory inventory = event.getInventory(); @@ -136,7 +136,7 @@ private void openMenu(@Nonnull ChallengeMenuClickInfo event) { open(event.getPlayer(), inventory, position, 0); } - private void open(@Nonnull Player player, @Nonnull Inventory inventory, @Nonnull MenuPosition position, int page) { + private void open(@NotNull Player player, @NotNull Inventory inventory, @NotNull MenuPosition position, int page) { if (inventories.isEmpty()) generateInventories(); if (inventories.isEmpty()) { SoundSample.BASS_OFF.play(player); @@ -148,14 +148,14 @@ private void open(@Nonnull Player player, @Nonnull Inventory inventory, @Nonnull player.openInventory(menu); } - @Nonnull + @NotNull @Override public final ItemBuilder createSettingsItem() { return isEnabled() ? DefaultItem.customize() : DefaultItem.disabled(); } @Override - public void writeSettings(@Nonnull Document document) { + public void writeSettings(@NotNull Document document) { document.set("enabled", isEnabled()); for (Entry entry : settings.entrySet()) { Document subDocument = document.getDocument(entry.getKey()); @@ -164,7 +164,7 @@ public void writeSettings(@Nonnull Document document) { } @Override - public void loadSettings(@Nonnull Document document) { + public void loadSettings(@NotNull Document document) { setEnabled(document.getBoolean("enabled")); for (Entry entry : settings.entrySet()) { if (!document.contains(entry.getKey())) continue; @@ -201,7 +201,7 @@ public final void updateItems() { inventory.setItem(slot + 9, buildSettingsItem()); } - @Nonnull + @NotNull private ItemStack buildSettingsItem() { ItemBuilder item = getSettingsItem(); String[] description = getSettingsDescription(); @@ -213,10 +213,10 @@ private ItemStack buildSettingsItem() { return item.build(); } - @Nonnull + @NotNull public abstract ItemBuilder getDisplayItem(); - @Nonnull + @NotNull public abstract ItemBuilder getSettingsItem(); @Nullable @@ -232,11 +232,11 @@ public boolean isEnabled() { public abstract void restoreDefaults(); - public abstract void loadSettings(@Nonnull Document document); + public abstract void loadSettings(@NotNull Document document); - public abstract void writeSettings(@Nonnull Document document); + public abstract void writeSettings(@NotNull Document document); - public abstract void handleClick(@Nonnull ChallengeMenuClickInfo info); + public abstract void handleClick(@NotNull ChallengeMenuClickInfo info); } @@ -247,32 +247,32 @@ public class BooleanSubSetting extends SubSetting { private final boolean enabledByDefault; private boolean enabled; - public BooleanSubSetting(@Nonnull Supplier item) { + public BooleanSubSetting(@NotNull Supplier item) { this(item, () -> null); } - public BooleanSubSetting(@Nonnull Supplier item, boolean enabledByDefault) { + public BooleanSubSetting(@NotNull Supplier item, boolean enabledByDefault) { this(item, () -> null, enabledByDefault); } - public BooleanSubSetting(@Nonnull Supplier item, @Nonnull Supplier description) { + public BooleanSubSetting(@NotNull Supplier item, @NotNull Supplier description) { this(item, description, false); } - public BooleanSubSetting(@Nonnull Supplier item, @Nonnull Supplier description, boolean enabledByDefault) { + public BooleanSubSetting(@NotNull Supplier item, @NotNull Supplier description, boolean enabledByDefault) { this.item = item; this.description = description; this.enabledByDefault = enabledByDefault; this.setEnabled(enabledByDefault); } - @Nonnull + @NotNull @Override public ItemBuilder getDisplayItem() { return item.get(); } - @Nonnull + @NotNull @Override public ItemBuilder getSettingsItem() { return DefaultItem.status(enabled); @@ -299,7 +299,7 @@ public void restoreDefaults() { this.setEnabled(enabledByDefault); } - @Nonnull + @NotNull public BooleanSubSetting setEnabled(boolean enabled) { if (this.enabled == enabled) return this; this.enabled = enabled; @@ -312,18 +312,18 @@ public BooleanSubSetting setEnabled(boolean enabled) { } @Override - public final void handleClick(@Nonnull ChallengeMenuClickInfo info) { + public final void handleClick(@NotNull ChallengeMenuClickInfo info) { this.setEnabled(!enabled); SoundSample.playStatusSound(info.getPlayer(), enabled); } @Override - public void loadSettings(@Nonnull Document document) { + public void loadSettings(@NotNull Document document) { this.setEnabled(document.getBoolean("enabled")); } @Override - public void writeSettings(@Nonnull Document document) { + public void writeSettings(@NotNull Document document) { document.set("enabled", enabled); } @@ -345,19 +345,19 @@ public class NumberSubSetting extends SubSetting { @Getter private int value; - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name) { + public NumberSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name) { this(item, description, name, 64); } - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int max) { + public NumberSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name, int max) { this(item, description, name, max, 1); } - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max) { + public NumberSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name, int min, int max) { this(item, description, name, min, max, min); } - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max, int defaultValue) { + public NumberSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name, int min, int max, int defaultValue) { if (max <= min) throw new IllegalArgumentException("max <= min"); if (min < 0) throw new IllegalArgumentException("min < 0"); if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); @@ -371,45 +371,45 @@ public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function item, @Nonnull Function description) { + public NumberSubSetting(@NotNull Supplier item, @NotNull Function description) { this(item, description, null, 64, 1); } - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, int max) { + public NumberSubSetting(@NotNull Supplier item, @NotNull Function description, int max) { this(item, description, null, max, 1); } - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max) { + public NumberSubSetting(@NotNull Supplier item, @NotNull Function description, int min, int max) { this(item, description, null, min, max, min); } - public NumberSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max, int defaultValue) { + public NumberSubSetting(@NotNull Supplier item, @NotNull Function description, int min, int max, int defaultValue) { this(item, description, null, min, max, defaultValue); } - public NumberSubSetting(@Nonnull Supplier item) { + public NumberSubSetting(@NotNull Supplier item) { this(item, value -> null); } - public NumberSubSetting(@Nonnull Supplier item, int max) { + public NumberSubSetting(@NotNull Supplier item, int max) { this(item, value -> null, max); } - public NumberSubSetting(@Nonnull Supplier item, int min, int max) { + public NumberSubSetting(@NotNull Supplier item, int min, int max) { this(item, value -> null, min, max); } - public NumberSubSetting(@Nonnull Supplier item, int min, int max, int defaultValue) { + public NumberSubSetting(@NotNull Supplier item, int min, int max, int defaultValue) { this(item, value -> null, min, max, defaultValue); } - @Nonnull + @NotNull @Override public ItemBuilder getDisplayItem() { return item.get(); } - @Nonnull + @NotNull @Override public ItemBuilder getSettingsItem() { if (name != null) @@ -448,7 +448,7 @@ public boolean getAsBoolean() { } @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + public void handleClick(@NotNull ChallengeMenuClickInfo info) { int amount = info.isShiftClick() ? 10 : 1; int newValue = value; if (info.isRightClick()) { @@ -467,12 +467,12 @@ public void handleClick(@Nonnull ChallengeMenuClickInfo info) { } @Override - public void loadSettings(@Nonnull Document document) { + public void loadSettings(@NotNull Document document) { this.setValue(document.getInt("value")); } @Override - public void writeSettings(@Nonnull Document document) { + public void writeSettings(@NotNull Document document) { document.set("value", value); } @@ -486,47 +486,47 @@ public class NumberAndBooleanSubSetting extends NumberSubSetting { private final boolean enabledByDefault = false; // Implement in future private boolean enabled; - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name) { + public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name) { super(item, description, name); } - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int max) { + public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name, int max) { super(item, description, name, max); } - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max) { + public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name, int min, int max) { super(item, description, name, min, max); } - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, @Nullable Function name, int min, int max, int defaultValue) { + public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name, int min, int max, int defaultValue) { super(item, description, name, min, max, defaultValue); } - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description) { + public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description) { super(item, description); } - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, int max) { + public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description, int max) { super(item, description, max); } - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max) { + public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description, int min, int max) { super(item, description, min, max); } - public NumberAndBooleanSubSetting(@Nonnull Supplier item, @Nonnull Function description, int min, int max, int defaultValue) { + public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description, int min, int max, int defaultValue) { super(item, description, min, max, defaultValue); } - public NumberAndBooleanSubSetting(@Nonnull Supplier item) { + public NumberAndBooleanSubSetting(@NotNull Supplier item) { super(item); } - public NumberAndBooleanSubSetting(@Nonnull Supplier item, int max) { + public NumberAndBooleanSubSetting(@NotNull Supplier item, int max) { super(item, max); } - public NumberAndBooleanSubSetting(@Nonnull Supplier item, int min, int max) { + public NumberAndBooleanSubSetting(@NotNull Supplier item, int min, int max) { super(item, min, max); } @@ -552,7 +552,7 @@ public boolean getAsBoolean() { } @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + public void handleClick(@NotNull ChallengeMenuClickInfo info) { if (info.isUpperItemClick() || !enabled) { this.setEnabled(!enabled); SoundSample.playStatusSound(info.getPlayer(), enabled); @@ -562,13 +562,13 @@ public void handleClick(@Nonnull ChallengeMenuClickInfo info) { } @Override - public void loadSettings(@Nonnull Document document) { + public void loadSettings(@NotNull Document document) { super.loadSettings(document); this.setEnabled(document.getBoolean("enabled")); } @Override - public void writeSettings(@Nonnull Document document) { + public void writeSettings(@NotNull Document document) { super.writeSettings(document); document.set("enabled", enabled); } @@ -587,14 +587,14 @@ private final class SettingMenuPosition implements MenuPosition { private final Inventory inventoryBefore; private final int page; - public SettingMenuPosition(@Nonnull MenuPosition before, @Nonnull Inventory inventoryBefore, int page) { + public SettingMenuPosition(@NotNull MenuPosition before, @NotNull Inventory inventoryBefore, int page) { this.before = before; this.inventoryBefore = inventoryBefore; this.page = page; } @Override - public void handleClick(@Nonnull MenuClickInfo info) { + public void handleClick(@NotNull MenuClickInfo info) { if (info.getSlot() == SettingsMenuGenerator.NAVIGATION_SLOTS[0]) { if (page == 0) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java index 97dd509a9..8761eff66 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java @@ -8,9 +8,7 @@ import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.common.config.Document; - -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public abstract class Modifier extends AbstractChallenge implements IModifier { @@ -18,19 +16,19 @@ public abstract class Modifier extends AbstractChallenge implements IModifier { private final int defaultValue; private int value; - public Modifier(@Nonnull MenuType menu) { + public Modifier(@NotNull MenuType menu) { this(menu, 64); } - public Modifier(@Nonnull MenuType menu, int max) { + public Modifier(@NotNull MenuType menu, int max) { this(menu, 1, max); } - public Modifier(@Nonnull MenuType menu, int min, int max) { + public Modifier(@NotNull MenuType menu, int min, int max) { this(menu, min, max, min); } - public Modifier(@Nonnull MenuType menu, int min, int max, int defaultValue) { + public Modifier(@NotNull MenuType menu, int min, int max, int defaultValue) { super(menu); if (max < min) throw new IllegalArgumentException("max < min"); if (min < 0) throw new IllegalArgumentException("min < 0"); @@ -42,7 +40,7 @@ public Modifier(@Nonnull MenuType menu, int min, int max, int defaultValue) { this.defaultValue = defaultValue; } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { return DefaultItem.value(value); @@ -54,7 +52,6 @@ public void restoreDefaults() { } @Override - @Nonnegative public final int getValue() { return value; } @@ -75,13 +72,11 @@ public void setValue(int value) { } @Override - @Nonnegative public final int getMaxValue() { return max; } @Override - @Nonnegative public final int getMinValue() { return min; } @@ -92,7 +87,7 @@ public boolean isEnabled() { } @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + public void handleClick(@NotNull ChallengeMenuClickInfo info) { ChallengeHelper.handleModifierClick(info, this); } @@ -105,12 +100,12 @@ protected void onValueChange() { } @Override - public void loadSettings(@Nonnull Document document) { + public void loadSettings(@NotNull Document document) { setValue(document.getInt("value", value)); } @Override - public void writeSettings(@Nonnull Document document) { + public void writeSettings(@NotNull Document document) { document.set("value", value); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java index ddced796e..2833b61cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java @@ -5,9 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.commons.common.config.Document; - -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public abstract class ModifierCollectionGoal extends CollectionGoal implements IModifier { @@ -15,11 +13,11 @@ public abstract class ModifierCollectionGoal extends CollectionGoal implements I private final int defaultValue; private int value; - public ModifierCollectionGoal(int min, int max, @Nonnull Object[] target) { + public ModifierCollectionGoal(int min, int max, @NotNull Object[] target) { this(min, max, min, target); } - public ModifierCollectionGoal(int min, int max, int defaultValue, @Nonnull Object[] target) { + public ModifierCollectionGoal(int min, int max, int defaultValue, @NotNull Object[] target) { super(target); if (max < min) throw new IllegalArgumentException("max < min"); if (min < 0) throw new IllegalArgumentException("min < 0"); @@ -37,7 +35,7 @@ public void restoreDefaults() { } @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + public void handleClick(@NotNull ChallengeMenuClickInfo info) { ChallengeHelper.handleModifierClick(info, this); } @@ -54,7 +52,6 @@ public void setEnabled(boolean enabled) { } @Override - @Nonnegative public final int getValue() { return value; } @@ -71,13 +68,11 @@ public void setValue(int value) { } @Override - @Nonnegative public final int getMaxValue() { return max; } @Override - @Nonnegative public final int getMinValue() { return min; } @@ -91,12 +86,12 @@ protected void onValueChange() { } @Override - public void loadSettings(@Nonnull Document document) { + public void loadSettings(@NotNull Document document) { setValue(document.getInt("value", value)); } @Override - public void writeSettings(@Nonnull Document document) { + public void writeSettings(@NotNull Document document) { document.set("value", value); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java index ccf50eede..5b3374220 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java @@ -9,9 +9,9 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; @@ -27,14 +27,14 @@ public abstract class NetherPortalSpawnSetting extends OneEnabledSetting { private final Collection groundMaterial; private final String unableToFindMessage; - public NetherPortalSpawnSetting(@Nonnull MenuType menu, @Nonnull StructureType structureType, @Nonnull String unableToFindMessage, @Nonnull Material... groundMaterial) { + public NetherPortalSpawnSetting(@NotNull MenuType menu, @NotNull StructureType structureType, @NotNull String unableToFindMessage, @NotNull Material... groundMaterial) { super(menu, id); this.structureType = structureType; this.unableToFindMessage = unableToFindMessage; this.groundMaterial = Arrays.asList(groundMaterial); } - public NetherPortalSpawnSetting(@Nonnull MenuType menu, @Nonnull StructureType structureType, @Nonnull String unableToFindMessage, @Nonnull Collection groundMaterial) { + public NetherPortalSpawnSetting(@NotNull MenuType menu, @NotNull StructureType structureType, @NotNull String unableToFindMessage, @NotNull Collection groundMaterial) { super(menu, id); this.structureType = structureType; this.unableToFindMessage = unableToFindMessage; @@ -42,7 +42,7 @@ public NetherPortalSpawnSetting(@Nonnull MenuType menu, @Nonnull StructureType s } @EventHandler - public void onNetherPortal(@Nonnull PlayerTeleportEvent event) { + public void onNetherPortal(@NotNull PlayerTeleportEvent event) { if (!isEnabled()) return; if (event.getCause() != TeleportCause.NETHER_PORTAL) return; if (event.getTo() == null) return; @@ -68,7 +68,7 @@ public void onNetherPortal(@Nonnull PlayerTeleportEvent event) { } @Nullable - private Location getNetherPortal(@Nonnull Location overworldPortal, @Nonnull World nether) { + private Location getNetherPortal(@NotNull Location overworldPortal, @NotNull World nether) { // Look if the current portal was used before for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { @@ -93,7 +93,7 @@ private Location getNetherPortal(@Nonnull Location overworldPortal, @Nonnull Wor } @Nullable - private Location getOverworldPortal(@Nonnull Location netherPortal) { + private Location getOverworldPortal(@NotNull Location netherPortal) { for (Entry entry : netherPortalsByOverworldPortals.entrySet()) { if (netherPortal.distance(entry.getValue()) < 100) return entry.getKey(); @@ -103,7 +103,7 @@ private Location getOverworldPortal(@Nonnull Location netherPortal) { @Nullable - private Location findNearestStructurePart(@Nonnull Location structure) { + private Location findNearestStructurePart(@NotNull Location structure) { Chunk chunk = structure.getChunk(); for (int x = 0; x < 16; x++) { @@ -123,7 +123,7 @@ private Location findNearestStructurePart(@Nonnull Location structure) { } - private void buildPortal(@Nonnull Location origin) { + private void buildPortal(@NotNull Location origin) { // Floor origin.clone().add(-1, -1, 0).getBlock().setType(Material.OBSIDIAN); @@ -168,7 +168,7 @@ private void buildPortal(@Nonnull Location origin) { } @Override - public void loadGameState(@Nonnull Document document) { + public void loadGameState(@NotNull Document document) { super.loadGameState(document); Document portals = document.getDocument("portals"); @@ -183,7 +183,7 @@ public void loadGameState(@Nonnull Document document) { } @Override - public void writeGameState(@Nonnull Document document) { + public void writeGameState(@NotNull Document document) { super.writeGameState(document); int index = 0; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java index 9bf18459d..be28372da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java @@ -2,19 +2,18 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.menu.MenuType; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public abstract class OneEnabledSetting extends Setting { private final String typeId; - public OneEnabledSetting(@Nonnull MenuType menu, @Nonnull String typeId) { + public OneEnabledSetting(@NotNull MenuType menu, @NotNull String typeId) { super(menu); this.typeId = typeId; } - public OneEnabledSetting(@Nonnull MenuType menu, boolean enabledByDefault, @Nonnull String typeId) { + public OneEnabledSetting(@NotNull MenuType menu, boolean enabledByDefault, @NotNull String typeId) { super(menu, enabledByDefault); this.typeId = typeId; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java index 122f82ffd..bc1787d9f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java @@ -4,9 +4,8 @@ import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.config.Document; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -39,7 +38,7 @@ protected void onDisable() { } @Override - public void loadGameState(@Nonnull Document document) { + public void loadGameState(@NotNull Document document) { super.loadGameState(document); Document scores = document.getDocument("scores"); @@ -55,7 +54,7 @@ public void loadGameState(@Nonnull Document document) { } @Override - public void writeGameState(@Nonnull Document document) { + public void writeGameState(@NotNull Document document) { super.writeGameState(document); Document scores = document.getDocument("scores"); @@ -63,42 +62,40 @@ public void writeGameState(@Nonnull Document document) { } @Override - public void getWinnersOnEnd(@Nonnull List winners) { + public void getWinnersOnEnd(@NotNull List winners) { GoalHelper.getWinnersOnEnd(winners, getPoints(new AtomicInteger(), false)); } - @Nonnull - @CheckReturnValue - protected Map getPoints(@Nonnull AtomicInteger mostPoints, boolean zeros) { + @NotNull + protected Map getPoints(@NotNull AtomicInteger mostPoints, boolean zeros) { return GoalHelper.createPointsFromValues(mostPoints, points, (uuid, integer) -> integer, zeros); } - protected void collect(@Nonnull Player player) { + protected void collect(@NotNull Player player) { collect(player, 1); } - protected void collect(@Nonnull Player player, int amount) { + protected void collect(@NotNull Player player, int amount) { points.compute(player.getUniqueId(), (uuid, points) -> points == null ? amount : points + amount); scoreboard.update(); } - protected void setPoints(@Nonnull UUID uuid, int amount) { + protected void setPoints(@NotNull UUID uuid, int amount) { points.put(uuid, amount); scoreboard.update(); } - protected void addPoints(@Nonnull UUID uuid, int amount) { + protected void addPoints(@NotNull UUID uuid, int amount) { points.put(uuid, getPoints(uuid) + amount); scoreboard.update(); } - protected void removePoints(@Nonnull UUID uuid, int amount) { + protected void removePoints(@NotNull UUID uuid, int amount) { points.put(uuid, getPoints(uuid) - amount); scoreboard.update(); } - @CheckReturnValue - protected int getPoints(@Nonnull UUID uuid) { + protected int getPoints(@NotNull UUID uuid) { Integer points = this.points.get(uuid); return points == null ? 0 : points; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java index 5ba7d94c8..b46dd8397 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java @@ -5,19 +5,18 @@ import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.collection.SeededRandomWrapper; import net.codingarea.commons.common.config.Document; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public abstract class RandomizerSetting extends Setting { protected IRandom random = IRandom.create(); - public RandomizerSetting(@Nonnull MenuType menu) { + public RandomizerSetting(@NotNull MenuType menu) { super(menu); setCategory(SettingCategory.RANDOMIZER); } - public RandomizerSetting(@Nonnull MenuType menu, boolean enabledByDefault) { + public RandomizerSetting(@NotNull MenuType menu, boolean enabledByDefault) { super(menu, enabledByDefault); setCategory(SettingCategory.RANDOMIZER); } @@ -36,7 +35,7 @@ protected void onEnable() { } @Override - public void loadGameState(@Nonnull Document document) { + public void loadGameState(@NotNull Document document) { super.loadGameState(document); if (!document.contains("seed")) { random = new SeededRandomWrapper(); @@ -53,7 +52,7 @@ public void loadGameState(@Nonnull Document document) { } @Override - public void writeGameState(@Nonnull Document document) { + public void writeGameState(@NotNull Document document) { super.writeGameState(document); document.set("seed", random.getSeed()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java index 6ee50fc3e..cb34987e4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java @@ -8,8 +8,7 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public abstract class Setting extends AbstractChallenge { @@ -17,18 +16,18 @@ public abstract class Setting extends AbstractChallenge { private final boolean enabledByDefault; protected boolean enabled; - public Setting(@Nonnull MenuType menu) { + public Setting(@NotNull MenuType menu) { this(menu, false); } - public Setting(@Nonnull MenuType menu, boolean enabledByDefault) { + public Setting(@NotNull MenuType menu, boolean enabledByDefault) { super(menu); this.enabledByDefault = enabledByDefault; setEnabled(enabledByDefault); } @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + public void handleClick(@NotNull ChallengeMenuClickInfo info) { setEnabled(!enabled); SoundSample.playStatusSound(info.getPlayer(), enabled); playStatusUpdateTitle(); @@ -43,7 +42,7 @@ public void playStatusUpdateTitle() { ChallengeHelper.playToggleChallengeTitle(this); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { return DefaultItem.status(enabled); @@ -83,12 +82,12 @@ public void setEnabled(boolean enabled) { } @Override - public void loadSettings(@Nonnull Document document) { + public void loadSettings(@NotNull Document document) { setEnabled(document.getBoolean("enabled", enabled)); } @Override - public void writeSettings(@Nonnull Document document) { + public void writeSettings(@NotNull Document document) { document.set("enabled", enabled); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java index 43f9bea9f..f166deb25 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java @@ -4,9 +4,8 @@ import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.commons.bukkit.utils.animation.SoundSample; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public abstract class SettingGoal extends Setting implements IGoal { @@ -18,7 +17,7 @@ public SettingGoal(boolean enabledByDefault) { super(MenuType.GOAL, enabledByDefault); } - @Nonnull + @NotNull public SoundSample getStartSound() { return SoundSample.DRAGON_BREATH; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java index 123453845..441902e25 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java @@ -8,31 +8,30 @@ import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; import org.bukkit.inventory.ItemStack; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public abstract class SettingModifier extends Modifier { private boolean enabled; - public SettingModifier(@Nonnull MenuType menu) { + public SettingModifier(@NotNull MenuType menu) { super(menu); } - public SettingModifier(@Nonnull MenuType menu, int max) { + public SettingModifier(@NotNull MenuType menu, int max) { super(menu, max); } - public SettingModifier(@Nonnull MenuType menu, int min, int max) { + public SettingModifier(@NotNull MenuType menu, int min, int max) { super(menu, min, max); } - public SettingModifier(@Nonnull MenuType menu, int min, int max, int defaultValue) { + public SettingModifier(@NotNull MenuType menu, int min, int max, int defaultValue) { super(menu, min, max, defaultValue); } @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + public void handleClick(@NotNull ChallengeMenuClickInfo info) { if (info.isUpperItemClick() || !enabled) { setEnabled(!enabled); SoundSample.playStatusSound(info.getPlayer(), enabled); @@ -48,13 +47,13 @@ public void restoreDefaults() { setEnabled(false); } - @Nonnull + @NotNull @Override public ItemStack getSettingsItem() { return isEnabled() ? super.getSettingsItem() : DefaultItem.disabled().build(); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { return DefaultItem.enabled().amount(getValue()); @@ -92,13 +91,13 @@ public void handleShutdown() { } @Override - public void writeSettings(@Nonnull Document document) { + public void writeSettings(@NotNull Document document) { super.writeSettings(document); document.set("enabled", enabled); } @Override - public void loadSettings(@Nonnull Document document) { + public void loadSettings(@NotNull Document document) { super.loadSettings(document); setEnabled(document.getBoolean("enabled")); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java index 8945fef12..20c2ac95e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java @@ -6,21 +6,20 @@ import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; import org.bukkit.inventory.ItemStack; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public abstract class SettingModifierCollectionGoal extends ModifierCollectionGoal { - public SettingModifierCollectionGoal(int min, int max, @Nonnull Object... target) { + public SettingModifierCollectionGoal(int min, int max, @NotNull Object... target) { super(min, max, target); } - public SettingModifierCollectionGoal(int min, int max, int defaultValue, @Nonnull Object... target) { + public SettingModifierCollectionGoal(int min, int max, int defaultValue, @NotNull Object... target) { super(min, max, defaultValue, target); } @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + public void handleClick(@NotNull ChallengeMenuClickInfo info) { if (info.isUpperItemClick() || !enabled) { setEnabled(!enabled); SoundSample.playStatusSound(info.getPlayer(), enabled); @@ -36,13 +35,13 @@ public void restoreDefaults() { setEnabled(false); } - @Nonnull + @NotNull @Override public ItemStack getSettingsItem() { return isEnabled() ? super.getSettingsItem() : DefaultItem.disabled().build(); } - @Nonnull + @NotNull @Override public ItemBuilder createSettingsItem() { return DefaultItem.enabled().amount(getValue()); @@ -61,13 +60,13 @@ public boolean isEnabled() { @Override - public void writeSettings(@Nonnull Document document) { + public void writeSettings(@NotNull Document document) { super.writeSettings(document); document.set("enabled", enabled); } @Override - public void loadSettings(@Nonnull Document document) { + public void loadSettings(@NotNull Document document) { super.loadSettings(document); setEnabled(document.getBoolean("enabled")); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java index ceea748b8..710888da6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java @@ -6,25 +6,24 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.commons.bukkit.utils.animation.SoundSample; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public abstract class SettingModifierGoal extends SettingModifier implements IGoal { - public SettingModifierGoal(@Nonnull MenuType menu) { + public SettingModifierGoal(@NotNull MenuType menu) { super(menu); } - public SettingModifierGoal(@Nonnull MenuType menu, int max) { + public SettingModifierGoal(@NotNull MenuType menu, int max) { super(menu, max); } - public SettingModifierGoal(@Nonnull MenuType menu, int min, int max) { + public SettingModifierGoal(@NotNull MenuType menu, int min, int max) { super(menu, min, max); } - public SettingModifierGoal(@Nonnull MenuType menu, int min, int max, int defaultValue) { + public SettingModifierGoal(@NotNull MenuType menu, int min, int max, int defaultValue) { super(menu, min, max, defaultValue); } @@ -35,7 +34,7 @@ public final void setEnabled(boolean enabled) { super.setEnabled(enabled); } - @Nonnull + @NotNull @Override public SoundSample getStartSound() { return SoundSample.DRAGON_BREATH; @@ -48,7 +47,7 @@ public SoundSample getWinSound() { } @Override - public void handleClick(@Nonnull ChallengeMenuClickInfo info) { + public void handleClick(@NotNull ChallengeMenuClickInfo info) { if (info.isLowerItemClick() && isEnabled()) { ChallengeHelper.handleModifierClick(info, this); } else { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java index b1c6931c6..619905f95 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java @@ -8,9 +8,6 @@ import org.bukkit.Bukkit; import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; - public abstract class TimedChallenge extends SettingModifier { private final boolean runAsync; @@ -20,38 +17,38 @@ public abstract class TimedChallenge extends SettingModifier { private boolean timerStatus = false; private boolean startedBefore = false; - public TimedChallenge(@Nonnull MenuType menu) { + public TimedChallenge(@NotNull MenuType menu) { this(menu, true); } - public TimedChallenge(@Nonnull MenuType menu, int max) { + public TimedChallenge(@NotNull MenuType menu, int max) { this(menu, max, true); } - public TimedChallenge(@Nonnull MenuType menu, int min, int max) { + public TimedChallenge(@NotNull MenuType menu, int min, int max) { this(menu, min, max, true); } - public TimedChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { + public TimedChallenge(@NotNull MenuType menu, int min, int max, int defaultValue) { this(menu, min, max, defaultValue, true); } - public TimedChallenge(@Nonnull MenuType menu, boolean runAsync) { + public TimedChallenge(@NotNull MenuType menu, boolean runAsync) { super(menu); this.runAsync = runAsync; } - public TimedChallenge(@Nonnull MenuType menu, int max, boolean runAsync) { + public TimedChallenge(@NotNull MenuType menu, int max, boolean runAsync) { super(menu, max); this.runAsync = runAsync; } - public TimedChallenge(@Nonnull MenuType menu, int min, int max, boolean runAsync) { + public TimedChallenge(@NotNull MenuType menu, int min, int max, boolean runAsync) { super(menu, min, max); this.runAsync = runAsync; } - public TimedChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue, boolean runAsync) { + public TimedChallenge(@NotNull MenuType menu, int min, int max, int defaultValue, boolean runAsync) { super(menu, min, max, defaultValue); this.runAsync = runAsync; } @@ -97,7 +94,7 @@ public final void executeTimeActivation() { } } - public final void shortCountDownTo(@Nonnegative int seconds) { + public final void shortCountDownTo(int seconds) { if (!timerStatus) throw new IllegalArgumentException("Countdown is not started"); if (seconds > originalSecondsUntilActivation) throw new IllegalArgumentException("Cannot short countdown to a higher length than originally set"); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java index 293b72f9f..5bc55e0eb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java @@ -14,9 +14,9 @@ import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.potion.PotionEffect; import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.List; import java.util.function.BiConsumer; @@ -26,35 +26,35 @@ public abstract class WorldDependentChallenge extends TimedChallenge { private BiConsumer lastTeleport; private int teleportIndex; - public WorldDependentChallenge(@Nonnull MenuType menu) { + public WorldDependentChallenge(@NotNull MenuType menu) { super(menu); } - public WorldDependentChallenge(@Nonnull MenuType menu, int max) { + public WorldDependentChallenge(@NotNull MenuType menu, int max) { super(menu, max); } - public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max) { + public WorldDependentChallenge(@NotNull MenuType menu, int min, int max) { super(menu, min, max); } - public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue) { + public WorldDependentChallenge(@NotNull MenuType menu, int min, int max, int defaultValue) { super(menu, min, max, defaultValue); } - public WorldDependentChallenge(@Nonnull MenuType menu, boolean runAsync) { + public WorldDependentChallenge(@NotNull MenuType menu, boolean runAsync) { super(menu, runAsync); } - public WorldDependentChallenge(@Nonnull MenuType menu, int max, boolean runAsync) { + public WorldDependentChallenge(@NotNull MenuType menu, int max, boolean runAsync) { super(menu, max, runAsync); } - public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max, boolean runAsync) { + public WorldDependentChallenge(@NotNull MenuType menu, int min, int max, boolean runAsync) { super(menu, min, max, runAsync); } - public WorldDependentChallenge(@Nonnull MenuType menu, int min, int max, int defaultValue, boolean runAsync) { + public WorldDependentChallenge(@NotNull MenuType menu, int min, int max, int defaultValue, boolean runAsync) { super(menu, min, max, defaultValue, runAsync); } @@ -77,7 +77,7 @@ protected boolean getTimerTrigger() { return inExtraWorld || !Challenges.getInstance().getWorldManager().isWorldInUse(); } - protected void teleportToWorld(boolean allowJoinCatchUp, @Nonnull BiConsumer action) { + protected void teleportToWorld(boolean allowJoinCatchUp, @NotNull BiConsumer action) { if (Challenges.getInstance().getWorldManager().isWorldInUse()) return; Challenges.getInstance().getWorldManager().setWorldInUse(inExtraWorld = true); lastTeleport = allowJoinCatchUp ? action : null; @@ -97,11 +97,11 @@ protected void teleportBack() { teleportIndex = 0; } - protected void teleportBack(@Nonnull Player player) { + protected void teleportBack(@NotNull Player player) { Challenges.getInstance().getWorldManager().restorePlayerData(player); } - private void teleport(@Nonnull Player player, @Nullable BiConsumer teleport) { + private void teleport(@NotNull Player player, @Nullable BiConsumer teleport) { player.getInventory().clear(); player.setFoodLevel(20); player.setSaturation(20); @@ -118,7 +118,7 @@ private void teleport(@Nonnull Player player, @Nullable BiConsumer ingamePlayers = ChallengeHelper.getIngamePlayers(); if (ingamePlayers.isEmpty()) return; @@ -128,7 +128,7 @@ protected void teleportSpectator(@Nonnull Player player) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onJoin(@Nonnull PlayerJoinEvent event) { + public void onJoin(@NotNull PlayerJoinEvent event) { if (isInExtraWorld()) { if (lastTeleport == null) return; if (Challenges.getInstance().getWorldManager().hasPlayerData(event.getPlayer())) return; @@ -138,12 +138,12 @@ public void onJoin(@Nonnull PlayerJoinEvent event) { } } - @Nonnull + @NotNull protected final World getExtraWorld() { return Challenges.getInstance().getWorldManager().getExtraWorld(); } - @Nonnull + @NotNull protected final WorldSettings getExtraWorldSettings() { return Challenges.getInstance().getWorldManager().getSettings(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java index 4c992555a..6184dffe1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeConfigHelper.java @@ -2,9 +2,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.commons.common.config.Document; - -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public final class ChallengeConfigHelper { @@ -17,8 +15,7 @@ public final class ChallengeConfigHelper { private ChallengeConfigHelper() { } - @Nonnull - @CheckReturnValue + @NotNull public static Document getSettingsDocument() { return settingsDocument; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index f5d4c9b7c..cc986a8b2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -27,10 +27,9 @@ import org.bukkit.event.entity.EntityDamageEvent.DamageModifier; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.List; import java.util.stream.Collectors; @@ -42,7 +41,7 @@ public final class ChallengeHelper { private ChallengeHelper() { } - public static void kill(@Nonnull Player player) { + public static void kill(@NotNull Player player) { if (!Bukkit.isPrimaryThread()) { Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> kill(player)); @@ -54,23 +53,23 @@ public static void kill(@Nonnull Player player) { inInstantKill = false; } - public static void kill(@Nonnull Player player, int delay) { + public static void kill(@NotNull Player player, int delay) { Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> kill(player), delay); } - public static void updateItems(@Nonnull IChallenge challenge) { + public static void updateItems(@NotNull IChallenge challenge) { challenge.getType().executeWithGenerator(ChallengeMenuGenerator.class, gen -> gen.updateItem(challenge)); } - public static boolean canInstaKillOnEnable(@Nonnull IChallenge challenge) { + public static boolean canInstaKillOnEnable(@NotNull IChallenge challenge) { return challenge.getClass().isAnnotationPresent(CanInstaKillOnEnable.class); } - public static boolean isExcludedFromRandomChallenges(@Nonnull IChallenge challenge) { + public static boolean isExcludedFromRandomChallenges(@NotNull IChallenge challenge) { return challenge.getClass().isAnnotationPresent(ExcludeFromRandomChallenges.class); } - public static void handleModifierClick(@Nonnull MenuClickInfo info, @Nonnull IModifier modifier) { + public static void handleModifierClick(@NotNull MenuClickInfo info, @NotNull IModifier modifier) { int newValue = modifier.getValue(); int amount = info.isShiftClick() ? (modifier.getValue() == modifier.getMinValue() || info.isRightClick() && modifier.getValue() == (10 - (modifier.getMinValue() - 1)) ? 9 : 10) @@ -87,19 +86,19 @@ public static void handleModifierClick(@Nonnull MenuClickInfo info, @Nonnull IMo SoundSample.CLICK.play(info.getPlayer()); } - @Nonnull - public static String getColoredChallengeName(@Nonnull AbstractChallenge challenge) { + @NotNull + public static String getColoredChallengeName(@NotNull AbstractChallenge challenge) { ItemBuilder item = challenge.createDisplayItem(); ItemDescription description = item.getBuiltByItemDescription(); if (description == null) return Message.NULL; return description.getOriginalName(); } - public static void breakBlock(@Nonnull Block block, @Nullable ItemStack tool) { + public static void breakBlock(@NotNull Block block, @Nullable ItemStack tool) { breakBlock(block, tool, null); } - public static void breakBlock(@Nonnull Block block, @Nullable ItemStack tool, @Nullable Inventory targetInventory) { + public static void breakBlock(@NotNull Block block, @Nullable ItemStack tool, @Nullable Inventory targetInventory) { if (!ChallengeAPI.getDropChance(block.getType())) return; boolean putIntoInventory = ChallengeAPI.getItemsDirectIntoInventory() && targetInventory != null; @@ -126,7 +125,7 @@ public static void breakBlock(@Nonnull Block block, @Nullable ItemStack tool, @N } - public static void dropItem(@Nonnull ItemStack itemStack, @Nonnull Location dropLocation, @Nonnull Inventory inventory) { + public static void dropItem(@NotNull ItemStack itemStack, @NotNull Location dropLocation, @NotNull Inventory inventory) { boolean directIntoInventory = Challenges.getInstance().getBlockDropManager().isItemsDirectIntoInventory(); if (directIntoInventory) { @@ -139,13 +138,13 @@ public static void dropItem(@Nonnull ItemStack itemStack, @Nonnull Location drop } - public static boolean ignoreDamager(@Nonnull Entity damager) { + public static boolean ignoreDamager(@NotNull Entity damager) { Player damagerPlayer = getDamagerPlayer(damager); if (damagerPlayer == null) return false; return AbstractChallenge.ignorePlayer(damagerPlayer); } - public static Player getDamagerPlayer(@Nonnull Entity damager) { + public static Player getDamagerPlayer(@NotNull Entity damager) { if (damager instanceof Player) return ((Player) damager); if (damager instanceof Projectile && ((Projectile) damager).getShooter() instanceof Player) return ((Player) ((Projectile) damager).getShooter()); @@ -156,61 +155,61 @@ public static List getIngamePlayers() { return Bukkit.getOnlinePlayers().stream().filter(player -> !AbstractChallenge.ignorePlayer(player)).collect(Collectors.toList()); } - public static void playToggleChallengeTitle(@Nonnull AbstractChallenge challenge) { + public static void playToggleChallengeTitle(@NotNull AbstractChallenge challenge) { playToggleChallengeTitle(challenge, challenge.isEnabled()); } - public static void playToggleChallengeTitle(@Nonnull AbstractChallenge challenge, boolean enabled) { + public static void playToggleChallengeTitle(@NotNull AbstractChallenge challenge, boolean enabled) { Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(enabled ? Message.forName("title-challenge-enabled") : Message.forName("title-challenge-disabled"), getColoredChallengeName(challenge)); } - public static void playChangeChallengeValueTitle(@Nonnull AbstractChallenge challenge, @Nonnull IModifier modifier) { + public static void playChangeChallengeValueTitle(@NotNull AbstractChallenge challenge, @NotNull IModifier modifier) { playChangeChallengeValueTitle(challenge, modifier.getValue()); } - public static void playChangeChallengeValueTitle(@Nonnull Modifier modifier) { + public static void playChangeChallengeValueTitle(@NotNull Modifier modifier) { playChangeChallengeValueTitle(modifier, modifier.getValue()); } - public static void playChangeChallengeValueTitle(@Nonnull AbstractChallenge modifier, @Nullable Object value) { + public static void playChangeChallengeValueTitle(@NotNull AbstractChallenge modifier, @Nullable Object value) { Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(Message.forName("title-challenge-value-changed"), getColoredChallengeName(modifier), value); } - public static void playChallengeHeartsValueChangeTitle(@Nonnull AbstractChallenge challenge, int health) { + public static void playChallengeHeartsValueChangeTitle(@NotNull AbstractChallenge challenge, int health) { playChangeChallengeValueTitle(challenge, (health / 2f) + " §c❤"); } - public static void playChallengeHeartsValueChangeTitle(@Nonnull Modifier modifier) { + public static void playChallengeHeartsValueChangeTitle(@NotNull Modifier modifier) { playChallengeHeartsValueChangeTitle(modifier, modifier.getValue()); } - public static void playChallengeSecondsValueChangeTitle(@Nonnull AbstractChallenge challenge, int seconds) { + public static void playChallengeSecondsValueChangeTitle(@NotNull AbstractChallenge challenge, int seconds) { playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds").asString(seconds)); } - public static void playChallengeSecondsRangeValueChangeTitle(@Nonnull AbstractChallenge challenge, int min, int max) { + public static void playChallengeSecondsRangeValueChangeTitle(@NotNull AbstractChallenge challenge, int min, int max) { playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds-range").asString(min, max)); } - public static void playChallengeMinutesValueChangeTitle(@Nonnull AbstractChallenge challenge, int seconds) { + public static void playChallengeMinutesValueChangeTitle(@NotNull AbstractChallenge challenge, int seconds) { playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-minutes").asString(seconds)); } - @Nonnull - public static String[] getTimeRangeSettingsDescription(@Nonnull Modifier modifier, @Nonnegative int multiplier, @Nonnegative int range) { + @NotNull + public static String[] getTimeRangeSettingsDescription(@NotNull Modifier modifier, int multiplier, int range) { return Message.forName("item-time-seconds-range-description").asArray(modifier.getValue() * multiplier - range, modifier.getValue() * multiplier + range); } - @Nonnull - public static String[] getTimeRangeSettingsDescription(@Nonnull Modifier modifier, @Nonnegative int range) { + @NotNull + public static String[] getTimeRangeSettingsDescription(@NotNull Modifier modifier, int range) { return getTimeRangeSettingsDescription(modifier, 1, range); } - public static boolean finalDamageIsNull(@Nonnull EntityDamageEvent event) { + public static boolean finalDamageIsNull(@NotNull EntityDamageEvent event) { return getFinalDamage(event) == 0; } - public static double getFinalDamage(@Nonnull EntityDamageEvent event) { + public static double getFinalDamage(@NotNull EntityDamageEvent event) { return event.getFinalDamage() + event.getDamage(DamageModifier.ABSORPTION); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java index 01db8cb5f..77e52dc2c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java @@ -11,8 +11,8 @@ import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicInteger; @@ -28,7 +28,7 @@ public final class GoalHelper { private GoalHelper() { } - public static void handleSetEnabled(@Nonnull IGoal goal, boolean enabled) { + public static void handleSetEnabled(@NotNull IGoal goal, boolean enabled) { if (Challenges.getInstance().getChallengeManager().getCurrentGoal() != goal && enabled) { Challenges.getInstance().getChallengeManager().setCurrentGoal(goal); } else if (Challenges.getInstance().getChallengeManager().getCurrentGoal() == goal && !enabled) { @@ -36,8 +36,8 @@ public static void handleSetEnabled(@Nonnull IGoal goal, boolean enabled) { } } - @Nonnull - public static SortedMap> createLeaderboardFromPoints(@Nonnull Map points) { + @NotNull + public static SortedMap> createLeaderboardFromPoints(@NotNull Map points) { SortedMap> leaderboard = new TreeMap<>(Collections.reverseOrder()); for (Entry entry : points.entrySet()) { List players = leaderboard.computeIfAbsent(entry.getValue(), key -> new ArrayList<>()); @@ -46,8 +46,8 @@ public static SortedMap> createLeaderboardFromPoints(@Nonn return leaderboard; } - @Nonnull - public static Map createPointsFromValues(@Nonnull AtomicInteger mostPoints, @Nonnull Map map, @Nonnull ToIntBiFunction mapper, boolean zeros) { + @NotNull + public static Map createPointsFromValues(@NotNull AtomicInteger mostPoints, @NotNull Map map, @NotNull ToIntBiFunction mapper, boolean zeros) { Map result = new HashMap<>(); if (zeros) ChallengeAPI.getIngamePlayers().forEach(player -> result.put(player, 0)); for (Entry entry : map.entrySet()) { @@ -69,7 +69,7 @@ public static Map createPointsFromValues(@Nonnull AtomicInt return result; } - public static int determinePosition(@Nonnull SortedMap> map, @Nonnull E target) { + public static int determinePosition(@NotNull SortedMap> map, @NotNull E target) { int position = 1; for (Entry> entry : map.entrySet()) { if (entry.getValue().contains(target)) break; @@ -78,13 +78,13 @@ public static int determinePosition(@Nonnull SortedMap> map, @Non return position; } - @Nonnull - public static BiConsumer createScoreboard(@Nonnull Supplier> points) { + @NotNull + public static BiConsumer createScoreboard(@NotNull Supplier> points) { return createScoreboard(points, player -> new LinkedList<>()); } - @Nonnull - public static BiConsumer createScoreboard(@Nonnull Supplier> points, Function> additionalLines) { + @NotNull + public static BiConsumer createScoreboard(@NotNull Supplier> points, Function> additionalLines) { return (scoreboard, player) -> { SortedMap> leaderboard = GoalHelper.createLeaderboardFromPoints(points.get()); int playerPlace = GoalHelper.determinePosition(leaderboard, player); @@ -120,7 +120,7 @@ public static BiConsumer createScoreboard(@Nonnull S }; } - public static void getWinnersOnEnd(@Nonnull List winners, @Nonnull Map points) { + public static void getWinnersOnEnd(@NotNull List winners, @NotNull Map points) { AtomicInteger mostPoints = new AtomicInteger(); List currentWinners = new LinkedList<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java index 69cdcba2e..18e0976c5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java @@ -4,8 +4,8 @@ import net.codingarea.challenges.plugin.utils.misc.ColorConversions; import net.codingarea.commons.common.config.Document; import org.bukkit.ChatColor; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; @@ -19,14 +19,14 @@ public final class ItemDescription { private final String name; private final String originalName; - public ItemDescription(@Nonnull String[] themeColors, @Nonnull String name, @Nonnull String[] formattedLore) { + public ItemDescription(@NotNull String[] themeColors, @NotNull String name, @NotNull String[] formattedLore) { this.colors = themeColors; this.name = Message.forName("item-prefix") + name; this.originalName = name; this.lore = formattedLore; } - public ItemDescription(@Nonnull String[] description) { + public ItemDescription(@NotNull String[] description) { if (description.length == 0) throw new IllegalArgumentException("Invalid item description: Cannot be empty"); @@ -43,27 +43,27 @@ public static ItemDescription empty() { return new ItemDescription(new String[]{"§e"}, Message.NULL, new String[0]); } - @Nonnull + @NotNull public String getName() { return name; } - @Nonnull + @NotNull public String getOriginalName() { return originalName; } - @Nonnull + @NotNull public String[] getTheme() { return colors; } - @Nonnull + @NotNull public String[] getLore() { return lore; } - private void fillLore(@Nonnull String[] origin, @Nonnull List output) { + private void fillLore(@NotNull String[] origin, @NotNull List output) { String colorBefore = "§7"; boolean inColor = false; @@ -107,7 +107,7 @@ private void fillLore(@Nonnull String[] origin, @Nonnull List output) { } - private String[] determineColors(@Nonnull String input) { + private String[] determineColors(@NotNull String input) { List colors = new LinkedList<>(); int colorIndex = 0; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java index cef0c1b7e..d76ab1145 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java @@ -6,10 +6,10 @@ import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; @@ -18,7 +18,7 @@ public interface Message { String NULL = "§r§fN/A"; Collection UNKNOWN_MESSAGES = new ArrayList<>(); - static String unknown(@Nonnull String name) { + static String unknown(@NotNull String name) { if (!UNKNOWN_MESSAGES.contains(name)) { UNKNOWN_MESSAGES.add(name); Logger.warn("Tried accessing unknown messages '{}'", name); @@ -27,57 +27,57 @@ static String unknown(@Nonnull String name) { return name; } - @Nonnull + @NotNull @CheckReturnValue - static Message forName(@Nonnull String name) { + static Message forName(@NotNull String name) { return MessageManager.getOrCreateMessage(name); } - @Nonnull - String asString(@Nonnull Object... args); + @NotNull + String asString(@NotNull Object... args); - @Nonnull - BaseComponent asComponent(@Nonnull Object... args); + @NotNull + BaseComponent asComponent(@NotNull Object... args); - @Nonnull - String asRandomString(@Nonnull IRandom random, @Nonnull Object... args); + @NotNull + String asRandomString(@NotNull IRandom random, @NotNull Object... args); - @Nonnull - BaseComponent asRandomComponent(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args); + @NotNull + BaseComponent asRandomComponent(@NotNull IRandom random, @NotNull Prefix prefix, @NotNull Object... args); - @Nonnull - String asRandomString(@Nonnull Object... args); + @NotNull + String asRandomString(@NotNull Object... args); - @Nonnull - String[] asArray(@Nonnull Object... args); + @NotNull + String[] asArray(@NotNull Object... args); - @Nonnull - BaseComponent[] asComponentArray(@Nullable Prefix prefix, @Nonnull Object... args); + @NotNull + BaseComponent[] asComponentArray(@Nullable Prefix prefix, @NotNull Object... args); - @Nonnull - ItemDescription asItemDescription(@Nonnull Object... args); + @NotNull + ItemDescription asItemDescription(@NotNull Object... args); - void send(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args); + void send(@NotNull CommandSender target, @NotNull Prefix prefix, @NotNull Object... args); - void sendRandom(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args); + void sendRandom(@NotNull CommandSender target, @NotNull Prefix prefix, @NotNull Object... args); - void sendRandom(@Nonnull IRandom random, @Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args); + void sendRandom(@NotNull IRandom random, @NotNull CommandSender target, @NotNull Prefix prefix, @NotNull Object... args); - void broadcast(@Nonnull Prefix prefix, @Nonnull Object... args); + void broadcast(@NotNull Prefix prefix, @NotNull Object... args); - void broadcastRandom(@Nonnull Prefix prefix, @Nonnull Object... args); + void broadcastRandom(@NotNull Prefix prefix, @NotNull Object... args); - void broadcastRandom(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args); + void broadcastRandom(@NotNull IRandom random, @NotNull Prefix prefix, @NotNull Object... args); - void broadcastTitle(@Nonnull Object... args); + void broadcastTitle(@NotNull Object... args); - void sendTitle(@Nonnull Player player, @Nonnull Object... args); + void sendTitle(@NotNull Player player, @NotNull Object... args); - void sendTitleInstant(@Nonnull Player player, @Nonnull Object... args); + void sendTitleInstant(@NotNull Player player, @NotNull Object... args); - void setValue(@Nonnull String[] value); + void setValue(@NotNull String[] value); - @Nonnull + @NotNull String getName(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java index 710264bdc..4fc52a295 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.content; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -24,31 +24,28 @@ public class Prefix { private final String defaultValue; private String value; - private Prefix(@Nonnull String name, @Nonnull String defaultValue) { + private Prefix(@NotNull String name, @NotNull String defaultValue) { this.defaultValue = getDefaultValueFor(defaultValue); this.name = name; } - @Nonnull - @CheckReturnValue + @NotNull public static Collection values() { return Collections.unmodifiableCollection(values.values()); } - @Nonnull - @CheckReturnValue - public static Prefix forName(@Nonnull String name, @Nonnull String defaultValue) { + @NotNull + public static Prefix forName(@NotNull String name, @NotNull String defaultValue) { return values.computeIfAbsent(name, key -> new Prefix(name, defaultValue)); } - @Nonnull - @CheckReturnValue - public static Prefix forName(@Nonnull String name) { + @NotNull + public static Prefix forName(@NotNull String name) { return forName(name, name); } - @Nonnull - public static String getDefaultValueFor(@Nonnull String value) { + @NotNull + public static String getDefaultValueFor(@NotNull String value) { return "§8§l┃ " + value + " §8┃ "; } @@ -56,13 +53,13 @@ public void setValue(@Nullable String value) { this.value = value == null ? null : value.endsWith(" ") ? value : value + " "; } - @Nonnull + @NotNull @Override public String toString() { return (value == null ? defaultValue : value) + "§7"; } - @Nonnull + @NotNull public String getName() { return name; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java index 77acaf2ee..a1dbc6e35 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java @@ -14,9 +14,9 @@ import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.LinkedList; import java.util.List; import java.util.function.BiConsumer; @@ -27,25 +27,25 @@ public class MessageImpl implements Message { protected final String name; protected String[] value; - public MessageImpl(@Nonnull String name) { + public MessageImpl(@NotNull String name) { this.name = name; } - @Nonnull + @NotNull protected static IRandom defaultRandom() { return IRandom.threadLocal(); } - @Nonnull + @NotNull @Override - public String asString(@Nonnull Object... args) { + public String asString(@NotNull Object... args) { if (value == null) return name; return String.join("\n", asArray(args)); } - @Nonnull + @NotNull @Override - public BaseComponent asComponent(@Nonnull Object... args) { + public BaseComponent asComponent(@NotNull Object... args) { if (value == null) return new TextComponent(name); BaseComponent[] components = asComponentArray(null, args); BaseComponent first = null; @@ -57,31 +57,31 @@ public BaseComponent asComponent(@Nonnull Object... args) { return first == null ? new TextComponent() : first; } - @Nonnull + @NotNull @Override - public String asRandomString(@Nonnull Object... args) { + public String asRandomString(@NotNull Object... args) { return asRandomString(defaultRandom(), args); } - @Nonnull + @NotNull @Override - public String asRandomString(@Nonnull IRandom random, @Nonnull Object... args) { + public String asRandomString(@NotNull IRandom random, @NotNull Object... args) { String[] array = asArray(args); if (array.length == 0) return Message.unknown(name); return random.choose(array); } - @Nonnull + @NotNull @Override - public BaseComponent asRandomComponent(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args) { + public BaseComponent asRandomComponent(@NotNull IRandom random, @NotNull Prefix prefix, @NotNull Object... args) { BaseComponent[] array = asComponentArray(prefix, args); if (array.length == 0) return new TextComponent(Message.unknown(name)); return random.choose(array); } - @Nonnull + @NotNull @Override - public String[] asArray(@Nonnull Object... args) { + public String[] asArray(@NotNull Object... args) { if (value == null) return new String[]{Message.unknown(name)}; args = BukkitStringUtils.replaceArguments(args, true); LanguageLoader loader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); @@ -90,16 +90,16 @@ public String[] asArray(@Nonnull Object... args) { return capsFont ? FontUtils.toSmallCaps(StringUtils.format(value, args)) : StringUtils.format(value, args); } - @Nonnull + @NotNull @Override - public BaseComponent[] asComponentArray(@Nullable Prefix prefix, @Nonnull Object... args) { + public BaseComponent[] asComponentArray(@Nullable Prefix prefix, @NotNull Object... args) { if (value == null) return new TextComponent[]{new TextComponent(Message.unknown(name))}; return BukkitStringUtils.format(prefix, value, args); } - @Nonnull + @NotNull @Override - public ItemDescription asItemDescription(@Nonnull Object... args) { + public ItemDescription asItemDescription(@NotNull Object... args) { if (value == null) { Message.unknown(name); return ItemDescription.empty(); @@ -108,42 +108,42 @@ public ItemDescription asItemDescription(@Nonnull Object... args) { } @Override - public void send(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args) { + public void send(@NotNull CommandSender target, @NotNull Prefix prefix, @NotNull Object... args) { doSendLines(component -> target.spigot().sendMessage(component), prefix, asComponentArray(prefix, args)); } @Override - public void sendRandom(@Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args) { + public void sendRandom(@NotNull CommandSender target, @NotNull Prefix prefix, @NotNull Object... args) { sendRandom(defaultRandom(), target, prefix, args); } @Override - public void sendRandom(@Nonnull IRandom random, @Nonnull CommandSender target, @Nonnull Prefix prefix, @Nonnull Object... args) { + public void sendRandom(@NotNull IRandom random, @NotNull CommandSender target, @NotNull Prefix prefix, @NotNull Object... args) { doSendLine(components -> target.spigot().sendMessage(components), prefix, asRandomComponent(random, prefix, args)); } @Override - public void broadcast(@Nonnull Prefix prefix, @Nonnull Object... args) { + public void broadcast(@NotNull Prefix prefix, @NotNull Object... args) { doSendLines(components -> Bukkit.spigot().broadcast(components), prefix, asComponentArray(prefix, args)); } @Override - public void broadcastRandom(@Nonnull Prefix prefix, @Nonnull Object... args) { + public void broadcastRandom(@NotNull Prefix prefix, @NotNull Object... args) { broadcastRandom(defaultRandom(), prefix, args); } @Override - public void broadcastRandom(@Nonnull IRandom random, @Nonnull Prefix prefix, @Nonnull Object... args) { + public void broadcastRandom(@NotNull IRandom random, @NotNull Prefix prefix, @NotNull Object... args) { doSendLine(component -> Bukkit.spigot().broadcast(component), prefix, asRandomComponent(random, prefix, args)); } - private void doSendLines(@Nonnull Consumer sender, @Nonnull Prefix prefix, @Nonnull BaseComponent[] components) { + private void doSendLines(@NotNull Consumer sender, @NotNull Prefix prefix, @NotNull BaseComponent[] components) { for (BaseComponent line : components) { doSendLine(sender, prefix, line); } } - private void doSendLine(@Nonnull Consumer sender, @Nonnull Prefix prefix, BaseComponent component) { + private void doSendLine(@NotNull Consumer sender, @NotNull Prefix prefix, BaseComponent component) { LanguageLoader loader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); boolean capsFont = false; if (loader != null) capsFont = loader.isSmallCapsFont(); @@ -177,41 +177,41 @@ private void doSendLine(@Nonnull Consumer sender, @Nonnul } @Override - public void broadcastTitle(@Nonnull Object... args) { + public void broadcastTitle(@NotNull Object... args) { String[] title = asArray(args); Bukkit.getOnlinePlayers().forEach(player -> doSendTitle(player, title)); } @Override - public void sendTitle(@Nonnull Player player, @Nonnull Object... args) { + public void sendTitle(@NotNull Player player, @NotNull Object... args) { doSendTitle(player, asArray(args)); } @Override - public void sendTitleInstant(@Nonnull Player player, @Nonnull Object... args) { + public void sendTitleInstant(@NotNull Player player, @NotNull Object... args) { doSendTitleInstant(player, asArray(args)); } - protected void doSendTitle(@Nonnull Player player, @Nonnull String[] title) { + protected void doSendTitle(@NotNull Player player, @NotNull String[] title) { sendTitle(title, (line1, line2) -> Challenges.getInstance().getTitleManager().sendTitle(player, line1, line2)); } - protected void doSendTitleInstant(@Nonnull Player player, @Nonnull String[] title) { + protected void doSendTitleInstant(@NotNull Player player, @NotNull String[] title) { sendTitle(title, (line1, line2) -> Challenges.getInstance().getTitleManager().sendTitleInstant(player, line1, line2)); } - protected void sendTitle(@Nonnull String[] title, @Nonnull BiConsumer send) { + protected void sendTitle(@NotNull String[] title, @NotNull BiConsumer send) { if (title.length == 0) send.accept("", ""); else if (title.length == 1) send.accept(title[0], ""); else send.accept(title[0], title[1]); } @Override - public void setValue(@Nonnull String[] value) { + public void setValue(@NotNull String[] value) { this.value = value; } - @Nonnull + @NotNull @Override public String getName() { return name; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java index bf3b08a3a..9b1d0c285 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java @@ -1,9 +1,8 @@ package net.codingarea.challenges.plugin.content.impl; import net.codingarea.challenges.plugin.content.Message; +import org.jetbrains.annotations.NotNull; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -14,14 +13,12 @@ public final class MessageManager { private MessageManager() { } - @Nonnull - @CheckReturnValue - public static Message getOrCreateMessage(@Nonnull String name) { + @NotNull + public static Message getOrCreateMessage(@NotNull String name) { return cache.computeIfAbsent(name, key -> new MessageImpl(key)); } - @CheckReturnValue - public static boolean hasMessageInCache(@Nonnull String name) { + public static boolean hasMessageInCache(@NotNull String name) { return cache.containsKey(name); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java index 7cc40dc00..653e3b45e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/ContentLoader.java @@ -1,24 +1,24 @@ package net.codingarea.challenges.plugin.content.loader; import net.codingarea.challenges.plugin.Challenges; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.io.File; public abstract class ContentLoader { - @Nonnull + @NotNull protected final File getMessagesFolder() { return Challenges.getInstance().getDataFile("messages"); } - @Nonnull - protected final File getMessageFile(@Nonnull String name, @Nonnull String extension) { + @NotNull + protected final File getMessageFile(@NotNull String name, @NotNull String extension) { return new File(getMessagesFolder(), name + "." + extension); } - @Nonnull - protected final String getGitHubUrl(@Nonnull String path) { + @NotNull + protected final String getGitHubUrl(@NotNull String path) { return "https://raw.githubusercontent.com/anweisen/Challenges/" + (Challenges.getInstance().isDevMode() ? "development" : "master") + "/" + path; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index 86404acea..3a0c3ddd3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -14,8 +14,8 @@ import net.codingarea.commons.common.config.FileDocument; import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.commons.common.misc.GsonUtils; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.io.File; import java.io.IOException; import java.util.Map.Entry; @@ -83,7 +83,7 @@ protected void load() { loadDefault(); } - public void changeLanguage(@Nonnull String language) { + public void changeLanguage(@NotNull String language) { if (language.equalsIgnoreCase(this.language)) { Logger.info("Language '{}' is already selected", language); return; @@ -157,7 +157,7 @@ private void download() { } } - private void verifyLanguage(@Nonnull Document download, @Nonnull File file, @Nonnull String name) throws IOException { + private void verifyLanguage(@NotNull Document download, @NotNull File file, @NotNull String name) throws IOException { Document existing = Document.readJsonFile(file); FileUtils.createFilesIfNecessary(file); download.forEach((key, value) -> { @@ -173,7 +173,7 @@ private void read() { readLanguage(getMessageFile(language, "json")); } - private void readLanguage(@Nonnull File file) { + private void readLanguage(@NotNull File file) { try { if (!file.exists()) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java index c6a63dd50..735e8522d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java @@ -3,8 +3,8 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; import net.codingarea.commons.bukkit.utils.logging.Logger; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; @@ -14,11 +14,11 @@ public final class LoaderRegistry { private final Map, Subscribers> subscribers = new HashMap<>(); private final Collection loaders; - public LoaderRegistry(@Nonnull ContentLoader... loaders) { + public LoaderRegistry(@NotNull ContentLoader... loaders) { this.loaders = Arrays.asList(loaders); } - private static void execute(@Nonnull Class classOfLoader, @Nonnull Runnable action) { + private static void execute(@NotNull Class classOfLoader, @NotNull Runnable action) { try { action.run(); } catch (Exception ex) { @@ -35,14 +35,14 @@ public void load() { loaders.forEach(this::executeLoader); } - private void executeLoader(@Nonnull ContentLoader loader) { + private void executeLoader(@NotNull ContentLoader loader) { loading.incrementAndGet(); loader.load(); loading.decrementAndGet(); handleCompleteLoading(loader.getClass()); } - private void handleCompleteLoading(@Nonnull Class classOfLoader) { + private void handleCompleteLoading(@NotNull Class classOfLoader) { Logger.debug("{} finished loading. {} loader(s) left", classOfLoader.getSimpleName(), loading); if (loading.get() == 0) @@ -70,7 +70,7 @@ public boolean isLoading() { return loading.get() > 0; } - public void subscribe(@Nonnull Class classOfLoader, @Nonnull Runnable action) { + public void subscribe(@NotNull Class classOfLoader, @NotNull Runnable action) { Subscribers subscribers = this.subscribers.computeIfAbsent(classOfLoader, key -> new Subscribers(classOfLoader)); subscribers.actions.add(action); @@ -79,7 +79,7 @@ public void subscribe(@Nonnull Class classOfLoader, @No } @SuppressWarnings("unchecked") - public T getFirstLoaderByClass(@Nonnull Class clazz) { + public T getFirstLoaderByClass(@NotNull Class clazz) { for (ContentLoader loader : loaders) { if (loader.getClass().equals(clazz)) { return (T) loader; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java index 626a1ef2f..01a4abb3e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java @@ -7,9 +7,9 @@ import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.*; import java.util.Map.Entry; import java.util.function.BooleanSupplier; @@ -21,8 +21,8 @@ public final class BlockDropManager { private final Map chance = new HashMap<>(); private SubSetting directInventorySetting; - @Nonnull - public Collection getDrops(@Nonnull Block block) { + @NotNull + public Collection getDrops(@NotNull Block block) { if (!getDropChance(block.getType()).getAsBoolean()) return new ArrayList<>(); List customDrops = getCustomDrops(block.getType()); if (!customDrops.isEmpty()) @@ -30,8 +30,8 @@ public Collection getDrops(@Nonnull Block block) { return block.getDrops(); } - @Nonnull - public Collection getDrops(@Nonnull Block block, @Nullable ItemStack tool) { + @NotNull + public Collection getDrops(@NotNull Block block, @Nullable ItemStack tool) { if (!getDropChance(block.getType()).getAsBoolean()) return new ArrayList<>(); List customDrops = getCustomDrops(block.getType()); if (!customDrops.isEmpty()) @@ -39,25 +39,25 @@ public Collection getDrops(@Nonnull Block block, @Nullable ItemStack return block.getDrops(tool); } - @Nonnull - public List getCustomDrops(@Nonnull Material block) { + @NotNull + public List getCustomDrops(@NotNull Material block) { RegisteredDrops option = drops.get(block); if (option == null) return new ArrayList<>(); return option.getFirst().orElse(new ArrayList<>()); } - public void setCustomDrops(@Nonnull Material block, @Nonnull Material item, byte priority) { + public void setCustomDrops(@NotNull Material block, @NotNull Material item, byte priority) { setCustomDrops(block, Collections.singletonList(item), priority); } - public void setCustomDrops(@Nonnull Material block, @Nonnull List items, byte priority) { + public void setCustomDrops(@NotNull Material block, @NotNull List items, byte priority) { Logger.debug("Setting block drop for {} to {} at priority {}", block, items, priority); RegisteredDrops option = this.drops.computeIfAbsent(block, key -> new RegisteredDrops()); option.setOption(priority, items); } - public void resetCustomDrop(@Nonnull Material block, byte priority) { + public void resetCustomDrop(@NotNull Material block, byte priority) { Logger.debug("Resetting block drop for {} at priority {}", block, priority); RegisteredDrops option = drops.get(block); @@ -81,14 +81,14 @@ public void resetCustomDrops(byte priority) { remove.forEach(drops::remove); } - @Nonnull - public BooleanSupplier getDropChance(@Nonnull Material block) { + @NotNull + public BooleanSupplier getDropChance(@NotNull Material block) { RegisteredChance option = chance.get(block); if (option == null) return () -> true; return option.getFirst().orElse(() -> true); } - public void setDropChance(@Nonnull Material block, byte priority, @Nonnull BooleanSupplier chance) { + public void setDropChance(@NotNull Material block, byte priority, @NotNull BooleanSupplier chance) { Logger.debug("Setting block drop chance for {} at priority {}", block, priority); RegisteredChance option = this.chance.computeIfAbsent(block, key -> new RegisteredChance()); @@ -109,7 +109,7 @@ public void resetDropChance(byte priority) { remove.forEach(drops::remove); } - @Nonnull + @NotNull public Map getRegisteredDrops() { return Collections.unmodifiableMap(drops); } @@ -135,7 +135,7 @@ private static abstract class RegisteredOptions { private final SortedMap optionByPriority = new TreeMap<>(Collections.reverseOrder()); - public void setOption(byte priority, @Nonnull T option) { + public void setOption(byte priority, @NotNull T option) { optionByPriority.put(priority, option); } @@ -143,7 +143,7 @@ public void resetOption(byte priority) { optionByPriority.remove(priority); } - @Nonnull + @NotNull public Optional getFirst() { return optionByPriority.values().stream().findFirst(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java index 40943b7cd..c1b83c739 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java @@ -13,9 +13,9 @@ import net.codingarea.commons.common.config.document.wrapper.FileDocumentWrapper; import net.codingarea.commons.database.exceptions.DatabaseException; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; @@ -29,25 +29,25 @@ public final class ChallengeManager { private IGoal currentGoal; - @Nonnull + @NotNull public List getChallenges() { return Collections.unmodifiableList(challenges); } - public void registerGameStateSaver(@Nonnull GamestateSaveable savable) { + public void registerGameStateSaver(@NotNull GamestateSaveable savable) { additionalSaver.add(savable); } - public void register(@Nonnull IChallenge challenge) { + public void register(@NotNull IChallenge challenge) { if (!challenge.getType().isUsable()) throw new IllegalArgumentException("Invalid MenuType"); challenges.add(challenge); } - public void unregister(@Nonnull IChallenge challenge) { + public void unregister(@NotNull IChallenge challenge) { challenges.remove(challenge); } - public void unregisterIf(@Nonnull Predicate predicate) { + public void unregisterIf(@NotNull Predicate predicate) { challenges.removeIf(predicate); } @@ -78,7 +78,7 @@ public void restoreDefaults() { } } - public void saveSettings(@Nonnull Player player) throws DatabaseException { + public void saveSettings(@NotNull Player player) throws DatabaseException { Document document = new GsonDocument(); saveSettingsInto(document); Challenges.getInstance().getDatabaseManager().getDatabase() @@ -88,7 +88,7 @@ public void saveSettings(@Nonnull Player player) throws DatabaseException { .execute(); } - public void saveCustomChallenges(@Nonnull Player player) throws DatabaseException { + public void saveCustomChallenges(@NotNull Player player) throws DatabaseException { Document document = new GsonDocument(); saveCustomChallengesInto(document); Challenges.getInstance().getDatabaseManager().getDatabase() @@ -104,7 +104,7 @@ public void enable() { loadCustomChallenges(Challenges.getInstance().getConfigManager().getCustomChallengesConfig().readonly()); } - public synchronized void loadSettings(@Nonnull Document config) { + public synchronized void loadSettings(@NotNull Document config) { for (IChallenge challenge : challenges) { if (challenge instanceof CustomChallenge) continue; @@ -120,7 +120,7 @@ public synchronized void loadSettings(@Nonnull Document config) { } } - public synchronized void loadGamestate(@Nonnull Document config) { + public synchronized void loadGamestate(@NotNull Document config) { LinkedList list = new LinkedList<>(challenges); list.addAll(additionalSaver); for (GamestateSaveable challenge : list) { @@ -146,7 +146,7 @@ public synchronized void loadGamestate(@Nonnull Document config) { } } - public synchronized void loadCustomChallenges(@Nonnull Document config) { + public synchronized void loadCustomChallenges(@NotNull Document config) { Challenges.getInstance().getCustomChallengesLoader().loadCustomChallengesFrom(config); } @@ -172,7 +172,7 @@ public void resetGamestate() { } } - public void saveGameStateInto(@Nonnull Document config) { + public void saveGameStateInto(@NotNull Document config) { LinkedList list = new LinkedList<>(challenges); list.addAll(additionalSaver); for (GamestateSaveable challenge : list) { @@ -191,7 +191,7 @@ public synchronized void saveGamestate(boolean async) { config.save(async); } - public void saveSettingsInto(@Nonnull Document config) { + public void saveSettingsInto(@NotNull Document config) { for (IChallenge challenge : challenges) { if (challenge instanceof CustomChallenge) continue; try { @@ -209,7 +209,7 @@ public synchronized void saveLocalSettings(boolean async) { config.save(async); } - public void saveCustomChallengesInto(@Nonnull Document config) { + public void saveCustomChallengesInto(@NotNull Document config) { Collection customChallenges = Challenges.getInstance().getCustomChallengesLoader() .getCustomChallenges().values(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java index 6fd7fc5e9..a6451c62e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java @@ -13,8 +13,8 @@ import net.codingarea.challenges.plugin.utils.misc.MapUtils; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.*; @Getter @@ -29,7 +29,7 @@ public CustomChallengesLoader() { maxNameLength = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-name-length"); } - public CustomChallenge registerCustomChallenge(@Nonnull UUID uuid, Material material, String name, ChallengeTrigger trigger, + public CustomChallenge registerCustomChallenge(@NotNull UUID uuid, Material material, String name, ChallengeTrigger trigger, Map subTriggers, ChallengeAction action, Map subActions, boolean generate) { CustomChallenge challenge = customChallenges.getOrDefault(uuid, new CustomChallenge(MenuType.CUSTOM, uuid, material, name, trigger, subTriggers, action, subActions)); if (!customChallenges.containsKey(uuid)) { @@ -42,14 +42,14 @@ public CustomChallenge registerCustomChallenge(@Nonnull UUID uuid, Material mate return challenge; } - public void unregisterCustomChallenge(@Nonnull UUID uuid) { + public void unregisterCustomChallenge(@NotNull UUID uuid) { CustomChallenge challenge = customChallenges.remove(uuid); if (challenge == null) return; Challenges.getInstance().getChallengeLoader().unregister(challenge); generateCustomChallenge(challenge, true, true); } - public void loadCustomChallengesFrom(@Nonnull Document document) { + public void loadCustomChallengesFrom(@NotNull Document document) { customChallenges.clear(); Challenges.getInstance().getChallengeManager().unregisterIf(iChallenge -> iChallenge.getType() == MenuType.CUSTOM); ((ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetChallengeCache(); @@ -104,7 +104,7 @@ private void generateCustomChallenge(CustomChallenge challenge, boolean deleted, } } - public List getCustomChallengesByTrigger(@Nonnull IChallengeTrigger trigger) { + public List getCustomChallengesByTrigger(@NotNull IChallengeTrigger trigger) { List challenges = new LinkedList<>(); for (CustomChallenge challenge : customChallenges.values()) { @@ -116,7 +116,7 @@ public List getCustomChallengesByTrigger(@Nonnull IChallengeTri return challenges; } - public void executeTrigger(@Nonnull ChallengeExecutionData challengeExecutionData) { + public void executeTrigger(@NotNull ChallengeExecutionData challengeExecutionData) { getCustomChallengesByTrigger(challengeExecutionData.getTrigger()) .forEach(customChallenge -> customChallenge .onTriggerFulfilled(challengeExecutionData)); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java index e8eede5ca..b8b71e465 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java @@ -14,8 +14,8 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.lang.reflect.Constructor; import java.util.Optional; @@ -23,11 +23,11 @@ public class ModuleChallengeLoader { protected final BukkitModule plugin; - public ModuleChallengeLoader(@Nonnull BukkitModule plugin) { + public ModuleChallengeLoader(@NotNull BukkitModule plugin) { this.plugin = plugin; } - public final void registerWithCommand(@Nonnull IChallenge challenge, @Nonnull String... commandNames) { + public final void registerWithCommand(@NotNull IChallenge challenge, @NotNull String... commandNames) { try { Challenges.getInstance().getChallengeManager().register(challenge); @@ -45,11 +45,11 @@ public final void registerWithCommand(@Nonnull IChallenge challenge, @Nonnull St } } - public final void register(@Nonnull IChallenge challenge) { + public final void register(@NotNull IChallenge challenge) { registerWithCommand(challenge); } - public final void registerWithCommand(@Nonnull Class classOfChallenge, @Nonnull String[] commandNames, @Nonnull Class[] parameterClasses, @Nonnull Object... parameters) { + public final void registerWithCommand(@NotNull Class classOfChallenge, @NotNull String[] commandNames, @NotNull Class[] parameterClasses, @NotNull Object... parameters) { try { if (classOfChallenge.isAnnotationPresent(RequireVersion.class)) { @@ -72,11 +72,11 @@ public final void registerWithCommand(@Nonnull Class class } } - public final void register(@Nonnull Class classOfChallenge, @Nonnull Class[] parameterClasses, @Nonnull Object... parameters) { + public final void register(@NotNull Class classOfChallenge, @NotNull Class[] parameterClasses, @NotNull Object... parameters) { registerWithCommand(classOfChallenge, new String[0], parameterClasses, parameters); } - public final void register(@Nonnull Class classOfChallenge, @Nonnull Object... parameters) { + public final void register(@NotNull Class classOfChallenge, @NotNull Object... parameters) { Class[] parameterClasses = new Class[parameters.length]; for (int i = 0; i < parameters.length; i++) { @@ -87,27 +87,27 @@ public final void register(@Nonnull Class classOfChallenge } - public final void registerWithCommand(@Nonnull Class classOfChallenge, @Nonnull String... commandNames) { + public final void registerWithCommand(@NotNull Class classOfChallenge, @NotNull String... commandNames) { registerWithCommand(classOfChallenge, commandNames, new Class[0]); } - public final void registerDamageRule(@Nonnull String name, @Nonnull Material material, @Nonnull DamageCause... causes) { + public final void registerDamageRule(@NotNull String name, @NotNull Material material, @NotNull DamageCause... causes) { registerDamageRule(name, new ItemBuilder(material), causes); } - public final void registerDamageRule(@Nonnull String name, @Nonnull ItemBuilder preset, @Nonnull DamageCause... causes) { + public final void registerDamageRule(@NotNull String name, @NotNull ItemBuilder preset, @NotNull DamageCause... causes) { register(DamageRuleSetting.class, new Class[]{ItemBuilder.class, String.class, DamageCause[].class}, preset, name, causes); } - public final void registerMaterialRule(@Nonnull String title, @Nonnull String replacement, @Nonnull Material... materials) { + public final void registerMaterialRule(@NotNull String title, @NotNull String replacement, @NotNull Material... materials) { registerMaterialRule("item-block-material", new Object[]{title, replacement}, materials); } - public final void registerMaterialRule(@Nonnull String name, Object[] replacements, @Nonnull Material... materials) { + public final void registerMaterialRule(@NotNull String name, Object[] replacements, @NotNull Material... materials) { registerMaterialRule(name, new ItemBuilder(materials[0]), replacements, materials); } - public final void registerMaterialRule(@Nonnull String name, @Nonnull ItemBuilder preset, Object[] replacements, @Nonnull Material... materials) { + public final void registerMaterialRule(@NotNull String name, @NotNull ItemBuilder preset, Object[] replacements, @NotNull Material... materials) { register(BlockMaterialSetting.class, new Class[]{String.class, ItemBuilder.class, Object[].class, Material[].class}, name, preset, replacements, materials); } @@ -116,7 +116,7 @@ public final void registerMaterialRule(@Nonnull String name, @Nonnull ItemBuilde * Unregisters an existing challenge and deletes its settings. * It does not unregister commands! */ - public final void unregister(@Nonnull IChallenge challenge) { + public final void unregister(@NotNull IChallenge challenge) { Challenges.getInstance().getChallengeManager().unregister(challenge); Challenges.getInstance().getScheduler().unregister(challenge); Challenges.getInstance().getConfigManager().getSettingsConfig().remove(challenge.getUniqueName()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java index 3f76cf0df..05d0f2c5c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.challenges.annotations; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -12,7 +12,7 @@ @Retention(RetentionPolicy.RUNTIME) public @interface RequireVersion { - @Nonnull + @NotNull MinecraftVersion value(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java index 58f269cee..6439006d9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/entities/GamestateSaveable.java @@ -1,15 +1,14 @@ package net.codingarea.challenges.plugin.management.challenges.entities; import net.codingarea.commons.common.config.Document; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public interface GamestateSaveable { String getUniqueGamestateName(); - void writeGameState(@Nonnull Document document); + void writeGameState(@NotNull Document document); - void loadGameState(@Nonnull Document document); + void loadGameState(@NotNull Document document); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java index 165675448..9b0f18cd3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/cloud/CloudSupportManager.java @@ -15,8 +15,8 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandSendEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.HashMap; import java.util.Map; import java.util.UUID; @@ -52,11 +52,11 @@ public CloudSupportManager() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onCommandsUpdate(@Nonnull PlayerCommandSendEvent event) { + public void onCommandsUpdate(@NotNull PlayerCommandSendEvent event) { cachedColoredNames.remove(event.getPlayer().getUniqueId()); } - private CloudSupport loadSupport(@Nonnull String name) { + private CloudSupport loadSupport(@NotNull String name) { switch (name) { default: return null; @@ -68,8 +68,8 @@ private CloudSupport loadSupport(@Nonnull String name) { } } - @Nonnull - public String getColoredName(@Nonnull Player player) { + @NotNull + public String getColoredName(@NotNull Player player) { if (support == null) throw new IllegalStateException("No support loaded! Check compatibility before use"); if (cachedColoredNames.containsKey(player.getUniqueId())) @@ -83,8 +83,8 @@ public String getColoredName(@Nonnull Player player) { } } - @Nonnull - public String getColoredName(@Nonnull UUID uuid) { + @NotNull + public String getColoredName(@NotNull UUID uuid) { if (support == null) throw new IllegalStateException("No support loaded! Check compatibility before use"); if (cachedColoredNames.containsKey(uuid)) return cachedColoredNames.get(uuid); @@ -97,13 +97,13 @@ public String getColoredName(@Nonnull UUID uuid) { } } - @Nonnull - private String cacheColoredName(@Nonnull UUID uuid, @Nonnull String name) { + @NotNull + private String cacheColoredName(@NotNull UUID uuid, @NotNull String name) { cachedColoredNames.put(uuid, name); return name; } - public boolean hasNameFor(@Nonnull UUID uuid) { + public boolean hasNameFor(@NotNull UUID uuid) { if (support == null) return false; try { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java index dfd72cf9a..e258caf72 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/database/DatabaseManager.java @@ -17,9 +17,9 @@ import org.bukkit.Bukkit; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.Map; @@ -125,11 +125,11 @@ public void disconnectIfConnected() { } @Nullable - private Tuple getDatabaseForName(@Nonnull String type) throws ClassNotFoundException { + private Tuple getDatabaseForName(@NotNull String type) throws ClassNotFoundException { return registry.get(type); } - public void registerDatabase(@Nonnull String name, @Nonnull Class classOfDatabase, @Nonnull JavaPlugin provider) { + public void registerDatabase(@NotNull String name, @NotNull Class classOfDatabase, @NotNull JavaPlugin provider) { registry.put(name, new Tuple<>(classOfDatabase.getName(), provider)); } @@ -141,7 +141,7 @@ public boolean isEnabled() { return database != null; } - private boolean checkDependencies(@Nonnull String... classes) { + private boolean checkDependencies(@NotNull String... classes) { try { for (String name : classes) { Class.forName(name); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java index 7aeb96bb1..13fcd2c1a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java @@ -10,9 +10,9 @@ import net.codingarea.commons.common.misc.FileUtils; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.io.*; import java.util.LinkedList; import java.util.List; @@ -90,7 +90,7 @@ private void copyLarge(InputStream input, OutputStream output, byte[] buffer) th } @Nullable - private FileDocument load(@Nonnull String filename) { + private FileDocument load(@NotNull String filename) { try { File file = Challenges.getInstance().getDataFile(filename); FileUtils.createFilesIfNecessary(file); @@ -101,7 +101,7 @@ private FileDocument load(@Nonnull String filename) { } } - @Nonnull + @NotNull public List getMissingConfigSettings() { return new LinkedList<>(missingConfigSettings); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java index a78e40c6d..7239613f2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java @@ -23,8 +23,8 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.*; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.LinkedList; import java.util.List; import java.util.function.Consumer; @@ -64,39 +64,39 @@ public void handleDisable() { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onCommandsUpdate(@Nonnull PlayerCommandSendEvent event) { + public void onCommandsUpdate(@NotNull PlayerCommandSendEvent event) { updateInventoryAuto(event.getPlayer()); } @EventHandler(priority = EventPriority.HIGH) - public void onJoin(@Nonnull PlayerJoinEvent event) { + public void onJoin(@NotNull PlayerJoinEvent event) { updateInventoryJoin(event.getPlayer(), true); } @EventHandler - public void onQuit(@Nonnull PlayerQuitEvent event) { + public void onQuit(@NotNull PlayerQuitEvent event) { removeItems(event.getPlayer()); } @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) - public void onGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { + public void onGameModeChange(@NotNull PlayerGameModeChangeEvent event) { updateInventoryGamemode(event.getPlayer(), event.getNewGameMode()); } @EventHandler(priority = EventPriority.HIGH) - public void onDrop(@Nonnull PlayerDropItemEvent event) { + public void onDrop(@NotNull PlayerDropItemEvent event) { if (ChallengeAPI.isStarted()) return; if (!hasItems(event.getPlayer())) return; event.setCancelled(true); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onRespawn(@Nonnull PlayerRespawnEvent event) { + public void onRespawn(@NotNull PlayerRespawnEvent event) { updateInventoryAlive(event.getPlayer(), true); } @EventHandler - public void onInteract(@Nonnull PlayerInteractEvent event) { + public void onInteract(@NotNull PlayerInteractEvent event) { switch (event.getAction()) { case LEFT_CLICK_AIR: case LEFT_CLICK_BLOCK: @@ -126,23 +126,23 @@ public void updateInventories() { Bukkit.getOnlinePlayers().forEach(this::updateInventoryAuto); } - public void updateInventoryAuto(@Nonnull Player player) { + public void updateInventoryAuto(@NotNull Player player) { updateInventory(player, player.getGameMode(), false, !player.isDead()); } - public void updateInventoryAlive(@Nonnull Player player, boolean alive) { + public void updateInventoryAlive(@NotNull Player player, boolean alive) { updateInventory(player, player.getGameMode(), false, alive); } - public void updateInventoryGamemode(@Nonnull Player player, @Nonnull GameMode gamemode) { + public void updateInventoryGamemode(@NotNull Player player, @NotNull GameMode gamemode) { updateInventory(player, gamemode, false, !player.isDead()); } - public void updateInventoryJoin(@Nonnull Player player, boolean join) { + public void updateInventoryJoin(@NotNull Player player, boolean join) { updateInventory(player, player.getGameMode(), join, !player.isDead()); } - public void updateInventory(@Nonnull Player player, @Nonnull GameMode gamemode, boolean join, boolean alive) { + public void updateInventory(@NotNull Player player, @NotNull GameMode gamemode, boolean join, boolean alive) { if (Bukkit.isPrimaryThread()) { Challenges.getInstance().runAsync(() -> updateInventory(player, gamemode, join, alive)); return; @@ -160,11 +160,11 @@ public void updateInventory(@Nonnull Player player, @Nonnull GameMode gamemode, } } - private void updateInventoryStarted(@Nonnull Player player, @Nonnull GameMode gamemode, boolean join, boolean alive) { + private void updateInventoryStarted(@NotNull Player player, @NotNull GameMode gamemode, boolean join, boolean alive) { removeItems(player); } - private void updateInventoryPaused(@Nonnull Player player, @Nonnull GameMode gamemode, boolean join, boolean alive) { + private void updateInventoryPaused(@NotNull Player player, @NotNull GameMode gamemode, boolean join, boolean alive) { if (gamemode == GameMode.CREATIVE || gamemode == GameMode.SPECTATOR) { removeItems(player); return; @@ -176,7 +176,7 @@ private void updateInventoryPaused(@Nonnull Player player, @Nonnull GameMode gam } } - private boolean hasItems(@Nonnull Player player) { + private boolean hasItems(@NotNull Player player) { Triple, String>[] pairs = createItemPairs(player); for (int i = 0; i < pairs.length; i++) { Triple, String> pair = pairs[i]; @@ -191,7 +191,7 @@ private boolean hasItems(@Nonnull Player player) { return true; } - private boolean canGiveItems(@Nonnull Player player) { + private boolean canGiveItems(@NotNull Player player) { Triple, String>[] pairs = createItemPairs(player); for (int i = 0; i < pairs.length; i++) { Triple, String> pair = pairs[i]; @@ -205,7 +205,7 @@ private boolean canGiveItems(@Nonnull Player player) { return true; } - private void removeItems(@Nonnull Player player) { + private void removeItems(@NotNull Player player) { Triple, String>[] pairs = createItemPairs(player); for (Triple, String> pair : pairs) { if (pair == null) continue; @@ -225,7 +225,7 @@ private void removeItems(@Nonnull Player player) { } } - private void giveItems(@Nonnull Player player) { + private void giveItems(@NotNull Player player) { Triple, String>[] pairs = createItemPairs(player); for (int i = 0; i < pairs.length; i++) { Triple, String> pair = pairs[i]; @@ -235,8 +235,8 @@ private void giveItems(@Nonnull Player player) { } } - @Nonnull - private Triple, String>[] createItemPairs(@Nonnull Player player) { + @NotNull + private Triple, String>[] createItemPairs(@NotNull Player player) { Triple, String>[] pairs = new Triple[9]; for (HotbarItem item : hotbarItems) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java index 3a82767da..bc11be198 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java @@ -1,36 +1,35 @@ package net.codingarea.challenges.plugin.management.menu; import net.codingarea.challenges.plugin.content.Message; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public final class InventoryTitleManager { private InventoryTitleManager() { } - @Nonnull - public static String getTitle(@Nonnull String name) { + @NotNull + public static String getTitle(@NotNull String name) { return "§8» " + Message.forName("inventory-color").asString() + name; } - @Nonnull + @NotNull public static String getMainMenuTitle() { return getTitle(Message.forName("menu-title").asString()); } - @Nonnull - public static String getTitle(@Nonnull MenuType menu, int page) { + @NotNull + public static String getTitle(@NotNull MenuType menu, int page) { return getTitle(menu.getName(), String.valueOf(page + 1)); } - @Nonnull - public static String getTitle(@Nonnull MenuType menu, String... sub) { + @NotNull + public static String getTitle(@NotNull MenuType menu, String... sub) { return getTitle(menu.getName(), sub); } - @Nonnull - public static String getTitle(@Nonnull String menu, String... sub) { + @NotNull + public static String getTitle(@NotNull String menu, String... sub) { StringBuilder name = new StringBuilder(menu); for (String s : sub) { name.append(getTitleSplitter()).append(s); @@ -38,28 +37,28 @@ public static String getTitle(@Nonnull String menu, String... sub) { return getTitle(name.toString()); } - @Nonnull + @NotNull public static String getTitleSplitter() { return " §8┃ " + Message.forName("inventory-color").asString(); } - @Nonnull - public static String getMenuSettingTitle(@Nonnull MenuType menu, @Nonnull String name, int page, boolean showPages) { + @NotNull + public static String getMenuSettingTitle(@NotNull MenuType menu, @NotNull String name, int page, boolean showPages) { return getTitle(menu.getName() + getTitleSplitter() + name + (showPages ? " §8• " + Message.forName("inventory-color") + (page + 1) : "")); } - @Nonnull - public static String getStatsTitle(@Nonnull String playerName) { + @NotNull + public static String getStatsTitle(@NotNull String playerName) { return getTitle("§2Stats §8┃ §2" + playerName); } - @Nonnull + @NotNull public static String getLeaderboardTitle() { return getTitle("§2Leaderboard"); } - @Nonnull - public static String getLeaderboardTitle(@Nonnull String name, int page) { + @NotNull + public static String getLeaderboardTitle(@NotNull String name, int page) { return getTitle("§2" + name + " §8┃ §2" + page); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java index 91f7eb945..c8b69d9ce 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java @@ -16,8 +16,7 @@ import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.entity.Player; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public final class MenuManager { @@ -90,13 +89,13 @@ public void generateMenus() { generated = true; } - public void openGUI(@Nonnull Player player) { + public void openGUI(@NotNull Player player) { SoundSample.PLOP.play(player); MenuPosition.set(player, new MainMenuPosition()); gui.open(player, Challenges.getInstance()); } - public void openGUIInstantly(@Nonnull Player player) { + public void openGUIInstantly(@NotNull Player player) { MenuPosition.set(player, new MainMenuPosition()); gui.openNotAnimated(player, true, Challenges.getInstance()); } @@ -105,7 +104,7 @@ public void openGUIInstantly(@Nonnull Player player) { * @return If the specified menu page could be opened. * The menu may not be opened, when there are no challenges registered to that menu or the languages are not loaded */ - public boolean openMenu(@Nonnull Player player, @Nonnull MenuType type, int page) { + public boolean openMenu(@NotNull Player player, @NotNull MenuType type, int page) { if (!generated) { SoundSample.BASS_OFF.play(player); player.sendMessage(Prefix.CHALLENGES + "§cCould not open gui, languages are not loaded"); @@ -118,7 +117,7 @@ public boolean openMenu(@Nonnull Player player, @Nonnull MenuType type, int page return true; } - public void playNoPermissionsEffect(@Nonnull Player player) { + public void playNoPermissionsEffect(@NotNull Player player) { SoundSample.BASS_OFF.play(player); Message.forName("no-permission").send(player, Prefix.CHALLENGES); } @@ -130,7 +129,7 @@ public boolean permissionToManageGUI() { private class MainMenuPosition implements MenuPosition { @Override - public void handleClick(@Nonnull MenuClickInfo info) { + public void handleClick(@NotNull MenuClickInfo info) { for (int i = 0; i < GUI_SLOTS.length; i++) { int current = GUI_SLOTS[i]; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java index 8dc5528c0..e27aa78c8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java @@ -10,8 +10,8 @@ import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.MainCustomMenuGenerator; import org.bukkit.ChatColor; import org.bukkit.Material; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.function.Consumer; @@ -33,7 +33,7 @@ public enum MenuType { @Getter private final boolean usable; - MenuType(@Nonnull String key, @Nonnull Material displayItem, MenuGenerator menuGenerator, boolean usable) { + MenuType(@NotNull String key, @NotNull Material displayItem, MenuGenerator menuGenerator, boolean usable) { this.key = key; this.displayItem = displayItem; this.menuGenerator = menuGenerator; @@ -42,16 +42,16 @@ public enum MenuType { menuGenerator.setMenuType(this); } - MenuType(@Nonnull String key, @Nonnull Material displayItem, MenuGenerator menuGenerator) { + MenuType(@NotNull String key, @NotNull Material displayItem, MenuGenerator menuGenerator) { this(key, displayItem, menuGenerator, true); } - @Nonnull + @NotNull public String getName() { return ChatColor.stripColor(getDisplayName()); } - @Nonnull + @NotNull public String getDisplayName() { return Message.forName("menu-" + key).asString(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java index 2cf752df1..2db7b6e1a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java @@ -17,9 +17,8 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; import java.util.LinkedList; import java.util.List; import java.util.function.Consumer; @@ -46,7 +45,7 @@ public ChallengeMenuGenerator() { this(0); } - public static boolean playNoPermissionsEffect(@Nonnull Player player) { + public static boolean playNoPermissionsEffect(@NotNull Player player) { MenuManager menuManager = Challenges.getInstance().getMenuManager(); if (!menuManager.permissionToManageGUI()) return false; if (mayManageSettings(player)) return false; @@ -54,7 +53,7 @@ public static boolean playNoPermissionsEffect(@Nonnull Player player) { return true; } - private static boolean mayManageSettings(@Nonnull Player player) { + private static boolean mayManageSettings(@NotNull Player player) { return player.hasPermission(MenuManager.MANAGE_GUI_PERMISSION); } @@ -69,7 +68,7 @@ public int getPagesCount() { } @Override - public void generatePage(@Nonnull Inventory inventory, int page) { + public void generatePage(@NotNull Inventory inventory, int page) { } @@ -112,7 +111,7 @@ public int getPageOfChallenge(IChallenge challenge) { return page; } - public void setSettingsItems(@Nonnull Inventory inventory, @Nonnull IChallenge challenge, int topSlot) { + public void setSettingsItems(@NotNull Inventory inventory, @NotNull IChallenge challenge, int topSlot) { inventory.setItem(getSlots()[topSlot], getDisplayItem(challenge)); inventory.setItem(getSlots()[topSlot] + 9, getSettingsItem(challenge)); } @@ -121,11 +120,11 @@ public void resetChallengeCache() { this.challenges.clear(); } - public boolean isInChallengeCache(@Nonnull IChallenge challenge) { + public boolean isInChallengeCache(@NotNull IChallenge challenge) { return challenges.contains(challenge); } - public void addChallengeToCache(@Nonnull IChallenge challenge) { + public void addChallengeToCache(@NotNull IChallenge challenge) { if (isNew(challenge) && Challenges.getInstance().getMenuManager().isDisplayNewInFront()) { challenges.add(countNewChallenges(), challenge); } else { @@ -133,15 +132,15 @@ public void addChallengeToCache(@Nonnull IChallenge challenge) { } } - public void removeChallengeFromCache(@Nonnull IChallenge challenge) { + public void removeChallengeFromCache(@NotNull IChallenge challenge) { challenges.remove(challenge); } - protected ItemStack getDisplayItem(@Nonnull IChallenge challenge) { + protected ItemStack getDisplayItem(@NotNull IChallenge challenge) { return getDisplayItemBuilder(challenge).build(); } - protected ItemBuilder getDisplayItemBuilder(@Nonnull IChallenge challenge) { + protected ItemBuilder getDisplayItemBuilder(@NotNull IChallenge challenge) { try { ItemBuilder item = new ItemBuilder(challenge.getDisplayItem()).hideAttributes(); if (newSuffix && isNew(challenge)) { @@ -155,7 +154,7 @@ protected ItemBuilder getDisplayItemBuilder(@Nonnull IChallenge challenge) { } } - protected ItemStack getSettingsItem(@Nonnull IChallenge challenge) { + protected ItemStack getSettingsItem(@NotNull IChallenge challenge) { try { ItemBuilder item = new ItemBuilder(challenge.getSettingsItem()).hideAttributes(); return item.build(); @@ -165,7 +164,7 @@ protected ItemStack getSettingsItem(@Nonnull IChallenge challenge) { } } - protected boolean isNew(@Nonnull IChallenge challenge) { + protected boolean isNew(@NotNull IChallenge challenge) { Version version = Challenges.getInstance().getVersion(); Version since = Version.getAnnotatedSince(challenge); return since.isNewerOrEqualThan(version); @@ -177,9 +176,9 @@ protected int countNewChallenges() { public abstract int[] getSlots(); - public abstract void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClickInfo info, int itemIndex); + public abstract void executeClickAction(@NotNull IChallenge challenge, @NotNull MenuClickInfo info, int itemIndex); - public void onPreChallengePageClicking(@Nonnull MenuClickInfo clickInfo, @Nonnegative int page) { + public void onPreChallengePageClicking(@NotNull MenuClickInfo clickInfo, int page) { } @@ -194,7 +193,7 @@ public ChallengeMenuPositionGenerator(MenuGenerator generator, int page) { } @Override - public void handleClick(@Nonnull MenuClickInfo info) { + public void handleClick(@NotNull MenuClickInfo info) { if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onLeaveClick.accept(info.getPlayer()))) { return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java index ba4774fd3..9bc7961ff 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java @@ -11,9 +11,8 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; import java.util.LinkedHashMap; public abstract class ChooseItemGenerator extends MultiPageMenuGenerator { @@ -24,17 +23,17 @@ public ChooseItemGenerator(LinkedHashMap items) { this.items = items; } - private static int getNextMiddleSlot(@Nonnegative int currentSlot) { + private static int getNextMiddleSlot(int currentSlot) { if (currentSlot >= 53) return currentSlot; if (isSideSlot(currentSlot)) return getNextMiddleSlot(currentSlot + 1); return currentSlot; } - private static boolean isSideSlot(@Nonnegative int slot) { + private static boolean isSideSlot(int slot) { return slot % 9 == 0 || slot % 9 == 8; } - private static boolean isTopOrBottomSlot(@Nonnegative int slot) { + private static boolean isTopOrBottomSlot(int slot) { return slot < 9 || slot > 35; } @@ -43,7 +42,7 @@ public MenuPosition getMenuPosition(int page) { return new GeneratorMenuPosition(this, page) { @Override - public void handleClick(@Nonnull MenuClickInfo info) { + public void handleClick(@NotNull MenuClickInfo info) { if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { return; @@ -91,7 +90,7 @@ public int getItemsPerPage() { } @Override - public void generatePage(@Nonnull Inventory inventory, int page) { + public void generatePage(@NotNull Inventory inventory, int page) { int lastSlot = 10; int startIndex = getItemsPerPage() * page; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java index 10eb68260..22b1bb908 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java @@ -16,9 +16,8 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; @@ -35,17 +34,17 @@ public ChooseMultipleItemGenerator(LinkedHashMap items) { selectedKeys = new LinkedList<>(); } - private static int getNextMiddleSlot(@Nonnegative int currentSlot) { + private static int getNextMiddleSlot(int currentSlot) { if (currentSlot >= 53) return currentSlot; if (isSideSlot(currentSlot)) return getNextMiddleSlot(currentSlot + 1); return currentSlot; } - private static boolean isSideSlot(@Nonnegative int slot) { + private static boolean isSideSlot(int slot) { return slot % 9 == 0 || slot % 9 == 8; } - private static boolean isTopOrBottomSlot(@Nonnegative int slot) { + private static boolean isTopOrBottomSlot(int slot) { return slot < 9 || slot > 35; } @@ -54,7 +53,7 @@ public MenuPosition getMenuPosition(int page) { return new GeneratorMenuPosition(this, page) { @Override - public void handleClick(@Nonnull MenuClickInfo info) { + public void handleClick(@NotNull MenuClickInfo info) { if (info.getSlot() == FINISH_SLOT) { onItemClick(info.getPlayer(), selectedKeys.toArray(new String[0])); @@ -112,7 +111,7 @@ public int getItemsPerPage() { } @Override - public void generatePage(@Nonnull Inventory inventory, int page) { + public void generatePage(@NotNull Inventory inventory, int page) { int lastSlot = 10; int startIndex = getItemsPerPage() * page; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java index 05d16d340..2882170ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java @@ -10,9 +10,8 @@ import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; import java.util.List; @Getter @@ -26,7 +25,7 @@ public abstract class MenuGenerator { public abstract List getInventories(); - public abstract MenuPosition getMenuPosition(@Nonnegative int page); + public abstract MenuPosition getMenuPosition(int page); public boolean hasInventoryOpen(Player player) { MenuPosition menuPosition = MenuPosition.get(player); @@ -50,7 +49,7 @@ public void reopenInventoryForPlayers() { } } - public void open(@Nonnull Player player, @Nonnegative int page) { + public void open(@NotNull Player player, int page) { List inventories = getInventories(); if (inventories == null || inventories.isEmpty()) generateInventories(); if (inventories == null || inventories.isEmpty()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java index eb7ec54d1..871fdf262 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java @@ -8,9 +8,8 @@ import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.Bukkit; import org.bukkit.inventory.Inventory; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; @@ -18,7 +17,7 @@ public abstract class MultiPageMenuGenerator extends MenuGenerator { protected final List inventories = new ArrayList<>(); - @Nonnull + @NotNull protected Inventory createNewInventory(int page) { Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, getSize(), getTitle(page)); InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); @@ -26,7 +25,7 @@ protected Inventory createNewInventory(int page) { return inventory; } - protected String getTitle(@Nonnegative int page) { + protected String getTitle(int page) { return InventoryTitleManager.getTitle(getMenuType(), page); } @@ -34,9 +33,9 @@ protected String getTitle(@Nonnegative int page) { public abstract int getPagesCount(); - public abstract void generatePage(@Nonnull Inventory inventory, int page); + public abstract void generatePage(@NotNull Inventory inventory, int page); - public abstract int[] getNavigationSlots(@Nonnegative int page); + public abstract int[] getNavigationSlots(int page); @Override public void generateInventories() { @@ -60,7 +59,7 @@ public List getInventories() { return inventories; } - public void addNavigationItems(@Nonnull Inventory inventory, int page) { + public void addNavigationItems(@NotNull Inventory inventory, int page) { InventoryUtils.setNavigationItems(inventory, getNavigationSlots(page), true, InventorySetter.INVENTORY, page, inventories.size(), diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java index 3322ba088..3b29c4fa6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java @@ -14,8 +14,8 @@ import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Map; @Getter @@ -34,7 +34,7 @@ public MenuPosition getMenuPosition(int page) { return new GeneratorMenuPosition(this, page) { @Override - public void handleClick(@Nonnull MenuClickInfo info) { + public void handleClick(@NotNull MenuClickInfo info) { if (info.getSlot() == FINISH_SLOT) { onSaveItemClick(info.getPlayer()); @@ -87,7 +87,7 @@ public int getItemsPerPage() { } @Override - public void generatePage(@Nonnull Inventory inventory, int page) { + public void generatePage(@NotNull Inventory inventory, int page) { int startIndex = getItemsPerPage() * page; for (int i = startIndex; i < startIndex + getItemsPerPage() && i < settings.size(); i++) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java index a3f7f8db4..b8fe953d6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java @@ -4,8 +4,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.ChallengeMenuGenerator; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class SettingsMenuGenerator extends ChallengeMenuGenerator { @@ -29,7 +28,7 @@ public int[] getNavigationSlots(int page) { } @Override - public void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClickInfo info, int itemIndex) { + public void executeClickAction(@NotNull IChallenge challenge, @NotNull MenuClickInfo info, int itemIndex) { if (itemIndex <= 1) { challenge.handleClick(new ChallengeMenuClickInfo(info, itemIndex == 0)); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java index 8935cf143..2331aaefb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java @@ -23,9 +23,8 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; @@ -80,14 +79,14 @@ public void updateSecondPage() { inventory.setItem(SECOND_SLOTS[1], getTimeItem(seconds, Message.forName("second"), Message.forName("seconds"))); } - private void setTimeNavigation(@Nonnull int[] slots, @Nonnull Message singular, @Nonnull Message plural) { + private void setTimeNavigation(@NotNull int[] slots, @NotNull Message singular, @NotNull Message plural) { Inventory inventory = inventories.get(1); inventory.setItem(slots[0], getNavigationItem(true, singular, plural)); inventory.setItem(slots[2], getNavigationItem(false, singular, plural)); } - @Nonnull - private ItemStack getNavigationItem(boolean up, @Nonnull Message singular, @Nonnull Message plural) { + @NotNull + private ItemStack getNavigationItem(boolean up, @NotNull Message singular, @NotNull Message plural) { return new ItemBuilder(up ? Material.DARK_OAK_BUTTON : Material.STONE_BUTTON).name( " ", "§7§o[Click] §8» §" + (up ? "a+" : "c-") + "1 " + singular, @@ -96,8 +95,8 @@ private ItemStack getNavigationItem(boolean up, @Nonnull Message singular, @Nonn ).hideAttributes().build(); } - @Nonnull - private ItemStack getTimeItem(long value, @Nonnull Message singular, @Nonnull Message plural) { + @NotNull + private ItemStack getTimeItem(long value, @NotNull Message singular, @NotNull Message plural) { return new ItemBuilder(Material.CLOCK).name( "§8» §7" + (value == 1 ? singular : plural) + ": §e" + value, " ", @@ -106,7 +105,7 @@ private ItemStack getTimeItem(long value, @Nonnull Message singular, @Nonnull Me ).hideAttributes().amount((int) Math.max(value, 1)).build(); } - @Nonnull + @NotNull private Inventory createNewInventory(int page) { Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, SIZE, InventoryTitleManager.getTitle(MenuType.TIMER, page)); InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); @@ -143,12 +142,12 @@ private class TimerMenuPosition implements MenuPosition { private final int page; - public TimerMenuPosition(@Nonnegative int page) { + public TimerMenuPosition(int page) { this.page = page; } @Override - public void handleClick(@Nonnull MenuClickInfo info) { + public void handleClick(@NotNull MenuClickInfo info) { if (info.getSlot() == NAVIGATION_SLOTS[0]) { SoundSample.CLICK.play(info.getPlayer()); @@ -212,13 +211,13 @@ public void handleClick(@Nonnull MenuClickInfo info) { } - private boolean playNoPermissionsEffect(@Nonnull Player player) { + private boolean playNoPermissionsEffect(@NotNull Player player) { if (mayManageTimer(player)) return false; Challenges.getInstance().getMenuManager().playNoPermissionsEffect(player); return true; } - private boolean mayManageTimer(@Nonnull Player player) { + private boolean mayManageTimer(@NotNull Player player) { return player.hasPermission("challenges.timer"); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java index 06d2a8dc8..4edcf7353 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java @@ -30,8 +30,8 @@ import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.*; @ToString @@ -147,7 +147,7 @@ public MenuPosition getMenuPosition(int page) { } @Override - public void open(@Nonnull Player player, int page) { + public void open(@NotNull Player player, int page) { if (inventory == null) generateInventories(); super.open(player, page); } @@ -215,7 +215,7 @@ public InfoMenuPosition(int page, InfoMenuGenerator generator) { } @Override - public void handleClick(@Nonnull MenuClickInfo info) { + public void handleClick(@NotNull MenuClickInfo info) { if (InventoryUtils.handleNavigationClicking(generator, new int[]{36 + 9}, page, info, () -> Challenges.getInstance().getMenuManager().openMenu(info.getPlayer(), MenuType.CUSTOM, 0))) { return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java index 3136d7f20..7dfcea904 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java @@ -14,8 +14,7 @@ import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import org.bukkit.Material; import org.bukkit.inventory.Inventory; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class MainCustomMenuGenerator extends ChallengeMenuGenerator { @@ -43,7 +42,7 @@ protected String getTitle(int page) { } @Override - public void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClickInfo info, int itemIndex) { + public void executeClickAction(@NotNull IChallenge challenge, @NotNull MenuClickInfo info, int itemIndex) { if (itemIndex == 0 || itemIndex == 2) { challenge.handleClick(new ChallengeMenuClickInfo(info, itemIndex == 0)); } else if (challenge instanceof CustomChallenge) { @@ -54,7 +53,7 @@ public void executeClickAction(@Nonnull IChallenge challenge, @Nonnull MenuClick } @Override - public void generatePage(@Nonnull Inventory inventory, int page) { + public void generatePage(@NotNull Inventory inventory, int page) { if (page == 0) { inventory.setItem(VIEW_SLOT, new ItemBuilder(Material.BOOK, Message.forName("custom-main-view-challenges")).build()); inventory.setItem(CREATE_SLOT, new ItemBuilder(Material.WRITABLE_BOOK, Message.forName("custom-main-create-challenge")).build()); @@ -62,7 +61,7 @@ public void generatePage(@Nonnull Inventory inventory, int page) { } @Override - public void onPreChallengePageClicking(@Nonnull MenuClickInfo info, int page) { + public void onPreChallengePageClicking(@NotNull MenuClickInfo info, int page) { if (info.getSlot() == VIEW_SLOT) { if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().isEmpty()) { Message.forName("custom-not-loaded").send(info.getPlayer(), Prefix.CUSTOM); @@ -85,7 +84,7 @@ public void onPreChallengePageClicking(@Nonnull MenuClickInfo info, int page) { } @Override - public void setSettingsItems(@Nonnull Inventory inventory, @Nonnull IChallenge challenge, int topSlot) { + public void setSettingsItems(@NotNull Inventory inventory, @NotNull IChallenge challenge, int topSlot) { inventory.setItem(getSlots()[topSlot], getDisplayItemBuilder(challenge).build()); inventory.setItem(getSlots()[topSlot] + 9, DefaultItem.customize().build()); inventory.setItem(getSlots()[topSlot] + 18, getSettingsItem(challenge)); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java index 53b285c9d..96298fefc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java @@ -4,20 +4,18 @@ import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; - -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @ToString public class ChallengeMenuClickInfo extends MenuClickInfo { protected final boolean upperItem; - public ChallengeMenuClickInfo(@Nonnull MenuClickInfo parent, boolean upperItem) { + public ChallengeMenuClickInfo(@NotNull MenuClickInfo parent, boolean upperItem) { this(parent.getPlayer(), parent.getInventory(), parent.isShiftClick(), parent.isRightClick(), parent.getSlot(), upperItem); } - public ChallengeMenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boolean shiftClick, boolean rightClick, @Nonnegative int slot, boolean upperItem) { + public ChallengeMenuClickInfo(@NotNull Player player, @NotNull Inventory inventory, boolean shiftClick, boolean rightClick, int slot, boolean upperItem) { super(player, inventory, shiftClick, rightClick, slot); this.upperItem = upperItem; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java index eecf8b281..f0bfa3527 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskExecutor.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.scheduler; import net.codingarea.commons.bukkit.utils.logging.Logger; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; @@ -22,14 +22,14 @@ public void run() { } } - @Nonnull + @NotNull public abstract AbstractTaskConfig getConfig(); - public void register(@Nonnull ScheduledFunction function) { + public void register(@NotNull ScheduledFunction function) { functions.add(function); } - public void unregister(@Nonnull Object holder) { + public void unregister(@NotNull Object holder) { functions.removeIf(function -> function.getHolder() == holder); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java index 7288d4d96..674863b42 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/PoliciesContainer.java @@ -3,8 +3,8 @@ import net.codingarea.challenges.plugin.management.scheduler.policy.IPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -13,7 +13,7 @@ public class PoliciesContainer { private final List policies = new ArrayList<>(); - public PoliciesContainer(@Nonnull ScheduledTask annotation) { + public PoliciesContainer(@NotNull ScheduledTask annotation) { addPolicies( annotation.challengePolicy(), annotation.timerPolicy(), @@ -23,7 +23,7 @@ public PoliciesContainer(@Nonnull ScheduledTask annotation) { ); } - public PoliciesContainer(@Nonnull TimerTask annotation) { + public PoliciesContainer(@NotNull TimerTask annotation) { addPolicies( annotation.challengePolicy(), annotation.playerPolicy(), @@ -32,11 +32,11 @@ public PoliciesContainer(@Nonnull TimerTask annotation) { ); } - private void addPolicies(@Nonnull IPolicy... policies) { + private void addPolicies(@NotNull IPolicy... policies) { this.policies.addAll(Arrays.asList(policies)); } - public boolean allPoliciesAreTrue(@Nonnull Object holder) { + public boolean allPoliciesAreTrue(@NotNull Object holder) { for (IPolicy policy : policies) { if (!policy.isApplicable(holder)) continue; if (!policy.check(holder)) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java index 678697934..7a6ab42de 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java @@ -5,8 +5,8 @@ import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.misc.ReflectionUtils; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -17,13 +17,13 @@ public final class ScheduleManager { private final Map timerTaskExecutorsByConfig = new ConcurrentHashMap<>(); private boolean started = false; - public void register(@Nonnull Object... schedulers) { + public void register(@NotNull Object... schedulers) { for (Object scheduler : schedulers) { register(scheduler); } } - public void register(@Nonnull Object scheduler) { + public void register(@NotNull Object scheduler) { for (Method method : ReflectionUtils.getMethodsAnnotatedWith(scheduler.getClass(), ScheduledTask.class)) { if (method.getParameterCount() != 0) { Logger.warn("Could not register scheduler " + method); @@ -50,13 +50,13 @@ public void register(@Nonnull Object scheduler) { } } - public void unregister(@Nonnull Object object) { + public void unregister(@NotNull Object object) { for (ScheduledTaskExecutor scheduler : scheduledTaskExecutorsByConfig.values()) { scheduler.unregister(object); } } - private void register(@Nonnull ScheduledFunction function, @Nonnull AbstractTaskConfig config) { + private void register(@NotNull ScheduledFunction function, @NotNull AbstractTaskConfig config) { if (config instanceof ScheduledTaskConfig) { ScheduledTaskConfig taskConfig = (ScheduledTaskConfig) config; if (taskConfig.getRate() < 1) { @@ -75,8 +75,8 @@ private void register(@Nonnull ScheduledFunction function, @Nonnull AbstractTask } } - @Nonnull - private ScheduledTaskExecutor getOrCreateScheduledTaskExecutor(@Nonnull ScheduledTaskConfig config) { + @NotNull + private ScheduledTaskExecutor getOrCreateScheduledTaskExecutor(@NotNull ScheduledTaskConfig config) { ScheduledTaskExecutor executor = scheduledTaskExecutorsByConfig.get(config); if (executor != null) return executor; @@ -87,8 +87,8 @@ private ScheduledTaskExecutor getOrCreateScheduledTaskExecutor(@Nonnull Schedule return executor; } - @Nonnull - private TimerTaskExecutor getOrCreateTimerTaskExecutor(@Nonnull TimerTaskConfig config) { + @NotNull + private TimerTaskExecutor getOrCreateTimerTaskExecutor(@NotNull TimerTaskConfig config) { TimerTaskExecutor executor = timerTaskExecutorsByConfig.get(config); if (executor != null) return executor; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java index ac7d2f019..8591b2c27 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledFunction.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.scheduler; import lombok.EqualsAndHashCode; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -13,7 +13,7 @@ public final class ScheduledFunction { private final Object holder; private final PoliciesContainer policies; - ScheduledFunction(@Nonnull Object holder, @Nonnull Method method, @Nonnull PoliciesContainer policies) { + ScheduledFunction(@NotNull Object holder, @NotNull Method method, @NotNull PoliciesContainer policies) { this.method = method; this.holder = holder; this.policies = policies; @@ -33,7 +33,7 @@ private boolean shouldInvoke() { return policies.allPoliciesAreTrue(holder); } - @Nonnull + @NotNull public Object getHolder() { return holder; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java index e2bccf522..73141a1a4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java @@ -3,9 +3,7 @@ import lombok.EqualsAndHashCode; import lombok.Getter; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; - -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Getter @EqualsAndHashCode(callSuper = false) @@ -13,11 +11,11 @@ public final class ScheduledTaskConfig extends AbstractTaskConfig { private final int rate; - ScheduledTaskConfig(@Nonnull ScheduledTask annotation) { + ScheduledTaskConfig(@NotNull ScheduledTask annotation) { this(annotation.ticks(), annotation.async()); } - ScheduledTaskConfig(@Nonnegative int rate, boolean async) { + ScheduledTaskConfig(int rate, boolean async) { super(async); this.rate = rate; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java index 763b1e8b3..ca95cac8f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskExecutor.java @@ -4,15 +4,14 @@ import org.bukkit.Bukkit; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; final class ScheduledTaskExecutor extends AbstractTaskExecutor { private final ScheduledTaskConfig config; private BukkitTask task; - ScheduledTaskExecutor(@Nonnull ScheduledTaskConfig config) { + ScheduledTaskExecutor(@NotNull ScheduledTaskConfig config) { this.config = config; } @@ -30,7 +29,7 @@ public void start() { scheduler.runTaskTimer(plugin, this, 0, config.getRate()); } - @Nonnull + @NotNull @Override public ScheduledTaskConfig getConfig() { return config; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java index dd70940d6..d8ddec095 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java @@ -2,29 +2,29 @@ import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Arrays; public final class TimerTaskConfig extends AbstractTaskConfig { private final TimerStatus[] status; - TimerTaskConfig(@Nonnull TimerTask annotation) { + TimerTaskConfig(@NotNull TimerTask annotation) { this(annotation.status(), annotation.async()); } - TimerTaskConfig(@Nonnull TimerStatus[] status, boolean async) { + TimerTaskConfig(@NotNull TimerStatus[] status, boolean async) { super(async); this.status = status; } - @Nonnull + @NotNull public TimerStatus[] getStatus() { return status; } - public boolean acceptsStatus(@Nonnull TimerStatus status) { + public boolean acceptsStatus(@NotNull TimerStatus status) { return Arrays.asList(this.status).contains(status); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java index 526198307..375c2d250 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskExecutor.java @@ -2,14 +2,13 @@ import net.codingarea.challenges.plugin.Challenges; import org.bukkit.Bukkit; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; final class TimerTaskExecutor extends AbstractTaskExecutor { private final TimerTaskConfig config; - TimerTaskExecutor(@Nonnull TimerTaskConfig config) { + TimerTaskExecutor(@NotNull TimerTaskConfig config) { this.config = config; } @@ -21,7 +20,7 @@ else if (!Bukkit.isPrimaryThread()) else this.run(); } - @Nonnull + @NotNull @Override public TimerTaskConfig getConfig() { return config; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java index 6ea65ffc3..787fdb727 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ChallengeStatusPolicy.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.scheduler.policy; import net.codingarea.challenges.plugin.challenges.type.IChallenge; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.function.Predicate; public enum ChallengeStatusPolicy implements IPolicy { @@ -13,17 +13,17 @@ public enum ChallengeStatusPolicy implements IPolicy { private final Predicate check; - ChallengeStatusPolicy(@Nonnull Predicate check) { + ChallengeStatusPolicy(@NotNull Predicate check) { this.check = check; } @Override - public boolean check(@Nonnull Object holder) { + public boolean check(@NotNull Object holder) { return check.test((IChallenge) holder); } @Override - public boolean isApplicable(@Nonnull Object holder) { + public boolean isApplicable(@NotNull Object holder) { return holder instanceof IChallenge; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java index 50de73c31..080ed3488 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/ExtraWorldPolicy.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.scheduler.policy; import net.codingarea.challenges.plugin.ChallengeAPI; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.function.BooleanSupplier; public enum ExtraWorldPolicy implements IPolicy { @@ -13,12 +13,12 @@ public enum ExtraWorldPolicy implements IPolicy { private final BooleanSupplier check; - ExtraWorldPolicy(@Nonnull BooleanSupplier check) { + ExtraWorldPolicy(@NotNull BooleanSupplier check) { this.check = check; } @Override - public boolean check(@Nonnull Object holder) { + public boolean check(@NotNull Object holder) { return check.getAsBoolean(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java index af87bdbd8..098e72dd2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/FreshnessPolicy.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.scheduler.policy; import net.codingarea.challenges.plugin.ChallengeAPI; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.function.BooleanSupplier; public enum FreshnessPolicy implements IPolicy { @@ -13,12 +13,12 @@ public enum FreshnessPolicy implements IPolicy { private final BooleanSupplier check; - FreshnessPolicy(@Nonnull BooleanSupplier check) { + FreshnessPolicy(@NotNull BooleanSupplier check) { this.check = check; } @Override - public boolean check(@Nonnull Object holder) { + public boolean check(@NotNull Object holder) { return check.getAsBoolean(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java index a2bed96cf..874188d54 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/IPolicy.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.management.scheduler.policy; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public interface IPolicy { - boolean check(@Nonnull Object holder); + boolean check(@NotNull Object holder); - default boolean isApplicable(@Nonnull Object holder) { + default boolean isApplicable(@NotNull Object holder) { return true; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java index 13b516467..06507b32c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/PlayerCountPolicy.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.scheduler.policy; import org.bukkit.Bukkit; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.function.BiPredicate; public enum PlayerCountPolicy implements IPolicy { @@ -14,12 +14,12 @@ public enum PlayerCountPolicy implements IPolicy { private final BiPredicate check; - PlayerCountPolicy(@Nonnull BiPredicate check) { + PlayerCountPolicy(@NotNull BiPredicate check) { this.check = check; } @Override - public boolean check(@Nonnull Object holder) { + public boolean check(@NotNull Object holder) { return check.test(Bukkit.getOnlinePlayers().size(), Bukkit.getMaxPlayers()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java index 34cf541be..820149a1d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/policy/TimerPolicy.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.scheduler.policy; import net.codingarea.challenges.plugin.ChallengeAPI; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.function.BooleanSupplier; public enum TimerPolicy implements IPolicy { @@ -13,12 +13,12 @@ public enum TimerPolicy implements IPolicy { private final BooleanSupplier check; - TimerPolicy(@Nonnull BooleanSupplier check) { + TimerPolicy(@NotNull BooleanSupplier check) { this.check = check; } @Override - public boolean check(@Nonnull Object holder) { + public boolean check(@NotNull Object holder) { return check.getAsBoolean(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java index 9b0a6c3b8..9b56af442 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/ScheduledTask.java @@ -1,9 +1,8 @@ package net.codingarea.challenges.plugin.management.scheduler.task; import net.codingarea.challenges.plugin.management.scheduler.policy.*; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -13,24 +12,23 @@ @Retention(RetentionPolicy.RUNTIME) public @interface ScheduledTask { - @Nonnegative int ticks(); boolean async() default true; - @Nonnull + @NotNull TimerPolicy timerPolicy() default TimerPolicy.STARTED; - @Nonnull + @NotNull ChallengeStatusPolicy challengePolicy() default ChallengeStatusPolicy.ENABLED; - @Nonnull + @NotNull PlayerCountPolicy playerPolicy() default PlayerCountPolicy.SOMEONE; - @Nonnull + @NotNull ExtraWorldPolicy worldPolicy() default ExtraWorldPolicy.NOT_USED; - @Nonnull + @NotNull FreshnessPolicy freshnessPolicy() default FreshnessPolicy.ALWAYS; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java index 68250f891..7ff75d2be 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/task/TimerTask.java @@ -5,8 +5,8 @@ import net.codingarea.challenges.plugin.management.scheduler.policy.FreshnessPolicy; import net.codingarea.challenges.plugin.management.scheduler.policy.PlayerCountPolicy; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -16,21 +16,21 @@ @Retention(RetentionPolicy.RUNTIME) public @interface TimerTask { - @Nonnull + @NotNull TimerStatus[] status(); boolean async() default true; - @Nonnull + @NotNull ChallengeStatusPolicy challengePolicy() default ChallengeStatusPolicy.ENABLED; - @Nonnull + @NotNull PlayerCountPolicy playerPolicy() default PlayerCountPolicy.SOMEONE; - @Nonnull + @NotNull ExtraWorldPolicy worldPolicy() default ExtraWorldPolicy.NOT_USED; - @Nonnull + @NotNull FreshnessPolicy freshnessPolicy() default FreshnessPolicy.ALWAYS; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java index 216893860..2b7de378f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java @@ -21,8 +21,7 @@ import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.*; import org.bukkit.entity.Player; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public final class ChallengeTimer { @@ -158,7 +157,7 @@ public void updateActionbar() { } - @Nonnull + @NotNull private String getActionbar() { Message message = !paused || (!countingUp && time > 0) ? (countingUp ? upMessage : downMessage) : stoppedMessage; String time = getFormattedTime(); @@ -204,12 +203,12 @@ public void setHidden(boolean hide) { updateActionbar(); } - @Nonnull + @NotNull public String getFormattedTime() { return format.format(time); } - @Nonnull + @NotNull public TimerStatus getStatus() { return paused ? TimerStatus.PAUSED : TimerStatus.RUNNING; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java index f96662dbc..6c141ecb4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java @@ -1,15 +1,13 @@ package net.codingarea.challenges.plugin.management.scheduler.timer; import net.codingarea.commons.common.config.Document; - -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public final class TimerFormat { private final String seconds, minutes, hours, day, days; - public TimerFormat(@Nonnull Document document) { + public TimerFormat(@NotNull Document document) { seconds = document.getString("seconds", ""); minutes = document.getString("minutes", ""); hours = document.getString("hours", ""); @@ -25,9 +23,8 @@ public TimerFormat() { days = "{d}:{hh}:{mm}:{ss}"; } - @Nonnull - public String format(@Nonnegative long time) { - + @NotNull + public String format(long time) { long seconds = time; long minutes = seconds / 60; long hours = minutes / 60; @@ -64,7 +61,7 @@ private String getFormat(long minutes, long hours, long days) { return format; } - private String digit2(@Nonnegative long number) { + private String digit2(long number) { return number > 9 ? String.valueOf(number) : "0" + number; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java index 114d0bff3..927823fbe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java @@ -2,9 +2,8 @@ import lombok.Getter; import net.codingarea.challenges.plugin.content.Message; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Getter public enum ChallengeEndCause { @@ -15,12 +14,12 @@ public enum ChallengeEndCause { private final Message noWinnerMessage, winnerMessage; - ChallengeEndCause(@Nonnull Message noWinnerMessage, @Nullable Message winnerMessage) { + ChallengeEndCause(@NotNull Message noWinnerMessage, @Nullable Message winnerMessage) { this.noWinnerMessage = noWinnerMessage; this.winnerMessage = winnerMessage; } - @Nonnull + @NotNull public Message getMessage(boolean withWinner) { return withWinner && winnerMessage != null ? winnerMessage : noWinnerMessage; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java index be78dc4e6..d4d18da94 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java @@ -10,9 +10,8 @@ import org.bukkit.WorldCreator; import org.bukkit.WorldType; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Collections; import java.util.LinkedList; import java.util.List; @@ -75,7 +74,7 @@ public void loadGameState(@NotNull Document document) { } } - @Nonnull + @NotNull public World getOrCreateVoidWorld() { if (voidWorld != null) { return voidWorld; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java index 82ed3d7de..433da08fc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GeneratorWorldPortalManager.java @@ -6,9 +6,8 @@ import org.bukkit.Location; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; @@ -27,15 +26,15 @@ public GeneratorWorldPortalManager() { } @Nullable - public Location getAndRemoveLastWorld(@Nonnull Player player) { + public Location getAndRemoveLastWorld(@NotNull Player player) { return lastWorldLocations.remove(player.getUniqueId()); } - public void setLastLocation(@Nonnull Player player, @Nonnull Location location) { + public void setLastLocation(@NotNull Player player, @NotNull Location location) { lastWorldLocations.put(player.getUniqueId(), location); } - public boolean isCustomWorld(@Nonnull String name) { + public boolean isCustomWorld(@NotNull String name) { return Challenges.getInstance().getGameWorldStorage().getCustomGeneratedGameWorlds().contains(name); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java index f054d28aa..9fe7fd1b0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java @@ -9,9 +9,9 @@ import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeScoreboard; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; @@ -25,7 +25,7 @@ public ScoreboardManager() { ChallengeAPI.registerScheduler(this); } - public void handleQuit(@Nonnull Player player) { + public void handleQuit(@NotNull Player player) { for (ChallengeBossBar bossbar : bossbars) { bossbar.applyHide(player); } @@ -35,7 +35,7 @@ public void handleQuit(@Nonnull Player player) { } } - public void handleJoin(@Nonnull Player player) { + public void handleJoin(@NotNull Player player) { updateAll(); } @@ -49,13 +49,13 @@ public void updateAll() { } } - public void showBossBar(@Nonnull ChallengeBossBar bossbar) { + public void showBossBar(@NotNull ChallengeBossBar bossbar) { if (bossbars.contains(bossbar)) return; bossbars.add(bossbar); bossbar.update(); } - public void hideBossBar(@Nonnull ChallengeBossBar bossbar) { + public void hideBossBar(@NotNull ChallengeBossBar bossbar) { if (!bossbars.remove(bossbar)) return; Bukkit.getOnlinePlayers().forEach(bossbar::applyHide); } @@ -87,11 +87,11 @@ public void disable() { setCurrentScoreboard(null); } - public boolean isShown(@Nonnull ChallengeBossBar bossbar) { + public boolean isShown(@NotNull ChallengeBossBar bossbar) { return bossbars.contains(bossbar); } - public boolean isShown(@Nonnull ChallengeScoreboard scoreboard) { + public boolean isShown(@NotNull ChallengeScoreboard scoreboard) { return currentScoreboard == scoreboard; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java index dcf2c78a9..d724a466c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java @@ -17,8 +17,8 @@ import org.bukkit.World.Environment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.LinkedList; import java.util.List; import java.util.function.Supplier; @@ -61,7 +61,7 @@ public boolean hasCheated() { return hasCheated; } - public void endChallenge(@Nonnull ChallengeEndCause endCause, Supplier> winnerGetter) { + public void endChallenge(@NotNull ChallengeEndCause endCause, Supplier> winnerGetter) { if (ChallengeAPI.isPaused()) { Logger.warn("Tried to end challenge while timer was paused"); return; @@ -111,12 +111,12 @@ private void setSpectator() { } } - private void dropItems(@Nonnull Player player) { + private void dropItems(@NotNull Player player) { dropItems(player.getLocation(), player.getInventory().getContents()); player.getInventory().clear(); } - private void dropItems(@Nonnull Location location, @Nonnull ItemStack[] items) { + private void dropItems(@NotNull Location location, @NotNull ItemStack[] items) { for (ItemStack item : items) { if (item == null) continue; if (BukkitReflectionUtils.isAir(item.getType())) continue; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java index c096a0ce1..43653fe91 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java @@ -5,8 +5,7 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.commons.common.config.Document; import org.bukkit.entity.Player; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Getter public final class TitleManager { @@ -22,21 +21,21 @@ public TitleManager() { challengeStatusEnabled = config.getBoolean("challenge-status"); } - public void sendTimerStatusTitle(@Nonnull Message message) { + public void sendTimerStatusTitle(@NotNull Message message) { if (!timerStatusEnabled) return; message.broadcastTitle(); } - public void sendChallengeStatusTitle(@Nonnull Message message, @Nonnull Object... args) { + public void sendChallengeStatusTitle(@NotNull Message message, @NotNull Object... args) { if (!challengeStatusEnabled) return; message.broadcastTitle(args); } - public void sendTitle(@Nonnull Player player, @Nonnull String title, @Nonnull String subtitle) { + public void sendTitle(@NotNull Player player, @NotNull String title, @NotNull String subtitle) { player.sendTitle(title, subtitle, fadein, duration, fadeout); } - public void sendTitleInstant(@Nonnull Player player, @Nonnull String title, @Nonnull String subtitle) { + public void sendTitleInstant(@NotNull Player player, @NotNull String title, @NotNull String subtitle) { player.sendTitle(title, subtitle, 0, duration, fadeout); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java index 326e085dc..6daef66c3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java @@ -15,9 +15,9 @@ import org.bukkit.World.Environment; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -183,7 +183,7 @@ private void teleportPlayersOutOfExtraWorld() { } @SuppressWarnings("unchecked") - private void disableGameRuleInFlatWorld(@Nonnull String name) { + private void disableGameRuleInFlatWorld(@NotNull String name) { GameRule gamerule = (GameRule) GameRule.getByName(name); if (gamerule == null) return; flatWorld.setGameRule(gamerule, false); @@ -219,13 +219,13 @@ public void executeWorldReset() { } - private void deleteWorld(@Nonnull String name) { + private void deleteWorld(@NotNull String name) { File folder = new File(Bukkit.getWorldContainer(), name); FileUtils.deleteWorldFolder(folder); Logger.info("Deleted world {}", name); } - private void copyPreGeneratedWorld(@Nonnull String name) { + private void copyPreGeneratedWorld(@NotNull String name) { File source = new File(Bukkit.getWorldContainer(), customSeedWorldPrefix + name); if (!source.exists() || !source.isDirectory()) { Logger.warn("Custom seed world '{}' does not exist!", name); @@ -241,7 +241,7 @@ private void copyPreGeneratedWorld(@Nonnull String name) { } } - private void deletePreGeneratedWorld(@Nonnull String name) { + private void deletePreGeneratedWorld(@NotNull String name) { File source = new File(Bukkit.getWorldContainer(), customSeedWorldPrefix + name); if (!source.exists() || !source.isDirectory()) return; @@ -249,7 +249,7 @@ private void deletePreGeneratedWorld(@Nonnull String name) { Logger.debug("Deleted pre generated custom seed world {}", name); } - public void copy(@Nonnull File source, @Nonnull File target) throws IOException { + public void copy(@NotNull File source, @NotNull File target) throws IOException { if (source.isDirectory()) { copyDirectory(source, target); } else { @@ -257,7 +257,7 @@ public void copy(@Nonnull File source, @Nonnull File target) throws IOException } } - private void copyDirectory(@Nonnull File source, @Nonnull File target) throws IOException { + private void copyDirectory(@NotNull File source, @NotNull File target) throws IOException { if (!target.exists()) { if (!target.mkdir()) { return; @@ -272,7 +272,7 @@ private void copyDirectory(@Nonnull File source, @Nonnull File target) throws IO } } - private void copyFile(@Nonnull File source, @Nonnull File target) throws IOException { + private void copyFile(@NotNull File source, @NotNull File target) throws IOException { try (InputStream in = Files.newInputStream(source.toPath()); OutputStream out = Files.newOutputStream(target.toPath())) { byte[] buf = new byte[1024]; int length; @@ -308,7 +308,7 @@ private void cachePlayerData() { Bukkit.getOnlinePlayers().forEach(this::cachePlayerData); } - public void cachePlayerData(@Nonnull Player player) { + public void cachePlayerData(@NotNull Player player) { playerData.put(player.getUniqueId(), new PlayerData(player)); } @@ -316,22 +316,22 @@ public void restorePlayerData() { Bukkit.getOnlinePlayers().forEach(this::restorePlayerData); } - public void restorePlayerData(@Nonnull Player player) { + public void restorePlayerData(@NotNull Player player) { PlayerData data = playerData.remove(player.getUniqueId()); if (data == null) return; data.apply(player); } - public boolean hasPlayerData(@Nonnull Player player) { + public boolean hasPlayerData(@NotNull Player player) { return playerData.containsKey(player.getUniqueId()); } - @Nonnull + @NotNull public World getExtraWorld() { return flatWorld; } - @Nonnull + @NotNull public WorldSettings getSettings() { return settings; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java index f2d44b052..4242266d9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java @@ -13,8 +13,8 @@ import org.bukkit.boss.BarStyle; import org.bukkit.boss.BossBar; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; @@ -25,13 +25,13 @@ public final class ChallengeBossBar { private BiConsumer content = (bossbar, player) -> { }; - private BossBar createBossbar(@Nonnull BossBarInstance instance) { + private BossBar createBossbar(@NotNull BossBarInstance instance) { BossBar bossbar = Bukkit.createBossBar(instance.title.toPlainText(), instance.color, instance.style); bossbar.setProgress(instance.progress); return bossbar; } - private void apply(@Nonnull BossBar bossbar, @Nonnull BossBarInstance instance) { + private void apply(@NotNull BossBar bossbar, @NotNull BossBarInstance instance) { if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_20_5)) { bossbar.setTitle(instance.title.toPlainText()); } else { @@ -43,11 +43,11 @@ private void apply(@Nonnull BossBar bossbar, @Nonnull BossBarInstance instance) bossbar.setVisible(instance.visible); } - public void setContent(@Nonnull BiConsumer content) { + public void setContent(@NotNull BiConsumer content) { this.content = content; } - public void applyHide(@Nonnull Player player) { + public void applyHide(@NotNull Player player) { BossBar bossbar = bossbars.get(player); if (bossbar == null) return; bossbar.removePlayer(player); @@ -57,7 +57,7 @@ public void update() { Bukkit.getOnlinePlayers().forEach(this::update); } - public void update(@Nonnull Player player) { + public void update(@NotNull Player player) { if (!isShown()) { Logger.warn("Tried to update bossbar which is not shown"); return; @@ -109,19 +109,19 @@ public static final class BossBarInstance { private BossBarInstance() { } - @Nonnull - public BossBarInstance setTitle(@Nonnull String title) { + @NotNull + public BossBarInstance setTitle(@NotNull String title) { this.title = new TextComponent(title); return this; } - @Nonnull - public BossBarInstance setTitle(@Nonnull BaseComponent title) { + @NotNull + public BossBarInstance setTitle(@NotNull BaseComponent title) { this.title = title; return this; } - @Nonnull + @NotNull public BossBarInstance setProgress(double progress) { if (progress < 0 || progress > 1) throw new IllegalArgumentException("Progress must be between 0 and 1; Got " + progress); @@ -129,19 +129,19 @@ public BossBarInstance setProgress(double progress) { return this; } - @Nonnull - public BossBarInstance setColor(@Nonnull BarColor color) { + @NotNull + public BossBarInstance setColor(@NotNull BarColor color) { this.color = color; return this; } - @Nonnull - public BossBarInstance setStyle(@Nonnull BarStyle style) { + @NotNull + public BossBarInstance setStyle(@NotNull BarStyle style) { this.style = style; return this; } - @Nonnull + @NotNull public BossBarInstance setVisible(boolean visible) { this.visible = visible; return this; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java index def523111..6746930b0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java @@ -11,9 +11,9 @@ import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Scoreboard; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; @@ -24,11 +24,11 @@ public final class ChallengeScoreboard { private BiConsumer content = (scoreboard, player) -> { }; - public void setContent(@Nonnull BiConsumer content) { + public void setContent(@NotNull BiConsumer content) { this.content = content; } - public void applyHide(@Nonnull Player player) { + public void applyHide(@NotNull Player player) { unregister(objectives.remove(player)); } @@ -38,7 +38,7 @@ public void update() { } } - public void update(@Nonnull Player player) { + public void update(@NotNull Player player) { if (!isShown()) { Logger.warn("Tried to update scoreboard which is not shown"); return; @@ -121,15 +121,15 @@ public static final class ScoreboardInstance { private ScoreboardInstance() { } - @Nonnull - public ScoreboardInstance addLine(@Nonnull String text) { + @NotNull + public ScoreboardInstance addLine(@NotNull String text) { if (linesIndex >= lines.length) throw new IllegalStateException("All lines are already used! (" + lines.length + ")"); lines[linesIndex++] = text; return this; } - @Nonnull + @NotNull public Collection getLines() { List list = new ArrayList<>(); for (String line : lines) { @@ -139,8 +139,8 @@ public Collection getLines() { return list; } - @Nonnull - public ScoreboardInstance setTitle(@Nonnull String title) { + @NotNull + public ScoreboardInstance setTitle(@NotNull String title) { this.title = title; return this; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java index 81d8a76a0..6e840e5a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/LeaderboardInfo.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.stats; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.util.EnumMap; import java.util.Map; @@ -9,11 +9,11 @@ public final class LeaderboardInfo { private final Map values = new EnumMap<>(Statistic.class); - public void setPlace(@Nonnull Statistic statistic, @Nonnegative int place) { + public void setPlace(@NotNull Statistic statistic, int place) { values.put(statistic, place); } - public int getPlace(@Nonnull Statistic statistic) { + public int getPlace(@NotNull Statistic statistic) { return values.getOrDefault(statistic, 1); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java index 32f93b00f..2b9460234 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/PlayerStats.java @@ -2,8 +2,8 @@ import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.config.Document; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.EnumMap; import java.util.Map; import java.util.Map.Entry; @@ -15,7 +15,7 @@ public class PlayerStats { private final UUID uuid; private final String name; - public PlayerStats(@Nonnull UUID uuid, @Nonnull String name, @Nonnull Document document) { + public PlayerStats(@NotNull UUID uuid, @NotNull String name, @NotNull Document document) { this.uuid = uuid; this.name = name; for (Statistic statistic : Statistic.values()) { @@ -23,18 +23,18 @@ public PlayerStats(@Nonnull UUID uuid, @Nonnull String name, @Nonnull Document d } } - public PlayerStats(@Nonnull UUID uuid, @Nonnull String name) { + public PlayerStats(@NotNull UUID uuid, @NotNull String name) { this.uuid = uuid; this.name = name; } - public void incrementStatistic(@Nonnull Statistic statistic, double amount) { + public void incrementStatistic(@NotNull Statistic statistic, double amount) { Logger.debug("Incrementing statistic {} by {} for {}", statistic, amount, name); double value = values.getOrDefault(statistic, 0d); values.put(statistic, value + amount); } - @Nonnull + @NotNull public Document asDocument() { Document document = Document.create(); for (Entry entry : values.entrySet()) { @@ -43,16 +43,16 @@ public Document asDocument() { return document; } - public double getStatisticValue(@Nonnull Statistic statistic) { + public double getStatisticValue(@NotNull Statistic statistic) { return values.getOrDefault(statistic, 0d); } - @Nonnull + @NotNull public UUID getPlayerUUID() { return uuid; } - @Nonnull + @NotNull public String getPlayerName() { return name; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java index c577f2b18..e2ab1baea 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/Statistic.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.management.stats; import net.codingarea.commons.common.collection.NumberFormatter; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.function.Function; public enum Statistic { @@ -20,11 +20,11 @@ public enum Statistic { private final Display display; - Statistic(@Nonnull Display display) { + Statistic(@NotNull Display display) { this.display = display; } - @Nonnull + @NotNull public String formatChat(double value) { return display.formatChat(value); } @@ -36,11 +36,11 @@ public enum Display { private final Function chatFormat; - Display(@Nonnull Function chatFormat) { + Display(@NotNull Function chatFormat) { this.chatFormat = chatFormat; } - @Nonnull + @NotNull public String formatChat(double value) { return chatFormat.apply(value); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java index 08269d1da..605f15ce5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/stats/StatsManager.java @@ -15,8 +15,8 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; @@ -38,8 +38,8 @@ public StatsManager() { noStatsAfterCheating = enabled && Challenges.getInstance().getConfigDocument().getBoolean("no-stats-after-cheating"); } - @Nonnull - public static Comparator getStatsComparator(@Nonnull Statistic statistic) { + @NotNull + public static Comparator getStatsComparator(@NotNull Statistic statistic) { return Comparator.comparingDouble(value -> value.getStatisticValue(statistic)).reversed(); } @@ -52,14 +52,14 @@ public void register() { } @EventHandler(priority = EventPriority.MONITOR) - public void onLeave(@Nonnull PlayerQuitEvent event) { + public void onLeave(@NotNull PlayerQuitEvent event) { PlayerStats cached = cache.remove(event.getPlayer().getUniqueId()); if (cached == null) return; store(event.getPlayer().getUniqueId(), cached); } @EventHandler(priority = EventPriority.MONITOR) - public void onJoin(@Nonnull PlayerJoinEvent event) { + public void onJoin(@NotNull PlayerJoinEvent event) { getStats(event.getPlayer()); // Cache stats } @@ -70,7 +70,7 @@ public void storeCached() { } } - private void store(@Nonnull UUID uuid, @Nonnull PlayerStats stats) { + private void store(@NotNull UUID uuid, @NotNull PlayerStats stats) { try { Challenges.getInstance().getDatabaseManager().getDatabase() .insertOrUpdate("challenges") @@ -83,13 +83,13 @@ private void store(@Nonnull UUID uuid, @Nonnull PlayerStats stats) { } } - @Nonnull - public PlayerStats getStats(@Nonnull Player player) { + @NotNull + public PlayerStats getStats(@NotNull Player player) { return getStats(player.getUniqueId(), player.getName()); } - @Nonnull - public PlayerStats getStats(@Nonnull UUID uuid, @Nonnull String name) { + @NotNull + public PlayerStats getStats(@NotNull UUID uuid, @NotNull String name) { PlayerStats cached = cache.get(uuid); if (cached != null) return cached; @@ -106,8 +106,8 @@ public PlayerStats getStats(@Nonnull UUID uuid, @Nonnull String name) { } } - @Nonnull - private PlayerStats getStatsFromDatabase(@Nonnull UUID uuid, @Nonnull String name) throws DatabaseException { + @NotNull + private PlayerStats getStatsFromDatabase(@NotNull UUID uuid, @NotNull String name) throws DatabaseException { return Challenges.getInstance().getDatabaseManager().getDatabase() .query("challenges") .select("stats", "name") @@ -117,7 +117,7 @@ private PlayerStats getStatsFromDatabase(@Nonnull UUID uuid, @Nonnull String nam .orElse(new PlayerStats(uuid, name)); } - @Nonnull + @NotNull private List getAllStats() throws DatabaseException { if (cachedLeaderboard != null && System.currentTimeMillis() - leaderboardCacheTimestamp < 3 * 60 * 1000) { return cachedLeaderboard; @@ -127,7 +127,7 @@ private List getAllStats() throws DatabaseException { return cachedLeaderboard = getAllStats0(); } - @Nonnull + @NotNull private List getAllStats0() throws DatabaseException { return Challenges.getInstance().getDatabaseManager().getDatabase() .query("challenges") @@ -138,8 +138,8 @@ private List getAllStats0() throws DatabaseException { .collect(Collectors.toList()); } - @Nonnull - public LeaderboardInfo getLeaderboardInfo(@Nonnull UUID uuid) { + @NotNull + public LeaderboardInfo getLeaderboardInfo(@NotNull UUID uuid) { try { List stats = getAllStats(); LeaderboardInfo info = new LeaderboardInfo(); @@ -155,8 +155,8 @@ public LeaderboardInfo getLeaderboardInfo(@Nonnull UUID uuid) { } } - @Nonnull - public List getLeaderboard(@Nonnull Statistic statistic) { + @NotNull + public List getLeaderboard(@NotNull Statistic statistic) { try { List stats = getAllStats(); stats.sort(getStatsComparator(statistic)); @@ -167,7 +167,7 @@ public List getLeaderboard(@Nonnull Statistic statistic) { } } - private int determineIndex(@Nonnull List list, @Nonnull Function extractor, @Nonnull U target, @Nonnull Comparator sort) { + private int determineIndex(@NotNull List list, @NotNull Function extractor, @NotNull U target, @NotNull Comparator sort) { list.sort(sort); int index = 0; for (T t : list) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java index 729716cad..1cb20040a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java @@ -12,14 +12,13 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.Arrays; import java.util.List; public class ChallengesCommand implements PlayerCommand, Completer { @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) { + public void onCommand(@NotNull Player player, @NotNull String[] args) { if (args.length > 1) { Message.forName("syntax").send(player, Prefix.CHALLENGES, "challenges [menu]"); return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java index 0d53c4ad7..802a7b6db 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java @@ -15,7 +15,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -128,7 +127,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc /** * Checks for disabled features and sends a proper messages to indicate that */ - private boolean checkFeatureDisabled(boolean enabled, @Nonnull Player player) { + private boolean checkFeatureDisabled(boolean enabled, @NotNull Player player) { if (!enabled) { Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); SoundSample.BASS_OFF.play(player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java index 381dff108..5cde1bc1a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java @@ -7,16 +7,16 @@ import net.codingarea.challenges.plugin.utils.misc.CommandHelper; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; public class FeedCommand implements SenderCommand, Completer { @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { List targets = new ArrayList<>(); @@ -49,7 +49,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) thr @Nullable @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { return CommandHelper.getCompletions(sender); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java index e09e858e9..e9c6cb455 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java @@ -7,16 +7,16 @@ import net.codingarea.challenges.plugin.utils.misc.CommandHelper; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; public class FlyCommand implements SenderCommand, Completer { @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { List targets = new ArrayList<>(); @@ -54,7 +54,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) thr @Nullable @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { return CommandHelper.getCompletions(sender); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java index 3836680ad..439135eb5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java @@ -12,7 +12,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; @@ -86,7 +85,7 @@ private GameMode getGameMode(String input) { @Nullable @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { if (args.length == 2) return CommandHelper.getCompletions(sender); if (args.length > 1) return null; return Utils.filterRecommendations(args[0], "0", "1", "2", "3", "survival", "creative", "spectator", "adventure", "s", "c", "sp", "a"); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java index bb775a5e3..92409f1d4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java @@ -8,16 +8,16 @@ import net.codingarea.challenges.plugin.utils.misc.Utils; import net.codingarea.commons.common.config.FileDocument; import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Collections; import java.util.List; public class GamestateCommand implements SenderCommand, Completer { @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (args.length != 1) { Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gamestate "); @@ -45,7 +45,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) thr @Nullable @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { return args.length == 1 ? Utils.filterRecommendations(args[0], "reset", "reload") : Collections.emptyList(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java index cfe48f18d..fcdf0397b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java @@ -12,9 +12,9 @@ import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; import java.util.UUID; @@ -24,7 +24,7 @@ public class GodModeCommand implements SenderCommand, Completer, Listener { private final List godModePlayers = new ArrayList<>(); @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { List targets = new ArrayList<>(); @@ -63,7 +63,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) thr @Nullable @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { return CommandHelper.getCompletions(sender); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java index 43fc75a07..381c8ef37 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java @@ -9,16 +9,16 @@ import org.bukkit.attribute.AttributeInstance; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; public class HealCommand implements SenderCommand, Completer { @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { List targets = new ArrayList<>(); @@ -59,7 +59,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { @Nullable @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { return CommandHelper.getCompletions(sender); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java index d5df6bd58..22eac5e40 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HelpCommand.java @@ -2,13 +2,12 @@ import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import org.bukkit.command.CommandSender; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class HelpCommand implements SenderCommand { @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java index a8d7e6ee5..5b0f63c79 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java @@ -21,8 +21,8 @@ import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.PlayerInventory; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @@ -42,7 +42,7 @@ public class InvseeCommand implements PlayerCommand, Listener { private final Map inventories = new HashMap<>(); @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (args.length < 1) { Message.forName("syntax").send(player, Prefix.CHALLENGES, "invsee "); @@ -61,7 +61,7 @@ public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exc Message.forName("command-invsee-open").send(player, Prefix.CHALLENGES, NameHelper.getName(target)); } - public Inventory getInventory(@Nonnull Player player) { + public Inventory getInventory(@NotNull Player player) { if (inventories.containsKey(player)) { return inventories.get(player); } @@ -74,7 +74,7 @@ public Inventory getInventory(@Nonnull Player player) { return inventory; } - public void updateInventoryContents(@Nonnull Inventory inventory, @Nonnull PlayerInventory playerInventory) { + public void updateInventoryContents(@NotNull Inventory inventory, @NotNull PlayerInventory playerInventory) { inventory.clear(); for (int slot = startBottom; slot <= endBottom; slot++) { @@ -93,26 +93,26 @@ public void updateInventoryContents(@Nonnull Inventory inventory, @Nonnull Playe } - public void updateInventory(@Nonnull Player player) { + public void updateInventory(@NotNull Player player) { if (!inventories.containsKey(player)) return; Inventory inventory = inventories.get(player); updateInventoryContents(inventory, player.getInventory()); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerInventoryClick(@Nonnull PlayerInventoryClickEvent event) { + public void onPlayerInventoryClick(@NotNull PlayerInventoryClickEvent event) { if (event.getClickedInventory() == null) return; if (event.getClickedInventory().getHolder() != event.getPlayer()) return; Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> updateInventory(event.getPlayer()), 1); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerDropItem(@Nonnull PlayerDropItemEvent event) { + public void onPlayerDropItem(@NotNull PlayerDropItemEvent event) { Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> updateInventory(event.getPlayer()), 1); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerQuit(@Nonnull PlayerQuitEvent event) { + public void onPlayerQuit(@NotNull PlayerQuitEvent event) { Inventory inventory = inventories.remove(event.getPlayer()); if (inventory == null) return; for (HumanEntity viewer : new ArrayList<>(inventory.getViewers())) { @@ -122,7 +122,7 @@ public void onPlayerQuit(@Nonnull PlayerQuitEvent event) { } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onClose(@Nonnull InventoryCloseEvent event) { + public void onClose(@NotNull InventoryCloseEvent event) { if (event.getInventory().getHolder() != MenuPosition.HOLDER) return; Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { for (Entry entry : inventories.entrySet()) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java index a31279eb6..b9f1ae311 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java @@ -19,9 +19,9 @@ import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; import java.util.List; public class LeaderboardCommand implements PlayerCommand { @@ -36,7 +36,7 @@ public class LeaderboardCommand implements PlayerCommand { } @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (!Challenges.getInstance().getStatsManager().isEnabled()) { Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); SoundSample.BASS_OFF.play(player); @@ -50,9 +50,9 @@ public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exc createInventory(player).open(player, Challenges.getInstance()); } - @Nonnull + @NotNull @CheckReturnValue - public AnimatedInventory createInventory(@Nonnull Player player) { + public AnimatedInventory createInventory(@NotNull Player player) { AnimatedInventory inventory = new AnimatedInventory(InventoryTitleManager.getLeaderboardTitle(), 4 * 9, MenuPosition.HOLDER); StatsHelper.setAccent(inventory, 2); SlottedMenuPosition position = new SlottedMenuPosition(); @@ -67,13 +67,13 @@ public AnimatedInventory createInventory(@Nonnull Player player) { return inventory; } - private void openMenu(@Nonnull Player player, @Nonnull Statistic statistic, int page, boolean openInstant) { + private void openMenu(@NotNull Player player, @NotNull Statistic statistic, int page, boolean openInstant) { loadingInventory.open(player, Challenges.getInstance()); MenuPosition.setEmpty(player); Challenges.getInstance().runAsync(() -> openMenu0(player, statistic, page, openInstant)); } - private void openMenu0(@Nonnull Player player, @Nonnull Statistic statistic, int page, boolean openInstant) { + private void openMenu0(@NotNull Player player, @NotNull Statistic statistic, int page, boolean openInstant) { int[] slots = { 10, 11, 12, 13, 14, 15, 16, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java index 89bfc3611..849ce5776 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java @@ -11,8 +11,8 @@ import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Collections; import java.util.List; @@ -29,7 +29,7 @@ public ResetCommand() { } @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { if (confirmReset && (args.length < 1 || !args[0].equalsIgnoreCase("confirm")) || (args.length > 0 && !args[0].equalsIgnoreCase("confirm"))) { if (args.length > 0 && args[0].equalsIgnoreCase("settings")) { @@ -79,7 +79,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { } @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { if (confirmReset && args.length == 1) return Utils.filterRecommendations( args[0], "confirm", "settings", "customs"); if (seedResetCommand && ((confirmReset && args.length == 2) || args.length == 1)) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java index b913d9029..dea9ecf4a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java @@ -12,9 +12,9 @@ import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Material; import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -25,7 +25,7 @@ public class SearchCommand implements SenderCommand, Completer { @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (args.length == 0) { Message.forName("syntax").send(sender, Prefix.CHALLENGES, "search "); @@ -62,7 +62,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) thr @Nullable @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { return args.length != 1 ? null : Arrays.stream(ExperimentalUtils.getMaterials()) .filter(ItemUtils::isObtainableInSurvival) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java index f81c8c976..236caeb6e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java @@ -18,8 +18,8 @@ import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.io.IOException; import java.util.Map; import java.util.UUID; @@ -30,7 +30,7 @@ public class StatsCommand implements PlayerCommand { private final Map submitTimeByPlayer = new ConcurrentHashMap<>(); @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) { + public void onCommand(@NotNull Player player, @NotNull String[] args) { if (!Challenges.getInstance().getStatsManager().isEnabled()) { Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); SoundSample.BASS_OFF.play(player); @@ -61,13 +61,13 @@ public void onCommand(@Nonnull Player player, @Nonnull String[] args) { } } - private void handleCommand(@Nonnull Player player) { + private void handleCommand(@NotNull Player player) { Challenges.getInstance().runAsync(() -> { open(player, player.getUniqueId(), player.getName()); }); } - private void handleCommand(@Nonnull Player player, @Nonnull String name) { + private void handleCommand(@NotNull Player player, @NotNull String name) { Challenges.getInstance().runAsync(() -> { Player target = Bukkit.getPlayer(name); if (target != null) { @@ -84,7 +84,7 @@ private void handleCommand(@Nonnull Player player, @Nonnull String name) { }); } - private void open(@Nonnull Player player, @Nonnull UUID uuid, @Nonnull String name) { + private void open(@NotNull Player player, @NotNull UUID uuid, @NotNull String name) { PlayerStats stats = Challenges.getInstance().getStatsManager().getStats(uuid, name); name = stats.getPlayerName(); @@ -105,7 +105,7 @@ private void open(@Nonnull Player player, @Nonnull UUID uuid, @Nonnull String na submitTimeByPlayer.remove(player); } - private void createInventory(@Nonnull PlayerStats stats, @Nonnull LeaderboardInfo info, @Nonnull AnimatedInventory inventory, @Nonnull int... slots) { + private void createInventory(@NotNull PlayerStats stats, @NotNull LeaderboardInfo info, @NotNull AnimatedInventory inventory, @NotNull int... slots) { for (int i = 0; i < Statistic.values().length; i++) { Statistic statistic = Statistic.values()[i]; double value = stats.getStatisticValue(statistic); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java index 332134945..dc02a1bc8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java @@ -9,9 +9,9 @@ import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.*; import java.util.Map.Entry; @@ -28,7 +28,7 @@ public TimeCommand() { } @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (args.length == 0) { Message.forName("syntax").send(player, Prefix.CHALLENGES, "time "); @@ -104,14 +104,14 @@ public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exc } - private String getNearestTime(@Nonnull World world) { + private String getNearestTime(@NotNull World world) { return names.entrySet().stream() .min(Comparator.comparingLong(entry -> Math.abs(world.getTime() - entry.getKey()))) .map(Entry::getValue) .orElse("Day"); } - private long getTime(@Nonnull String input) { + private long getTime(@NotNull String input) { for (Entry entry : names.entrySet()) { if (entry.getValue().equalsIgnoreCase(input)) return entry.getKey(); @@ -119,7 +119,7 @@ private long getTime(@Nonnull String input) { return getLongFromString(input); } - private long getLongFromString(@Nonnull String input) { + private long getLongFromString(@NotNull String input) { try { return Long.parseLong(input); } catch (NumberFormatException ex) { @@ -129,7 +129,7 @@ private long getLongFromString(@Nonnull String input) { @Nullable @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { if (args.length <= 1) return Utils.filterRecommendations(args[0], "set", "subtract", "query", "day", "night", "noon", "midnight"); if (args[0].equalsIgnoreCase("set")) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java index 391c875e8..64490235f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java @@ -12,8 +12,8 @@ import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -22,7 +22,7 @@ public class TimerCommand implements SenderCommand, Completer { @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { if (args.length == 0) { if (sender instanceof Player) { @@ -97,7 +97,7 @@ public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) { } @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { if (args.length == 0) return new ArrayList<>(); String last = args[args.length - 1]; if (args.length == 1) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java index fd5f10b74..8d59317ce 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java @@ -9,13 +9,12 @@ import org.bukkit.Location; import org.bukkit.StructureType; import org.bukkit.entity.Player; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class VillageCommand implements PlayerCommand { @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { player.setNoDamageTicks(10); Message.forName("command-village-search").send(player, Prefix.CHALLENGES); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java index 67244e1d2..be2494ca3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java @@ -8,16 +8,16 @@ import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; public class WeatherCommand implements PlayerCommand, Completer { @Override - public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (args.length == 0) { Message.forName("syntax").send(player, Prefix.CHALLENGES, "weather "); @@ -52,7 +52,7 @@ public void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exc @Nullable @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { if (args.length > 1) return new ArrayList<>(); return Utils.filterRecommendations(args[0], "sun", "clear", "rain", "thunder"); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java index 30157b8a9..1dd6a6130 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java @@ -17,7 +17,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.List; public class WorldCommand implements PlayerCommand, TabCompleter { @@ -52,7 +51,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc player.teleport(location); } - public Location getSpawn(@Nonnull World world, @Nonnull Player player) { + public Location getSpawn(@NotNull World world, @NotNull Player player) { Location location = world.getSpawnLocation(); Location bedSpawnLocation = player.getBedSpawnLocation(); if (bedSpawnLocation != null && bedSpawnLocation.getWorld() == world) { @@ -63,7 +62,7 @@ public Location getSpawn(@Nonnull World world, @Nonnull Player player) { return location; } - public String getWorldName(@Nonnull Location location) { + public String getWorldName(@NotNull Location location) { if (location.getWorld() == null) return "?"; switch (location.getWorld().getEnvironment()) { default: diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java index 93b836718..1657f08ca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/InventoryClickEventWrapper.java @@ -9,16 +9,16 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.List; public abstract class InventoryClickEventWrapper extends Event { private final InventoryClickEvent event; - public InventoryClickEventWrapper(@Nonnull InventoryClickEvent event) { + public InventoryClickEventWrapper(@NotNull InventoryClickEvent event) { this.event = event; } @@ -27,22 +27,22 @@ public Inventory getClickedInventory() { return event.getClickedInventory(); } - @Nonnull + @NotNull public Inventory getInventory() { return event.getInventory(); } - @Nonnull + @NotNull public InventoryView getView() { return event.getView(); } - @Nonnull + @NotNull public ClickType getClick() { return event.getClick(); } - @Nonnull + @NotNull public HumanEntity getWhoClicked() { return event.getWhoClicked(); } @@ -55,7 +55,7 @@ public int getRawSlot() { return event.getRawSlot(); } - @Nonnull + @NotNull public InventoryAction getAction() { return event.getAction(); } @@ -69,17 +69,17 @@ public int getHotbarButton() { return event.getHotbarButton(); } - @Nonnull + @NotNull public SlotType getSlotType() { return event.getSlotType(); } - @Nonnull + @NotNull public Result getResult() { return event.getResult(); } - public void setResult(@Nonnull Result result) { + public void setResult(@NotNull Result result) { event.setResult(result); } @@ -92,12 +92,12 @@ public void setCurrentItem(@Nullable ItemStack item) { event.setCurrentItem(item); } - @Nonnull + @NotNull public List getViewers() { return event.getViewers(); } - @Nonnull + @NotNull public InventoryClickEvent getEvent() { return event; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java index ff347c0a1..5da2d4185 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java @@ -4,8 +4,7 @@ import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.bukkit.event.inventory.InventoryClickEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Getter public class PlayerInventoryClickEvent extends InventoryClickEventWrapper { @@ -14,17 +13,17 @@ public class PlayerInventoryClickEvent extends InventoryClickEventWrapper { private final Player player; - public PlayerInventoryClickEvent(@Nonnull InventoryClickEvent event) { + public PlayerInventoryClickEvent(@NotNull InventoryClickEvent event) { super(event); player = ((Player) event.getWhoClicked()); } - @Nonnull + @NotNull public static HandlerList getHandlerList() { return handlers; } - @Nonnull + @NotNull @Override public HandlerList getHandlers() { return getHandlerList(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java index ec02033e9..30ef37887 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerJumpEvent.java @@ -5,8 +5,7 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.player.PlayerStatisticIncrementEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class PlayerJumpEvent extends PlayerEvent implements Cancellable { @@ -14,12 +13,12 @@ public class PlayerJumpEvent extends PlayerEvent implements Cancellable { private final PlayerStatisticIncrementEvent event; - public PlayerJumpEvent(@Nonnull Player who, PlayerStatisticIncrementEvent statisticIncrementEvent) { + public PlayerJumpEvent(@NotNull Player who, PlayerStatisticIncrementEvent statisticIncrementEvent) { super(who); this.event = statisticIncrementEvent; } - @Nonnull + @NotNull public static HandlerList getHandlerList() { return handlers; } @@ -34,7 +33,7 @@ public void setCancelled(boolean b) { event.setCancelled(true); } - @Nonnull + @NotNull @Override public HandlerList getHandlers() { return handlers; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java index bf1ece3e6..804605211 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerPickupItemEvent.java @@ -6,8 +6,7 @@ import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; @Getter public class PlayerPickupItemEvent extends PlayerEvent implements Cancellable { @@ -18,13 +17,13 @@ public class PlayerPickupItemEvent extends PlayerEvent implements Cancellable { private final int remaining; private boolean cancel = false; - public PlayerPickupItemEvent(@Nonnull Player player, @Nonnull Item item, int remaining) { + public PlayerPickupItemEvent(@NotNull Player player, @NotNull Item item, int remaining) { super(player); this.item = item; this.remaining = remaining; } - @Nonnull + @NotNull public static HandlerList getHandlerList() { return handlers; } @@ -39,7 +38,7 @@ public void setCancelled(boolean cancel) { this.cancel = cancel; } - @Nonnull + @NotNull @Override public HandlerList getHandlers() { return handlers; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java index 387af43cb..7daac0ce7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/generator/VoidMapGenerator.java @@ -7,8 +7,8 @@ import org.bukkit.block.BlockFace; import org.bukkit.block.data.Directional; import org.bukkit.generator.ChunkGenerator; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Random; public class VoidMapGenerator extends ChunkGenerator { @@ -16,8 +16,8 @@ public class VoidMapGenerator extends ChunkGenerator { private static final boolean generateEndPortal = MinecraftVersion.current().getMinor() == 18; @Override - @Nonnull - public ChunkData generateChunkData(@Nonnull World world, @Nonnull Random random, int x, int z, @Nonnull BiomeGrid biome) { + @NotNull + public ChunkData generateChunkData(@NotNull World world, @NotNull Random random, int x, int z, @NotNull BiomeGrid biome) { ChunkData chunkData = createChunkData(world); if (x == 0 && z == 0) { @@ -45,7 +45,7 @@ public ChunkData generateChunkData(@Nonnull World world, @Nonnull Random random, return chunkData; } - public void generateEndPortal(@Nonnull ChunkData data) { + public void generateEndPortal(@NotNull ChunkData data) { int x = 6; int y = 29; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java index 7b52cb48d..3935e43c4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/BlockDropListener.java @@ -15,36 +15,36 @@ import org.bukkit.event.block.BlockExplodeEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.List; public class BlockDropListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { + public void onBlockBreak(@NotNull BlockBreakEvent event) { if (event.getPlayer().getGameMode() == GameMode.CREATIVE) return; if (!event.isDropItems()) return; dropCustomDrops(event.getBlock(), () -> event.setDropItems(false)); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockExplosion(@Nonnull BlockExplodeEvent event) { + public void onBlockExplosion(@NotNull BlockExplodeEvent event) { handleExplosion(event.blockList(), () -> event.setYield(0)); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityExplosion(@Nonnull EntityExplodeEvent event) { + public void onEntityExplosion(@NotNull EntityExplodeEvent event) { handleExplosion(event.blockList(), () -> event.setYield(0)); } - protected void handleExplosion(@Nonnull Iterable blocklist, @Nonnull Runnable dropsExist) { + protected void handleExplosion(@NotNull Iterable blocklist, @NotNull Runnable dropsExist) { for (Block block : blocklist) { dropCustomDrops(block, dropsExist); } } - protected void dropCustomDrops(@Nonnull Block block, @Nonnull Runnable dropsExist) { + protected void dropCustomDrops(@NotNull Block block, @NotNull Runnable dropsExist) { Material material = block.getType(); if (BukkitReflectionUtils.isAir(material)) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java index f78290b11..fe1bd2994 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java @@ -14,8 +14,7 @@ import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent; import org.bukkit.event.player.PlayerToggleSneakEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class CheatListener implements Listener { @@ -26,7 +25,7 @@ public CheatListener() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onGameModeChange(@Nonnull PlayerGameModeChangeEvent event) { + public void onGameModeChange(@NotNull PlayerGameModeChangeEvent event) { if (event.getNewGameMode() == GameMode.CREATIVE) handleCheatsDetected(event.getPlayer()); } @@ -40,7 +39,7 @@ public void onSneak(PlayerToggleSneakEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onCommand(@Nonnull PlayerCommandPreprocessEvent event) { + public void onCommand(@NotNull PlayerCommandPreprocessEvent event) { String[] commands = { "give", "replaceitem", @@ -70,7 +69,7 @@ public void onCommand(@Nonnull PlayerCommandPreprocessEvent event) { } } - private boolean hasPermission(@Nonnull Player player, @Nonnull String command) { + private boolean hasPermission(@NotNull Player player, @NotNull String command) { String[] prefixes = { "challenges.", "minecraft.command.", @@ -86,7 +85,7 @@ private boolean hasPermission(@Nonnull Player player, @Nonnull String command) { return false; } - private void handleCheatsDetected(@Nonnull Player player) { + private void handleCheatsDetected(@NotNull Player player) { if (Challenges.getInstance().getServerManager().hasCheated()) return; if (!Challenges.getInstance().getStatsManager().isNoStatsAfterCheating()) return; Challenges.getInstance().getServerManager().setHasCheated(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java index 2ef1f4e40..7f46899e8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CustomEventListener.java @@ -17,8 +17,7 @@ import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent; import org.bukkit.event.player.PlayerStatisticIncrementEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class CustomEventListener implements Listener { @@ -26,7 +25,7 @@ public class CustomEventListener implements Listener { * Detecting jumps and calls a {@link PlayerJumpEvent} */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerStatisticIncrement(@Nonnull PlayerStatisticIncrementEvent event) { + public void onPlayerStatisticIncrement(@NotNull PlayerStatisticIncrementEvent event) { if (BukkitReflectionUtils.isInWater(event.getPlayer())) return; if (event.getStatistic() == Statistic.JUMP) { Bukkit.getPluginManager().callEvent(new PlayerJumpEvent(event.getPlayer(), event)); @@ -34,7 +33,7 @@ public void onPlayerStatisticIncrement(@Nonnull PlayerStatisticIncrementEvent ev } @EventHandler(priority = EventPriority.HIGHEST) - public void onInventoryClick(@Nonnull InventoryClickEvent event) { + public void onInventoryClick(@NotNull InventoryClickEvent event) { if (!(event.getWhoClicked() instanceof Player)) return; PlayerInventoryClickEvent eventCall = new PlayerInventoryClickEvent(event); eventCall.setCancelled(event.isCancelled()); @@ -43,7 +42,7 @@ public void onInventoryClick(@Nonnull InventoryClickEvent event) { } @EventHandler(priority = EventPriority.HIGHEST) - public void onEntityPickupItem(@Nonnull EntityPickupItemEvent event) { + public void onEntityPickupItem(@NotNull EntityPickupItemEvent event) { if (!(event.getEntity() instanceof Player)) return; PlayerPickupItemEvent eventCall = new PlayerPickupItemEvent(((Player) event.getEntity()), event.getItem(), event.getRemaining()); eventCall.setCancelled(event.isCancelled()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java index 22da2139f..f29366593 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ExtraWorldRestrictionListener.java @@ -10,13 +10,12 @@ import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.player.PlayerDropItemEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class ExtraWorldRestrictionListener implements Listener { @EventHandler(priority = EventPriority.LOW) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + public void onBlockPlace(@NotNull BlockPlaceEvent event) { if (!isInExtraWorld(event.getBlock().getLocation())) return; if (Challenges.getInstance().getWorldManager().getSettings().isPlaceBlocks()) return; @@ -25,7 +24,7 @@ public void onBlockPlace(@Nonnull BlockPlaceEvent event) { } @EventHandler(priority = EventPriority.LOW) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { + public void onBlockBreak(@NotNull BlockBreakEvent event) { if (!isInExtraWorld(event.getBlock().getLocation())) return; if (Challenges.getInstance().getWorldManager().getSettings().isDestroyBlocks()) return; @@ -33,7 +32,7 @@ public void onBlockBreak(@Nonnull BlockBreakEvent event) { } @EventHandler(priority = EventPriority.LOW) - public void onDrop(@Nonnull PlayerDropItemEvent event) { + public void onDrop(@NotNull PlayerDropItemEvent event) { if (!isInExtraWorld(event.getPlayer().getWorld())) return; if (Challenges.getInstance().getWorldManager().getSettings().isDropItems()) return; @@ -41,19 +40,19 @@ public void onDrop(@Nonnull PlayerDropItemEvent event) { } @EventHandler(priority = EventPriority.LOW) - public void onPickUp(@Nonnull PlayerPickupItemEvent event) { + public void onPickUp(@NotNull PlayerPickupItemEvent event) { if (!isInExtraWorld(event.getPlayer().getWorld())) return; if (Challenges.getInstance().getWorldManager().getSettings().isPickupItems()) return; event.setCancelled(true); } - private boolean isInExtraWorld(@Nonnull Location location) { + private boolean isInExtraWorld(@NotNull Location location) { if (location.getWorld() == null) return false; return isInExtraWorld(location.getWorld()); } - private boolean isInExtraWorld(@Nonnull World world) { + private boolean isInExtraWorld(@NotNull World world) { return Challenges.getInstance().getWorldManager().getExtraWorld().equals(world); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java index 244ca2a48..85fe5178e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java @@ -11,15 +11,15 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; public class HelpListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) - public void onCommand(@Nonnull PlayerCommandPreprocessEvent event) { + public void onCommand(@NotNull PlayerCommandPreprocessEvent event) { String message = event.getMessage().toLowerCase(); if (message.isEmpty()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index b3b2081d0..eb607a322 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -17,8 +17,8 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.List; public class PlayerConnectionListener implements Listener { @@ -41,7 +41,7 @@ public PlayerConnectionListener() { } @EventHandler(priority = EventPriority.HIGH) - public void onJoin(@Nonnull PlayerJoinEvent event) { + public void onJoin(@NotNull PlayerJoinEvent event) { Player player = event.getPlayer(); @@ -113,7 +113,7 @@ public void onJoin(@Nonnull PlayerJoinEvent event) { } @EventHandler(priority = EventPriority.HIGH) - public void onQuit(@Nonnull PlayerQuitEvent event) { + public void onQuit(@NotNull PlayerQuitEvent event) { try { Player player = event.getPlayer(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java index f111ace66..f11bf6dae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/RestrictionListener.java @@ -20,13 +20,12 @@ import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.event.weather.ThunderChangeEvent; import org.bukkit.event.weather.WeatherChangeEvent; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class RestrictionListener implements Listener { @EventHandler(priority = EventPriority.LOW) - public void onEntityDamage(@Nonnull EntityDamageEvent event) { + public void onEntityDamage(@NotNull EntityDamageEvent event) { if (ChallengeAPI.isStarted()) return; Entity entity = event.getEntity(); if (entity instanceof Player && ((Player) entity).getGameMode() == GameMode.CREATIVE) { @@ -41,7 +40,7 @@ public void onEntityDamage(@Nonnull EntityDamageEvent event) { } @EventHandler(priority = EventPriority.LOW) - public void onEntityDeath(@Nonnull EntityDeathEvent event) { + public void onEntityDeath(@NotNull EntityDeathEvent event) { if (ChallengeAPI.isStarted()) return; if (!(event.getEntity() instanceof Player)) return; event.getDrops().clear(); @@ -49,31 +48,31 @@ public void onEntityDeath(@Nonnull EntityDeathEvent event) { } @EventHandler(priority = EventPriority.LOW) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { + public void onBlockBreak(@NotNull BlockBreakEvent event) { if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOW) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + public void onBlockPlace(@NotNull BlockPlaceEvent event) { if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOW) - public void onFoodLevelChange(@Nonnull FoodLevelChangeEvent event) { + public void onFoodLevelChange(@NotNull FoodLevelChangeEvent event) { if (ChallengeAPI.isPaused()) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOW) - public void onEntityRegainHealth(@Nonnull EntityRegainHealthEvent event) { + public void onEntityRegainHealth(@NotNull EntityRegainHealthEvent event) { if (ChallengeAPI.isPaused()) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOW) - public void onItemPickup(@Nonnull EntityPickupItemEvent event) { + public void onItemPickup(@NotNull EntityPickupItemEvent event) { if (ChallengeAPI.isStarted()) return; if (!(event.getEntity() instanceof Player)) return; Player player = (Player) event.getEntity(); @@ -82,38 +81,38 @@ public void onItemPickup(@Nonnull EntityPickupItemEvent event) { } @EventHandler(priority = EventPriority.LOW) - public void onDrop(@Nonnull PlayerDropItemEvent event) { + public void onDrop(@NotNull PlayerDropItemEvent event) { if (ChallengeAPI.isStarted()) return; if (event.getPlayer().getGameMode() != GameMode.CREATIVE) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOW) - public void onInteract(@Nonnull PlayerInteractEvent event) { + public void onInteract(@NotNull PlayerInteractEvent event) { if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOW) - public void onInteract(@Nonnull PlayerInteractAtEntityEvent event) { + public void onInteract(@NotNull PlayerInteractAtEntityEvent event) { if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOW) - public void onInteract(@Nonnull PlayerInteractEntityEvent event) { + public void onInteract(@NotNull PlayerInteractEntityEvent event) { if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOW) - public void onOffHandItemSwitch(@Nonnull PlayerSwapHandItemsEvent event) { + public void onOffHandItemSwitch(@NotNull PlayerSwapHandItemsEvent event) { if (ChallengeAPI.isPaused() && event.getPlayer().getGameMode() != GameMode.CREATIVE) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOW) - public void onDamage(@Nonnull VehicleDamageEvent event) { + public void onDamage(@NotNull VehicleDamageEvent event) { if (ChallengeAPI.isStarted()) return; Entity entity = event.getVehicle(); event.setCancelled(true); @@ -125,31 +124,31 @@ public void onDamage(@Nonnull VehicleDamageEvent event) { } @EventHandler(priority = EventPriority.LOW) - public void onDamage(@Nonnull VehicleDestroyEvent event) { + public void onDamage(@NotNull VehicleDestroyEvent event) { if (ChallengeAPI.isPaused() && !(event.getAttacker() instanceof Player && ((Player) event.getAttacker()).getGameMode() == GameMode.CREATIVE)) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOW) - public void onWeatherChange(@Nonnull WeatherChangeEvent event) { + public void onWeatherChange(@NotNull WeatherChangeEvent event) { if (ChallengeAPI.isPaused() && event.toWeatherState()) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOW) - public void onThunderChange(@Nonnull ThunderChangeEvent event) { + public void onThunderChange(@NotNull ThunderChangeEvent event) { if (ChallengeAPI.isPaused() && event.toThunderState()) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOW) - public void onTarget(@Nonnull EntityTargetEvent event) { + public void onTarget(@NotNull EntityTargetEvent event) { if (ChallengeAPI.isPaused() && event.getTarget() != null) event.setCancelled(true); } @EventHandler(priority = EventPriority.LOW) - public void onClick(@Nonnull InventoryClickEvent event) { + public void onClick(@NotNull InventoryClickEvent event) { if (!(event.getWhoClicked() instanceof Player)) return; Player player = (Player) event.getWhoClicked(); if (ChallengeAPI.isPaused() && player.getGameMode() != GameMode.CREATIVE) @@ -157,7 +156,7 @@ public void onClick(@Nonnull InventoryClickEvent event) { } @EventHandler(priority = EventPriority.LOW) - public void onBlockSpread(@Nonnull BlockSpreadEvent event) { + public void onBlockSpread(@NotNull BlockSpreadEvent event) { if (ChallengeAPI.isStarted()) return; event.setCancelled(true); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java index 163aaac8e..e7550b8ef 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/StatsListener.java @@ -28,8 +28,8 @@ import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerMoveEvent; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; @@ -47,7 +47,7 @@ public void onStart() { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageEvent event) { + public void onDamage(@NotNull EntityDamageEvent event) { if (countNoStats()) return; if (!(event.getEntity() instanceof Player)) return; if (event.getCause() == DamageCause.VOID) return; @@ -58,7 +58,7 @@ public void onDamage(@Nonnull EntityDamageEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(@Nonnull EntityDamageByEntityEvent event) { + public void onDamage(@NotNull EntityDamageByEntityEvent event) { if (countNoStats()) return; if (event.getDamager() instanceof Player) { @@ -82,27 +82,27 @@ public void onDamage(@Nonnull EntityDamageByEntityEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(@Nonnull BlockPlaceEvent event) { + public void onBlockPlace(@NotNull BlockPlaceEvent event) { if (countNoStats()) return; if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; incrementStatistic(event.getPlayer(), Statistic.BLOCKS_PLACED, 1); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(@Nonnull BlockBreakEvent event) { + public void onBlockBreak(@NotNull BlockBreakEvent event) { if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; if (countNoStats()) return; incrementStatistic(event.getPlayer(), Statistic.BLOCKS_MINED, 1); } @EventHandler(priority = EventPriority.MONITOR) - public void onDeath(@Nonnull PlayerDeathEvent event) { + public void onDeath(@NotNull PlayerDeathEvent event) { if (countNoStats()) return; incrementStatistic(event.getEntity(), Statistic.DEATHS, 1); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onKill(@Nonnull EntityDeathEvent event) { + public void onKill(@NotNull EntityDeathEvent event) { if (countNoStats()) return; LivingEntity entity = event.getEntity(); Player player = entity.getKiller(); @@ -117,7 +117,7 @@ public void onKill(@Nonnull EntityDeathEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(@Nonnull PlayerMoveEvent event) { + public void onMove(@NotNull PlayerMoveEvent event) { if (countNoStats()) return; if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; if (ChallengeAPI.isPaused()) return; @@ -127,14 +127,14 @@ public void onMove(@Nonnull PlayerMoveEvent event) { } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onJump(@Nonnull PlayerJumpEvent event) { + public void onJump(@NotNull PlayerJumpEvent event) { if (countNoStats()) return; if (AbstractChallenge.ignorePlayer(event.getPlayer())) return; if (ChallengeAPI.isPaused()) return; incrementStatistic(event.getPlayer(), Statistic.JUMPS, 1); } - private void incrementStatistic(@Nonnull Player player, @Nonnull Statistic statistic, double amount) { + private void incrementStatistic(@NotNull Player player, @NotNull Statistic statistic, double amount) { PlayerStats stats = Challenges.getInstance().getStatsManager().getStats(player); stats.incrementStatistic(statistic, amount); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java index 685acfe58..8cb55071b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/Completer.java @@ -3,19 +3,19 @@ import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.List; public interface Completer extends TabCompleter { @Override @Nullable - default List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) { + default List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { return onTabComplete(sender, args); } @Nullable - List onTabComplete(@Nonnull CommandSender sender, @Nonnull String[] args); + List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java index 258830152..06432f831 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/ForwardingCommand.java @@ -4,9 +4,9 @@ import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; @@ -15,23 +15,23 @@ public class ForwardingCommand implements SenderCommand, TabCompleter { private final String forwardCommand; private final boolean overrideTab; - public ForwardingCommand(@Nonnull String forwardCommand) { + public ForwardingCommand(@NotNull String forwardCommand) { this(forwardCommand, true); } - public ForwardingCommand(@Nonnull String forwardCommand, boolean overrideTab) { + public ForwardingCommand(@NotNull String forwardCommand, boolean overrideTab) { this.forwardCommand = forwardCommand; this.overrideTab = overrideTab; } @Override - public void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception { + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { Bukkit.dispatchCommand(sender, forwardCommand + " " + String.join(" ", args)); } @Nullable @Override - public List onTabComplete(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String alias, @Nonnull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { return overrideTab ? new ArrayList<>() : null; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java index 7fff7578e..e6050d843 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java @@ -7,13 +7,12 @@ import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public interface PlayerCommand extends CommandExecutor { @Override - default boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) { + default boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { if (sender instanceof Player) { try { onCommand((Player) sender, args); @@ -27,6 +26,6 @@ default boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command comman return true; } - void onCommand(@Nonnull Player player, @Nonnull String[] args) throws Exception; + void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java index 6675f0632..c94470132 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java @@ -5,13 +5,12 @@ import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public interface SenderCommand extends CommandExecutor { @Override - default boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command command, @Nonnull String label, @Nonnull String[] args) { + default boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { try { onCommand(sender, args); } catch (Exception ex) { @@ -21,6 +20,6 @@ default boolean onCommand(@Nonnull CommandSender sender, @Nonnull Command comman return true; } - void onCommand(@Nonnull CommandSender sender, @Nonnull String[] args) throws Exception; + void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java index 07c18695f..47f1340d6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/PlayerData.java @@ -6,8 +6,8 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Collection; @Data @@ -26,7 +26,7 @@ public final class PlayerData { private final boolean allowedFlight; private final boolean flying; - public PlayerData(@Nonnull Player player) { + public PlayerData(@NotNull Player player) { this( player.getGameMode(), player.getLocation(), @@ -43,11 +43,11 @@ public PlayerData(@Nonnull Player player) { } public PlayerData( - @Nonnull GameMode gamemode, - @Nonnull Location location, - @Nonnull ItemStack[] inventory, - @Nonnull ItemStack[] armor, - @Nonnull Collection effects, + @NotNull GameMode gamemode, + @NotNull Location location, + @NotNull ItemStack[] inventory, + @NotNull ItemStack[] armor, + @NotNull Collection effects, double health, int food, float saturation, @@ -68,7 +68,7 @@ public PlayerData( this.flying = allowedFlight && flying; } - public void apply(@Nonnull Player player) { + public void apply(@NotNull Player player) { for (PotionEffect effect : player.getActivePotionEffects()) { player.removePotionEffect(effect.getType()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java index f403eeceb..391d97aba 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/IJumpGenerator.java @@ -2,15 +2,14 @@ import net.codingarea.commons.common.collection.IRandom; import org.bukkit.block.Block; - -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; @FunctionalInterface public interface IJumpGenerator { - @Nonnull + @NotNull @CheckReturnValue - Block next(@Nonnull IRandom random, @Nonnull Block startingPoint, boolean includeFourBlockJumps, boolean includeUpGoing); + Block next(@NotNull IRandom random, @NotNull Block startingPoint, boolean includeFourBlockJumps, boolean includeUpGoing); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java index fe582fe7c..8b359189e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/jumpgeneration/RandomJumpGenerator.java @@ -2,17 +2,16 @@ import net.codingarea.commons.common.collection.IRandom; import org.bukkit.block.Block; - -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; public class RandomJumpGenerator implements IJumpGenerator { - @Nonnull + @NotNull @Override @CheckReturnValue - public Block next(@Nonnull IRandom random, @Nonnull Block startingPoint, boolean includeFourBlockJumps, boolean includeUpGoing) { + public Block next(@NotNull IRandom random, @NotNull Block startingPoint, boolean includeFourBlockJumps, boolean includeUpGoing) { int layer = random.nextInt(includeUpGoing ? 3 : 2) - 1; int range = layer == 0 ? 4 : 3; @@ -29,7 +28,7 @@ public Block next(@Nonnull IRandom random, @Nonnull Block startingPoint, boolean } - protected int determineSecondDirection(@Nonnull IRandom random, int mainDirection, int range) { + protected int determineSecondDirection(@NotNull IRandom random, int mainDirection, int range) { if (mainDirection == range || mainDirection == range - 1) { return random.choose(-1, 0, 1); } else if (mainDirection == range - 2) { @@ -42,9 +41,9 @@ protected int determineSecondDirection(@Nonnull IRandom random, int mainDirectio throw new IllegalArgumentException("Could not determine second direction for main direction " + mainDirection + ", range " + range); } - @Nonnull + @NotNull @CheckReturnValue - protected Block translate(@Nonnull Block startingPoint, @Nonnull IRandom random, int layer, int mainDirection, int secondDirection) { + protected Block translate(@NotNull Block startingPoint, @NotNull IRandom random, int layer, int mainDirection, int secondDirection) { boolean intoX = random.nextBoolean(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java index db71db9c7..09563e29b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java @@ -11,9 +11,9 @@ import org.bukkit.entity.EntityType; import org.bukkit.loot.LootTable; import org.bukkit.potion.PotionEffectType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; @@ -23,8 +23,8 @@ public class BukkitStringUtils { - @Nonnull - public static BaseComponent[] format(@Nullable Prefix prefix, @Nonnull String[] array, @Nonnull Object... args) { + @NotNull + public static BaseComponent[] format(@Nullable Prefix prefix, @NotNull String[] array, @NotNull Object... args) { List results = new ArrayList<>(); for (String value : array) { String s = value; @@ -44,8 +44,8 @@ public static BaseComponent[] format(@Nullable Prefix prefix, @Nonnull String[] return results.toArray(new BaseComponent[0]); } - @Nonnull - public static List format(@Nonnull String sequence, @Nonnull Object... args) { + @NotNull + public static List format(@NotNull String sequence, @NotNull Object... args) { args = replaceArguments(args, false); @@ -182,18 +182,18 @@ public static Object[] replaceArguments(Object[] args, boolean toStrings) { return args; } - public static TranslatableComponent getItemName(@Nonnull Material material) { + public static TranslatableComponent getItemName(@NotNull Material material) { NamespacedKey key = material.getKey(); return new TranslatableComponent((material.isBlock() ? "block" : "item") + "." + key.getNamespace() + "." + key.getKey()); } - public static @Nullable BaseComponent getMusicDiscName(@Nonnull Material material) { + public static @Nullable BaseComponent getMusicDiscName(@NotNull Material material) { if (!material.name().startsWith("MUSIC_DISC")) return null; String key = "item.minecraft." + material.name().toLowerCase() + ".desc"; return new TranslatableComponent(key); } - public static BaseComponent getItemComponent(@Nonnull Material material) { + public static BaseComponent getItemComponent(@NotNull Material material) { BaseComponent component = getItemName(material); BaseComponent musicDiscName = getMusicDiscName(material); if (musicDiscName != null) { @@ -205,7 +205,7 @@ public static BaseComponent getItemComponent(@Nonnull Material material) { } - public static TranslatableComponent getEntityName(@Nonnull EntityType type) { + public static TranslatableComponent getEntityName(@NotNull EntityType type) { String key; String namespace = "minecraft"; @@ -221,12 +221,12 @@ public static TranslatableComponent getEntityName(@Nonnull EntityType type) { return new TranslatableComponent("entity." + namespace + "." + key); } - public static TranslatableComponent getEntityName(@Nonnull LootTable type) { + public static TranslatableComponent getEntityName(@NotNull LootTable type) { NamespacedKey key = type.getKey(); return new TranslatableComponent("entity." + key.getNamespace() + "." + key.getKey().replace("entities/", "")); } - public static TranslatableComponent getPotionEffectName(@Nonnull PotionEffectType type) { + public static TranslatableComponent getPotionEffectName(@NotNull PotionEffectType type) { String key; String namespace = "minecraft"; @@ -243,7 +243,7 @@ public static TranslatableComponent getPotionEffectName(@Nonnull PotionEffectTyp return new TranslatableComponent("effect." + namespace + "." + key); } - public static TranslatableComponent getBiomeName(@Nonnull Biome biome) { + public static TranslatableComponent getBiomeName(@NotNull Biome biome) { String key; String namespace = "minecraft"; @@ -258,21 +258,21 @@ public static TranslatableComponent getBiomeName(@Nonnull Biome biome) { return new TranslatableComponent("biome." + namespace + "." + key); } - public static TranslatableComponent getGameModeName(@Nonnull GameMode gameMode) { + public static TranslatableComponent getGameModeName(@NotNull GameMode gameMode) { return new TranslatableComponent("selectWorld.gameMode." + gameMode.name().toLowerCase()); } - public static BaseComponent getAdvancementTitle(@Nonnull Advancement advancement) { + public static BaseComponent getAdvancementTitle(@NotNull Advancement advancement) { String replace = advancement.getKey().getKey().replace("/", "."); return new TranslatableComponent("advancements." + correctAdvancementKeys(replace) + ".title"); } - public static BaseComponent getAdvancementDescription(@Nonnull Advancement advancement) { + public static BaseComponent getAdvancementDescription(@NotNull Advancement advancement) { String replace = advancement.getKey().getKey().replace("/", "."); return new TranslatableComponent("advancements." + correctAdvancementKeys(replace) + ".description"); } - public static BaseComponent getAdvancementComponent(@Nonnull Advancement advancement) { + public static BaseComponent getAdvancementComponent(@NotNull Advancement advancement) { BaseComponent title = getAdvancementTitle(advancement); BaseComponent description = getAdvancementDescription(advancement); description.setColor(net.md_5.bungee.api.ChatColor.GREEN); @@ -284,7 +284,7 @@ private static String correctAdvancementKeys(String s) { return s.replace("bred_all_animals", "breed_all_animals").replace("obtain_netherite_hoe", "netherite_hoe"); // mc sucks } - public static TranslatableComponent getDifficultyName(@Nonnull Difficulty difficulty) { + public static TranslatableComponent getDifficultyName(@NotNull Difficulty difficulty) { return new TranslatableComponent("options.difficulty." + difficulty.name().toLowerCase()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java index 942aa4f58..fccfd0b95 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java @@ -4,82 +4,81 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder.SkullBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Material; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public final class DefaultItem { private static final String ARROW_LEFT = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjAwNmVjMWVjYTJmMjY4NWY3MGU2NTQxMWNmZTg4MDhhMDg4ZjdjZjA4MDg3YWQ4ZWVjZTk2MTgzNjEwNzBlMyJ9fX0=", ARROW_RIGHT = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZmY5ZTE5ZTVmMmNlMzQ4OGMyOTU4MmI2ZDI2MDE1MDA2MjZlOGRiMmE4OGNkMTgxNjQ0MzJmZWYyZTM0ZGU2YiJ9fX0="; - @Nonnull + @NotNull public static String getItemPrefix() { return Message.forName("item-prefix").asString() + "§e"; } - @Nonnull + @NotNull public static ItemBuilder navigateBack() { return new SkullBuilder().setBase64Texture(ARROW_LEFT).setName(Message.forName("navigate-back")).hideAttributes(); } - @Nonnull + @NotNull public static ItemBuilder navigateNext() { return new SkullBuilder().setBase64Texture(ARROW_RIGHT).setName(Message.forName("navigate-next")).hideAttributes(); } - @Nonnull + @NotNull public static ItemBuilder navigateBackMainMenu() { return new ItemBuilder(Material.DARK_OAK_DOOR).setName(Message.forName("navigate-back")).hideAttributes(); } - @Nonnull + @NotNull public static ItemBuilder status(boolean enabled) { return enabled ? enabled() : disabled(); } - @Nonnull + @NotNull public static ItemBuilder enabled() { return new ItemBuilder(Material.LIME_DYE).setName(getTitle(Message.forName("enabled"))).hideAttributes(); } - @Nonnull + @NotNull public static ItemBuilder disabled() { return new ItemBuilder(MinecraftNameWrapper.RED_DYE).setName(getTitle(Message.forName("disabled"))).hideAttributes(); } - @Nonnull + @NotNull public static ItemBuilder customize() { return new ItemBuilder(MinecraftNameWrapper.SIGN).setName(getTitle(Message.forName("customize"))).hideAttributes(); } - @Nonnull + @NotNull public static ItemBuilder value(int value) { return value(value, "§e"); } - @Nonnull - public static ItemBuilder value(int value, @Nonnull String prefix) { + @NotNull + public static ItemBuilder value(int value, @NotNull String prefix) { return create(Material.STONE_BUTTON, prefix + value).amount(Math.max(value, 1)); } - @Nonnull - public static ItemBuilder create(@Nonnull Material material, @Nonnull String name) { + @NotNull + public static ItemBuilder create(@NotNull Material material, @NotNull String name) { return new ItemBuilder(material, getTitle(name)); } - @Nonnull - public static ItemBuilder create(@Nonnull Material material, @Nonnull Message message) { + @NotNull + public static ItemBuilder create(@NotNull Material material, @NotNull Message message) { ItemBuilder itemBuilder = new ItemBuilder(material, message); return itemBuilder.setName(getTitle(message)); } - @Nonnull - private static String getTitle(@Nonnull Message message) { + @NotNull + private static String getTitle(@NotNull Message message) { return getTitle(message.asString()); } - @Nonnull - private static String getTitle(@Nonnull String text) { + @NotNull + private static String getTitle(@NotNull String text) { return Message.forName("item-setting-info").asString(text); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index fc5804288..331ddb148 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -1,7 +1,6 @@ package net.codingarea.challenges.plugin.utils.item; import com.google.gson.JsonParser; -import lombok.NonNull; import net.codingarea.challenges.plugin.content.ItemDescription; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.commons.bukkit.utils.item.BannerPattern; @@ -15,10 +14,9 @@ import org.bukkit.potion.PotionEffect; import org.bukkit.profile.PlayerProfile; import org.bukkit.profile.PlayerTextures; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; @@ -33,11 +31,11 @@ public class ItemBuilder extends net.codingarea.commons.bukkit.utils.item.ItemBu protected ItemDescription builtByItemDescription; - public ItemBuilder(@Nonnull ItemStack item) { + public ItemBuilder(@NotNull ItemStack item) { super(item); } - public ItemBuilder(@Nonnull ItemStack item, @Nullable ItemMeta meta) { + public ItemBuilder(@NotNull ItemStack item, @Nullable ItemMeta meta) { super(item, meta); } @@ -45,162 +43,162 @@ public ItemBuilder() { this(Material.BARRIER, ItemDescription.empty()); } - public ItemBuilder(@Nonnull Material material) { + public ItemBuilder(@NotNull Material material) { super(material); } - public ItemBuilder(@Nonnull Material material, @Nonnull Message message) { + public ItemBuilder(@NotNull Material material, @NotNull Message message) { this(material, message.asItemDescription()); } - public ItemBuilder(@Nonnull Material material, @Nonnull Message message, Object... args) { + public ItemBuilder(@NotNull Material material, @NotNull Message message, Object... args) { this(material, message.asItemDescription(args)); } - public ItemBuilder(@Nonnull Material material, @Nonnull ItemDescription description) { + public ItemBuilder(@NotNull Material material, @NotNull ItemDescription description) { this(material); applyFormat(description); } - public ItemBuilder(@Nonnull Material material, @Nonnull String name) { + public ItemBuilder(@NotNull Material material, @NotNull String name) { super(material, name); } - public ItemBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + public ItemBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { super(material, name, lore); } - public ItemBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + public ItemBuilder(@NotNull Material material, @NotNull String name, int amount) { super(material, name, amount); } - @Nonnull - public ItemBuilder setLore(@Nonnull Message message) { + @NotNull + public ItemBuilder setLore(@NotNull Message message) { return setLore(message.asArray()); } - @Nonnull - public ItemBuilder setLore(@Nonnull List lore) { + @NotNull + public ItemBuilder setLore(@NotNull List lore) { return (ItemBuilder) super.setLore(lore); } - @Nonnull - public ItemBuilder setLore(@Nonnull String... lore) { + @NotNull + public ItemBuilder setLore(@NotNull String... lore) { return (ItemBuilder) super.setLore(lore); } - @Nonnull - public ItemBuilder appendLore(@Nonnull String... lore) { + @NotNull + public ItemBuilder appendLore(@NotNull String... lore) { return (ItemBuilder) super.appendLore(lore); } - @Nonnull - public ItemBuilder appendLore(@Nonnull Collection lore) { + @NotNull + public ItemBuilder appendLore(@NotNull Collection lore) { return (ItemBuilder) super.appendLore(lore); } - @Nonnull + @NotNull public ItemBuilder setName(@Nullable String name) { return (ItemBuilder) super.setName(name); } - @Nonnull + @NotNull public ItemBuilder setName(@Nullable Object name) { return (ItemBuilder) super.setName(name); } - @Nonnull - public ItemBuilder setName(@Nonnull String... content) { + @NotNull + public ItemBuilder setName(@NotNull String... content) { return (ItemBuilder) super.setName(content); } - @Nonnull + @NotNull public ItemBuilder appendName(@Nullable Object sequence) { return (ItemBuilder) super.appendName(sequence); } - @Nonnull + @NotNull public ItemBuilder name(@Nullable Object name) { return (ItemBuilder) super.name(name); } - @Nonnull - public ItemBuilder name(@Nonnull String... content) { + @NotNull + public ItemBuilder name(@NotNull String... content) { return (ItemBuilder) super.name(content); } - @Nonnull - public ItemBuilder addEnchantment(@Nonnull Enchantment enchantment, int level) { + @NotNull + public ItemBuilder addEnchantment(@NotNull Enchantment enchantment, int level) { return (ItemBuilder) super.addEnchantment(enchantment, level); } - @Nonnull - public ItemBuilder enchant(@Nonnull Enchantment enchantment, int level) { + @NotNull + public ItemBuilder enchant(@NotNull Enchantment enchantment, int level) { return (ItemBuilder) super.enchant(enchantment, level); } - @Nonnull - public ItemBuilder addFlag(@Nonnull ItemFlag... flags) { + @NotNull + public ItemBuilder addFlag(@NotNull ItemFlag... flags) { return (ItemBuilder) super.addFlag(flags); } - @Nonnull - public ItemBuilder removeFlag(@Nonnull ItemFlag... flags) { + @NotNull + public ItemBuilder removeFlag(@NotNull ItemFlag... flags) { return (ItemBuilder) super.removeFlag(flags); } - @Nonnull + @NotNull public ItemBuilder hideAttributes() { return (ItemBuilder) super.hideAttributes(); } - @Nonnull + @NotNull public ItemBuilder showAttributes() { return (ItemBuilder) super.showAttributes(); } - @Nonnull + @NotNull public ItemBuilder setUnbreakable(boolean unbreakable) { return (ItemBuilder) super.setUnbreakable(unbreakable); } - @Nonnull + @NotNull public ItemBuilder unbreakable() { return (ItemBuilder) super.unbreakable(); } - @Nonnull + @NotNull public ItemBuilder breakable() { return (ItemBuilder) super.breakable(); } - @Nonnull + @NotNull public ItemBuilder setAmount(int amount) { return (ItemBuilder) super.setAmount(amount); } - @Nonnull + @NotNull public ItemBuilder amount(int amount) { return (ItemBuilder) super.amount(amount); } - @Nonnull + @NotNull public ItemBuilder setDamage(int damage) { return (ItemBuilder) super.setDamage(damage); } - @Nonnull + @NotNull public ItemBuilder damage(int damage) { return (ItemBuilder) super.damage(damage); } - @Nonnull - public ItemBuilder setType(@Nonnull Material material) { + @NotNull + public ItemBuilder setType(@NotNull Material material) { return (ItemBuilder) super.setType(material); } - @Nonnull - public ItemBuilder applyFormat(@Nonnull ItemDescription description) { + @NotNull + public ItemBuilder applyFormat(@NotNull ItemDescription description) { builtByItemDescription = description; setName(description.getName()); setLore(description.getLore()); @@ -221,46 +219,46 @@ public ItemBuilder clone() { public static class BannerBuilder extends ItemBuilder { - public BannerBuilder(@Nonnull Material material) { + public BannerBuilder(@NotNull Material material) { super(material); } - public BannerBuilder(@Nonnull Material material, @Nonnull Message message) { + public BannerBuilder(@NotNull Material material, @NotNull Message message) { super(material, message); } - public BannerBuilder(@Nonnull Material material, @Nonnull ItemDescription description) { + public BannerBuilder(@NotNull Material material, @NotNull ItemDescription description) { super(material, description); } - public BannerBuilder(@Nonnull Material material, @Nonnull String name) { + public BannerBuilder(@NotNull Material material, @NotNull String name) { super(material, name); } - public BannerBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + public BannerBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { super(material, name, lore); } - public BannerBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + public BannerBuilder(@NotNull Material material, @NotNull String name, int amount) { super(material, name, amount); } - public BannerBuilder(@Nonnull ItemStack item) { + public BannerBuilder(@NotNull ItemStack item) { super(item); } - @Nonnull - public ItemBuilder.BannerBuilder addPattern(@Nonnull BannerPattern pattern, @Nonnull DyeColor color) { + @NotNull + public ItemBuilder.BannerBuilder addPattern(@NotNull BannerPattern pattern, @NotNull DyeColor color) { return addPattern(pattern.getPatternType(), color); } - @Nonnull - public ItemBuilder.BannerBuilder addPattern(@Nonnull PatternType pattern, @Nonnull DyeColor color) { + @NotNull + public ItemBuilder.BannerBuilder addPattern(@NotNull PatternType pattern, @NotNull DyeColor color) { getMeta().addPattern(new Pattern(color, pattern)); return this; } - @Nonnull + @NotNull @Override public BannerMeta getMeta() { return getCastedMeta(); @@ -282,20 +280,20 @@ public SkullBuilder(String name, String... lore) { super(Material.PLAYER_HEAD, name, lore); } - @NonNull - public ItemBuilder.SkullBuilder setOwner(@NonNull OfflinePlayer owner) { + @NotNull + public ItemBuilder.SkullBuilder setOwner(@NotNull OfflinePlayer owner) { getMeta().setOwningPlayer(owner); return this; } - @NonNull - public ItemBuilder.SkullBuilder setOwner(@NonNull UUID uuid, @NonNull String name) { + @NotNull + public ItemBuilder.SkullBuilder setOwner(@NotNull UUID uuid, @NotNull String name) { PlayerProfile profile = Bukkit.createPlayerProfile(uuid, name); getMeta().setOwnerProfile(profile); return this; } - public ItemBuilder.SkullBuilder setTexture(@NonNull String textureUrl) { + public ItemBuilder.SkullBuilder setTexture(@NotNull String textureUrl) { UUID uuid = UUID.nameUUIDFromBytes(textureUrl.getBytes()); PlayerProfile profile = Bukkit.createPlayerProfile(uuid); @@ -312,7 +310,7 @@ public ItemBuilder.SkullBuilder setTexture(@NonNull String textureUrl) { return this; } - public ItemBuilder.SkullBuilder setBase64Texture(@NonNull String base64Texture) { + public ItemBuilder.SkullBuilder setBase64Texture(@NotNull String base64Texture) { String textureUrlJson = new String(Base64.getDecoder().decode(base64Texture), StandardCharsets.UTF_8); @@ -325,7 +323,7 @@ public ItemBuilder.SkullBuilder setBase64Texture(@NonNull String base64Texture) return setTexture(textureUrl); } - @Nonnull + @NotNull @Override public SkullMeta getMeta() { return getCastedMeta(); @@ -335,54 +333,53 @@ public SkullMeta getMeta() { public static class PotionBuilder extends ItemBuilder { - public PotionBuilder(@Nonnull Material material) { + public PotionBuilder(@NotNull Material material) { super(material); } - public PotionBuilder(@Nonnull Material material, @Nonnull Message message) { + public PotionBuilder(@NotNull Material material, @NotNull Message message) { super(material, message); } - public PotionBuilder(@Nonnull Material material, @Nonnull String name) { + public PotionBuilder(@NotNull Material material, @NotNull String name) { super(material, name); } - public PotionBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + public PotionBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { super(material, name, lore); } - public PotionBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + public PotionBuilder(@NotNull Material material, @NotNull String name, int amount) { super(material, name, amount); } - public PotionBuilder(@Nonnull ItemStack item) { + public PotionBuilder(@NotNull ItemStack item) { super(item); } - @Nonnull - @CheckReturnValue + @NotNull public static ItemBuilder createWaterBottle() { return new ItemBuilder.PotionBuilder(Material.POTION).setColor(Color.BLUE).hideAttributes(); } - @Nonnull - public ItemBuilder.PotionBuilder addEffect(@Nonnull PotionEffect effect) { + @NotNull + public ItemBuilder.PotionBuilder addEffect(@NotNull PotionEffect effect) { getMeta().addCustomEffect(effect, true); return this; } - @Nonnull - public ItemBuilder.PotionBuilder setColor(@Nonnull Color color) { + @NotNull + public ItemBuilder.PotionBuilder setColor(@NotNull Color color) { getMeta().setColor(color); return this; } - @Nonnull - public ItemBuilder.PotionBuilder color(@Nonnull Color color) { + @NotNull + public ItemBuilder.PotionBuilder color(@NotNull Color color) { return setColor(color); } - @Nonnull + @NotNull @Override public PotionMeta getMeta() { return getCastedMeta(); @@ -392,42 +389,42 @@ public PotionMeta getMeta() { public static class LeatherArmorBuilder extends ItemBuilder { - public LeatherArmorBuilder(@Nonnull Material material) { + public LeatherArmorBuilder(@NotNull Material material) { super(material); } - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull Message message) { + public LeatherArmorBuilder(@NotNull Material material, @NotNull Message message) { super(material, message); } - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name) { + public LeatherArmorBuilder(@NotNull Material material, @NotNull String name) { super(material, name); } - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + public LeatherArmorBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { super(material, name, lore); } - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + public LeatherArmorBuilder(@NotNull Material material, @NotNull String name, int amount) { super(material, name, amount); } - public LeatherArmorBuilder(@Nonnull ItemStack item) { + public LeatherArmorBuilder(@NotNull ItemStack item) { super(item); } - @Nonnull - public ItemBuilder.LeatherArmorBuilder setColor(@Nonnull Color color) { + @NotNull + public ItemBuilder.LeatherArmorBuilder setColor(@NotNull Color color) { getMeta().setColor(color); return this; } - @Nonnull - public ItemBuilder.LeatherArmorBuilder color(@Nonnull Color color) { + @NotNull + public ItemBuilder.LeatherArmorBuilder color(@NotNull Color color) { return setColor(color); } - @Nonnull + @NotNull @Override public LeatherArmorMeta getMeta() { return getCastedMeta(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java index 771eb1737..583394aac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/logging/ConsolePrint.java @@ -2,9 +2,8 @@ import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Bukkit; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public final class ConsolePrint { @@ -72,7 +71,7 @@ public static void noMongoDependencies() { log(""); } - private static void log(@Nonnull String message) { + private static void log(@NotNull String message) { Logger.error(message); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java index dc533cbb8..4397f4db1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/BlockUtils.java @@ -5,9 +5,9 @@ import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; @@ -37,18 +37,18 @@ public static boolean isSameBlockLocationIgnoreHeight(@Nullable Location loc1, @ && loc1.getBlockZ() == loc2.getBlockZ(); } - public static boolean isSameLocation(@Nonnull Location loc1, @Nonnull Location loc2) { + public static boolean isSameLocation(@NotNull Location loc1, @NotNull Location loc2) { if (loc1.getWorld() != loc2.getWorld()) return false; return loc1.distance(loc2) < 0.1; } - public static boolean isSameLocationIgnoreHeight(@Nonnull Location loc1, @Nonnull Location loc2) { + public static boolean isSameLocationIgnoreHeight(@NotNull Location loc1, @NotNull Location loc2) { if (loc1.getWorld() != loc2.getWorld()) return false; return loc1.getX() == loc2.getX() && loc1.getZ() == loc2.getZ(); } - public static boolean isSameChunk(@Nonnull Chunk chunk1, @Nonnull Chunk chunk2) { + public static boolean isSameChunk(@NotNull Chunk chunk1, @NotNull Chunk chunk2) { if (chunk1.getWorld() != chunk2.getWorld()) return false; return chunk1.getX() == chunk2.getX() && chunk1.getZ() == chunk2.getZ(); } @@ -63,8 +63,8 @@ public static boolean isSameBlockIgnoreHeight(@Nullable Location loc1, @Nullable * @param block middle block * @return the block above, under, in the front, behind, to the left and to the right of the middle block */ - @Nonnull - public static List getBlocksAroundBlock(@Nonnull Block block) { + @NotNull + public static List getBlocksAroundBlock(@NotNull Block block) { List list = new ArrayList<>(); for (BlockFace face : faces) { list.add(block.getRelative(face)); @@ -109,11 +109,11 @@ public static Material getTerracotta(int subId) { } } - public static void createBlockPath(@Nullable Location from, @Nullable Location to, @Nonnull Material type) { + public static void createBlockPath(@Nullable Location from, @Nullable Location to, @NotNull Material type) { createBlockPath(from, to, type, true); } - public static void createBlockPath(@Nullable Location from, @Nullable Location to, @Nonnull Material type, boolean playSound) { + public static void createBlockPath(@Nullable Location from, @Nullable Location to, @NotNull Material type, boolean playSound) { if (from == null || to == null) return; if (isSameBlockLocationIgnoreHeight(from, to)) return; @@ -126,7 +126,7 @@ public static void createBlockPath(@Nullable Location from, @Nullable Location t * @param block the block of block to replace * @param type the type to set as the block type */ - public static void setBlockNatural(@Nullable Block block, @Nonnull Material type, boolean blockUpdate) { + public static void setBlockNatural(@Nullable Block block, @NotNull Material type, boolean blockUpdate) { setBlockNatural(block, type, blockUpdate, true); } @@ -137,7 +137,7 @@ public static void setBlockNatural(@Nullable Block block, @Nonnull Material type * @param type the type to set as the block type * @param playSound if a breaking sound for the block on top should be played */ - public static void setBlockNatural(@Nullable Block block, @Nonnull Material type, boolean blockUpdate, boolean playSound) { + public static void setBlockNatural(@Nullable Block block, @NotNull Material type, boolean blockUpdate, boolean playSound) { if (block == null || !block.getType().isSolid()) return; Block upperBlock = block.getLocation().add(0, 1, 0).getBlock(); @@ -156,7 +156,7 @@ public static void setBlockNatural(@Nullable Block block, @Nonnull Material type * @return the block below the location */ @Nullable - public static Block getBlockBelow(@Nonnull Location location) { + public static Block getBlockBelow(@NotNull Location location) { return getBlockBelow(location, 0.1); } @@ -165,7 +165,7 @@ public static Block getBlockBelow(@Nonnull Location location) { * @return the block below the location */ @Nullable - public static Block getBlockBelow(@Nonnull Location location, boolean ignoreNonSolid) { + public static Block getBlockBelow(@NotNull Location location, boolean ignoreNonSolid) { return getBlockBelow(location, 0.1, ignoreNonSolid); } @@ -174,7 +174,7 @@ public static Block getBlockBelow(@Nonnull Location location, boolean ignoreNonS * @return the block below the location */ @Nullable - public static Block getBlockBelow(@Nonnull Location location, double offset) { + public static Block getBlockBelow(@NotNull Location location, double offset) { return getBlockBelow(location, offset, true); } @@ -183,7 +183,7 @@ public static Block getBlockBelow(@Nonnull Location location, double offset) { * @return the block below the location */ @Nullable - public static Block getBlockBelow(@Nonnull Location location, double offset, boolean ignoreNonSolid) { + public static Block getBlockBelow(@NotNull Location location, double offset, boolean ignoreNonSolid) { Block block; if (offset == -1) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java index 86d28fe59..a8de5057e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java @@ -3,8 +3,8 @@ import org.bukkit.ChatColor; import org.bukkit.DyeColor; import org.bukkit.Material; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.awt.*; import java.util.HashMap; import java.util.Map; @@ -36,8 +36,8 @@ public final class ColorConversions { private ColorConversions() { } - @Nonnull - public static ChatColor convertDyeColorToChatColor(@Nonnull DyeColor color) { + @NotNull + public static ChatColor convertDyeColorToChatColor(@NotNull DyeColor color) { switch (color) { case RED: return ChatColor.RED; @@ -73,8 +73,8 @@ public static ChatColor convertDyeColorToChatColor(@Nonnull DyeColor color) { } } - @Nonnull - public static Material convertDyeColorToMaterial(@Nonnull DyeColor color) { + @NotNull + public static Material convertDyeColorToMaterial(@NotNull DyeColor color) { switch (color) { case YELLOW: return MinecraftNameWrapper.YELLOW_DYE; @@ -112,25 +112,25 @@ public static Material convertDyeColorToMaterial(@Nonnull DyeColor color) { } } - @Nonnull - public static ChatColor convertAwtColorToChatColor(@Nonnull Color color) { + @NotNull + public static ChatColor convertAwtColorToChatColor(@NotNull Color color) { return colorsByChatColor.entrySet().stream() .min((o1, o2) -> (int) ((calculateDifferenceBetweenColors(color, o1.getValue()) - calculateDifferenceBetweenColors(color, o2.getValue())) * 100)) .orElseThrow(() -> new IllegalStateException("Could not find a ChatColor for the given input")) .getKey(); } - @Nonnull - public static Color convertChatColorToAwtColor(@Nonnull ChatColor color) { + @NotNull + public static Color convertChatColorToAwtColor(@NotNull ChatColor color) { return Optional.ofNullable(colorsByChatColor.get(color)).orElseThrow(() -> new IllegalStateException("Could not find a color for ChatColor." + color.name())); } - @Nonnull - public static float[] convertAwtColorToHSB(@Nonnull Color color) { + @NotNull + public static float[] convertAwtColorToHSB(@NotNull Color color) { return Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); } - public static double calculateDifferenceBetweenColors(@Nonnull Color color1, @Nonnull Color color2) { + public static double calculateDifferenceBetweenColors(@NotNull Color color1, @NotNull Color color2) { int diffRed = Math.abs(color1.getRed() - color2.getRed()); int diffGreen = Math.abs(color1.getGreen() - color2.getGreen()); @@ -151,7 +151,7 @@ public static boolean isValidColorCode(char code) { return false; } - public static boolean isValidColorCode(@Nonnull String code) { + public static boolean isValidColorCode(@NotNull String code) { if (code.length() != 1) return false; return isValidColorCode(code.toCharArray()[0]); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java index 2d9965ee3..8c220d8e6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/CommandHelper.java @@ -5,9 +5,9 @@ import org.bukkit.command.BlockCommandSender; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; @@ -31,7 +31,7 @@ public static List getCompletions(CommandSender sender) { return list; } - public static List getPlayers(@Nonnull CommandSender sender, @Nonnull String input) { + public static List getPlayers(@NotNull CommandSender sender, @NotNull String input) { ArrayList list = new ArrayList<>(); Location senderLocation = getSenderLocation(sender); @@ -66,7 +66,7 @@ public static List getPlayers(@Nonnull CommandSender sender, @Nonnull St } @Nullable - public static Location getSenderLocation(@Nonnull CommandSender sender) { + public static Location getSenderLocation(@NotNull CommandSender sender) { if (sender instanceof Player) return ((Player) sender).getLocation(); if (sender instanceof BlockCommandSender) return ((BlockCommandSender) sender).getBlock().getLocation(); @@ -74,7 +74,7 @@ public static Location getSenderLocation(@Nonnull CommandSender sender) { } @Nullable - public static Player getNearestPlayer(@Nonnull Location location) { + public static Player getNearestPlayer(@NotNull Location location) { if (location.getWorld() == null) return null; Player currentPlayer = null; double playersDistance = -1; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java index 3c6ae809e..75f5f6467 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/DatabaseHelper.java @@ -8,9 +8,9 @@ import net.codingarea.commons.bukkit.utils.misc.GameProfileUtils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.*; public final class DatabaseHelper { @@ -21,14 +21,14 @@ private DatabaseHelper() { } @Nullable - public static String getPlayerTextures(@Nonnull Player player) { + public static String getPlayerTextures(@NotNull Player player) { GameProfile profile = GameProfileUtils.getGameProfile(player); PropertyMap properties = profile.getProperties(); List textures = new ArrayList<>(properties.get("textures")); return textures.isEmpty() ? null : textures.get(0).getValue(); } - public static void savePlayerData(@Nonnull Player player) { + public static void savePlayerData(@NotNull Player player) { try { String textures = getPlayerTextures(player); @@ -47,7 +47,7 @@ public static void savePlayerData(@Nonnull Player player) { } @Nullable - public static String getTextures(@Nonnull UUID uuid) { + public static String getTextures(@NotNull UUID uuid) { String cached = cachedTextures.get(uuid); if (cached != null) return cached; @@ -78,7 +78,7 @@ public static String getTextures(@Nonnull UUID uuid) { } } - public static void clearCache(@Nonnull UUID uuid) { + public static void clearCache(@NotNull UUID uuid) { cachedTextures.remove(uuid); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java index 54fe92a8a..c95e6f6cb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/EntityUtils.java @@ -4,16 +4,15 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.util.Vector; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public final class EntityUtils { private EntityUtils() { } - public static Vector getSucceedingVelocity(@Nonnull Vector vector) { + public static Vector getSucceedingVelocity(@NotNull Vector vector) { return new Vector(vector.getX(), getSucceedingVelocity(vector.getY()), vector.getX()); } @@ -21,7 +20,7 @@ public static double getSucceedingVelocity(double currentYVelocity) { return 0.98 * ((currentYVelocity) - 0.08); } - public static boolean isStandingOnBlock(@Nonnull Entity entity, Material block) { + public static boolean isStandingOnBlock(@NotNull Entity entity, Material block) { for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { for (int y = -1; y <= 1; y++) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java index f81f27ba2..4d1a8cc26 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ImageUtils.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.utils.misc; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; @@ -19,18 +19,18 @@ private ImageUtils() { } @Nullable - public static BufferedImage getImage(@Nonnull String url) throws IOException { + public static BufferedImage getImage(@NotNull String url) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); return ImageIO.read(connection.getInputStream()); } - public static BufferedImage getPlayerHead(@Nonnull Player player, int size) throws IOException { + public static BufferedImage getPlayerHead(@NotNull Player player, int size) throws IOException { String url = "https://crafatar.com/avatars/" + player.getUniqueId() + "?size=" + size + "&overlay"; return getImage(url); } - public static String[] convertImageToText(@Nonnull BufferedImage image) { + public static String[] convertImageToText(@NotNull BufferedImage image) { String[] output = new String[image.getHeight()]; for (int y = 0; y < output.length; y++) { StringBuilder text = new StringBuilder(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java index b39fd976f..db768d90a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java @@ -15,9 +15,9 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -37,49 +37,49 @@ public final class InventoryUtils { private InventoryUtils() { } - public static void fillInventory(@Nonnull Inventory inventory, @Nullable ItemStack item) { + public static void fillInventory(@NotNull Inventory inventory, @Nullable ItemStack item) { for (int i = 0; i < inventory.getSize(); i++) { inventory.setItem(i, item); } } - public static void fillInventory(@Nonnull Inventory inventory, @Nullable ItemStack item, @Nonnull int... slots) { + public static void fillInventory(@NotNull Inventory inventory, @Nullable ItemStack item, @NotNull int... slots) { for (int i : slots) { inventory.setItem(i, item); } } - public static void setNavigationItemsToInventory(@Nonnull List inventories, @Nonnull int[] navigationSlots) { + public static void setNavigationItemsToInventory(@NotNull List inventories, @NotNull int[] navigationSlots) { setNavigationItemsToInventory(inventories, navigationSlots, true); } - public static void setNavigationItemsToInventory(@Nonnull List inventories, @Nonnull int[] navigationSlots, boolean goBackExit) { + public static void setNavigationItemsToInventory(@NotNull List inventories, @NotNull int[] navigationSlots, boolean goBackExit) { setNavigationItems(inventories, navigationSlots, goBackExit, InventorySetter.INVENTORY); } - public static void setNavigationItemsToFrame(@Nonnull List frames, @Nonnull int[] navigationSlots) { + public static void setNavigationItemsToFrame(@NotNull List frames, @NotNull int[] navigationSlots) { setNavigationItemsToFrame(frames, navigationSlots, true); } - public static void setNavigationItemsToFrame(@Nonnull List inventories, @Nonnull int[] navigationSlots, boolean goBackExit) { + public static void setNavigationItemsToFrame(@NotNull List inventories, @NotNull int[] navigationSlots, boolean goBackExit) { setNavigationItems(inventories, navigationSlots, goBackExit, InventorySetter.FRAME); } - public static void setNavigationItemsToFrame(@Nonnull AnimationFrame frame, @Nonnull int[] navigationSlots, boolean goBackExit, int index, int size) { + public static void setNavigationItemsToFrame(@NotNull AnimationFrame frame, @NotNull int[] navigationSlots, boolean goBackExit, int index, int size) { setNavigationItems(frame, navigationSlots, goBackExit, InventorySetter.FRAME, index, size); } - public static void setNavigationItems(@Nonnull List inventories, @Nonnull int[] navigationSlots, boolean goBackExit, @Nonnull InventorySetter setter) { + public static void setNavigationItems(@NotNull List inventories, @NotNull int[] navigationSlots, boolean goBackExit, @NotNull InventorySetter setter) { for (int i = 0; i < inventories.size(); i++) { setNavigationItems(inventories.get(i), navigationSlots, goBackExit, setter, i, inventories.size()); } } - public static void setNavigationItems(@Nonnull I inventory, @Nonnull int[] navigationSlots, boolean goBackExit, @Nonnull InventorySetter setter, int index, int size) { + public static void setNavigationItems(@NotNull I inventory, @NotNull int[] navigationSlots, boolean goBackExit, @NotNull InventorySetter setter, int index, int size) { setNavigationItems(inventory, navigationSlots, goBackExit, setter, index, size, DefaultItem.navigateBack(), DefaultItem.navigateNext()); } - public static void setNavigationItems(@Nonnull I inventory, @Nonnull int[] navigationSlots, boolean goBackExit, @Nonnull InventorySetter setter, int index, int size, ItemBuilder navigateBack, ItemBuilder navigateNext) { + public static void setNavigationItems(@NotNull I inventory, @NotNull int[] navigationSlots, boolean goBackExit, @NotNull InventorySetter setter, int index, int size, ItemBuilder navigateBack, ItemBuilder navigateNext) { if (navigationSlots.length >= 1) { ItemBuilder left = index == 0 && goBackExit ? DefaultItem.navigateBackMainMenu() : navigateBack; setter.set(inventory, navigationSlots[0], left); @@ -88,14 +88,14 @@ public static void setNavigationItems(@Nonnull I inventory, @Nonnull int[] n setter.set(inventory, navigationSlots[1], navigateNext); } - public static boolean isEmpty(@Nonnull Inventory inventory) { + public static boolean isEmpty(@NotNull Inventory inventory) { for (ItemStack content : inventory.getContents()) { if (content != null) return false; } return true; } - public static int getRandomEmptySlot(@Nonnull Inventory inventory) { + public static int getRandomEmptySlot(@NotNull Inventory inventory) { List emptySlots = new ArrayList<>(); for (int slot = 0; slot < inventory.getSize(); slot++) { @@ -109,7 +109,7 @@ public static int getRandomEmptySlot(@Nonnull Inventory inventory) { return emptySlots.get(ThreadLocalRandom.current().nextInt(emptySlots.size())); } - public static int getRandomFullSlot(@Nonnull Inventory inventory) { + public static int getRandomFullSlot(@NotNull Inventory inventory) { List fullSlots = new ArrayList<>(); for (int slot = 0; slot < inventory.getSize(); slot++) { @@ -124,7 +124,7 @@ public static int getRandomFullSlot(@Nonnull Inventory inventory) { return fullSlots.get(ThreadLocalRandom.current().nextInt(fullSlots.size())); } - public static int getRandomSlot(@Nonnull Inventory inventory) { + public static int getRandomSlot(@NotNull Inventory inventory) { List slots = new ArrayList<>(); for (int slot = 0; slot < inventory.getSize(); slot++) { @@ -138,17 +138,17 @@ public static int getRandomSlot(@Nonnull Inventory inventory) { return slots.get(ThreadLocalRandom.current().nextInt(slots.size())); } - public static void dropItemByPlayer(@Nonnull Location location, @Nonnull ItemStack itemStack) { + public static void dropItemByPlayer(@NotNull Location location, @NotNull ItemStack itemStack) { if (location.getWorld() == null) return; Item droppedItem = location.getWorld().dropItem(location.clone().add(0, 1.4, 0), itemStack); droppedItem.setVelocity(location.getDirection().multiply(0.4)); } - public static void dropOrGiveItem(@Nonnull Inventory inventory, @Nonnull Location location, @Nonnull Material material) { + public static void dropOrGiveItem(@NotNull Inventory inventory, @NotNull Location location, @NotNull Material material) { dropOrGiveItem(inventory, location, new ItemStack(material)); } - public static void dropOrGiveItem(@Nonnull Inventory inventory, @Nonnull Location location, @Nonnull ItemStack itemStack) { + public static void dropOrGiveItem(@NotNull Inventory inventory, @NotNull Location location, @NotNull ItemStack itemStack) { location = location.clone(); if (inventory.firstEmpty() == -1) { if (location.getWorld() == null) @@ -159,17 +159,17 @@ public static void dropOrGiveItem(@Nonnull Inventory inventory, @Nonnull Locatio inventory.addItem(itemStack); } - public static void removeRandomItem(@Nonnull Inventory inventory) { + public static void removeRandomItem(@NotNull Inventory inventory) { int slot = InventoryUtils.getRandomFullSlot(inventory); if (slot == -1) return; inventory.setItem(slot, null); } - public static void giveItem(@Nonnull Player player, @Nonnull ItemStack itemStack) { + public static void giveItem(@NotNull Player player, @NotNull ItemStack itemStack) { giveItem(player.getInventory(), player.getLocation(), itemStack); } - public static void giveItem(@Nonnull Inventory inventory, @Nonnull Location locationToDrop, @Nonnull ItemStack itemStack) { + public static void giveItem(@NotNull Inventory inventory, @NotNull Location locationToDrop, @NotNull ItemStack itemStack) { if (inventory.firstEmpty() == -1) { dropItemByPlayer(locationToDrop, itemStack); return; @@ -218,7 +218,7 @@ public interface InventorySetter { InventorySetter FRAME = AnimationFrame::setItem; InventorySetter INVENTORY = (inventory, slot, item) -> inventory.setItem(slot, item.build()); - void set(@Nonnull I inventory, int slot, @Nonnull ItemBuilder item); + void set(@NotNull I inventory, int slot, @NotNull ItemBuilder item); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java index d161f2419..d12660961 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java @@ -7,8 +7,8 @@ import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.EntityType; import org.bukkit.potion.PotionEffectType; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.lang.reflect.Field; import java.util.Arrays; @@ -37,34 +37,34 @@ public class MinecraftNameWrapper { private MinecraftNameWrapper() { } - @Nonnull - private static Material getItemByNames(@Nonnull String... names) { + @NotNull + private static Material getItemByNames(@NotNull String... names) { return ReflectionUtils.getFirstEnumByNames(Material.class, names); } - @Nonnull - private static EntityType getEntityByNames(@Nonnull String... names) { + @NotNull + private static EntityType getEntityByNames(@NotNull String... names) { return ReflectionUtils.getFirstEnumByNames(EntityType.class, names); } - @Nonnull - private static Particle getParticleByNames(@Nonnull String... names) { + @NotNull + private static Particle getParticleByNames(@NotNull String... names) { return ReflectionUtils.getFirstEnumByNames(Particle.class, names); } - @Nonnull - private static PotionEffectType getPotionByNames(@Nonnull String... names) { + @NotNull + private static PotionEffectType getPotionByNames(@NotNull String... names) { return getFirstAttributeByNames(PotionEffectType.class, names); } - @Nonnull - private static Enchantment getEnchantByNames(@Nonnull String... names) { + @NotNull + private static Enchantment getEnchantByNames(@NotNull String... names) { return getFirstAttributeByNames(Enchantment.class, names); } @SuppressWarnings("unchecked") - @Nonnull - public static T getFirstAttributeByNames(@Nonnull Class clazz, @Nonnull String... names) { + @NotNull + public static T getFirstAttributeByNames(@NotNull Class clazz, @NotNull String... names) { for (String name : names) { try { Field field = ReflectionUtil.getField(clazz, name); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java index 3d3e251a1..5923acc84 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java @@ -3,16 +3,15 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.cloud.CloudSupportManager; import org.bukkit.OfflinePlayer; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public final class NameHelper { private NameHelper() { } - @Nonnull - public static String getName(@Nonnull OfflinePlayer player) { + @NotNull + public static String getName(@NotNull OfflinePlayer player) { CloudSupportManager cloudSupport = Challenges.getInstance().getCloudSupportManager(); if (cloudSupport.isNameSupport() && cloudSupport.hasNameFor(player.getUniqueId())) { if (player.isOnline() && player.getPlayer() != null) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java index 985a65410..bc23a9fd4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java @@ -8,9 +8,9 @@ import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.BoundingBox; import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; import java.util.Objects; import java.util.function.BiConsumer; @@ -21,7 +21,7 @@ public final class ParticleUtils { private ParticleUtils() { } - private static void spawnParticleCircle(@Nonnull Location location, int points, double radius, @Nonnull BiConsumer player) { + private static void spawnParticleCircle(@NotNull Location location, int points, double radius, @NotNull BiConsumer player) { World world = location.getWorld(); if (world == null) return; @@ -32,15 +32,15 @@ private static void spawnParticleCircle(@Nonnull Location location, int points, } } - public static void spawnParticleCircle(@Nonnull Location location, @Nonnull Effect particle, int points, double radius) { + public static void spawnParticleCircle(@NotNull Location location, @NotNull Effect particle, int points, double radius) { spawnParticleCircle(location, points, radius, (world, point) -> world.playEffect(point, particle, 1)); } - public static void spawnParticleCircle(@Nonnull Location location, @Nonnull Particle particle, int points, double radius) { + public static void spawnParticleCircle(@NotNull Location location, @NotNull Particle particle, int points, double radius) { spawnParticleCircle(location, points, radius, (world, point) -> world.spawnParticle(particle, point, 1)); } - private static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnull Location location, int points, double radius, double height, @Nonnull BiConsumer player) { + private static void spawnUpGoingParticleCircle(@NotNull JavaPlugin plugin, @NotNull Location location, int points, double radius, double height, @NotNull BiConsumer player) { for (double y = 0, i = 0; y < height; y += .25, i++) { final double Y = y; Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { @@ -49,11 +49,11 @@ private static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonn } } - public static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Effect effect, int points, double radius, double height) { + public static void spawnUpGoingParticleCircle(@NotNull JavaPlugin plugin, @NotNull Location location, @NotNull Effect effect, int points, double radius, double height) { spawnUpGoingParticleCircle(plugin, location, points, radius, height, (world, point) -> world.playEffect(point, effect, 1)); } - public static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Particle particle, int points, double radius, double height) { + public static void spawnUpGoingParticleCircle(@NotNull JavaPlugin plugin, @NotNull Location location, @NotNull Particle particle, int points, double radius, double height) { if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_20_5)) { for (double y = 0, i = 0; y < height; y += .25, i++) { final double Y = y; @@ -77,19 +77,19 @@ public static void spawnUpGoingParticleCircle(@Nonnull JavaPlugin plugin, @Nonnu } } - public static void spawnParticleCircleAroundEntity(@Nonnull JavaPlugin plugin, @Nonnull Entity entity) { + public static void spawnParticleCircleAroundEntity(@NotNull JavaPlugin plugin, @NotNull Entity entity) { spawnParticleCircleAroundBoundingBox(plugin, entity.getLocation(), MinecraftNameWrapper.INSTANT_EFFECT, entity.getBoundingBox(), 0.25); } - public static void spawnParticleCircleAroundBoundingBox(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Particle particle, @Nonnull BoundingBox box, double height) { + public static void spawnParticleCircleAroundBoundingBox(@NotNull JavaPlugin plugin, @NotNull Location location, @NotNull Particle particle, @NotNull BoundingBox box, double height) { spawnParticleCircleAroundRadius(plugin, location, particle, box.getWidthX(), height); } - public static void spawnParticleCircleAroundRadius(@Nonnull JavaPlugin plugin, @Nonnull Location location, @Nonnull Particle particle, double radius, double height) { + public static void spawnParticleCircleAroundRadius(@NotNull JavaPlugin plugin, @NotNull Location location, @NotNull Particle particle, double radius, double height) { spawnUpGoingParticleCircle(plugin, location, particle, (int) (radius * 15), radius, height); } - public static void drawLine(@Nonnull Player player, @Nonnull Location point1, @Nonnull Location point2, @Nonnull Particle particle, @Nullable Particle.DustOptions dustOptions, int count, double space, int max) { + public static void drawLine(@NotNull Player player, @NotNull Location point1, @NotNull Location point2, @NotNull Particle particle, @Nullable Particle.DustOptions dustOptions, int count, double space, int max) { World world = point1.getWorld(); if (!Objects.equals(world, point2.getWorld())) return; double distance = point1.distance(point2); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java index cf9ccd5e2..ac7d6228a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java @@ -5,15 +5,14 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; import org.bukkit.Material; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public final class StatsHelper { private StatsHelper() { } - @Nonnull + @NotNull public static int[] getSlots(int row) { int[] slots = {1, 2, 3, 4, 5, 6, 7, 11, 12, 13, 14, 15}; for (int i = 0; i < slots.length; i++) { @@ -22,7 +21,7 @@ public static int[] getSlots(int row) { return slots; } - public static void setAccent(@Nonnull AnimatedInventory inventory, int row) { + public static void setAccent(@NotNull AnimatedInventory inventory, int row) { inventory.createAndAdd().fill(ItemBuilder.FILL_ITEM); int offset = row * 9; inventory.cloneLastAndAdd().setAccent(offset, offset + 8); @@ -32,13 +31,13 @@ public static void setAccent(@Nonnull AnimatedInventory inventory, int row) { inventory.cloneLastAndAdd().setAccent(offset + 12, offset + 14); } - @Nonnull - public static Message getNameMessage(@Nonnull Statistic statistic) { + @NotNull + public static Message getNameMessage(@NotNull Statistic statistic) { return Message.forName("stat-" + statistic.name().toLowerCase().replace('_', '-')); } - @Nonnull - public static Material getMaterial(@Nonnull Statistic statistic) { + @NotNull + public static Material getMaterial(@NotNull Statistic statistic) { switch (statistic) { default: return Material.PAPER; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java index c4df7e13a..ae730ab40 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/Utils.java @@ -5,10 +5,9 @@ import net.codingarea.commons.common.misc.ReflectionUtils; import org.bukkit.Material; import org.bukkit.entity.EntityType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.io.IOException; import java.net.URL; import java.util.*; @@ -19,8 +18,8 @@ public final class Utils { private Utils() { } - @Nonnull - public static List filterRecommendations(@Nonnull String argument, @Nonnull String... recommendations) { + @NotNull + public static List filterRecommendations(@NotNull String argument, @NotNull String... recommendations) { argument = argument.toLowerCase(); List list = new ArrayList<>(); for (String current : recommendations) { @@ -30,8 +29,8 @@ public static List filterRecommendations(@Nonnull String argument, @Nonn return list; } - @Nonnull - public static UUID fetchUUID(@Nonnull String name) throws IOException { + @NotNull + public static UUID fetchUUID(@NotNull String name) throws IOException { String url = "https://api.mojang.com/users/profiles/minecraft/" + name; String content = IOUtils.toString(new URL(url)); Document document = Document.parseJson(content); @@ -46,18 +45,16 @@ public static UUID matchUUID(@Nullable String uuid) { } @Nullable - @CheckReturnValue public static Material getMaterial(@Nullable String name) { return ReflectionUtils.getEnumOrNull(name, Material.class); } @Nullable - @CheckReturnValue public static EntityType getEntityType(@Nullable String name) { return ReflectionUtils.getEnumOrNull(name, EntityType.class); } - public static > void removeEnums(@Nonnull Collection collection, @Nonnull String... names) { + public static > void removeEnums(@NotNull Collection collection, @NotNull String... names) { List nameList = Arrays.asList(names); collection.removeIf(element -> nameList.contains(element.name())); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java index beaa0c21b..069eac759 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java @@ -29,8 +29,8 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.bukkit.plugin.java.JavaPlugin; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.io.File; import java.io.InputStreamReader; import java.lang.reflect.Field; @@ -167,12 +167,12 @@ public final boolean isFirstInstance() { return firstInstance == this; } - @Nonnull + @NotNull public JavaILogger getILogger() { return logger != null ? logger : (logger = new BukkitLoggerWrapper(super.getLogger())); } - @Nonnull + @NotNull public Document getConfigDocument() { checkLoaded(); return config != null ? config : (config = new YamlDocument(super.getConfig())); @@ -187,23 +187,23 @@ public void reloadConfig() { /** * @return the plugin configuration (plugin.yml) as document */ - @Nonnull + @NotNull public Document getPluginDocument() { return pluginConfig != null ? pluginConfig : (pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(getResource("plugin.yml"), Charsets.UTF_8)))); } - @Nonnull - public FileDocument getConfig(@Nonnull String filename) { + @NotNull + public FileDocument getConfig(@NotNull String filename) { return configManager.getDocument(filename); } - @Nonnull + @NotNull public Version getVersion() { return version != null ? version : (version = Version.parse(getDescription().getVersion())); } - @Nonnull + @NotNull @Deprecated @DeprecatedSince("1.3.0") @ReplaceWith("MinecraftVersion.current()") @@ -211,7 +211,7 @@ public MinecraftVersion getServerVersion() { return MinecraftVersion.current(); } - @Nonnull + @NotNull @Deprecated @DeprecatedSince("1.3.0") @ReplaceWith("MinecraftVersion.currentExact()") @@ -219,7 +219,7 @@ public Version getServerVersionExact() { return MinecraftVersion.currentExact(); } - @Nonnull + @NotNull @Override @Deprecated @ReplaceWith("getConfigDocument()") @@ -237,12 +237,12 @@ public void setRequirementsFailed() { this.requirementsMet = false; } - public final void registerListenerCommand(@Nonnull T listenerAndExecutor, @Nonnull String... names) { + public final void registerListenerCommand(@NotNull T listenerAndExecutor, @NotNull String... names) { registerCommand(listenerAndExecutor, names); registerListener(listenerAndExecutor); } - public final void registerCommand(@Nonnull CommandExecutor executor, @Nonnull String... names) { + public final void registerCommand(@NotNull CommandExecutor executor, @NotNull String... names) { for (String name : names) { if (isEnabled()) { registerCommand0(executor, name); @@ -252,7 +252,7 @@ public final void registerCommand(@Nonnull CommandExecutor executor, @Nonnull St } } - private void registerCommand0(@Nonnull CommandExecutor executor, @Nonnull String name) { + private void registerCommand0(@NotNull CommandExecutor executor, @NotNull String name) { PluginCommand command = getCommand(name); if (command == null) { getILogger().warn("Tried to register invalid command '{}'", name); @@ -261,7 +261,7 @@ private void registerCommand0(@Nonnull CommandExecutor executor, @Nonnull String } } - public final void registerListener(@Nonnull Listener... listeners) { + public final void registerListener(@NotNull Listener... listeners) { if (isEnabled()) { for (Listener listener : listeners) { registerListener0(listener); @@ -271,7 +271,7 @@ public final void registerListener(@Nonnull Listener... listeners) { } } - private void registerListener0(@Nonnull Listener listener) { + private void registerListener0(@NotNull Listener listener) { if (listener instanceof ActionListener) { ActionListener actionListener = (ActionListener) listener; getServer().getPluginManager().registerEvent( @@ -283,15 +283,15 @@ private void registerListener0(@Nonnull Listener listener) { } } - public final void on(@Nonnull Class classOfEvent, @Nonnull Consumer action) { + public final void on(@NotNull Class classOfEvent, @NotNull Consumer action) { on(classOfEvent, EventPriority.NORMAL, action); } - public final void on(@Nonnull Class classOfEvent, @Nonnull EventPriority priority, @Nonnull Consumer action) { + public final void on(@NotNull Class classOfEvent, @NotNull EventPriority priority, @NotNull Consumer action) { on(classOfEvent, priority, false, action); } - public final void on(@Nonnull Class classOfEvent, @Nonnull EventPriority priority, boolean ignoreCancelled, @Nonnull Consumer action) { + public final void on(@NotNull Class classOfEvent, @NotNull EventPriority priority, boolean ignoreCancelled, @NotNull Consumer action) { registerListener(new ActionListener<>(classOfEvent, action, priority, ignoreCancelled)); } @@ -299,22 +299,22 @@ public final void disablePlugin() { getServer().getPluginManager().disablePlugin(this); } - @Nonnull - public final File getDataFile(@Nonnull String filename) { + @NotNull + public final File getDataFile(@NotNull String filename) { return new File(getDataFolder(), filename); } - @Nonnull - public final File getDataFile(@Nonnull String subfolder, @Nonnull String filename) { + @NotNull + public final File getDataFile(@NotNull String subfolder, @NotNull String filename) { return new File(getDataFile(subfolder), filename); } - @Nonnull + @NotNull public ExecutorService getExecutor() { return executorService != null ? executorService : (executorService = Executors.newCachedThreadPool(new NamedThreadFactory(threadId -> String.format("%s-Task-%s", this.getName(), threadId)))); } - public void runAsync(@Nonnull Runnable task) { + public void runAsync(@NotNull Runnable task) { getExecutor().submit(task); } @@ -353,7 +353,7 @@ private void injectInstance() { } } - @Nonnull + @NotNull public static BukkitModule getFirstInstance() { if (firstInstance == null) { JavaPlugin provider = JavaPlugin.getProvidingPlugin(BukkitModule.class); @@ -365,14 +365,14 @@ public static BukkitModule getFirstInstance() { return firstInstance; } - private static synchronized void setFirstInstance(@Nonnull BukkitModule module) { + private static synchronized void setFirstInstance(@NotNull BukkitModule module) { setFirstInstance = false; firstInstance = module; module.registerAsFirstInstance(); } - @Nonnull - public static BukkitModule getProvidingModule(@Nonnull Class clazz) { + @NotNull + public static BukkitModule getProvidingModule(@NotNull Class clazz) { JavaPlugin provider = JavaPlugin.getProvidingPlugin(clazz); if (!(provider instanceof BukkitModule)) throw new IllegalStateException(clazz.getName() + " is not provided by a BukkitModule"); diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java index 0097459d8..37edf2f78 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/RequirementsChecker.java @@ -4,24 +4,23 @@ import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.version.Version; import org.bukkit.Bukkit; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public final class RequirementsChecker { private final BukkitModule module; - public RequirementsChecker(@Nonnull BukkitModule module) { + public RequirementsChecker(@NotNull BukkitModule module) { this.module = module; } - public void checkExceptionally(@Nonnull Document requirements) throws IllegalStateException { + public void checkExceptionally(@NotNull Document requirements) throws IllegalStateException { if (requirements.getBoolean("spigot")) requireSpigot(); if (requirements.getBoolean("paper")) requirePaper(); if (requirements.contains("version")) requireVersion(requirements.getVersion("version")); } - public boolean checkBoolean(@Nonnull Document requirements) { + public boolean checkBoolean(@NotNull Document requirements) { try { checkExceptionally(requirements); return true; @@ -69,7 +68,7 @@ private void requirePaper() { } } - private void requireVersion(@Nonnull Version required) { + private void requireVersion(@NotNull Version required) { if (MinecraftVersion.currentExact().isOlderThan(required)) { log(""); log("============================== {} ==============================", module.getName()); @@ -87,7 +86,7 @@ private void requireVersion(@Nonnull Version required) { } } - private void log(@Nonnull String line, @Nonnull Object... args) { + private void log(@NotNull String line, @NotNull Object... args) { module.getILogger().error(line, args); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java index 65fd437b1..c3f4f03a6 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java @@ -5,8 +5,8 @@ import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.commons.common.config.document.YamlDocument; import net.codingarea.commons.common.misc.FileUtils; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.io.File; import java.util.HashMap; import java.util.Map; @@ -16,23 +16,23 @@ public class SimpleConfigManager { protected final Map configs = new HashMap<>(); protected final BukkitModule module; - public SimpleConfigManager(@Nonnull BukkitModule module) { + public SimpleConfigManager(@NotNull BukkitModule module) { this.module = module; } - @Nonnull - public FileDocument getDocument(@Nonnull String filename) { + @NotNull + public FileDocument getDocument(@NotNull String filename) { if (!filename.contains(".")) filename += ".json"; return getDocument(module.getDataFile(filename)); } - public synchronized FileDocument getDocument(@Nonnull File file) { + public synchronized FileDocument getDocument(@NotNull File file) { String extension = FileUtils.getFileExtension(file); return configs.computeIfAbsent(file.getName(), key -> FileDocument.readFile(resolveType(extension), file)); } - @Nonnull - public static Class resolveType(@Nonnull String extension) { + @NotNull + public static Class resolveType(@NotNull String extension) { switch (extension.toLowerCase()) { case "json": return GsonDocument.class; diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java index 0ebd04e9f..bb39085d7 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java @@ -6,9 +6,9 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.plugin.java.JavaPlugin; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; @@ -22,21 +22,21 @@ public class AnimatedInventory { private SoundSample frameSound = SoundSample.CLICK, endSound = SoundSample.OPEN; private int frameDelay = 1; - public AnimatedInventory(@Nonnull String title, int size) { + public AnimatedInventory(@NotNull String title, int size) { this(title, size, null); } - public AnimatedInventory(@Nonnull String title, int size, @Nullable InventoryHolder holder) { + public AnimatedInventory(@NotNull String title, int size, @Nullable InventoryHolder holder) { this.title = title; this.size = size; this.holder = holder; } - public void open(@Nonnull Player player) { + public void open(@NotNull Player player) { open(player, BukkitModule.getFirstInstance()); } - public void open(@Nonnull Player player, @Nonnull JavaPlugin plugin) { + public void open(@NotNull Player player, @NotNull JavaPlugin plugin) { if (!Bukkit.isPrimaryThread()) { Bukkit.getScheduler().runTask(plugin, () -> open(player, plugin)); return; @@ -63,11 +63,11 @@ public void open(@Nonnull Player player, @Nonnull JavaPlugin plugin) { } - public void openNotAnimated(@Nonnull Player player, boolean playSound) { + public void openNotAnimated(@NotNull Player player, boolean playSound) { openNotAnimated(player, playSound, BukkitModule.getFirstInstance()); } - public void openNotAnimated(@Nonnull Player player, boolean playSound, @Nonnull JavaPlugin plugin) { + public void openNotAnimated(@NotNull Player player, boolean playSound, @NotNull JavaPlugin plugin) { if (!Bukkit.isPrimaryThread()) { Bukkit.getScheduler().runTask(plugin, () -> openNotAnimated(player, playSound, plugin)); return; @@ -86,7 +86,7 @@ public void openNotAnimated(@Nonnull Player player, boolean playSound, @Nonnull } - private void applyFrame(@Nonnull Inventory inventory, int index, @Nonnull Player viewer) { + private void applyFrame(@NotNull Inventory inventory, int index, @NotNull Player viewer) { AnimationFrame frame = frames.get(index); inventory.setContents(frame.getContent()); @@ -94,27 +94,27 @@ private void applyFrame(@Nonnull Inventory inventory, int index, @Nonnull Player else if (frameSound != null && frame.shouldPlaySound()) frameSound.play(viewer); } - @Nonnull - public AnimatedInventory addFrame(@Nonnull AnimationFrame frame) { + @NotNull + public AnimatedInventory addFrame(@NotNull AnimationFrame frame) { if (size != frame.getSize()) throw new IllegalArgumentException("AnimationFrame must have the same size (Expected " + size + "; Got " + frame.getSize() + ")"); frames.add(frame); return this; } - @Nonnull + @NotNull public AnimationFrame createAndAdd() { AnimationFrame frame = new AnimationFrame(size); addFrame(frame); return frame; } - @Nonnull + @NotNull public AnimationFrame getFrame(int index) { return frames.get(index); } - @Nonnull + @NotNull public AnimationFrame getOrCreateFrame(int index) { while (frames.size() <= index) { cloneLastAndAdd(); @@ -122,46 +122,46 @@ public AnimationFrame getOrCreateFrame(int index) { return getFrame(index); } - @Nonnull + @NotNull public AnimationFrame cloneAndAdd(int index) { AnimationFrame frame = getFrame(index).clone(); addFrame(frame); return frame; } - @Nonnull + @NotNull public AnimationFrame getLastFrame() { if (frames.isEmpty()) throw new IllegalStateException("Frames are empty"); return getFrame(frames.size() - 1); } - @Nonnull + @NotNull public AnimationFrame cloneLastAndAdd() { AnimationFrame frame = getLastFrame().clone(); addFrame(frame); return frame; } - @Nonnull + @NotNull public AnimatedInventory setEndSound(@Nullable SoundSample endSound) { this.endSound = endSound; return this; } - @Nonnull + @NotNull public AnimatedInventory setFrameSound(@Nullable SoundSample frameSound) { this.frameSound = frameSound; return this; } - @Nonnull + @NotNull public AnimatedInventory setFrameDelay(int delay) { if (delay < 1) throw new IllegalArgumentException("Delay cannot be smaller than 1"); this.frameDelay = delay; return this; } - @Nonnull + @NotNull private Inventory createInventory() { return Bukkit.createInventory(holder, size, title); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java index 02e9b8a04..f0a917a0e 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java @@ -3,9 +3,9 @@ import net.codingarea.commons.bukkit.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Arrays; public class AnimationFrame implements Cloneable { @@ -13,7 +13,7 @@ public class AnimationFrame implements Cloneable { private final ItemStack[] content; private boolean sound = true; - public AnimationFrame(@Nonnull ItemStack[] content) { + public AnimationFrame(@NotNull ItemStack[] content) { this.content = Arrays.copyOf(content, content.length); } @@ -21,13 +21,13 @@ public AnimationFrame(int size) { this.content = new ItemStack[size]; } - @Nonnull - public AnimationFrame fill(@Nonnull ItemStack item) { + @NotNull + public AnimationFrame fill(@NotNull ItemStack item) { Arrays.fill(content, item); return this; } - @Nonnull + @NotNull public AnimationFrame setAccent(int... slots) { for (int slot : slots) { content[slot] = ItemBuilder.FILL_ITEM_2; @@ -35,18 +35,18 @@ public AnimationFrame setAccent(int... slots) { return this; } - @Nonnull - public AnimationFrame setItem(int slot, @Nonnull ItemBuilder item) { + @NotNull + public AnimationFrame setItem(int slot, @NotNull ItemBuilder item) { return setItem(slot, item.build()); } - @Nonnull - public AnimationFrame setItem(int slot, @Nonnull ItemStack item) { + @NotNull + public AnimationFrame setItem(int slot, @NotNull ItemStack item) { content[slot] = item; return this; } - @Nonnull + @NotNull public AnimationFrame setSound(boolean play) { this.sound = play; return this; @@ -62,7 +62,7 @@ public Material getItemType(int slot) { return getItem(slot) == null ? Material.AIR : getItem(slot).getType(); } - @Nonnull + @NotNull public ItemStack[] getContent() { return content; } @@ -75,7 +75,7 @@ public int getSize() { return content.length; } - @Nonnull + @NotNull @Override public AnimationFrame clone() { return new AnimationFrame(content); diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java index 665fa6461..bbfa1a881 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java @@ -4,8 +4,8 @@ import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; @@ -29,7 +29,7 @@ public final class SoundSample { WIN = new SoundSample().addSound(Sound.UI_TOAST_CHALLENGE_COMPLETE, 1), DRAGON_BREATH = new SoundSample().addSound(Sound.ENTITY_ENDER_DRAGON_GROWL, 0.5F); - public static void playStatusSound(@Nonnull Player player, boolean enabled) { + public static void playStatusSound(@NotNull Player player, boolean enabled) { (enabled ? BASS_ON : BASS_OFF).play(player); } @@ -38,17 +38,17 @@ private static final class SoundFrame { private final float pitch, volume; private final Sound sound; - public SoundFrame(@Nonnull Sound sound, float volume, float pitch) { + public SoundFrame(@NotNull Sound sound, float volume, float pitch) { this.volume = volume; this.pitch = pitch; this.sound = sound; } - public SoundFrame(@Nonnull Sound sound, float volume) { + public SoundFrame(@NotNull Sound sound, float volume) { this(sound, volume, 1); } - public void play(@Nonnull Player player, @Nonnull Location location) { + public void play(@NotNull Player player, @NotNull Location location) { player.playSound(location, sound, volume, pitch); } @@ -60,7 +60,7 @@ public float getVolume() { return volume; } - @Nonnull + @NotNull public Sound getSound() { return sound; } @@ -69,35 +69,35 @@ public Sound getSound() { private final List frames = new ArrayList<>(); - @Nonnull - public SoundSample addSound(@Nonnull Sound sound, float volume, float pitch) { + @NotNull + public SoundSample addSound(@NotNull Sound sound, float volume, float pitch) { frames.add(new SoundFrame(sound, volume, pitch)); return this; } - @Nonnull - public SoundSample addSound(@Nonnull Sound sound, float volume) { + @NotNull + public SoundSample addSound(@NotNull Sound sound, float volume) { frames.add(new SoundFrame(sound, volume)); return this; } - @Nonnull - public SoundSample addSound(@Nonnull SoundSample sound) { + @NotNull + public SoundSample addSound(@NotNull SoundSample sound) { frames.addAll(sound.frames); return this; } - public void play(@Nonnull Player player) { + public void play(@NotNull Player player) { play(player, player.getLocation()); } - public void play(@Nonnull Player player, @Nonnull Location location) { + public void play(@NotNull Player player, @NotNull Location location) { for (SoundFrame frame : frames) { frame.play(player, location); } } - public void playIfPlayer(@Nonnull Object target) { + public void playIfPlayer(@NotNull Object target) { if (target instanceof Player) play((Player) target); } @@ -106,7 +106,7 @@ public void broadcast() { Bukkit.getOnlinePlayers().forEach(this::play); } - public void broadcast(@Nonnull Location location) { + public void broadcast(@NotNull Location location) { Bukkit.getOnlinePlayers().forEach(player -> play(player, location)); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java index 0e5bba154..18a4811ba 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java @@ -1,8 +1,7 @@ package net.codingarea.commons.bukkit.utils.item; import org.bukkit.block.banner.PatternType; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public enum BannerPattern { @@ -47,16 +46,16 @@ public enum BannerPattern { private final PatternType patternType; - BannerPattern(@Nonnull PatternType patternType) { + BannerPattern(@NotNull PatternType patternType) { this.patternType = patternType; } - @Nonnull + @NotNull public PatternType getPatternType() { return patternType; } - @Nonnull + @NotNull public String getIdentifier() { return patternType.getKeyOrThrow().getKey(); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java index 527a3971b..c3196bd4a 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java @@ -10,10 +10,9 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.*; import org.bukkit.potion.PotionEffect; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -29,65 +28,65 @@ public class ItemBuilder { protected ItemStack item; protected ItemMeta meta; - public ItemBuilder(@Nonnull ItemStack item) { + public ItemBuilder(@NotNull ItemStack item) { this(item, item.getItemMeta()); } - public ItemBuilder(@Nonnull ItemStack item, @Nullable ItemMeta meta) { + public ItemBuilder(@NotNull ItemStack item, @Nullable ItemMeta meta) { this.item = item; this.meta = meta; } - public ItemBuilder(@Nonnull Material material) { + public ItemBuilder(@NotNull Material material) { this(new ItemStack(material)); } - public ItemBuilder(@Nonnull Material material, @Nonnull String name) { + public ItemBuilder(@NotNull Material material, @NotNull String name) { this(material); setName(name); } - public ItemBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + public ItemBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { this(material); setName(name); setLore(lore); } - public ItemBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + public ItemBuilder(@NotNull Material material, @NotNull String name, int amount) { this(material); setName(name); setAmount(amount); } - @Nonnull + @NotNull public ItemMeta getMeta() { return getCastedMeta(); } - @Nonnull + @NotNull @SuppressWarnings("unchecked") public final M getCastedMeta() { return (M) (meta == null ? meta = item.getItemMeta() : meta); } - @Nonnull - public ItemBuilder setLore(@Nonnull List lore) { + @NotNull + public ItemBuilder setLore(@NotNull List lore) { getMeta().setLore(lore); return this; } - @Nonnull - public ItemBuilder setLore(@Nonnull String... lore) { + @NotNull + public ItemBuilder setLore(@NotNull String... lore) { return setLore(Arrays.asList(lore)); } - @Nonnull - public ItemBuilder appendLore(@Nonnull String... lore) { + @NotNull + public ItemBuilder appendLore(@NotNull String... lore) { return appendLore(Arrays.asList(lore)); } - @Nonnull - public ItemBuilder appendLore(@Nonnull Collection lore) { + @NotNull + public ItemBuilder appendLore(@NotNull Collection lore) { List newLore = getMeta().getLore(); if (newLore == null) newLore = new ArrayList<>(); newLore.addAll(lore); @@ -95,140 +94,140 @@ public ItemBuilder appendLore(@Nonnull Collection lore) { return this; } - @Nonnull - public ItemBuilder lore(@Nonnull String... lore) { + @NotNull + public ItemBuilder lore(@NotNull String... lore) { return setLore(lore); } - @Nonnull + @NotNull public ItemBuilder setName(@Nullable String name) { getMeta().setDisplayName(name); return this; } - @Nonnull + @NotNull public ItemBuilder setName(@Nullable Object name) { return setName(name == null ? null : name.toString()); } - @Nonnull - public ItemBuilder setName(@Nonnull String... content) { + @NotNull + public ItemBuilder setName(@NotNull String... content) { if (content.length > 0) setName(content[0]); if (content.length > 1) setLore(Arrays.copyOfRange(content, 1, content.length)); return this; } - @Nonnull + @NotNull public ItemBuilder appendName(@Nullable Object sequence) { String name = getMeta().getDisplayName(); return setName(name + sequence); } - @Nonnull + @NotNull public ItemBuilder name(@Nullable Object name) { return setName(name); } - @Nonnull - public ItemBuilder name(@Nonnull String... content) { + @NotNull + public ItemBuilder name(@NotNull String... content) { return setName(content); } - @Nonnull - public ItemBuilder addEnchantment(@Nonnull Enchantment enchantment, int level) { + @NotNull + public ItemBuilder addEnchantment(@NotNull Enchantment enchantment, int level) { getMeta().addEnchant(enchantment, level, true); return this; } - @Nonnull - public ItemBuilder enchant(@Nonnull Enchantment enchantment, int level) { + @NotNull + public ItemBuilder enchant(@NotNull Enchantment enchantment, int level) { return addEnchantment(enchantment, level); } - @Nonnull - public ItemBuilder addFlag(@Nonnull ItemFlag... flags) { + @NotNull + public ItemBuilder addFlag(@NotNull ItemFlag... flags) { getMeta().addItemFlags(flags); return this; } - @Nonnull - public ItemBuilder flag(@Nonnull ItemFlag... flags) { + @NotNull + public ItemBuilder flag(@NotNull ItemFlag... flags) { return addFlag(flags); } - @Nonnull - public ItemBuilder removeFlag(@Nonnull ItemFlag... flags) { + @NotNull + public ItemBuilder removeFlag(@NotNull ItemFlag... flags) { getMeta().removeItemFlags(flags); return this; } - @Nonnull + @NotNull public ItemBuilder hideAttributes() { return addFlag(ItemFlag.values()); } - @Nonnull + @NotNull public ItemBuilder showAttributes() { return removeFlag(ItemFlag.values()); } - @Nonnull + @NotNull public ItemBuilder setUnbreakable(boolean unbreakable) { getMeta().setUnbreakable(unbreakable); return this; } - @Nonnull + @NotNull public ItemBuilder unbreakable() { return setUnbreakable(true); } - @Nonnull + @NotNull public ItemBuilder breakable() { return setUnbreakable(false); } - @Nonnull + @NotNull public ItemBuilder setAmount(int amount) { item.setAmount(Math.min(Math.max(amount, 0), 64)); return this; } - @Nonnull + @NotNull public ItemBuilder amount(int amount) { return setAmount(amount); } - @Nonnull + @NotNull public ItemBuilder setDamage(int damage) { this.getCastedMeta().setDamage(damage); return this; } - @Nonnull + @NotNull public ItemBuilder damage(int damage) { return setDamage(damage); } - @Nonnull - public ItemBuilder setType(@Nonnull Material material) { + @NotNull + public ItemBuilder setType(@NotNull Material material) { item.setType(material); meta = item.getItemMeta(); return this; } - @Nonnull + @NotNull public String getName() { return getMeta().getDisplayName(); } - @Nonnull + @NotNull public List getLore() { List lore = getMeta().getLore(); return lore == null ? new ArrayList<>() : lore; } - @Nonnull + @NotNull public Material getType() { return item.getType(); } @@ -241,13 +240,13 @@ public int getDamage() { return this.getCastedMeta().getDamage(); } - @Nonnull + @NotNull public ItemStack build() { item.setItemMeta(getMeta()); // Call to getter to prevent null value return item; } - @Nonnull + @NotNull public ItemStack toItem() { return build(); } @@ -259,38 +258,38 @@ public ItemBuilder clone() { public static class BannerBuilder extends ItemBuilder { - public BannerBuilder(@Nonnull Material material) { + public BannerBuilder(@NotNull Material material) { super(material); } - public BannerBuilder(@Nonnull Material material, @Nonnull String name) { + public BannerBuilder(@NotNull Material material, @NotNull String name) { super(material, name); } - public BannerBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + public BannerBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { super(material, name, lore); } - public BannerBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + public BannerBuilder(@NotNull Material material, @NotNull String name, int amount) { super(material, name, amount); } - public BannerBuilder(@Nonnull ItemStack item) { + public BannerBuilder(@NotNull ItemStack item) { super(item); } - @Nonnull - public BannerBuilder addPattern(@Nonnull BannerPattern pattern, @Nonnull DyeColor color) { + @NotNull + public BannerBuilder addPattern(@NotNull BannerPattern pattern, @NotNull DyeColor color) { return addPattern(pattern.getPatternType(), color); } - @Nonnull - public BannerBuilder addPattern(@Nonnull PatternType pattern, @Nonnull DyeColor color) { + @NotNull + public BannerBuilder addPattern(@NotNull PatternType pattern, @NotNull DyeColor color) { getMeta().addPattern(new Pattern(color, pattern)); return this; } - @Nonnull + @NotNull @Override public BannerMeta getMeta() { return getCastedMeta(); @@ -304,22 +303,22 @@ public SkullBuilder() { super(Material.PLAYER_HEAD); } - public SkullBuilder(@Nonnull String owner) { + public SkullBuilder(@NotNull String owner) { super(Material.PLAYER_HEAD); setOwner(owner); } - public SkullBuilder(@Nonnull String owner, @Nonnull String name, @Nonnull String... lore) { + public SkullBuilder(@NotNull String owner, @NotNull String name, @NotNull String... lore) { super(Material.PLAYER_HEAD, name, lore); setOwner(owner); } - public SkullBuilder setOwner(@Nonnull String owner) { + public SkullBuilder setOwner(@NotNull String owner) { getMeta().setOwner(owner); return this; } - @Nonnull + @NotNull @Override public SkullMeta getMeta() { return getCastedMeta(); @@ -329,50 +328,49 @@ public SkullMeta getMeta() { public static class PotionBuilder extends ItemBuilder { - @Nonnull - @CheckReturnValue + @NotNull public static ItemBuilder createWaterBottle() { return new PotionBuilder(Material.POTION).setColor(Color.BLUE).hideAttributes(); } - public PotionBuilder(@Nonnull Material material) { + public PotionBuilder(@NotNull Material material) { super(material); } - public PotionBuilder(@Nonnull Material material, @Nonnull String name) { + public PotionBuilder(@NotNull Material material, @NotNull String name) { super(material, name); } - public PotionBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + public PotionBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { super(material, name, lore); } - public PotionBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + public PotionBuilder(@NotNull Material material, @NotNull String name, int amount) { super(material, name, amount); } - public PotionBuilder(@Nonnull ItemStack item) { + public PotionBuilder(@NotNull ItemStack item) { super(item); } - @Nonnull - public PotionBuilder addEffect(@Nonnull PotionEffect effect) { + @NotNull + public PotionBuilder addEffect(@NotNull PotionEffect effect) { getMeta().addCustomEffect(effect, true); return this; } - @Nonnull - public PotionBuilder setColor(@Nonnull Color color) { + @NotNull + public PotionBuilder setColor(@NotNull Color color) { getMeta().setColor(color); return this; } - @Nonnull - public PotionBuilder color(@Nonnull Color color) { + @NotNull + public PotionBuilder color(@NotNull Color color) { return setColor(color); } - @Nonnull + @NotNull @Override public PotionMeta getMeta() { return getCastedMeta(); @@ -382,38 +380,38 @@ public PotionMeta getMeta() { public static class LeatherArmorBuilder extends ItemBuilder { - public LeatherArmorBuilder(@Nonnull Material material) { + public LeatherArmorBuilder(@NotNull Material material) { super(material); } - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name) { + public LeatherArmorBuilder(@NotNull Material material, @NotNull String name) { super(material, name); } - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, @Nonnull String... lore) { + public LeatherArmorBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { super(material, name, lore); } - public LeatherArmorBuilder(@Nonnull Material material, @Nonnull String name, int amount) { + public LeatherArmorBuilder(@NotNull Material material, @NotNull String name, int amount) { super(material, name, amount); } - public LeatherArmorBuilder(@Nonnull ItemStack item) { + public LeatherArmorBuilder(@NotNull ItemStack item) { super(item); } - @Nonnull - public LeatherArmorBuilder setColor(@Nonnull Color color) { + @NotNull + public LeatherArmorBuilder setColor(@NotNull Color color) { getMeta().setColor(color); return this; } - @Nonnull - public LeatherArmorBuilder color(@Nonnull Color color) { + @NotNull + public LeatherArmorBuilder color(@NotNull Color color) { return setColor(color); } - @Nonnull + @NotNull @Override public LeatherArmorMeta getMeta() { return getCastedMeta(); diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java index 31e95a13b..5eaec2c7b 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java @@ -6,13 +6,12 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.Damageable; import org.bukkit.inventory.meta.ItemMeta; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class ItemUtils { - @Nonnull - public static Material convertFoodToCookedFood(@Nonnull Material material) { + @NotNull + public static Material convertFoodToCookedFood(@NotNull Material material) { try { return Material.valueOf("COOKED_" + material.name()); } catch (Exception ex) { @@ -20,7 +19,7 @@ public static Material convertFoodToCookedFood(@Nonnull Material material) { } } - public static boolean isObtainableInSurvival(@Nonnull Material material) { + public static boolean isObtainableInSurvival(@NotNull Material material) { String name = material.name(); if (BukkitReflectionUtils.isAir(material)) return false; if (name.endsWith("_SPAWN_EGG")) return false; @@ -71,7 +70,7 @@ public static boolean isObtainableInSurvival(@Nonnull Material material) { return true; } - public static boolean blockIsAvailableInSurvival(@Nonnull Material material) { + public static boolean blockIsAvailableInSurvival(@NotNull Material material) { if (!material.isBlock()) return false; String name = material.name(); if (BukkitReflectionUtils.isAir(material)) return false; @@ -101,11 +100,11 @@ public static boolean blockIsAvailableInSurvival(@Nonnull Material material) { return true; } - public static void damageItem(@Nonnull ItemStack item) { + public static void damageItem(@NotNull ItemStack item) { damageItem(item, 1); } - public static void damageItem(@Nonnull ItemStack item, int amount) { + public static void damageItem(@NotNull ItemStack item, int amount) { ItemMeta meta = item.getItemMeta(); if (meta == null) return; if (!(meta instanceof Damageable)) return; diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java index 29c385e2c..3f407d532 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/logging/Logger.java @@ -3,37 +3,36 @@ import net.codingarea.commons.bukkit.core.BukkitModule; import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.misc.ReflectionUtils; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public final class Logger { private Logger() { } - @Nonnull + @NotNull public static ILogger getInstance() { return BukkitModule.getProvidingModule(ReflectionUtils.getCaller()).getILogger(); } - public static void error(@Nullable Object message, @Nonnull Object... args) { + public static void error(@Nullable Object message, @NotNull Object... args) { getInstance().error(message, args); } - public static void warn(@Nullable Object message, @Nonnull Object... args) { + public static void warn(@Nullable Object message, @NotNull Object... args) { getInstance().warn(message, args); } - public static void info(@Nullable Object message, @Nonnull Object... args) { + public static void info(@Nullable Object message, @NotNull Object... args) { getInstance().info(message, args); } - public static void debug(@Nullable Object message, @Nonnull Object... args) { + public static void debug(@Nullable Object message, @NotNull Object... args) { getInstance().debug(message, args); } - public static void trace(@Nullable Object message, @Nonnull Object... args) { + public static void trace(@Nullable Object message, @NotNull Object... args) { getInstance().trace(message, args); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java index 91dc239b1..5b172a784 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java @@ -4,10 +4,8 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; - -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class MenuClickInfo { @@ -17,7 +15,7 @@ public class MenuClickInfo { protected final boolean rightClick; protected final int slot; - public MenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boolean shiftClick, boolean rightClick, @Nonnegative int slot) { + public MenuClickInfo(@NotNull Player player, @NotNull Inventory inventory, boolean shiftClick, boolean rightClick, int slot) { this.player = player; this.inventory = inventory; this.shiftClick = shiftClick; @@ -25,12 +23,12 @@ public MenuClickInfo(@Nonnull Player player, @Nonnull Inventory inventory, boole this.slot = slot; } - @Nonnull + @NotNull public Player getPlayer() { return player; } - @Nonnull + @NotNull public Inventory getInventory() { return inventory; } @@ -56,7 +54,7 @@ public ItemStack getClickedItem() { return inventory.getItem(slot); } - @Nonnull + @NotNull public Material getClickedMaterial() { return getClickedItem() == null ? Material.AIR : getClickedItem().getType(); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java index 9df01539e..6ad64ff3e 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java @@ -3,9 +3,9 @@ import net.codingarea.commons.bukkit.utils.menu.positions.EmptyMenuPosition; import org.bukkit.entity.Player; import org.bukkit.inventory.InventoryHolder; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -23,23 +23,23 @@ private Holder() { InventoryHolder HOLDER = new MenuPositionHolder(); - static void set(@Nonnull Player player, @Nullable MenuPosition position) { + static void set(@NotNull Player player, @Nullable MenuPosition position) { Holder.positions.put(player, position); } - static void remove(@Nonnull Player player) { + static void remove(@NotNull Player player) { Holder.positions.remove(player); } @Nullable - static MenuPosition get(@Nonnull Player player) { + static MenuPosition get(@NotNull Player player) { return Holder.positions.get(player); } - static void setEmpty(@Nonnull Player player) { + static void setEmpty(@NotNull Player player) { set(player, new EmptyMenuPosition()); } - void handleClick(@Nonnull MenuClickInfo info); + void handleClick(@NotNull MenuClickInfo info); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java index 283f7b3c4..97ecff0cc 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java @@ -2,12 +2,11 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; class MenuPositionHolder implements InventoryHolder { - @Nonnull + @NotNull @Override public Inventory getInventory() { return null; diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java index 69a025729..49c2e9b1e 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java @@ -8,13 +8,12 @@ import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.Inventory; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public final class MenuPositionListener implements Listener { @EventHandler(priority = EventPriority.LOW) - public void onClick(@Nonnull InventoryClickEvent event) { + public void onClick(@NotNull InventoryClickEvent event) { HumanEntity human = event.getWhoClicked(); if (!(human instanceof Player)) return; diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java index badfbf48a..9f44d8261 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/EmptyMenuPosition.java @@ -3,13 +3,12 @@ import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class EmptyMenuPosition implements MenuPosition { @Override - public void handleClick(@Nonnull MenuClickInfo info) { + public void handleClick(@NotNull MenuClickInfo info) { SoundSample.CLICK.play(info.getPlayer()); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java index 5b7755881..cb5c32452 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/positions/SlottedMenuPosition.java @@ -4,8 +4,8 @@ import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; @@ -16,7 +16,7 @@ public class SlottedMenuPosition implements MenuPosition { protected boolean emptySound = true; @Override - public void handleClick(@Nonnull MenuClickInfo info) { + public void handleClick(@NotNull MenuClickInfo info) { Consumer action = actions.get(info.getSlot()); if (action == null) { if (emptySound) SoundSample.CLICK.play(info.getPlayer()); @@ -26,19 +26,19 @@ public void handleClick(@Nonnull MenuClickInfo info) { action.accept(info); } - @Nonnull - public SlottedMenuPosition setAction(int slot, @Nonnull Consumer action) { + @NotNull + public SlottedMenuPosition setAction(int slot, @NotNull Consumer action) { actions.put(slot, action); return this; } - @Nonnull - public SlottedMenuPosition setPlayerAction(int slot, @Nonnull Consumer action) { + @NotNull + public SlottedMenuPosition setPlayerAction(int slot, @NotNull Consumer action) { return setAction(slot, info -> action.accept(info.getPlayer())); } - @Nonnull - public SlottedMenuPosition setAction(int slot, @Nonnull Runnable action) { + @NotNull + public SlottedMenuPosition setAction(int slot, @NotNull Runnable action) { return setAction(slot, info -> action.run()); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java index 7fad422f7..dd55136cf 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java @@ -8,9 +8,9 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.lang.reflect.Method; import java.util.regex.Pattern; @@ -26,7 +26,7 @@ public final class BukkitReflectionUtils { private BukkitReflectionUtils() { } - public static double getAbsorptionAmount(@Nonnull Player player) { + public static double getAbsorptionAmount(@NotNull Player player) { Class classOfPlayer = player.getClass(); try { @@ -51,7 +51,7 @@ public static double getAbsorptionAmount(@Nonnull Player player) { return 0; } - public static boolean isAir(@Nonnull Material material) { + public static boolean isAir(@NotNull Material material) { try { return material.isAir(); } catch (Throwable ignored) { @@ -68,7 +68,7 @@ public static boolean isAir(@Nonnull Material material) { } } - public static int getMinHeight(@Nonnull World world) { + public static int getMinHeight(@NotNull World world) { try { return world.getMinHeight(); } catch (Throwable ignored) { @@ -82,7 +82,7 @@ public static int getMinHeight(@Nonnull World world) { * @deprecated not implemented in all forks of bukkit */ @Deprecated - public static boolean isInWater(@Nonnull Entity entity) { + public static boolean isInWater(@NotNull Entity entity) { try { return entity.isInWater(); } catch (Throwable ignored) { @@ -104,7 +104,7 @@ public static boolean isInWater(@Nonnull Entity entity) { * @see #fromString(String, Plugin) */ @Nullable - public static NamespacedKey fromString(@Nonnull String key) { + public static NamespacedKey fromString(@NotNull String key) { return fromString(key, null); } @@ -135,7 +135,7 @@ public static NamespacedKey fromString(@Nonnull String key) { * @see #fromString(String) */ @Nullable - public static NamespacedKey fromString(@Nonnull String string, @Nullable Plugin defaultNamespace) { + public static NamespacedKey fromString(@NotNull String string, @Nullable Plugin defaultNamespace) { Preconditions.checkArgument(string != null && !string.isEmpty(), "Input string must not be empty or null"); String[] components = string.split(":", 3); diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java index 47cd94c9d..bd88c6942 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java @@ -5,10 +5,10 @@ import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.Nonnull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -24,7 +24,7 @@ public class CompatibilityUtils { private CompatibilityUtils() { } - public static Inventory getTopInventory(@Nonnull Player player) { + public static Inventory getTopInventory(@NotNull Player player) { InventoryView view = player.getOpenInventory(); try { @@ -36,7 +36,7 @@ public static Inventory getTopInventory(@Nonnull Player player) { } } - public static Inventory getTopInventory(@Nonnull InventoryClickEvent event) { + public static Inventory getTopInventory(@NotNull InventoryClickEvent event) { InventoryView view = event.getView(); try { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java index b847c02d3..3912861aa 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/GameProfileUtils.java @@ -6,9 +6,9 @@ import net.codingarea.commons.common.logging.ILogger; import org.bukkit.entity.Player; import org.bukkit.inventory.meta.SkullMeta; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.UUID; @@ -20,8 +20,8 @@ public final class GameProfileUtils { private GameProfileUtils() { } - @Nonnull - public static GameProfile getGameProfile(@Nonnull Player player) { + @NotNull + public static GameProfile getGameProfile(@NotNull Player player) { try { Class classOfPlayer = player.getClass(); @@ -35,11 +35,11 @@ public static GameProfile getGameProfile(@Nonnull Player player) { } } - public static void applyTextures(@Nonnull SkullMeta meta, @Nullable UUID uuid, @Nullable String name, @Nullable String texture) { + public static void applyTextures(@NotNull SkullMeta meta, @Nullable UUID uuid, @Nullable String name, @Nullable String texture) { applyTextures(meta, uuid, name, texture, null); } - public static void applyTextures(@Nonnull SkullMeta meta, @Nullable UUID uuid, @Nullable String name, @Nullable String texture, @Nullable String signature) { + public static void applyTextures(@NotNull SkullMeta meta, @Nullable UUID uuid, @Nullable String name, @Nullable String texture, @Nullable String signature) { if (texture == null || texture.isEmpty()) return; GameProfile profile = new GameProfile(uuid == null ? UUID.randomUUID() : uuid, name); @@ -75,8 +75,8 @@ public static void applyTextures(@Nonnull SkullMeta meta, @Nullable UUID uuid, @ } - @Nonnull - public static GameProfile getTextures(@Nonnull SkullMeta meta) { + @NotNull + public static GameProfile getTextures(@NotNull SkullMeta meta) { Class classOfMeta = meta.getClass(); try { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java index a131416f3..cfd43bccf 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java @@ -2,46 +2,45 @@ import net.codingarea.commons.common.version.Version; import org.bukkit.Bukkit; - -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; public enum MinecraftVersion implements Version { - V1_0, // 1.0 - V1_1, // 1.1 - V1_2_1, // 1.2.1 - V1_3_1, // 1.3.1 - V1_4_2, // 1.4.2 - V1_5, // 1.5 - V1_6, // 1.6 - V1_7, // 1.7 - V1_7_2, // 1.7.2 - V1_8, // 1.8 - V1_9, // 1.9 - V1_10, // 1.10 - V1_11, // 1.11 - V1_12, // 1.12 - V1_13, // 1.13 - V1_14, // 1.14 - V1_15, // 1.15 - V1_16, // 1.16 - V1_16_5, // 1.16.5 - V1_17, // 1.17 + V1_0, // 1.0 + V1_1, // 1.1 + V1_2_1, // 1.2.1 + V1_3_1, // 1.3.1 + V1_4_2, // 1.4.2 + V1_5, // 1.5 + V1_6, // 1.6 + V1_7, // 1.7 + V1_7_2, // 1.7.2 + V1_8, // 1.8 + V1_9, // 1.9 + V1_10, // 1.10 + V1_11, // 1.11 + V1_12, // 1.12 + V1_13, // 1.13 + V1_14, // 1.14 + V1_15, // 1.15 + V1_16, // 1.16 + V1_16_5, // 1.16.5 + V1_17, // 1.17 V1_18, // 1.18 V1_19, // 1.19 V1_20, // 1.20 - V1_20_1, // 1.20.1 - V1_20_2, // 1.20.2 - V1_20_3, // 1.20.3 - V1_20_4, // 1.20.4 - V1_20_5, // 1.20.5 - V1_21, // 1.21 - V1_21_1, // 1.21.1 - V1_21_2, // 1.21.2 - V1_21_3, // 1.21.3 - V1_21_4, // 1.21.4 - V1_21_5 // 1.21.5 + V1_20_1, // 1.20.1 + V1_20_2, // 1.20.2 + V1_20_3, // 1.20.3 + V1_20_4, // 1.20.4 + V1_20_5, // 1.20.5 + V1_21, // 1.21 + V1_21_1, // 1.21.1 + V1_21_2, // 1.21.2 + V1_21_3, // 1.21.3 + V1_21_4, // 1.21.4 + V1_21_5, // 1.21.5 ; private final int major, minor, revision; @@ -80,35 +79,30 @@ public String toString() { return this.format(); } - @Nonnull + @NotNull @CheckReturnValue - public static Version parseExact(@Nonnull String bukkitVersion) { + public static Version parseExact(@NotNull String bukkitVersion) { bukkitVersion = bukkitVersion.substring(0, bukkitVersion.indexOf("-")); return Version.parse(bukkitVersion); } - @Nonnull - @CheckReturnValue - public static MinecraftVersion findNearest(@Nonnull Version realVersion) { + @NotNull + public static MinecraftVersion findNearest(@NotNull Version realVersion) { return Version.findNearest(realVersion, values()); } private static Version currentExact; private static MinecraftVersion current; - @Nonnull - @CheckReturnValue + @NotNull public static Version currentExact() { - if (currentExact == null) - currentExact = parseExact(Bukkit.getBukkitVersion()); + if (currentExact == null) currentExact = parseExact(Bukkit.getBukkitVersion()); return currentExact; } - @Nonnull - @CheckReturnValue + @NotNull public static MinecraftVersion current() { - if (current == null) - current = findNearest(currentExact()); + if (current == null) current = findNearest(currentExact()); return current; } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java index 7b15596df..42591350e 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/ActionListener.java @@ -3,8 +3,8 @@ import org.bukkit.event.Event; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Objects; import java.util.function.Consumer; @@ -15,7 +15,7 @@ public final class ActionListener implements Listener { private final EventPriority priority; private final boolean ignoreCancelled; - public ActionListener(@Nonnull Class classOfEvent, @Nonnull Consumer listener, @Nonnull EventPriority priority, boolean ignoreCancelled) { + public ActionListener(@NotNull Class classOfEvent, @NotNull Consumer listener, @NotNull EventPriority priority, boolean ignoreCancelled) { this.classOfEvent = classOfEvent; this.listener = listener; this.priority = priority; @@ -35,17 +35,17 @@ public int hashCode() { return Objects.hash(listener); } - @Nonnull + @NotNull public Consumer getListener() { return listener; } - @Nonnull + @NotNull public EventPriority getPriority() { return priority; } - @Nonnull + @NotNull public Class getClassOfEvent() { return classOfEvent; } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java index 394e5c037..420222c25 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/MaterialWrapper.java @@ -2,8 +2,7 @@ import net.codingarea.commons.common.misc.ReflectionUtils; import org.bukkit.Material; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; /** * This class allows you to use materials, whose names are changed at some point, in most versions. @@ -20,8 +19,8 @@ private MaterialWrapper() { public static final Material YELLOW_DYE = getMaterialByNames("DANDELION_YELLOW", "YELLOW_DYE"); public static final Material SIGN = getMaterialByNames("SIGN", "OAK_SIGN"); - @Nonnull - private static Material getMaterialByNames(@Nonnull String... names) { + @NotNull + private static Material getMaterialByNames(@NotNull String... names) { return ReflectionUtils.getFirstEnumByNames(Material.class, names); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java index 67e433db0..f4d4d6a3a 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/SimpleEventExecutor.java @@ -4,8 +4,8 @@ import org.bukkit.event.EventException; import org.bukkit.event.Listener; import org.bukkit.plugin.EventExecutor; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.function.Consumer; public class SimpleEventExecutor implements EventExecutor { @@ -13,13 +13,13 @@ public class SimpleEventExecutor implements EventExecutor { private final Class classOfEvent; private final Consumer action; - public SimpleEventExecutor(@Nonnull Class classOfEvent, @Nonnull Consumer action) { + public SimpleEventExecutor(@NotNull Class classOfEvent, @NotNull Consumer action) { this.classOfEvent = classOfEvent; this.action = action; } @Override - public void execute(@Nonnull Listener listener, @Nonnull Event event) throws EventException { + public void execute(@NotNull Listener listener, @NotNull Event event) throws EventException { if (!classOfEvent.isAssignableFrom(event.getClass())) return; try { action.accept(event); diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java index 586f5eaec..a98576b97 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/AlsoKnownAs.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.annotations; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.lang.annotation.*; /** @@ -11,7 +12,7 @@ @Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE}) public @interface AlsoKnownAs { - @Nonnull + @NotNull String[] value(); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java index 4d7ad3555..003e52d65 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/DeprecatedSince.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.annotations; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.lang.annotation.*; /** @@ -11,7 +12,7 @@ @Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE}) public @interface DeprecatedSince { - @Nonnull + @NotNull String value(); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java index 4ddc70147..08f32fffa 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/ReplaceWith.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.annotations; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.lang.annotation.*; /** @@ -11,7 +12,7 @@ @Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE}) public @interface ReplaceWith { - @Nonnull + @NotNull String value(); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java b/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java index eed4e34d0..88721c953 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java +++ b/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.annotations; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.lang.annotation.*; @Documented @@ -8,7 +9,7 @@ @Retention(RetentionPolicy.RUNTIME) public @interface Since { - @Nonnull + @NotNull String value(); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java b/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java index e4e54e98d..aa139434f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/ArrayWalker.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.collection; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.lang.reflect.Array; import java.util.Iterator; import java.util.NoSuchElementException; @@ -11,18 +12,18 @@ public class ArrayWalker implements Iterable { protected final Object array; protected final int length; - protected ArrayWalker(@Nonnull Object array) { + protected ArrayWalker(@NotNull Object array) { if (!array.getClass().isArray()) throw new IllegalArgumentException(array.getClass().getName() + " is not an array"); this.array = array; this.length = Array.getLength(array); } - public static ArrayWalker walk(@Nonnull Object array) { + public static ArrayWalker walk(@NotNull Object array) { return new ArrayWalker<>(array); } - public static ArrayWalker walk(@Nonnull T... array) { + public static ArrayWalker walk(@NotNull T... array) { return new ArrayWalker<>(array); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java index 5ecf33fcf..bea3edb11 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/ClassWalker.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.collection; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.util.*; /** @@ -11,24 +12,24 @@ public class ClassWalker implements Iterable> { protected final Class clazz; protected final Class end; - protected ClassWalker(@Nonnull Class clazz) { + protected ClassWalker(@NotNull Class clazz) { this(clazz, Object.class); } - protected ClassWalker(@Nonnull Class clazz, @Nonnull Class end) { + protected ClassWalker(@NotNull Class clazz, @NotNull Class end) { this.clazz = clazz; this.end = end; } - public static ClassWalker range(@Nonnull Class start, @Nonnull Class end) { + public static ClassWalker range(@NotNull Class start, @NotNull Class end) { return new ClassWalker(start, end); } - public static ClassWalker walk(@Nonnull Class start) { + public static ClassWalker walk(@NotNull Class start) { return new ClassWalker(start); } - @Nonnull + @NotNull @Override public Iterator> iterator() { return new Iterator>() { diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java b/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java index 592b996e9..213bdcdd8 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/Colors.java @@ -1,7 +1,7 @@ package net.codingarea.commons.common.collection; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.awt.*; import static java.awt.Color.decode; @@ -23,9 +23,8 @@ private Colors() { LIGHT_BLACK = decode("#1c1c1c"); - @Nonnull - @CheckReturnValue - public static String asHex(@Nonnull Color color) { + @NotNull + public static String asHex(@NotNull Color color) { String red = Integer.toHexString(color.getRed()); String green = Integer.toHexString(color.getGreen()); String blue = Integer.toHexString(color.getBlue()); diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java b/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java index 34f1fd43f..d890e350d 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/FontBuilder.java @@ -1,7 +1,8 @@ package net.codingarea.commons.common.collection; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; + import java.awt.*; import java.io.File; import java.io.IOException; @@ -11,68 +12,68 @@ public class FontBuilder { private Font font; - public FontBuilder(@Nonnull File file) throws IOException, FontFormatException { + public FontBuilder(@NotNull File file) throws IOException, FontFormatException { this(file, Font.TRUETYPE_FONT); } - public FontBuilder(@Nonnull File file, int type) throws IOException, FontFormatException { + public FontBuilder(@NotNull File file, int type) throws IOException, FontFormatException { this.font = Font.createFont(type, file); } - public FontBuilder(@Nonnull String resource) throws IOException, FontFormatException { + public FontBuilder(@NotNull String resource) throws IOException, FontFormatException { this(resource, Font.TRUETYPE_FONT); } - public FontBuilder(@Nonnull String resource, int type) throws IOException, FontFormatException { + public FontBuilder(@NotNull String resource, int type) throws IOException, FontFormatException { this.font = Font.createFont(type, Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(resource))); } - @Nonnull + @NotNull @CheckReturnValue public FontBuilder bold() { return style(Font.BOLD); } - @Nonnull + @NotNull @CheckReturnValue public FontBuilder italic() { return style(Font.ITALIC); } - @Nonnull + @NotNull @CheckReturnValue public FontBuilder style(int style) { font = font.deriveFont(style); return this; } - @Nonnull + @NotNull @CheckReturnValue public FontBuilder size(float size) { font = font.deriveFont(size); return this; } - @Nonnull + @NotNull @CheckReturnValue public FontBuilder derive(int style, float size) { font = font.deriveFont(style, size); return this; } - @Nonnull + @NotNull public Font build() { registerFont(font); return font; } - public static void registerFont(@Nonnull Font font) { + public static void registerFont(@NotNull Font font) { GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(font); } - @Nonnull + @NotNull @CheckReturnValue - public static FontBuilder fromFile(@Nonnull String filename) { + public static FontBuilder fromFile(@NotNull String filename) { try { return new FontBuilder(new File(filename)); } catch (Exception ex) { @@ -80,9 +81,9 @@ public static FontBuilder fromFile(@Nonnull String filename) { } } - @Nonnull + @NotNull @CheckReturnValue - public static FontBuilder fromResource(@Nonnull String resource) { + public static FontBuilder fromResource(@NotNull String resource) { try { return new FontBuilder(resource); } catch (Exception ex) { diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java b/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java index 04b094c8f..f8bd66d62 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/IOUtils.java @@ -1,7 +1,7 @@ package net.codingarea.commons.common.collection; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -15,27 +15,26 @@ public final class IOUtils { private IOUtils() { } - public static String toString(@Nonnull String url) throws IOException { + public static String toString(@NotNull String url) throws IOException { return toString(new URL(url)); } - public static String toString(@Nonnull URL url) throws IOException { + public static String toString(@NotNull URL url) throws IOException { InputStream input = url.openStream(); String string = toString(input); input.close(); return string; } - public static String toString(@Nonnull InputStream input) throws IOException { + public static String toString(@NotNull InputStream input) throws IOException { StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); reader.lines().forEach(builder::append); return builder.toString(); } - @Nonnull - @CheckReturnValue - public static HttpURLConnection createConnection(@Nonnull String url) throws IOException { + @NotNull + public static HttpURLConnection createConnection(@NotNull String url) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); return connection; diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java b/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java index 2ef4a2c3f..1326e79a3 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java @@ -1,8 +1,8 @@ package net.codingarea.commons.common.collection; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; + import java.security.SecureRandom; import java.util.*; import java.util.concurrent.ThreadLocalRandom; @@ -12,37 +12,37 @@ public interface IRandom { - @Nonnull + @NotNull @CheckReturnValue static IRandom create() { return new SeededRandomWrapper(); } - @Nonnull + @NotNull @CheckReturnValue static IRandom create(long seed) { return new SeededRandomWrapper(seed); } - @Nonnull + @NotNull @CheckReturnValue - static IRandom wrap(@Nonnull Random random) { + static IRandom wrap(@NotNull Random random) { return new RandomWrapper(random); } - @Nonnull + @NotNull @CheckReturnValue static IRandom threadLocal() { return wrap(ThreadLocalRandom.current()); } - @Nonnull + @NotNull @CheckReturnValue static IRandom secure() { return wrap(new SecureRandom()); } - @Nonnull + @NotNull @CheckReturnValue static IRandom singleton() { return SingletonRandom.INSTANCE; @@ -52,7 +52,7 @@ static IRandom singleton() { void setSeed(long seed); - void nextBytes(@Nonnull byte[] bytes); + void nextBytes(@NotNull byte[] bytes); boolean nextBoolean(); @@ -60,79 +60,67 @@ static IRandom singleton() { int nextInt(int bound); - @Nonnull - @CheckReturnValue + @NotNull IntStream ints(); - @Nonnull - @CheckReturnValue - IntStream ints(@Nonnegative long streamSize); + @NotNull + IntStream ints(long streamSize); - @Nonnull - @CheckReturnValue + @NotNull IntStream ints(int randomNumberOrigin, int randomNumberBound); - @Nonnull - @CheckReturnValue - IntStream ints(@Nonnegative long streamSize, int randomNumberOrigin, int randomNumberBound); + @NotNull + IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound); - @Nonnull - @CheckReturnValue + @NotNull LongStream longs(); long nextLong(); - @Nonnull - @CheckReturnValue - LongStream longs(@Nonnegative long streamSize); + @NotNull + LongStream longs(long streamSize); - @Nonnull - @CheckReturnValue + @NotNull LongStream longs(long randomNumberOrigin, long randomNumberBound); - @Nonnull - @CheckReturnValue - LongStream longs(@Nonnegative long streamSize, long randomNumberOrigin, long randomNumberBound); + @NotNull + LongStream longs(long streamSize, long randomNumberOrigin, long randomNumberBound); double nextDouble(); double nextGaussian(); - @Nonnull - @CheckReturnValue + @NotNull DoubleStream doubles(); - @Nonnull - @CheckReturnValue - DoubleStream doubles(@Nonnegative long streamSize); + @NotNull + DoubleStream doubles(long streamSize); - @Nonnull - @CheckReturnValue + @NotNull DoubleStream doubles(double randomNumberOrigin, double randomNumberBound); - @Nonnull - @CheckReturnValue - DoubleStream doubles(@Nonnegative long streamSize, double randomNumberOrigin, double randomNumberBound); + @NotNull + DoubleStream doubles(long streamSize, double randomNumberOrigin, double randomNumberBound); float nextFloat(); - default T choose(@Nonnull T... array) { + default T choose(@NotNull T... array) { return array[nextInt(array.length)]; } - default T choose(@Nonnull List list) { + default T choose(@NotNull List list) { return list.get(nextInt(list.size())); } - default T choose(@Nonnull Collection collection) { + default T choose(@NotNull Collection collection) { return choose(new ArrayList<>(collection)); } - default void shuffle(@Nonnull List list) { + default void shuffle(@NotNull List list) { Collections.shuffle(list, asRandom()); } - default int around(int value, @Nonnegative int range) { + default int around(int value, int range) { return range(value - range, value + range); } @@ -141,7 +129,7 @@ default int range(int min, int max) { return nextInt(max - min) + min; } - @Nonnull + @NotNull @CheckReturnValue default Random asRandom() { if (!(this instanceof Random)) diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java index e1c7a8473..c10d0100d 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NamedThreadFactory.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.collection; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.IntFunction; @@ -14,17 +15,17 @@ public class NamedThreadFactory implements ThreadFactory { protected final ThreadGroup group; protected final AtomicInteger threadNumber = new AtomicInteger(1); - public NamedThreadFactory(@Nonnull IntFunction nameFunction) { + public NamedThreadFactory(@NotNull IntFunction nameFunction) { this.group = Thread.currentThread().getThreadGroup(); this.nameFunction = nameFunction; } - public NamedThreadFactory(@Nonnull String prefix) { + public NamedThreadFactory(@NotNull String prefix) { this(id -> prefix + "-" + id); } @Override - public Thread newThread(@Nonnull Runnable task) { + public Thread newThread(@NotNull Runnable task) { Thread thread = new Thread(group, task, nameFunction.apply(threadNumber.getAndIncrement())); if (thread.isDaemon()) thread.setDaemon(false); diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java index 7955433a5..589781823 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/NumberFormatter.java @@ -1,50 +1,43 @@ package net.codingarea.commons.common.collection; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.function.Consumer; public interface NumberFormatter { - @Nonnull - @CheckReturnValue + @NotNull String format(double value); - @Nonnull - @CheckReturnValue + @NotNull default String format(float value) { return format(Float.valueOf(value)); } - @Nonnull - @CheckReturnValue + @NotNull default String format(long value) { return format(Long.valueOf(value)); } - @Nonnull - @CheckReturnValue + @NotNull default String format(int value) { return format(Integer.valueOf(value)); } - @Nonnull - @CheckReturnValue + @NotNull default String format(short value) { return format(Short.valueOf(value)); } - @Nonnull - @CheckReturnValue + @NotNull default String format(byte value) { return format(Byte.valueOf(value)); } - @Nonnull - @CheckReturnValue - default String format(@Nonnull Number number) { + @NotNull + default String format(@NotNull Number number) { return format(number.doubleValue()); } @@ -328,29 +321,25 @@ default String format(@Nonnull Number number) { }, GERMAN_ORDINAL = fromPattern("0", ".", false); - @Nonnull - @CheckReturnValue - public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive) { + @NotNull + public static NumberFormatter fromPattern(@NotNull String pattern, String ending, boolean positive) { return fromPattern(pattern, ending, positive, null); } - @Nonnull - @CheckReturnValue - public static NumberFormatter fromPattern(@Nonnull String pattern, String ending, boolean positive, Consumer init) { + @NotNull + public static NumberFormatter fromPattern(@NotNull String pattern, String ending, boolean positive, Consumer init) { DecimalFormat format = new DecimalFormat(pattern); if (init != null) init.accept(format); return value -> Double.isNaN(value) ? "NaN" : format.format(positive ? (value > 0 ? value : 0) : value) + (ending != null ? ending : ""); } - @Nonnull - @CheckReturnValue - public static DecimalFormatSymbols updateSymbols(@Nonnull DecimalFormatSymbols symbols, @Nonnull Consumer action) { + @NotNull + public static DecimalFormatSymbols updateSymbols(@NotNull DecimalFormatSymbols symbols, @NotNull Consumer action) { action.accept(symbols); return symbols; } - @CheckReturnValue - public static void updateSymbols(@Nonnull DecimalFormat format, @Nonnull Consumer action) { + public static void updateSymbols(@NotNull DecimalFormat format, @NotNull Consumer action) { format.setDecimalFormatSymbols(updateSymbols(format.getDecimalFormatSymbols(), action)); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java index e81ec4ec9..822978d6b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/RandomWrapper.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.collection; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.util.Random; import java.util.stream.DoubleStream; import java.util.stream.IntStream; @@ -10,7 +11,7 @@ public class RandomWrapper implements IRandom { private final Random random; - public RandomWrapper(@Nonnull Random random) { + public RandomWrapper(@NotNull Random random) { this.random = random; } @@ -25,7 +26,7 @@ public void setSeed(long seed) { } @Override - public void nextBytes(@Nonnull byte[] bytes) { + public void nextBytes(@NotNull byte[] bytes) { random.nextBytes(bytes); } @@ -44,31 +45,31 @@ public int nextInt(int bound) { return random.nextInt(bound); } - @Nonnull + @NotNull @Override public IntStream ints() { return random.ints(); } - @Nonnull + @NotNull @Override public IntStream ints(long streamSize) { return random.ints(streamSize); } - @Nonnull + @NotNull @Override public IntStream ints(int randomNumberOrigin, int randomNumberBound) { return random.ints(randomNumberOrigin, randomNumberBound); } - @Nonnull + @NotNull @Override public IntStream ints(long streamSize, int randomNumberOrigin, int randomNumberBound) { return random.ints(streamSize, randomNumberOrigin, randomNumberBound); } - @Nonnull + @NotNull @Override public LongStream longs() { return random.longs(); @@ -79,19 +80,19 @@ public long nextLong() { return random.nextLong(); } - @Nonnull + @NotNull @Override public LongStream longs(long streamSize) { return random.longs(streamSize); } - @Nonnull + @NotNull @Override public LongStream longs(long randomNumberOrigin, long randomNumberBound) { return random.longs(randomNumberOrigin, randomNumberBound); } - @Nonnull + @NotNull @Override public LongStream longs(long streamSize, long randomNumberOrigin, long randomNumberBound) { return random.longs(streamSize, randomNumberOrigin, randomNumberBound); @@ -107,25 +108,25 @@ public double nextGaussian() { return random.nextGaussian(); } - @Nonnull + @NotNull @Override public DoubleStream doubles() { return random.doubles(); } - @Nonnull + @NotNull @Override public DoubleStream doubles(long streamSize) { return random.doubles(streamSize); } - @Nonnull + @NotNull @Override public DoubleStream doubles(double randomNumberOrigin, double randomNumberBound) { return random.doubles(randomNumberOrigin, randomNumberBound); } - @Nonnull + @NotNull @Override public DoubleStream doubles(long streamSize, double randomNumberOrigin, double randomNumberBound) { return random.doubles(streamSize, randomNumberOrigin, randomNumberBound); @@ -136,7 +137,7 @@ public float nextFloat() { return random.nextFloat(); } - @Nonnull + @NotNull @Override public Random asRandom() { return random; diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java b/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java index aa8f1bf87..529bf547b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/RomanNumerals.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.collection; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.util.TreeMap; public final class RomanNumerals { @@ -34,7 +35,7 @@ private IllegalRomanNumeralException(int number) { private RomanNumerals() { } - @Nonnull + @NotNull public static String forNumber(int number) { if (number < 0 || number > 3999) throw new IllegalRomanNumeralException(number); if (number == 0) return ""; diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java b/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java index c6b26b7d5..90b95559e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/RunnableTimerTask.java @@ -1,13 +1,14 @@ package net.codingarea.commons.common.collection; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.util.TimerTask; public class RunnableTimerTask extends TimerTask { protected final Runnable action; - public RunnableTimerTask(@Nonnull Runnable action) { + public RunnableTimerTask(@NotNull Runnable action) { this.action = action; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java index 0e61626e3..081292620 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderPrintWriter.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.collection; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.io.PrintWriter; /** @@ -15,7 +16,7 @@ public StringBuilderPrintWriter() { writer = (StringBuilderWriter) out; } - @Nonnull + @NotNull public StringBuilder getBuilder() { return writer.getBuilder(); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java index 0abbd6637..85a883d58 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/StringBuilderWriter.java @@ -1,7 +1,8 @@ package net.codingarea.commons.common.collection; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + import java.io.Writer; /** @@ -44,7 +45,7 @@ public void close() { public void flush() { } - public void write(@Nonnull String value) { + public void write(@NotNull String value) { builder.append(value); } @@ -54,7 +55,7 @@ public void write(@Nullable char[] value, int offset, int length) { } } - @Nonnull + @NotNull public StringBuilder getBuilder() { return this.builder; } @@ -65,4 +66,3 @@ public String toString() { } } - diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java index f7622edc4..4081c5179 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/Triple.java @@ -1,6 +1,6 @@ package net.codingarea.commons.common.collection; -import javax.annotation.Nullable; +import org.jetbrains.annotations.Nullable; /** * @param The type of the first value diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java index d47bf885b..aad504696 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/Tuple.java @@ -1,6 +1,6 @@ package net.codingarea.commons.common.collection; -import javax.annotation.Nullable; +import org.jetbrains.annotations.Nullable; /** * @param The type of the first value diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java b/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java index 8668f4cc0..95cf72f07 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/WrappedException.java @@ -1,7 +1,7 @@ package net.codingarea.commons.common.collection; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; /** * This class is used to rethrow signed exception as unsigned exceptions. @@ -10,11 +10,11 @@ public class WrappedException extends RuntimeException { public static class SilentWrappedException extends WrappedException { - public SilentWrappedException(@Nullable String message, @Nonnull Throwable cause) { + public SilentWrappedException(@Nullable String message, @NotNull Throwable cause) { super(message, cause); } - public SilentWrappedException(@Nonnull Throwable cause) { + public SilentWrappedException(@NotNull Throwable cause) { super(cause); } @@ -25,22 +25,22 @@ public synchronized Throwable fillInStackTrace() { } - public WrappedException(@Nullable String message, @Nonnull Throwable cause) { + public WrappedException(@Nullable String message, @NotNull Throwable cause) { super(message, cause); } - public WrappedException(@Nonnull Throwable cause) { + public WrappedException(@NotNull Throwable cause) { super(cause); } - @Nonnull + @NotNull @Override public Throwable getCause() { return super.getCause(); } - @Nonnull - public static RuntimeException rethrow(@Nonnull Throwable ex) { + @NotNull + public static RuntimeException rethrow(@NotNull Throwable ex) { if (ex instanceof Error) throw (Error) ex; if (ex instanceof RuntimeException) @@ -48,13 +48,13 @@ public static RuntimeException rethrow(@Nonnull Throwable ex) { throw silent(ex); } - @Nonnull - public static WrappedException silent(@Nonnull Throwable cause) { + @NotNull + public static WrappedException silent(@NotNull Throwable cause) { return new SilentWrappedException(cause); } - @Nonnull - public static WrappedException silent(@Nullable String message, @Nonnull Throwable cause) { + @NotNull + public static WrappedException silent(@Nullable String message, @NotNull Throwable cause) { return new SilentWrappedException(message, cause); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java index 2e41faccb..5d0d581dc 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java @@ -1,7 +1,6 @@ package net.codingarea.commons.common.collection.pair; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; /** * @see Tuple @@ -13,10 +12,9 @@ public interface Pair { /** * @return The amount of values */ - @Nonnegative int amount(); - @Nonnull + @NotNull Object[] values(); /** diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java index 0d61041c3..d4ba425ac 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Quadro.java @@ -1,8 +1,9 @@ package net.codingarea.commons.common.collection.pair; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + import java.util.Objects; import java.util.function.Function; @@ -34,7 +35,7 @@ public final int amount() { return 4; } - @Nonnull + @NotNull @Override public final Object[] values() { return new Object[]{first, second, third, first}; @@ -72,12 +73,12 @@ public void setFourth(@Nullable FF fourth) { this.fourth = fourth; } - @Nonnull + @NotNull @CheckReturnValue - public Quadro map(@Nonnull Function firstMapper, - @Nonnull Function secondMapper, - @Nonnull Function thirdMapper, - @Nonnull Function fourthMapper) { + public Quadro map(@NotNull Function firstMapper, + @NotNull Function secondMapper, + @NotNull Function thirdMapper, + @NotNull Function fourthMapper) { return of(firstMapper.apply(first), secondMapper.apply(second), thirdMapper.apply(third), fourthMapper.apply(fourth)); } @@ -107,32 +108,32 @@ public String toString() { return "Quadro[" + first + ", " + second + ", " + third + ", " + fourth + "]"; } - @Nonnull + @NotNull public static Quadro ofFirst(@Nullable F first) { return of(first, null, null, null); } - @Nonnull + @NotNull public static Quadro ofSecond(@Nullable S second) { return of(null, second, null, null); } - @Nonnull + @NotNull public static Quadro ofThird(@Nullable T third) { return of(null, null, third, null); } - @Nonnull + @NotNull public static Quadro ofFourth(@Nullable FF fourth) { return of(null, null, null, fourth); } - @Nonnull + @NotNull public static Quadro of(@Nullable F first, @Nullable S second, @Nullable T third, @Nullable FF fourth) { return new Quadro<>(first, second, third, fourth); } - @Nonnull + @NotNull public static Quadro empty() { return new Quadro<>(); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java index e99ef90a4..383186610 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Triple.java @@ -1,8 +1,9 @@ package net.codingarea.commons.common.collection.pair; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + import java.util.Objects; import java.util.function.Function; @@ -31,7 +32,7 @@ public final int amount() { return 3; } - @Nonnull + @NotNull @Override public final Object[] values() { return new Object[]{first, second, third}; @@ -61,11 +62,11 @@ public void setThird(@Nullable T third) { this.third = third; } - @Nonnull + @NotNull @CheckReturnValue - public Triple map(@Nonnull Function firstMapper, - @Nonnull Function secondMapper, - @Nonnull Function thirdMapper) { + public Triple map(@NotNull Function firstMapper, + @NotNull Function secondMapper, + @NotNull Function thirdMapper) { return of(firstMapper.apply(first), secondMapper.apply(second), thirdMapper.apply(third)); } @@ -95,27 +96,27 @@ public String toString() { return "Triple[" + first + ", " + second + ", " + third + "]"; } - @Nonnull + @NotNull public static Triple ofFirst(@Nullable F first) { return of(first, null, null); } - @Nonnull + @NotNull public static Triple ofSecond(@Nullable S second) { return of(null, second, null); } - @Nonnull + @NotNull public static Triple ofThird(@Nullable T third) { return of(null, null, third); } - @Nonnull + @NotNull public static Triple of(@Nullable F first, @Nullable S second, @Nullable T third) { return new Triple<>(first, second, third); } - @Nonnull + @NotNull public static Triple empty() { return new Triple<>(); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java index f94e44523..d07d7538e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Tuple.java @@ -1,8 +1,9 @@ package net.codingarea.commons.common.collection.pair; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + import java.util.Objects; import java.util.function.Function; @@ -28,7 +29,7 @@ public final int amount() { return 2; } - @Nonnull + @NotNull @Override public final Object[] values() { return new Object[]{first, second}; @@ -50,10 +51,10 @@ public void setSecond(@Nullable S second) { this.second = second; } - @Nonnull + @NotNull @CheckReturnValue - public Tuple map(@Nonnull Function firstMapper, - @Nonnull Function secondMapper) { + public Tuple map(@NotNull Function firstMapper, + @NotNull Function secondMapper) { return of(firstMapper.apply(first), secondMapper.apply(second)); } @@ -83,22 +84,22 @@ public String toString() { return "Tuple[" + first + ", " + second + "]"; } - @Nonnull + @NotNull public static Tuple ofFirst(@Nullable F frist) { return new Tuple<>(frist, null); } - @Nonnull + @NotNull public static Tuple ofSecond(@Nullable S second) { return new Tuple<>(null, second); } - @Nonnull + @NotNull public static Tuple of(@Nullable F first, @Nullable S second) { return new Tuple<>(first, second); } - @Nonnull + @NotNull public static Tuple empty() { return new Tuple<>(); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java index 2333ac96b..d0afae8e8 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanAndWriteDatabaseCache.java @@ -4,10 +4,9 @@ import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.misc.SimpleCollectionUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -31,9 +30,9 @@ public class CleanAndWriteDatabaseCache implements DatabaseCache { protected final long cleanAndWriteInterval; protected final ILogger logger; - public CleanAndWriteDatabaseCache(@Nullable ILogger logger, @Nonnegative long unusedTimeBeforeClean, @Nonnegative long cleanAndWriteInterval, @Nonnull String taskName, - @Nonnull Predicate check, @Nonnull Function fallback, - @Nonnull Function query, @Nonnull BiConsumer writer) { + public CleanAndWriteDatabaseCache(@Nullable ILogger logger, long unusedTimeBeforeClean, long cleanAndWriteInterval, @NotNull String taskName, + @NotNull Predicate check, @NotNull Function fallback, + @NotNull Function query, @NotNull BiConsumer writer) { this.logger = logger; this.unusedTimeBeforeClean = unusedTimeBeforeClean; this.cleanAndWriteInterval = cleanAndWriteInterval; @@ -51,9 +50,9 @@ public void writeCache() { cleanAndWrite(cache, unusedTimeBeforeClean, logger, check, writer); } - @Nonnull + @NotNull @Override - public V getData(@Nonnull K key) { + public V getData(@NotNull K key) { Tuple cached = cache.get(key); if (cached != null) { cached.setFirst(System.currentTimeMillis()); @@ -72,7 +71,7 @@ public V getData(@Nonnull K key) { } @Override - public boolean contains(@Nonnull K key) { + public boolean contains(@NotNull K key) { return cache.containsKey(key); } @@ -86,8 +85,8 @@ public void clear() { cache.clear(); } - public static void cleanAndWrite(@Nonnull Map> cache, @Nonnegative long unusedTimeBeforeClean, @Nullable ILogger logger, - @Nonnull Predicate check, @Nonnull BiConsumer writer) { + public static void cleanAndWrite(@NotNull Map> cache, long unusedTimeBeforeClean, @Nullable ILogger logger, + @NotNull Predicate check, @NotNull BiConsumer writer) { long now = System.currentTimeMillis(); Collection remove = new ArrayList<>(); cache.forEach((key, pair) -> { @@ -110,7 +109,7 @@ public static void cleanAndWrite(@Nonnull Map> cache, @ remove.forEach(cache::remove); } - @Nonnull + @NotNull @Override public Map values() { return Collections.unmodifiableMap(SimpleCollectionUtils.convertMap(cache, k -> k, Tuple::getSecond)); diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java index c321f8604..a749126d3 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CleanWriteableCache.java @@ -4,10 +4,9 @@ import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.misc.SimpleCollectionUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -24,7 +23,7 @@ public class CleanWriteableCache implements WriteableCache { protected final long cleanInterval; protected final long unusedTimeBeforeClean; - public CleanWriteableCache(@Nullable ILogger logger, @Nonnegative long unusedTimeBeforeClean, @Nonnegative long cleanInterval, @Nonnull String taskName) { + public CleanWriteableCache(@Nullable ILogger logger, long unusedTimeBeforeClean, long cleanInterval, @NotNull String taskName) { this.logger = logger; this.cleanInterval = cleanInterval; this.unusedTimeBeforeClean = unusedTimeBeforeClean; @@ -48,7 +47,7 @@ public void cleanCache() { @Nullable @Override - public V getData(@Nonnull K key) { + public V getData(@NotNull K key) { Tuple pair = cache.get(key); if (pair == null) return null; pair.setFirst(System.currentTimeMillis()); @@ -56,12 +55,12 @@ public V getData(@Nonnull K key) { } @Override - public void setData(@Nonnull K key, @Nullable V value) { + public void setData(@NotNull K key, @Nullable V value) { cache.put(key, new Tuple<>(System.currentTimeMillis(), value)); } @Override - public boolean contains(@Nonnull K key) { + public boolean contains(@NotNull K key) { return cache.containsKey(key); } @@ -75,7 +74,7 @@ public void clear() { cache.clear(); } - @Nonnull + @NotNull @Override public Map values() { return Collections.unmodifiableMap(SimpleCollectionUtils.convertMap(cache, k -> k, Tuple::getSecond)); diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java index 0c5fd162e..c4f2b3244 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/CoolDownCache.java @@ -2,9 +2,8 @@ import net.codingarea.commons.common.collection.RunnableTimerTask; import net.codingarea.commons.common.logging.ILogger; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collection; import java.util.Map; @@ -19,7 +18,7 @@ public class CoolDownCache { protected final ToLongFunction cooldownTime; protected final long cleanInterval; - public CoolDownCache(@Nonnull ILogger logger, @Nonnegative long cleanInterval, @Nonnull String taskName, @Nonnull ToLongFunction cooldownTime) { + public CoolDownCache(@NotNull ILogger logger, long cleanInterval, @NotNull String taskName, @NotNull ToLongFunction cooldownTime) { this.logger = logger; this.cooldownTime = cooldownTime; this.cleanInterval = cleanInterval; @@ -41,38 +40,38 @@ public void cleanCache() { remove.forEach(cache::remove); } - public boolean isOnCoolDown(long now, long suspect, @Nonnull K key) { + public boolean isOnCoolDown(long now, long suspect, @NotNull K key) { long difference = now - suspect; return difference < getCoolDownTime(key); } - public boolean isOnCoolDown(@Nonnull K key) { + public boolean isOnCoolDown(@NotNull K key) { Long time = cache.get(key); if (time == null) return false; return isOnCoolDown(System.currentTimeMillis(), time, key); } - public boolean checkCoolDown(@Nonnull K key) { + public boolean checkCoolDown(@NotNull K key) { boolean cooldown = isOnCoolDown(key); if (!cooldown) setOnCoolDown(key); return cooldown; } - public void setOnCoolDown(@Nonnull K key) { + public void setOnCoolDown(@NotNull K key) { cache.put(key, System.currentTimeMillis()); } - public long getCoolDown(@Nonnull K key) { + public long getCoolDown(@NotNull K key) { Long time = cache.get(key); if (time == null) return 0; return System.currentTimeMillis() - time; } - public float getCoolDownSeconds(@Nonnull K key) { + public float getCoolDownSeconds(@NotNull K key) { return getCoolDown(key) / 1000f; } - public long getCoolDownTime(@Nonnull K key) { + public long getCoolDownTime(@NotNull K key) { return cooldownTime.applyAsLong(key); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java index 544c2e499..068ec8cdf 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/DatabaseCache.java @@ -1,8 +1,7 @@ package net.codingarea.commons.common.concurrent.cache; import net.codingarea.commons.common.annotations.ReplaceWith; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; /** * @see com.google.common.cache.LoadingCache @@ -12,7 +11,7 @@ @ReplaceWith("com.google.common.cache.LoadingCache") public interface DatabaseCache extends ICache { - @Nonnull - V getData(@Nonnull K key); + @NotNull + V getData(@NotNull K key); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java index 9a73f8854..94035e7ab 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/ICache.java @@ -2,8 +2,8 @@ import net.codingarea.commons.common.annotations.ReplaceWith; import net.codingarea.commons.common.collection.NamedThreadFactory; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -19,7 +19,7 @@ public interface ICache { ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(2, new NamedThreadFactory(threadId -> String.format("CacheTask-%s", threadId))); - boolean contains(@Nonnull K key); + boolean contains(@NotNull K key); int size(); @@ -29,10 +29,10 @@ default boolean isEmpty() { void clear(); - @Nonnull + @NotNull Map values(); - default void forEach(@Nonnull BiConsumer action) { + default void forEach(@NotNull BiConsumer action) { values().forEach(action); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java index 645e59bd8..de5bda73d 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/cache/WriteableCache.java @@ -1,17 +1,16 @@ package net.codingarea.commons.common.concurrent.cache; import net.codingarea.commons.common.annotations.ReplaceWith; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; @Deprecated @ReplaceWith("com.google.common.cache.Cache") public interface WriteableCache extends ICache { @Nullable - V getData(@Nonnull K key); + V getData(@NotNull K key); - void setData(@Nonnull K key, @Nullable V value); + void setData(@NotNull K key, @Nullable V value); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java index 582372d43..180bde1dc 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletableTask.java @@ -1,9 +1,9 @@ package net.codingarea.commons.common.concurrent.task; import net.codingarea.commons.common.collection.NamedThreadFactory; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.*; @@ -22,7 +22,7 @@ public CompletableTask() { this(new CompletableFuture<>()); } - private CompletableTask(@Nonnull CompletableFuture future) { + private CompletableTask(@NotNull CompletableFuture future) { this.future = future; this.future.exceptionally(ex -> { this.failure = ex; @@ -30,8 +30,8 @@ private CompletableTask(@Nonnull CompletableFuture future) { }); } - @Nonnull - public static Task callAsync(@Nonnull Callable callable) { + @NotNull + public static Task callAsync(@NotNull Callable callable) { CompletableTask task = new CompletableTask<>(); SERVICE.execute(() -> { try { @@ -43,8 +43,8 @@ public static Task callAsync(@Nonnull Callable callable) { return task; } - @Nonnull - public static Task callSync(@Nonnull Callable callable) { + @NotNull + public static Task callSync(@NotNull Callable callable) { CompletableTask task = new CompletableTask<>(); try { task.complete(callable.call()); @@ -54,9 +54,9 @@ public static Task callSync(@Nonnull Callable callable) { return task; } - @Nonnull + @NotNull @Override - public Task addListener(@Nonnull TaskListener listener) { + public Task addListener(@NotNull TaskListener listener) { if (future.isDone()) { V value = future.getNow(null); if (future.isCancelled() || value != null) { @@ -73,7 +73,7 @@ public Task addListener(@Nonnull TaskListener listener) { return this; } - @Nonnull + @NotNull @Override public Task clearListeners() { this.listeners.clear(); @@ -141,11 +141,11 @@ public V get() throws InterruptedException, ExecutionException { } @Override - public V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + public V get(long timeout, @NotNull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return future.get(timeout, unit); } - @Nonnull + @NotNull @Override public Task map(@Nullable Function mapper) { CompletableTask task = new CompletableTask<>(); @@ -161,7 +161,7 @@ public Task map(@Nullable Function mapper) { return task; } - @Nonnull + @NotNull @Override public CompletionStage stage() { return future; diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java index 1ae7724f3..90d7c3ef5 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/CompletedTask.java @@ -1,7 +1,8 @@ package net.codingarea.commons.common.concurrent.task; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + import java.util.concurrent.*; import java.util.function.Function; @@ -22,9 +23,9 @@ public CompletedTask(@Nullable Throwable failure) { this.failure = failure; } - @Nonnull + @NotNull @Override - public Task addListener(@Nonnull TaskListener listener) { + public Task addListener(@NotNull TaskListener listener) { if (failure != null) { listener.onFailure(this, failure); } else if (value != null) { @@ -36,13 +37,13 @@ public Task addListener(@Nonnull TaskListener listener) { return this; } - @Nonnull + @NotNull @Override public Task clearListeners() { return this; } - @Nonnull + @NotNull @Override public Task map(@Nullable Function mapper) { if (failure != null) @@ -52,7 +53,7 @@ public Task map(@Nullable Function mapper) { } @Override - public V getOrDefault(long timeout, @Nonnull TimeUnit unit, V def) { + public V getOrDefault(long timeout, @NotNull TimeUnit unit, V def) { if (value != null) return value; @@ -85,11 +86,11 @@ public V get() throws InterruptedException, ExecutionException { } @Override - public V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + public V get(long timeout, @NotNull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return value; } - @Nonnull + @NotNull @Override public CompletionStage stage() { if (future == null) { diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java index 200b6ab27..1def32d51 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/Task.java @@ -3,10 +3,10 @@ import net.codingarea.commons.common.collection.WrappedException; import net.codingarea.commons.common.function.ExceptionallyFunction; import net.codingarea.commons.common.function.ExceptionallyRunnable; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.concurrent.*; import java.util.function.BiConsumer; import java.util.function.Consumer; @@ -23,161 +23,161 @@ */ public interface Task extends Future, Callable { - @Nonnull + @NotNull static ExecutorService getAsyncExecutor() { return CompletableTask.SERVICE; } - @Nonnull + @NotNull static Task empty() { return completed(null); } - @Nonnull + @NotNull static Task completed(@Nullable V value) { return new CompletedTask<>(value); } - @Nonnull + @NotNull static Task completedVoid() { return empty(); } - @Nonnull - static Task failed(@Nonnull Throwable failure) { + @NotNull + static Task failed(@NotNull Throwable failure) { return new CompletedTask<>(failure); } - @Nonnull + @NotNull static CompletableTask completable() { return new CompletableTask<>(); } - @Nonnull - static Task asyncCall(@Nonnull Callable callable) { + @NotNull + static Task asyncCall(@NotNull Callable callable) { return CompletableTask.callAsync(callable); } - @Nonnull - static Task asyncSupply(@Nonnull Supplier supplier) { + @NotNull + static Task asyncSupply(@NotNull Supplier supplier) { return asyncCall(supplier::get); } - @Nonnull - static Task asyncRun(@Nonnull Runnable runnable) { + @NotNull + static Task asyncRun(@NotNull Runnable runnable) { return asyncCall(() -> { runnable.run(); return null; }); } - @Nonnull - static Task asyncRunExceptionally(@Nonnull ExceptionallyRunnable runnable) { + @NotNull + static Task asyncRunExceptionally(@NotNull ExceptionallyRunnable runnable) { return asyncRun(runnable); } - @Nonnull - static Task syncCall(@Nonnull Callable callable) { + @NotNull + static Task syncCall(@NotNull Callable callable) { return CompletableTask.callSync(callable); } - @Nonnull - static Task syncSupply(@Nonnull Supplier supplier) { + @NotNull + static Task syncSupply(@NotNull Supplier supplier) { return syncCall(supplier::get); } - @Nonnull - static Task syncRun(@Nonnull Runnable runnable) { + @NotNull + static Task syncRun(@NotNull Runnable runnable) { return syncCall(() -> { runnable.run(); return null; }); } - @Nonnull - static Task syncRunExceptionally(@Nonnull ExceptionallyRunnable runnable) { + @NotNull + static Task syncRunExceptionally(@NotNull ExceptionallyRunnable runnable) { return syncRun(runnable); } - @Nonnull - default Task onComplete(@Nonnull Runnable action) { + @NotNull + default Task onComplete(@NotNull Runnable action) { return onComplete(v -> action.run()); } - @Nonnull - default Task onComplete(@Nonnull Consumer action) { + @NotNull + default Task onComplete(@NotNull Consumer action) { return onComplete((task, value) -> action.accept(value)); } - @Nonnull - default Task onComplete(@Nonnull BiConsumer, ? super V> action) { + @NotNull + default Task onComplete(@NotNull BiConsumer, ? super V> action) { return addListener(new TaskListener() { @Override - public void onComplete(@Nonnull Task task, @Nonnull V value) { + public void onComplete(@NotNull Task task, @NotNull V value) { action.accept(task, value); } }); } - @Nonnull - default Task onFailure(@Nonnull Runnable action) { + @NotNull + default Task onFailure(@NotNull Runnable action) { return onFailure(ex -> action.run()); } - @Nonnull - default Task onFailure(@Nonnull Consumer action) { + @NotNull + default Task onFailure(@NotNull Consumer action) { return onFailure((task, ex) -> action.accept(ex)); } - @Nonnull - default Task onFailure(@Nonnull BiConsumer, ? super Throwable> action) { + @NotNull + default Task onFailure(@NotNull BiConsumer, ? super Throwable> action) { return addListener(new TaskListener() { @Override - public void onFailure(@Nonnull Task task, @Nonnull Throwable ex) { + public void onFailure(@NotNull Task task, @NotNull Throwable ex) { action.accept(task, ex); } }); } - @Nonnull + @NotNull default Task throwOnFailure() { return onFailure(ex -> ex.printStackTrace()); } - @Nonnull - default Task onCancelled(@Nonnull Runnable action) { + @NotNull + default Task onCancelled(@NotNull Runnable action) { return onCancelled(task -> action.run()); } - @Nonnull - default Task onCancelled(@Nonnull Consumer> action) { + @NotNull + default Task onCancelled(@NotNull Consumer> action) { return addListener(new TaskListener() { @Override - public void onCancelled(@Nonnull Task task) { + public void onCancelled(@NotNull Task task) { action.accept(task); } }); } - @Nonnull - default Task addListeners(@Nonnull TaskListener... listeners) { + @NotNull + default Task addListeners(@NotNull TaskListener... listeners) { for (TaskListener listener : listeners) addListener(listener); return this; } - @Nonnull - Task addListener(@Nonnull TaskListener listener); + @NotNull + Task addListener(@NotNull TaskListener listener); - @Nonnull + @NotNull Task clearListeners(); @Override V get() throws InterruptedException, ExecutionException; @Override - V get(long timeout, @Nonnull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; + V get(long timeout, @NotNull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; default V getOrDefault(V def) { try { @@ -189,7 +189,7 @@ default V getOrDefault(V def) { } } - default V getOrDefault(long timeout, @Nonnull TimeUnit unit, V def) { + default V getOrDefault(long timeout, @NotNull TimeUnit unit, V def) { try { return this.get(timeout, unit); } catch (InterruptedException ex) { @@ -199,7 +199,7 @@ default V getOrDefault(long timeout, @Nonnull TimeUnit unit, V def) { } } - default V getBeforeTimeout(long timeout, @Nonnull TimeUnit unit) { + default V getBeforeTimeout(long timeout, @NotNull TimeUnit unit) { try { return get(timeout, unit); } catch (ExecutionException | InterruptedException ex) { @@ -209,25 +209,25 @@ default V getBeforeTimeout(long timeout, @Nonnull TimeUnit unit) { } } - @Nonnull + @NotNull Task map(@Nullable Function mapper); - @Nonnull + @NotNull default Task mapExceptionally(@Nullable ExceptionallyFunction mapper) { return map(mapper); } - @Nonnull + @NotNull default Task mapVoid() { return map(v -> null); } - @Nonnull - default Task map(@Nonnull Class target) { + @NotNull + default Task map(@NotNull Class target) { return map(target::cast); } - @Nonnull + @NotNull @CheckReturnValue CompletionStage stage(); diff --git a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java index e5d87a35e..36510376c 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java +++ b/plugin/src/main/java/net/codingarea/commons/common/concurrent/task/TaskListener.java @@ -1,16 +1,16 @@ package net.codingarea.commons.common.concurrent.task; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public interface TaskListener { - default void onComplete(@Nonnull Task task, @Nonnull T value) { + default void onComplete(@NotNull Task task, @NotNull T value) { } - default void onCancelled(@Nonnull Task task) { + default void onCancelled(@NotNull Task task) { } - default void onFailure(@Nonnull Task task, @Nonnull Throwable ex) { + default void onFailure(@NotNull Task task, @NotNull Throwable ex) { } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Config.java b/plugin/src/main/java/net/codingarea/commons/common/config/Config.java index ad769e1ad..fc197429d 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/Config.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Config.java @@ -1,10 +1,10 @@ package net.codingarea.commons.common.config; import net.codingarea.commons.common.config.exceptions.ConfigReadOnlyException; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.function.Consumer; /** @@ -22,13 +22,13 @@ public interface Config extends Propertyable { * @return {@code this} for chaining * @throws ConfigReadOnlyException If this is {@link #isReadonly() readonly} */ - @Nonnull - Config set(@Nonnull String path, @Nullable Object value); + @NotNull + Config set(@NotNull String path, @Nullable Object value); /** * @throws ConfigReadOnlyException If this is {@link #isReadonly() readonly} */ - @Nonnull + @NotNull Config clear(); /** @@ -38,52 +38,52 @@ public interface Config extends Propertyable { * @return {@code this} for chaining * @throws ConfigReadOnlyException If this is {@link #isReadonly() readonly} */ - @Nonnull - Config remove(@Nonnull String path); + @NotNull + Config remove(@NotNull String path); boolean isReadonly(); /** * @return A new config which is readonly, or {@code this} if already {@link #isReadonly() readonly} */ - @Nonnull + @NotNull @CheckReturnValue Config readonly(); - @Nonnull + @NotNull @Override - default Config apply(@Nonnull Consumer action) { + default Config apply(@NotNull Consumer action) { return (Config) Propertyable.super.apply(action); } - @Nonnull + @NotNull @Override - default Config applyIf(boolean expression, @Nonnull Consumer action) { + default Config applyIf(boolean expression, @NotNull Consumer action) { return (Config) Propertyable.super.applyIf(expression, action); } - @Nonnull - default Config increment(@Nonnull String path, double amount) { + @NotNull + default Config increment(@NotNull String path, double amount) { return set(path, getDouble(path) + amount); } - @Nonnull - default Config decrement(@Nonnull String path, double amount) { + @NotNull + default Config decrement(@NotNull String path, double amount) { return set(path, getDouble(path) - amount); } - @Nonnull - default Config multiply(@Nonnull String path, double factor) { + @NotNull + default Config multiply(@NotNull String path, double factor) { return set(path, getDouble(path) * factor); } - @Nonnull - default Config divide(@Nonnull String path, double divisor) { + @NotNull + default Config divide(@NotNull String path, double divisor) { return set(path, getDouble(path) / divisor); } - @Nonnull - default Config setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { + @NotNull + default Config setIfAbsent(@NotNull String path, @NotNull Object defaultValue) { if (!contains(path)) set(path, defaultValue); return this; diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Document.java b/plugin/src/main/java/net/codingarea/commons/common/config/Document.java index dc617554f..c37ab9570 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/Document.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Document.java @@ -7,10 +7,10 @@ import net.codingarea.commons.common.config.document.PropertiesDocument; import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.commons.common.misc.GsonUtils; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.io.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -32,8 +32,8 @@ public interface Document extends Config, Json { * * @return the document assigned to this path */ - @Nonnull - Document getDocument(@Nonnull String path); + @NotNull + Document getDocument(@NotNull String path); /** * Returns the list of documents located at the given path. @@ -45,11 +45,11 @@ public interface Document extends Config, Json { * * @return the list of documents assigned to this path */ - @Nonnull - List getDocumentList(@Nonnull String path); + @NotNull + List getDocumentList(@NotNull String path); - @Nonnull - default List getInstanceList(@Nonnull String path, @Nonnull Class classOfT) { + @NotNull + default List getInstanceList(@NotNull String path, @NotNull Class classOfT) { List documents = getDocumentList(path); List result = new ArrayList<>(documents.size()); for (Document document : documents) { @@ -58,26 +58,26 @@ default List getInstanceList(@Nonnull String path, @Nonnull Class clas return result; } - @Nonnull - List getSerializableList(@Nonnull String path, @Nonnull Class classOfT); + @NotNull + List getSerializableList(@NotNull String path, @NotNull Class classOfT); @Nullable - T getSerializable(@Nonnull String path, @Nonnull Class classOfT); + T getSerializable(@NotNull String path, @NotNull Class classOfT); - @Nonnull - T getSerializable(@Nonnull String path, @Nonnull T def); + @NotNull + T getSerializable(@NotNull String path, @NotNull T def); - @Nonnull - Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper); + @NotNull + Map mapDocuments(@NotNull Function keyMapper, @NotNull Function valueMapper); - @Nonnull - R mapDocument(@Nonnull String path, @Nonnull Function mapper); + @NotNull + R mapDocument(@NotNull String path, @NotNull Function mapper); @Nullable - R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper); + R mapDocumentNullable(@NotNull String path, @NotNull Function mapper); @Nullable - T toInstanceOf(@Nonnull Class classOfT); + T toInstanceOf(@NotNull Class classOfT); /** * Returns the parent document of this document. @@ -94,75 +94,75 @@ default List getInstanceList(@Nonnull String path, @Nonnull Class clas * * @return the root document of this document */ - @Nonnull + @NotNull Document getRoot(); /** * {@inheritDoc} */ - @Nonnull + @NotNull @Override - Document set(@Nonnull String path, @Nullable Object value); + Document set(@NotNull String path, @Nullable Object value); /** * {@inheritDoc} */ - @Nonnull + @NotNull @Override Document clear(); /** * {@inheritDoc} */ - @Nonnull + @NotNull @Override - Document remove(@Nonnull String path); + Document remove(@NotNull String path); /** * {@inheritDoc} */ - @Nonnull + @NotNull @Override - default Document apply(@Nonnull Consumer action) { + default Document apply(@NotNull Consumer action) { return (Document) Config.super.apply(action); } - @Nonnull + @NotNull @Override - default Document applyIf(boolean expression, @Nonnull Consumer action) { + default Document applyIf(boolean expression, @NotNull Consumer action) { return (Document) Config.super.applyIf(expression, action); } /** * {@inheritDoc} */ - @Nonnull + @NotNull @Override - default Document setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { + default Document setIfAbsent(@NotNull String path, @NotNull Object defaultValue) { return (Document) Config.super.setIfAbsent(path, defaultValue); } - @Nonnull - Document set(@Nonnull Object value); + @NotNull + Document set(@NotNull Object value); /** * {@inheritDoc} */ - @Nonnull + @NotNull @Override @CheckReturnValue Document readonly(); - @Nonnull + @NotNull Map children(); - boolean isDocument(@Nonnull String path); + boolean isDocument(@NotNull String path); - boolean hasChildren(@Nonnull String path); + boolean hasChildren(@NotNull String path); - void write(@Nonnull Writer writer) throws IOException; + void write(@NotNull Writer writer) throws IOException; - default void saveToFile(@Nonnull File file) throws IOException { + default void saveToFile(@NotNull File file) throws IOException { FileUtils.createFilesIfNecessary(file); Writer writer = FileUtils.newBufferedWriter(file); write(writer); @@ -170,7 +170,7 @@ default void saveToFile(@Nonnull File file) throws IOException { writer.close(); } - default void saveToFile(@Nonnull Path file) throws IOException { + default void saveToFile(@NotNull Path file) throws IOException { FileUtils.createFile(file); Writer writer = FileUtils.newBufferedWriter(file); write(writer); @@ -178,20 +178,20 @@ default void saveToFile(@Nonnull Path file) throws IOException { writer.close(); } - @Nonnull + @NotNull @CheckReturnValue - default FileDocument asFileDocument(@Nonnull File file) { + default FileDocument asFileDocument(@NotNull File file) { return (this instanceof FileDocument && ((FileDocument) this).getFile().equals(file)) ? (FileDocument) this : FileDocument.wrap(this, file); } - @Nonnull + @NotNull @CheckReturnValue - default FileDocument asFileDocument(@Nonnull Path file) { + default FileDocument asFileDocument(@NotNull Path file) { return asFileDocument(file.toFile()); } - @Nonnull + @NotNull @CheckReturnValue default Document copyJson() { Document document = create(); @@ -203,15 +203,15 @@ default Document copyJson() { * @return an empty and immutable document * @see EmptyDocument */ - @Nonnull + @NotNull @CheckReturnValue static Document empty() { return EmptyDocument.ROOT; } - @Nonnull + @NotNull @CheckReturnValue - static Document readFile(@Nonnull Class classOfDocument, @Nonnull File file) { + static Document readFile(@NotNull Class classOfDocument, @NotNull File file) { try { if (file.exists()) { Constructor constructor = classOfDocument.getConstructor(File.class); @@ -227,9 +227,9 @@ static Document readFile(@Nonnull Class classOfDocument, @No } } - @Nonnull + @NotNull @CheckReturnValue - static Document readFile(@Nonnull Class classOfDocument, @Nonnull Path file) { + static Document readFile(@NotNull Class classOfDocument, @NotNull Path file) { return readFile(classOfDocument, file.toFile()); } @@ -237,37 +237,37 @@ static Document readFile(@Nonnull Class classOfDocument, @No * @return a json document parsed by the input * @see GsonDocument */ - @Nonnull + @NotNull @CheckReturnValue - static Document parseJson(@Nonnull String jsonInput) { + static Document parseJson(@NotNull String jsonInput) { return new GsonDocument(jsonInput); } - @Nonnull + @NotNull @CheckReturnValue - static Document parseJson(@Nonnull Reader reader) throws IOException { + static Document parseJson(@NotNull Reader reader) throws IOException { return new GsonDocument(reader); } - @Nonnull + @NotNull @CheckReturnValue - static Document parseJson(@Nonnull InputStream input) throws IOException { + static Document parseJson(@NotNull InputStream input) throws IOException { return new GsonDocument(new InputStreamReader(input, StandardCharsets.UTF_8)); } - @Nonnull + @NotNull @CheckReturnValue - static List parseJsonArray(@Nonnull String jsonInput) { + static List parseJsonArray(@NotNull String jsonInput) { return GsonDocument.convertArrayToDocuments(GsonDocument.GSON.fromJson(jsonInput, JsonArray.class)); } - @Nonnull + @NotNull @CheckReturnValue - static List parseStringArray(@Nonnull String jsonInput) { + static List parseStringArray(@NotNull String jsonInput) { return GsonDocument.convertArrayToStrings(GsonDocument.GSON.fromJson(jsonInput, JsonArray.class)); } - static void saveArray(@Nonnull Iterable objects, @Nonnull Path file) throws IOException { + static void saveArray(@NotNull Iterable objects, @NotNull Path file) throws IOException { FileUtils.createFile(file); Writer writer = FileUtils.newBufferedWriter(file); JsonArray array = GsonUtils.convertIterableToJsonArray(GsonDocument.GSON, objects); @@ -276,21 +276,21 @@ static void saveArray(@Nonnull Iterable objects, @Nonnull Path file) throws I writer.close(); } - @Nonnull + @NotNull @CheckReturnValue - static Document readJsonFile(@Nonnull File file) { + static Document readJsonFile(@NotNull File file) { return readFile(GsonDocument.class, file); } - @Nonnull + @NotNull @CheckReturnValue - static Document readJsonFile(@Nonnull Path file) { + static Document readJsonFile(@NotNull Path file) { return readJsonFile(file.toFile()); } - @Nonnull + @NotNull @CheckReturnValue - static List readJsonArrayFile(@Nonnull Path file) { + static List readJsonArrayFile(@NotNull Path file) { try { JsonArray array = GsonDocument.GSON.fromJson(FileUtils.newBufferedReader(file), JsonArray.class); if (array == null) return new ArrayList<>(); @@ -302,27 +302,27 @@ static List readJsonArrayFile(@Nonnull Path file) { } } - @Nonnull + @NotNull @CheckReturnValue - static Document readPropertiesFile(@Nonnull File file) { + static Document readPropertiesFile(@NotNull File file) { return readFile(PropertiesDocument.class, file); } - @Nonnull + @NotNull @CheckReturnValue - static Document readPropertiesFile(@Nonnull Path file) { + static Document readPropertiesFile(@NotNull Path file) { return readPropertiesFile(file.toFile()); } - @Nonnull + @NotNull @CheckReturnValue static Document create() { return new GsonDocument(); } - @Nonnull + @NotNull @CheckReturnValue - static Document of(@Nonnull Object object) { + static Document of(@NotNull Object object) { return new GsonDocument(object); } @@ -332,9 +332,9 @@ static Document ofNullable(@Nullable Object object) { return object == null ? null : of(object); } - @Nonnull + @NotNull @CheckReturnValue - static List arrayOf(@Nonnull Collection objects) { + static List arrayOf(@NotNull Collection objects) { List documents = new ArrayList<>(objects.size()); objects.forEach(object -> documents.add(Document.of(object))); return documents; diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java index 0a568223a..09ecfb8b1 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/FileDocument.java @@ -5,10 +5,10 @@ import net.codingarea.commons.common.config.document.PropertiesDocument; import net.codingarea.commons.common.config.document.wrapper.FileDocumentWrapper; import net.codingarea.commons.common.logging.ILogger; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.nio.file.Path; @@ -38,7 +38,7 @@ default void save() { } } - @Nonnull + @NotNull default Task saveAsync() { return Task.asyncRunExceptionally(this::save); } @@ -53,118 +53,118 @@ default void save(boolean async) { else save(); } - @Nonnull + @NotNull File getFile(); - @Nonnull + @NotNull Path getPath(); /** * {@inheritDoc} */ - @Nonnull + @NotNull @Override - FileDocument set(@Nonnull String path, @Nullable Object value); + FileDocument set(@NotNull String path, @Nullable Object value); /** * {@inheritDoc} */ - @Nonnull + @NotNull @Override - FileDocument set(@Nonnull Object value); + FileDocument set(@NotNull Object value); /** * {@inheritDoc} */ - @Nonnull + @NotNull @Override FileDocument clear(); /** * {@inheritDoc} */ - @Nonnull + @NotNull @Override - FileDocument remove(@Nonnull String path); + FileDocument remove(@NotNull String path); /** * {@inheritDoc} */ - @Nonnull + @NotNull @Override - default FileDocument apply(@Nonnull Consumer action) { + default FileDocument apply(@NotNull Consumer action) { return (FileDocument) Document.super.apply(action); } - @Nonnull + @NotNull @Override - default FileDocument setIfAbsent(@Nonnull String path, @Nonnull Object defaultValue) { + default FileDocument setIfAbsent(@NotNull String path, @NotNull Object defaultValue) { return (FileDocument) Document.super.setIfAbsent(path, defaultValue); } - @Nonnull + @NotNull @Override - default FileDocument increment(@Nonnull String path, double amount) { + default FileDocument increment(@NotNull String path, double amount) { return (FileDocument) Document.super.increment(path, amount); } - @Nonnull + @NotNull @Override - default FileDocument decrement(@Nonnull String path, double amount) { + default FileDocument decrement(@NotNull String path, double amount) { return (FileDocument) Document.super.decrement(path, amount); } - @Nonnull + @NotNull @Override - default FileDocument multiply(@Nonnull String path, double factor) { + default FileDocument multiply(@NotNull String path, double factor) { return (FileDocument) Document.super.multiply(path, factor); } - @Nonnull + @NotNull @Override - default FileDocument divide(@Nonnull String path, double divisor) { + default FileDocument divide(@NotNull String path, double divisor) { return (FileDocument) Document.super.divide(path, divisor); } - @Nonnull + @NotNull @CheckReturnValue - static FileDocument wrap(@Nonnull Document document, @Nonnull File file) { + static FileDocument wrap(@NotNull Document document, @NotNull File file) { return new FileDocumentWrapper(file, document); } - @Nonnull + @NotNull @CheckReturnValue - static FileDocument readFile(@Nonnull Class classOfDocument, @Nonnull File file) { + static FileDocument readFile(@NotNull Class classOfDocument, @NotNull File file) { return Document.readFile(classOfDocument, file).asFileDocument(file); } - @Nonnull + @NotNull @CheckReturnValue - static FileDocument readFile(@Nonnull Class classOfDocument, @Nonnull Path file) { + static FileDocument readFile(@NotNull Class classOfDocument, @NotNull Path file) { return Document.readFile(classOfDocument, file).asFileDocument(file); } - @Nonnull + @NotNull @CheckReturnValue - static FileDocument readJsonFile(@Nonnull File file) { + static FileDocument readJsonFile(@NotNull File file) { return readFile(GsonDocument.class, file); } - @Nonnull + @NotNull @CheckReturnValue - static FileDocument readJsonFile(@Nonnull Path file) { + static FileDocument readJsonFile(@NotNull Path file) { return readFile(GsonDocument.class, file); } - @Nonnull + @NotNull @CheckReturnValue - static FileDocument readPropertiesFile(@Nonnull File file) { + static FileDocument readPropertiesFile(@NotNull File file) { return readFile(PropertiesDocument.class, file); } - @Nonnull + @NotNull @CheckReturnValue - static FileDocument readPropertiesFile(@Nonnull Path file) { + static FileDocument readPropertiesFile(@NotNull Path file) { return readFile(PropertiesDocument.class, file); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Json.java b/plugin/src/main/java/net/codingarea/commons/common/config/Json.java index a0090052f..2900fb681 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/Json.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Json.java @@ -1,7 +1,8 @@ package net.codingarea.commons.common.config; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; + import java.util.function.Supplier; /** @@ -9,29 +10,29 @@ */ public interface Json { - @Nonnull + @NotNull String toJson(); - @Nonnull + @NotNull String toPrettyJson(); - @Nonnull + @NotNull @CheckReturnValue static Json empty() { return constant("{}", "{}"); } - @Nonnull + @NotNull @CheckReturnValue - static Json supply(@Nonnull Supplier normal, @Nonnull Supplier pretty) { + static Json supply(@NotNull Supplier normal, @NotNull Supplier pretty) { return new Json() { - @Nonnull + @NotNull @Override public String toJson() { return normal.get(); } - @Nonnull + @NotNull @Override public String toPrettyJson() { return pretty.get(); @@ -39,9 +40,9 @@ public String toPrettyJson() { }; } - @Nonnull + @NotNull @CheckReturnValue - static Json constant(@Nonnull String json, @Nonnull String prettyJson) { + static Json constant(@NotNull String json, @NotNull String prettyJson) { return supply(() -> json, () -> prettyJson); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java b/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java index 58ce3da88..fac94b441 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/PropertyHelper.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.config; -import javax.annotation.Nullable; +import org.jetbrains.annotations.Nullable; + import java.awt.*; import java.lang.reflect.Type; import java.text.DateFormat; diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java b/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java index 1a22c1308..4fe2f45e6 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Propertyable.java @@ -1,10 +1,9 @@ package net.codingarea.commons.common.config; import net.codingarea.commons.common.version.Version; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.awt.*; import java.time.OffsetDateTime; import java.util.*; @@ -21,179 +20,178 @@ */ public interface Propertyable { - T getInstance(@Nonnull String path, @Nonnull Class classOfT); + T getInstance(@NotNull String path, @NotNull Class classOfT); @Nullable - Object getObject(@Nonnull String path); + Object getObject(@NotNull String path); - @Nonnull - Object getObject(@Nonnull String path, @Nonnull Object def); + @NotNull + Object getObject(@NotNull String path, @NotNull Object def); - @Nonnull + @NotNull @SuppressWarnings("unchecked") - default Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { + default Optional getOptional(@NotNull String key, @NotNull BiFunction extractor) { return Optional.ofNullable(extractor.apply((O) this, key)); } - @Nonnull + @NotNull @SuppressWarnings("unchecked") - default Propertyable apply(@Nonnull Consumer action) { + default Propertyable apply(@NotNull Consumer action) { action.accept((O) this); return this; } - @Nonnull - default Propertyable applyIf(boolean expression, @Nonnull Consumer action) { + @NotNull + default Propertyable applyIf(boolean expression, @NotNull Consumer action) { if (expression) apply(action); return this; } @Nullable - String getString(@Nonnull String path); + String getString(@NotNull String path); - @Nonnull - String getString(@Nonnull String path, @Nonnull String def); + @NotNull + String getString(@NotNull String path, @NotNull String def); @Nullable - byte[] getBinary(@Nonnull String path); + byte[] getBinary(@NotNull String path); - char getChar(@Nonnull String path); + char getChar(@NotNull String path); - char getChar(@Nonnull String path, char def); + char getChar(@NotNull String path, char def); - long getLong(@Nonnull String path); + long getLong(@NotNull String path); - long getLong(@Nonnull String path, long def); + long getLong(@NotNull String path, long def); - int getInt(@Nonnull String path); + int getInt(@NotNull String path); - int getInt(@Nonnull String path, int def); + int getInt(@NotNull String path, int def); - short getShort(@Nonnull String path); + short getShort(@NotNull String path); - short getShort(@Nonnull String path, short def); + short getShort(@NotNull String path, short def); - byte getByte(@Nonnull String path); + byte getByte(@NotNull String path); - byte getByte(@Nonnull String path, byte def); + byte getByte(@NotNull String path, byte def); - float getFloat(@Nonnull String path); + float getFloat(@NotNull String path); - float getFloat(@Nonnull String path, float def); + float getFloat(@NotNull String path, float def); - double getDouble(@Nonnull String path); + double getDouble(@NotNull String path); - double getDouble(@Nonnull String path, double def); + double getDouble(@NotNull String path, double def); - boolean getBoolean(@Nonnull String path); + boolean getBoolean(@NotNull String path); - boolean getBoolean(@Nonnull String path, boolean def); + boolean getBoolean(@NotNull String path, boolean def); - @Nonnull - List getStringList(@Nonnull String path); + @NotNull + List getStringList(@NotNull String path); - @Nonnull - String[] getStringArray(@Nonnull String path); + @NotNull + String[] getStringArray(@NotNull String path); - @Nonnull - > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum); + @NotNull + > List getEnumList(@NotNull String path, @NotNull Class classOfEnum); - @Nonnull - List getUUIDList(@Nonnull String path); + @NotNull + List getUUIDList(@NotNull String path); - @Nonnull - List getCharacterList(@Nonnull String path); + @NotNull + List getCharacterList(@NotNull String path); - @Nonnull - List getByteList(@Nonnull String path); + @NotNull + List getByteList(@NotNull String path); - @Nonnull - List getShortList(@Nonnull String path); + @NotNull + List getShortList(@NotNull String path); - @Nonnull - List getIntegerList(@Nonnull String path); + @NotNull + List getIntegerList(@NotNull String path); - @Nonnull - List getLongList(@Nonnull String path); + @NotNull + List getLongList(@NotNull String path); - @Nonnull - List getFloatList(@Nonnull String path); + @NotNull + List getFloatList(@NotNull String path); - @Nonnull - List getDoubleList(@Nonnull String path); + @NotNull + List getDoubleList(@NotNull String path); @Nullable - UUID getUUID(@Nonnull String path); + UUID getUUID(@NotNull String path); - @Nonnull - UUID getUUID(@Nonnull String path, @Nonnull UUID def); + @NotNull + UUID getUUID(@NotNull String path, @NotNull UUID def); @Nullable - OffsetDateTime getDateTime(@Nonnull String path); + OffsetDateTime getDateTime(@NotNull String path); - @Nonnull - OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def); + @NotNull + OffsetDateTime getDateTime(@NotNull String path, @NotNull OffsetDateTime def); @Nullable - Date getDate(@Nonnull String path); + Date getDate(@NotNull String path); - @Nonnull - Date getDate(@Nonnull String path, @Nonnull Date def); + @NotNull + Date getDate(@NotNull String path, @NotNull Date def); @Nullable - Color getColor(@Nonnull String path); + Color getColor(@NotNull String path); - @Nonnull - Color getColor(@Nonnull String path, @Nonnull Color def); + @NotNull + Color getColor(@NotNull String path, @NotNull Color def); @Nullable - > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum); + > E getEnum(@NotNull String path, @NotNull Class classOfEnum); - @Nonnull - > E getEnum(@Nonnull String path, @Nonnull E def); + @NotNull + > E getEnum(@NotNull String path, @NotNull E def); @Nullable - Class getClass(@Nonnull String path); + Class getClass(@NotNull String path); - @Nonnull - Class getClass(@Nonnull String path, @Nonnull Class def); + @NotNull + Class getClass(@NotNull String path, @NotNull Class def); @Nullable - Version getVersion(@Nonnull String path); + Version getVersion(@NotNull String path); - @Nonnull - Version getVersion(@Nonnull String path, @Nonnull Version def); + @NotNull + Version getVersion(@NotNull String path, @NotNull Version def); - boolean isList(@Nonnull String path); + boolean isList(@NotNull String path); - boolean isObject(@Nonnull String path); + boolean isObject(@NotNull String path); - boolean contains(@Nonnull String path); + boolean contains(@NotNull String path); boolean isEmpty(); - @Nonnegative int size(); - @Nonnull + @NotNull Map values(); - @Nonnull + @NotNull Map valuesAsStrings(); - @Nonnull - Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper); + @NotNull + Map mapValues(@NotNull Function keyMapper, @NotNull Function valueMapper); - @Nonnull - List mapList(@Nonnull String path, @Nonnull Function mapper); + @NotNull + List mapList(@NotNull String path, @NotNull Function mapper); - @Nonnull + @NotNull Collection keys(); - @Nonnull + @NotNull Set> entrySet(); - void forEach(@Nonnull BiConsumer action); + void forEach(@NotNull BiConsumer action); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java index 1c8176767..e77a026a1 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractConfig.java @@ -4,9 +4,9 @@ import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.misc.ReflectionUtils; import net.codingarea.commons.common.version.Version; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.awt.*; import java.time.OffsetDateTime; import java.util.*; @@ -19,32 +19,32 @@ public abstract class AbstractConfig implements Config { protected static final ILogger logger = ILogger.forThisClass(); - @Nonnull - protected T getDef(@Nonnull T def, @Nonnull Supplier getter) { + @NotNull + protected T getDef(@NotNull T def, @NotNull Supplier getter) { T value = getter.get(); return value == null ? def : value; } - @Nonnull + @NotNull @Override - public Object getObject(@Nonnull String path, @Nonnull Object def) { + public Object getObject(@NotNull String path, @NotNull Object def) { Object value = getObject(path); return value == null ? def : value; } - @Nonnull + @NotNull @Override - public String getString(@Nonnull String path, @Nonnull String def) { + public String getString(@NotNull String path, @NotNull String def) { return getDef(def, () -> getString(path)); } @Override - public char getChar(@Nonnull String path) { + public char getChar(@NotNull String path) { return getChar(path, (char) 0); } @Override - public char getChar(@Nonnull String path, char def) { + public char getChar(@NotNull String path, char def) { try { return getString(path).charAt(0); } catch (NullPointerException | IndexOutOfBoundsException ex) { @@ -53,80 +53,80 @@ public char getChar(@Nonnull String path, char def) { } @Override - public double getDouble(@Nonnull String path) { + public double getDouble(@NotNull String path) { return getDouble(path, 0); } @Override - public float getFloat(@Nonnull String path) { + public float getFloat(@NotNull String path) { return getFloat(path, 0); } @Override - public long getLong(@Nonnull String path) { + public long getLong(@NotNull String path) { return getLong(path, 0); } @Override - public int getInt(@Nonnull String path) { + public int getInt(@NotNull String path) { return getInt(path, 0); } @Override - public short getShort(@Nonnull String path) { + public short getShort(@NotNull String path) { return getShort(path, (short) 0); } @Override - public byte getByte(@Nonnull String path) { + public byte getByte(@NotNull String path) { return getByte(path, (byte) 0); } @Override - public boolean getBoolean(@Nonnull String path) { + public boolean getBoolean(@NotNull String path) { return getBoolean(path, false); } - @Nonnull + @NotNull @Override - public UUID getUUID(@Nonnull String path, @Nonnull UUID def) { + public UUID getUUID(@NotNull String path, @NotNull UUID def) { return getDef(def, () -> getUUID(path)); } - @Nonnull + @NotNull @Override - public OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { + public OffsetDateTime getDateTime(@NotNull String path, @NotNull OffsetDateTime def) { return getDef(def, () -> getDateTime(path)); } - @Nonnull + @NotNull @Override - public Date getDate(@Nonnull String path, @Nonnull Date def) { + public Date getDate(@NotNull String path, @NotNull Date def) { return getDef(def, () -> getDate(path)); } - @Nonnull + @NotNull @Override - public Color getColor(@Nonnull String path, @Nonnull Color def) { + public Color getColor(@NotNull String path, @NotNull Color def) { return getDef(def, () -> getColor(path)); } @Nullable @Override - public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + public > E getEnum(@NotNull String path, @NotNull Class classOfEnum) { return ReflectionUtils.getEnumOrNull(getString(path), classOfEnum); } - @Nonnull + @NotNull @Override - public > E getEnum(@Nonnull String path, @Nonnull E def) { + public > E getEnum(@NotNull String path, @NotNull E def) { E value = getEnum(path, def.getDeclaringClass()); return value == null ? def : value; } @Nullable @Override - public Class getClass(@Nonnull String path) { + public Class getClass(@NotNull String path) { try { return Class.forName(getString(path)); } catch (Exception ex) { @@ -134,95 +134,95 @@ public Class getClass(@Nonnull String path) { } } - @Nonnull + @NotNull @Override - public Class getClass(@Nonnull String path, @Nonnull Class def) { + public Class getClass(@NotNull String path, @NotNull Class def) { return getDef(def, () -> getClass(path)); } @Nullable @Override - public Version getVersion(@Nonnull String path) { + public Version getVersion(@NotNull String path) { return Version.parse(getString(path), null); } - @Nonnull + @NotNull @Override - public Version getVersion(@Nonnull String path, @Nonnull Version def) { + public Version getVersion(@NotNull String path, @NotNull Version def) { return getDef(def, () -> getVersion(path)); } @Nullable @Override - public byte[] getBinary(@Nonnull String path) { + public byte[] getBinary(@NotNull String path) { String string = getString(path); if (string == null) return null; return Base64.getDecoder().decode(string); } - @Nonnull + @NotNull @Override - public String[] getStringArray(@Nonnull String path) { + public String[] getStringArray(@NotNull String path) { return getStringList(path).toArray(new String[0]); } - @Nonnull + @NotNull @Override - public > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { + public > List getEnumList(@NotNull String path, @NotNull Class classOfEnum) { return mapList(path, name -> ReflectionUtils.getEnumOrNull(name, classOfEnum)); } - @Nonnull + @NotNull @Override - public List getCharacterList(@Nonnull String path) { + public List getCharacterList(@NotNull String path) { return mapList(path, string -> string == null || string.length() == 0 ? (char) 0 : string.charAt(0)); } - @Nonnull + @NotNull @Override - public List getUUIDList(@Nonnull String path) { + public List getUUIDList(@NotNull String path) { return mapList(path, UUID::fromString); } - @Nonnull + @NotNull @Override - public List getByteList(@Nonnull String path) { + public List getByteList(@NotNull String path) { return mapList(path, Byte::parseByte); } - @Nonnull + @NotNull @Override - public List getShortList(@Nonnull String path) { + public List getShortList(@NotNull String path) { return mapList(path, Short::parseShort); } - @Nonnull + @NotNull @Override - public List getIntegerList(@Nonnull String path) { + public List getIntegerList(@NotNull String path) { return mapList(path, Integer::parseInt); } - @Nonnull + @NotNull @Override - public List getLongList(@Nonnull String path) { + public List getLongList(@NotNull String path) { return mapList(path, Long::parseLong); } - @Nonnull + @NotNull @Override - public List getFloatList(@Nonnull String path) { + public List getFloatList(@NotNull String path) { return mapList(path, Float::parseFloat); } - @Nonnull + @NotNull @Override - public List getDoubleList(@Nonnull String path) { + public List getDoubleList(@NotNull String path) { return mapList(path, Double::parseDouble); } - @Nonnull + @NotNull @Override - public List mapList(@Nonnull String path, @Nonnull Function mapper) { + public List mapList(@NotNull String path, @NotNull Function mapper) { List list = getStringList(path); List result = new ArrayList<>(list.size()); for (String string : list) { @@ -240,7 +240,7 @@ public boolean isEmpty() { return size() == 0; } - @Nonnull + @NotNull @Override public Map valuesAsStrings() { Map map = new HashMap<>(); @@ -248,22 +248,22 @@ public Map valuesAsStrings() { return map; } - @Nonnull + @NotNull @Override - public Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + public Map mapValues(@NotNull Function keyMapper, @NotNull Function valueMapper) { return map(valuesAsStrings(), keyMapper, valueMapper); } - @Nonnull + @NotNull @Override public Set> entrySet() { return values().entrySet(); } - @Nonnull - public Map map(@Nonnull Map values, - @Nonnull Function keyMapper, - @Nonnull Function valueMapper) { + @NotNull + public Map map(@NotNull Map values, + @NotNull Function keyMapper, + @NotNull Function valueMapper) { Map result = new HashMap<>(); values.forEach((key, value) -> { try { diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java index 6ab9842e1..f79c22d3b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/AbstractDocument.java @@ -4,10 +4,9 @@ import net.codingarea.commons.common.config.document.readonly.ReadOnlyDocumentWrapper; import net.codingarea.commons.common.config.exceptions.ConfigReadOnlyException; import net.codingarea.commons.common.misc.BukkitReflectionSerializationUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Base64; import java.util.HashMap; import java.util.List; @@ -19,7 +18,7 @@ public abstract class AbstractDocument extends AbstractConfig implements Documen protected final Document root, parent; - public AbstractDocument(@Nonnull Document root, @Nullable Document parent) { + public AbstractDocument(@NotNull Document root, @Nullable Document parent) { this.root = root; this.parent = parent; } @@ -29,59 +28,59 @@ public AbstractDocument() { this.parent = null; } - @Nonnull + @NotNull @Override - public T getSerializable(@Nonnull String path, @Nonnull T def) { + public T getSerializable(@NotNull String path, @NotNull T def) { T value = getSerializable(path, (Class) def.getClass()); return value == null ? def : value; } @Nullable @Override - public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + public T getSerializable(@NotNull String path, @NotNull Class classOfT) { if (!contains(path)) return null; return BukkitReflectionSerializationUtils.deserializeObject(getDocument(path).values(), classOfT); } - @Nonnull + @NotNull @Override - public List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { + public List getSerializableList(@NotNull String path, @NotNull Class classOfT) { return getDocumentList(path).stream() .map(Document::values) .map(map -> BukkitReflectionSerializationUtils.deserializeObject(map, classOfT)) .collect(Collectors.toList()); } - @Nonnull + @NotNull @Override - public Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + public Map mapDocuments(@NotNull Function keyMapper, @NotNull Function valueMapper) { return map(children(), keyMapper, valueMapper); } - @Nonnull + @NotNull @Override - public R mapDocument(@Nonnull String path, @Nonnull Function mapper) { + public R mapDocument(@NotNull String path, @NotNull Function mapper) { Document document = getDocument(path); return mapper.apply(document); } @Nullable @Override - public R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { + public R mapDocumentNullable(@NotNull String path, @NotNull Function mapper) { if (!contains(path)) return null; return mapDocument(path, mapper); } - @Nonnull + @NotNull @Override - public Document getDocument(@Nonnull String path) { + public Document getDocument(@NotNull String path) { Document document = getDocument0(path, root, this); return isReadonly() && !document.isReadonly() ? new ReadOnlyDocumentWrapper(document) : document; } - @Nonnull + @NotNull @Override - public Document set(@Nonnull String path, @Nullable Object value) { + public Document set(@NotNull String path, @Nullable Object value) { if (isReadonly()) throw new ConfigReadOnlyException("set"); if (value instanceof byte[]) @@ -91,24 +90,24 @@ public Document set(@Nonnull String path, @Nullable Object value) { return this; } - @Nonnull + @NotNull @Override - public Document set(@Nonnull Object object) { + public Document set(@NotNull Object object) { if (isReadonly()) throw new ConfigReadOnlyException("set"); Document.of(object).forEach(this::set); return this; } - @Nonnull + @NotNull @Override - public Document remove(@Nonnull String path) { + public Document remove(@NotNull String path) { if (isReadonly()) throw new ConfigReadOnlyException("remove"); remove0(path); return this; } - @Nonnull + @NotNull @Override public Document clear() { if (isReadonly()) throw new ConfigReadOnlyException("clear"); @@ -116,22 +115,22 @@ public Document clear() { return this; } - @Nonnull - @CheckReturnValue + @NotNull + @Override public Document readonly() { return isReadonly() ? this : new ReadOnlyDocumentWrapper(this); } - @Nonnull - protected abstract Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent); + @NotNull + protected abstract Document getDocument0(@NotNull String path, @NotNull Document root, @Nullable Document parent); - protected abstract void set0(@Nonnull String path, @Nullable Object value); + protected abstract void set0(@NotNull String path, @Nullable Object value); - protected abstract void remove0(@Nonnull String path); + protected abstract void remove0(@NotNull String path); protected abstract void clear0(); - @Nonnull + @NotNull @Override public Map children() { Map map = new HashMap<>(); @@ -143,11 +142,11 @@ public Map children() { } @Override - public boolean hasChildren(@Nonnull String path) { + public boolean hasChildren(@NotNull String path) { return !getDocument(path).isEmpty(); } - @Nonnull + @NotNull @Override public Document getRoot() { return root; diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java index 42a9acb81..b27bb1b0f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/EmptyDocument.java @@ -4,9 +4,9 @@ import net.codingarea.commons.common.config.Propertyable; import net.codingarea.commons.common.config.exceptions.ConfigReadOnlyException; import net.codingarea.commons.common.version.Version; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.awt.*; import java.io.File; import java.io.IOException; @@ -25,7 +25,7 @@ public class EmptyDocument implements Document { protected final Document root, parent; - public EmptyDocument(@Nonnull Document root, @Nullable Document parent) { + public EmptyDocument(@NotNull Document root, @Nullable Document parent) { this.root = root; this.parent = parent; } @@ -35,366 +35,366 @@ public EmptyDocument() { this.parent = null; } - @Nonnull + @NotNull @Override - public Document getDocument(@Nonnull String path) { + public Document getDocument(@NotNull String path) { return new EmptyDocument(); } - @Nonnull + @NotNull @Override - public R mapDocument(@Nonnull String path, @Nonnull Function mapper) { + public R mapDocument(@NotNull String path, @NotNull Function mapper) { return mapper.apply(Document.empty()); } @Nullable @Override - public R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { + public R mapDocumentNullable(@NotNull String path, @NotNull Function mapper) { return null; } - @Nonnull + @NotNull @Override - public List getDocumentList(@Nonnull String path) { + public List getDocumentList(@NotNull String path) { return new ArrayList<>(); } - @Nonnull + @NotNull @Override - public List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { + public List getSerializableList(@NotNull String path, @NotNull Class classOfT) { return new ArrayList<>(); } - @Nonnull + @NotNull @Override - public Document set(@Nonnull String path, @Nullable Object value) { + public Document set(@NotNull String path, @Nullable Object value) { throw new ConfigReadOnlyException("set"); } - @Nonnull + @NotNull @Override - public Document set(@Nonnull Object value) { + public Document set(@NotNull Object value) { throw new ConfigReadOnlyException("set"); } - @Nonnull + @NotNull @Override public Document clear() { return this; } - @Nonnull + @NotNull @Override - public Document remove(@Nonnull String path) { + public Document remove(@NotNull String path) { return this; } @Override - public void write(@Nonnull Writer writer) throws IOException { + public void write(@NotNull Writer writer) throws IOException { throw new UnsupportedOperationException("EmptyDocument.write(Writer)"); } @Override - public void saveToFile(@Nonnull File file) throws IOException { + public void saveToFile(@NotNull File file) throws IOException { throw new UnsupportedOperationException("EmptyDocument.save(File)"); } @Nullable @Override - public Object getObject(@Nonnull String path) { + public Object getObject(@NotNull String path) { return null; } - @Nonnull + @NotNull @Override - public Object getObject(@Nonnull String path, @Nonnull Object def) { + public Object getObject(@NotNull String path, @NotNull Object def) { return def; } @Override - public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + public T getInstance(@NotNull String path, @NotNull Class classOfT) { return null; } @Override - public T toInstanceOf(@Nonnull Class classOfT) { + public T toInstanceOf(@NotNull Class classOfT) { throw new UnsupportedOperationException(); } - @Nonnull + @NotNull @Override - public Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { + public Optional getOptional(@NotNull String key, @NotNull BiFunction extractor) { return Optional.empty(); } @Nullable @Override - public String getString(@Nonnull String path) { + public String getString(@NotNull String path) { return null; } - @Nonnull + @NotNull @Override - public String getString(@Nonnull String path, @Nonnull String def) { + public String getString(@NotNull String path, @NotNull String def) { return def; } @Override - public char getChar(@Nonnull String path) { + public char getChar(@NotNull String path) { return 0; } @Override - public char getChar(@Nonnull String path, char def) { + public char getChar(@NotNull String path, char def) { return def; } @Override - public long getLong(@Nonnull String path) { + public long getLong(@NotNull String path) { return 0; } @Override - public long getLong(@Nonnull String path, long def) { + public long getLong(@NotNull String path, long def) { return def; } @Override - public int getInt(@Nonnull String path) { + public int getInt(@NotNull String path) { return 0; } @Override - public int getInt(@Nonnull String path, int def) { + public int getInt(@NotNull String path, int def) { return def; } @Override - public short getShort(@Nonnull String path) { + public short getShort(@NotNull String path) { return 0; } @Override - public short getShort(@Nonnull String path, short def) { + public short getShort(@NotNull String path, short def) { return def; } @Override - public byte getByte(@Nonnull String path) { + public byte getByte(@NotNull String path) { return 0; } @Override - public byte getByte(@Nonnull String path, byte def) { + public byte getByte(@NotNull String path, byte def) { return def; } @Override - public float getFloat(@Nonnull String path) { + public float getFloat(@NotNull String path) { return 0; } @Override - public float getFloat(@Nonnull String path, float def) { + public float getFloat(@NotNull String path, float def) { return def; } @Override - public double getDouble(@Nonnull String path) { + public double getDouble(@NotNull String path) { return 0; } @Override - public double getDouble(@Nonnull String path, double def) { + public double getDouble(@NotNull String path, double def) { return def; } @Override - public boolean getBoolean(@Nonnull String path) { + public boolean getBoolean(@NotNull String path) { return false; } @Override - public boolean getBoolean(@Nonnull String path, boolean def) { + public boolean getBoolean(@NotNull String path, boolean def) { return def; } @Nullable @Override - public byte[] getBinary(@Nonnull String path) { + public byte[] getBinary(@NotNull String path) { return null; } - @Nonnull + @NotNull @Override - public List getStringList(@Nonnull String path) { + public List getStringList(@NotNull String path) { return new ArrayList<>(); } - @Nonnull + @NotNull @Override - public String[] getStringArray(@Nonnull String path) { + public String[] getStringArray(@NotNull String path) { return new String[0]; } - @Nonnull + @NotNull @Override - public > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { + public > List getEnumList(@NotNull String path, @NotNull Class classOfEnum) { return new ArrayList<>(); } - @Nonnull + @NotNull @Override - public List mapList(@Nonnull String path, @Nonnull Function mapper) { + public List mapList(@NotNull String path, @NotNull Function mapper) { return new ArrayList<>(); } - @Nonnull + @NotNull @Override - public List getUUIDList(@Nonnull String path) { + public List getUUIDList(@NotNull String path) { return new ArrayList<>(); } - @Nonnull + @NotNull @Override - public List getCharacterList(@Nonnull String path) { + public List getCharacterList(@NotNull String path) { return new ArrayList<>(); } - @Nonnull + @NotNull @Override - public List getByteList(@Nonnull String path) { + public List getByteList(@NotNull String path) { return new ArrayList<>(); } - @Nonnull + @NotNull @Override - public List getShortList(@Nonnull String path) { + public List getShortList(@NotNull String path) { return new ArrayList<>(); } - @Nonnull + @NotNull @Override - public List getIntegerList(@Nonnull String path) { + public List getIntegerList(@NotNull String path) { return new ArrayList<>(); } - @Nonnull + @NotNull @Override - public List getLongList(@Nonnull String path) { + public List getLongList(@NotNull String path) { return new ArrayList<>(); } - @Nonnull + @NotNull @Override - public List getFloatList(@Nonnull String path) { + public List getFloatList(@NotNull String path) { return new ArrayList<>(); } - @Nonnull + @NotNull @Override - public List getDoubleList(@Nonnull String path) { + public List getDoubleList(@NotNull String path) { return new ArrayList<>(); } @Nullable @Override - public UUID getUUID(@Nonnull String path) { + public UUID getUUID(@NotNull String path) { return null; } - @Nonnull + @NotNull @Override - public UUID getUUID(@Nonnull String path, @Nonnull UUID def) { + public UUID getUUID(@NotNull String path, @NotNull UUID def) { return def; } @Nullable @Override - public Date getDate(@Nonnull String path) { + public Date getDate(@NotNull String path) { return null; } - @Nonnull + @NotNull @Override - public Date getDate(@Nonnull String path, @Nonnull Date def) { + public Date getDate(@NotNull String path, @NotNull Date def) { return def; } @Nullable @Override - public OffsetDateTime getDateTime(@Nonnull String path) { + public OffsetDateTime getDateTime(@NotNull String path) { return null; } - @Nonnull + @NotNull @Override - public OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { + public OffsetDateTime getDateTime(@NotNull String path, @NotNull OffsetDateTime def) { return def; } @Nullable @Override - public Color getColor(@Nonnull String path) { + public Color getColor(@NotNull String path) { return null; } - @Nonnull + @NotNull @Override - public Color getColor(@Nonnull String path, @Nonnull Color def) { + public Color getColor(@NotNull String path, @NotNull Color def) { return def; } @Nullable @Override - public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + public > E getEnum(@NotNull String path, @NotNull Class classOfEnum) { return null; } - @Nonnull + @NotNull @Override - public > E getEnum(@Nonnull String path, @Nonnull E def) { + public > E getEnum(@NotNull String path, @NotNull E def) { return def; } @Nullable @Override - public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + public T getSerializable(@NotNull String path, @NotNull Class classOfT) { return null; } - @Nonnull + @NotNull @Override - public T getSerializable(@Nonnull String path, @Nonnull T def) { + public T getSerializable(@NotNull String path, @NotNull T def) { return def; } @Nullable @Override - public Class getClass(@Nonnull String path) { + public Class getClass(@NotNull String path) { return null; } - @Nonnull + @NotNull @Override - public Class getClass(@Nonnull String path, @Nonnull Class def) { + public Class getClass(@NotNull String path, @NotNull Class def) { return def; } @Nullable @Override - public Version getVersion(@Nonnull String path) { + public Version getVersion(@NotNull String path) { return null; } - @Nonnull + @NotNull @Override - public Version getVersion(@Nonnull String path, @Nonnull Version def) { + public Version getVersion(@NotNull String path, @NotNull Version def) { return def; } @Override - public boolean contains(@Nonnull String path) { + public boolean contains(@NotNull String path) { return false; } @@ -404,22 +404,22 @@ public boolean isEmpty() { } @Override - public boolean hasChildren(@Nonnull String path) { + public boolean hasChildren(@NotNull String path) { return false; } @Override - public boolean isList(@Nonnull String path) { + public boolean isList(@NotNull String path) { return false; } @Override - public boolean isObject(@Nonnull String path) { + public boolean isObject(@NotNull String path) { return false; } @Override - public boolean isDocument(@Nonnull String path) { + public boolean isDocument(@NotNull String path) { return false; } @@ -428,65 +428,65 @@ public int size() { return 0; } - @Nonnull + @NotNull @Override public Map values() { return Collections.emptyMap(); } - @Nonnull + @NotNull @Override public Map valuesAsStrings() { return new HashMap<>(); } - @Nonnull + @NotNull @Override public Map children() { return new HashMap<>(); } - @Nonnull + @NotNull @Override - public Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + public Map mapValues(@NotNull Function keyMapper, @NotNull Function valueMapper) { return new HashMap<>(); } - @Nonnull + @NotNull @Override - public Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + public Map mapDocuments(@NotNull Function keyMapper, @NotNull Function valueMapper) { return new HashMap<>(); } - @Nonnull + @NotNull @Override public Collection keys() { return Collections.emptyList(); } - @Nonnull + @NotNull @Override public Set> entrySet() { return Collections.emptySet(); } @Override - public void forEach(@Nonnull BiConsumer action) { + public void forEach(@NotNull BiConsumer action) { } - @Nonnull + @NotNull @Override public String toJson() { return "{}"; } - @Nonnull + @NotNull @Override public String toPrettyJson() { return "{}"; } - @Nonnull + @NotNull @Override public String toString() { return "{}"; @@ -497,7 +497,7 @@ public boolean isReadonly() { return true; } - @Nonnull + @NotNull @Override public Document readonly() { return this; @@ -509,7 +509,7 @@ public Document getParent() { return parent; } - @Nonnull + @NotNull @Override public Document getRoot() { return root; diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java index 92a957a2f..800d3c4ad 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java @@ -12,9 +12,9 @@ import net.codingarea.commons.common.misc.BukkitReflectionSerializationUtils; import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.commons.common.misc.GsonUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.awt.*; import java.io.*; import java.time.OffsetDateTime; @@ -85,8 +85,8 @@ public static boolean isWritePrettyJson() { return writePrettyJson; } - @Nonnull - public static List convertArrayToDocuments(@Nonnull JsonArray array) { + @NotNull + public static List convertArrayToDocuments(@NotNull JsonArray array) { List list = new ArrayList<>(array.size()); for (JsonElement element : array) { if (!element.isJsonObject()) continue; @@ -95,8 +95,8 @@ public static List convertArrayToDocuments(@Nonnull JsonArray array) { return list; } - @Nonnull - public static List convertArrayToStrings(@Nonnull JsonArray array) { + @NotNull + public static List convertArrayToStrings(@NotNull JsonArray array) { List list = new ArrayList<>(array.size()); for (JsonElement element : array) { if (!element.isJsonObject()) continue; @@ -107,23 +107,23 @@ public static List convertArrayToStrings(@Nonnull JsonArray array) { protected JsonObject jsonObject; - public GsonDocument(@Nonnull File file) throws IOException { + public GsonDocument(@NotNull File file) throws IOException { this(FileUtils.newBufferedReader(file)); } - public GsonDocument(@Nonnull Reader reader) throws IOException { + public GsonDocument(@NotNull Reader reader) throws IOException { this(new BufferedReader(reader)); } - public GsonDocument(@Nonnull BufferedReader reader) throws IOException { + public GsonDocument(@NotNull BufferedReader reader) throws IOException { this(reader.ready() ? GSON.fromJson(reader, JsonObject.class) : new JsonObject()); } - public GsonDocument(@Nonnull String json) { + public GsonDocument(@NotNull String json) { this(GSON.fromJson(json, JsonObject.class)); } - public GsonDocument(@Nonnull String json, @Nonnull Document root, @Nullable Document parent) { + public GsonDocument(@NotNull String json, @NotNull Document root, @Nullable Document parent) { this(GSON.fromJson(json, JsonObject.class), root, parent); } @@ -131,12 +131,12 @@ public GsonDocument(@Nullable JsonObject jsonObject) { this.jsonObject = jsonObject == null ? new JsonObject() : jsonObject; } - public GsonDocument(@Nullable JsonObject jsonObject, @Nonnull Document root, @Nullable Document parent) { + public GsonDocument(@Nullable JsonObject jsonObject, @NotNull Document root, @Nullable Document parent) { super(root, parent); this.jsonObject = jsonObject == null ? new JsonObject() : jsonObject; } - public GsonDocument(@Nonnull Map values) { + public GsonDocument(@NotNull Map values) { this(); GsonUtils.setDocumentProperties(GSON, jsonObject, values); } @@ -145,54 +145,54 @@ public GsonDocument() { this(new JsonObject()); } - public GsonDocument(@Nonnull Object object) { + public GsonDocument(@NotNull Object object) { this(GSON.toJsonTree(object).getAsJsonObject()); } @Nullable @Override - public String getString(@Nonnull String path) { + public String getString(@NotNull String path) { JsonElement element = getElement(path).orElse(null); return GsonUtils.convertJsonElementToString(element); } @Nullable @Override - public Object getObject(@Nonnull String path) { + public Object getObject(@NotNull String path) { JsonElement element = getElement(path).orElse(null); return GsonUtils.unpackJsonElement(element); } @Nullable @Override - public T getInstance(@Nonnull String path, @Nonnull Class classOfType) { + public T getInstance(@NotNull String path, @NotNull Class classOfType) { JsonElement element = getElement(path).orElse(null); return GSON.fromJson(element, classOfType); } @Override - public T toInstanceOf(@Nonnull Class classOfT) { + public T toInstanceOf(@NotNull Class classOfT) { if (isEmpty()) return null; return GSON.fromJson(jsonObject, classOfT); } @Nullable @Override - public T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + public T getSerializable(@NotNull String path, @NotNull Class classOfT) { return getInstance(path, classOfT); } - @Nonnull + @NotNull @Override - public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + public Document getDocument0(@NotNull String path, @NotNull Document root, @Nullable Document parent) { JsonElement element = getElement(path).orElse(null); if (element == null || !element.isJsonObject()) setElement(path, element = new JsonObject()); return new GsonDocument(element.getAsJsonObject(), root, parent); } - @Nonnull + @NotNull @Override - public List getDocumentList(@Nonnull String path) { + public List getDocumentList(@NotNull String path) { JsonElement element = getElement(path).orElse(new JsonArray()); if (element.isJsonNull()) return new ArrayList<>(); JsonArray array = element.getAsJsonArray(); @@ -205,53 +205,53 @@ public List getDocumentList(@Nonnull String path) { } @Override - public char getChar(@Nonnull String path) { + public char getChar(@NotNull String path) { return getChar(path, (char) 0); } @Override - public char getChar(@Nonnull String path, char def) { + public char getChar(@NotNull String path, char def) { return getPrimitive(path).map(JsonPrimitive::getAsCharacter).orElse(def); } @Override - public long getLong(@Nonnull String path, long def) { + public long getLong(@NotNull String path, long def) { return getPrimitive(path).map(JsonPrimitive::getAsLong).orElse(def); } @Override - public int getInt(@Nonnull String path, int def) { + public int getInt(@NotNull String path, int def) { return getPrimitive(path).map(JsonPrimitive::getAsInt).orElse(def); } @Override - public short getShort(@Nonnull String path, short def) { + public short getShort(@NotNull String path, short def) { return getPrimitive(path).map(JsonPrimitive::getAsShort).orElse(def); } @Override - public byte getByte(@Nonnull String path, byte def) { + public byte getByte(@NotNull String path, byte def) { return getPrimitive(path).map(JsonPrimitive::getAsByte).orElse(def); } @Override - public double getDouble(@Nonnull String path, double def) { + public double getDouble(@NotNull String path, double def) { return getPrimitive(path).map(JsonPrimitive::getAsDouble).orElse(def); } @Override - public float getFloat(@Nonnull String path, float def) { + public float getFloat(@NotNull String path, float def) { return getPrimitive(path).map(JsonPrimitive::getAsFloat).orElse(def); } @Override - public boolean getBoolean(@Nonnull String path, boolean def) { + public boolean getBoolean(@NotNull String path, boolean def) { return getPrimitive(path).map(JsonPrimitive::getAsBoolean).orElse(def); } - @Nonnull + @NotNull @Override - public List getStringList(@Nonnull String path) { + public List getStringList(@NotNull String path) { JsonElement element = getElement(path).orElse(null); if (element == null || element.isJsonNull()) return new ArrayList<>(); if (element.isJsonPrimitive()) @@ -263,55 +263,55 @@ public List getStringList(@Nonnull String path) { @Nullable @Override - public UUID getUUID(@Nonnull String path) { + public UUID getUUID(@NotNull String path) { return getInstance(path, UUID.class); } @Nullable @Override - public Date getDate(@Nonnull String path) { + public Date getDate(@NotNull String path) { return getInstance(path, Date.class); } @Nullable @Override - public OffsetDateTime getDateTime(@Nonnull String path) { + public OffsetDateTime getDateTime(@NotNull String path) { return getInstance(path, OffsetDateTime.class); } @Nullable @Override - public Color getColor(@Nonnull String path) { + public Color getColor(@NotNull String path) { return getInstance(path, Color.class); } @Nullable @Override - public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + public > E getEnum(@NotNull String path, @NotNull Class classOfEnum) { return getInstance(path, classOfEnum); } @Override - public boolean isList(@Nonnull String path) { + public boolean isList(@NotNull String path) { return checkElement(path, JsonElement::isJsonArray); } @Override - public boolean isDocument(@Nonnull String path) { + public boolean isDocument(@NotNull String path) { return checkElement(path, JsonElement::isJsonObject); } @Override - public boolean isObject(@Nonnull String path) { + public boolean isObject(@NotNull String path) { return checkElement(path, JsonElement::isJsonPrimitive); } - private boolean checkElement(@Nonnull String path, @Nonnull Function check) { + private boolean checkElement(@NotNull String path, @NotNull Function check) { return getElement(path).map(check).orElse(false); } @Override - public boolean contains(@Nonnull String path) { + public boolean contains(@NotNull String path) { return getElement(path).isPresent(); } @@ -321,13 +321,13 @@ public int size() { } @Override - public void set0(@Nonnull String path, @Nullable Object value) { + public void set0(@NotNull String path, @Nullable Object value) { setElement(path, value); } - @Nonnull + @NotNull @Override - public Document set(@Nonnull Object object) { + public Document set(@NotNull Object object) { JsonObject json = GSON.toJsonTree(object).getAsJsonObject(); for (Entry entry : json.entrySet()) { jsonObject.add(entry.getKey(), entry.getValue()); @@ -341,22 +341,22 @@ public void clear0() { } @Override - public void remove0(@Nonnull String path) { + public void remove0(@NotNull String path) { setElement(path, null); } - @Nonnull + @NotNull @Override public Map values() { return GsonUtils.convertJsonObjectToMap(jsonObject); } @Override - public void forEach(@Nonnull BiConsumer action) { + public void forEach(@NotNull BiConsumer action) { values().forEach(action); } - @Nonnull + @NotNull @Override public Collection keys() { Collection keys = new ArrayList<>(size()); @@ -366,20 +366,20 @@ public Collection keys() { return keys; } - @Nonnull - private Optional getPrimitive(@Nonnull String path) { + @NotNull + private Optional getPrimitive(@NotNull String path) { return getElement(path) .filter(JsonPrimitive.class::isInstance) .map(JsonPrimitive.class::cast); } - @Nonnull - private Optional getElement(@Nonnull String path) { + @NotNull + private Optional getElement(@NotNull String path) { return getElement(path, jsonObject); } - @Nonnull - private Optional getElement(@Nonnull String path, @Nonnull JsonObject object) { + @NotNull + private Optional getElement(@NotNull String path, @NotNull JsonObject object) { JsonElement fullPathElement = object.get(path); if (fullPathElement != null) return Optional.of(fullPathElement); @@ -397,7 +397,7 @@ private Optional getElement(@Nonnull String path, @Nonnull JsonObje } - private void setElement(@Nonnull String path, @Nullable Object value) { + private void setElement(@NotNull String path, @Nullable Object value) { LinkedList paths = determinePath(path); JsonObject object = jsonObject; @@ -429,8 +429,8 @@ private void setElement(@Nonnull String path, @Nullable Object value) { } - @Nonnull - private LinkedList determinePath(@Nonnull String path) { + @NotNull + private LinkedList determinePath(@NotNull String path) { LinkedList paths = new LinkedList<>(); String pathCopy = path; @@ -446,13 +446,13 @@ private LinkedList determinePath(@Nonnull String path) { } - @Nonnull + @NotNull @Override public String toJson() { return GSON.toJson(jsonObject); } - @Nonnull + @NotNull @Override public String toPrettyJson() { return GSON_PRETTY_PRINT.toJson(jsonObject); @@ -477,12 +477,12 @@ public int hashCode() { } @Override - public void write(@Nonnull Writer writer) throws IOException { + public void write(@NotNull Writer writer) throws IOException { cleanup(); (writePrettyJson ? GSON_PRETTY_PRINT : GSON).toJson(jsonObject, writer); } - @Nonnull + @NotNull public JsonObject getJsonObject() { return jsonObject; } @@ -496,7 +496,7 @@ public void cleanup() { cleanup(jsonObject); } - public static void cleanup(@Nonnull JsonObject jsonObject) { + public static void cleanup(@NotNull JsonObject jsonObject) { Iterator> iterator = jsonObject.entrySet().iterator(); while (iterator.hasNext()) { Entry entry = iterator.next(); diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java index 1a2e1d693..a7874d7a3 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/MapDocument.java @@ -5,9 +5,9 @@ import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.PropertyHelper; import net.codingarea.commons.common.misc.GsonUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.awt.*; import java.io.IOException; import java.io.Writer; @@ -26,12 +26,12 @@ public class MapDocument extends AbstractDocument { private final Map values; - public MapDocument(@Nonnull Map values) { + public MapDocument(@NotNull Map values) { Preconditions.checkNotNull(values, "Map cannot be null"); this.values = values; } - public MapDocument(@Nonnull Map values, @Nonnull Document root, @Nullable Document parent) { + public MapDocument(@NotNull Map values, @NotNull Document root, @Nullable Document parent) { super(root, parent); this.values = values; } @@ -45,9 +45,9 @@ public boolean isReadonly() { return false; } - @Nonnull + @NotNull @Override - public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + public Document getDocument0(@NotNull String path, @NotNull Document root, @Nullable Document parent) { Object value = this.values.computeIfAbsent(path, key -> new HashMap<>()); if (value instanceof Map) return new MapDocument((Map) value, root, parent); if (value instanceof Document) return (Document) value; @@ -55,9 +55,9 @@ public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Null throw new IllegalStateException("Expected java.util.Map, found " + values.getClass().getName()); } - @Nonnull + @NotNull @Override - public List getDocumentList(@Nonnull String path) { + public List getDocumentList(@NotNull String path) { List documents = new ArrayList<>(); Object value = values.get(path); if (value instanceof List) { @@ -72,7 +72,7 @@ public List getDocumentList(@Nonnull String path) { } @Override - public void set0(@Nonnull String path, @Nullable Object value) { + public void set0(@NotNull String path, @Nullable Object value) { values.put(path, value); } @@ -82,22 +82,22 @@ public void clear0() { } @Override - public void remove0(@Nonnull String path) { + public void remove0(@NotNull String path) { values.remove(path); } @Override - public void write(@Nonnull Writer writer) throws IOException { + public void write(@NotNull Writer writer) throws IOException { new GsonDocument(values).write(writer); } - @Nonnull + @NotNull @Override public String toJson() { return new GsonDocument(values).toJson(); } - @Nonnull + @NotNull @Override public String toPrettyJson() { return new GsonDocument(values).toPrettyJson(); @@ -105,29 +105,29 @@ public String toPrettyJson() { @Nullable @Override - public Object getObject(@Nonnull String path) { + public Object getObject(@NotNull String path) { return values.get(path); } @Override - public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + public T getInstance(@NotNull String path, @NotNull Class classOfT) { return classOfT.cast(getObject(path)); } @Override - public T toInstanceOf(@Nonnull Class classOfT) { + public T toInstanceOf(@NotNull Class classOfT) { return copyJson().toInstanceOf(classOfT); } @Nullable @Override - public String getString(@Nonnull String path) { + public String getString(@NotNull String path) { Object value = values.get(path); return value == null ? null : value.toString(); } @Override - public long getLong(@Nonnull String path, long def) { + public long getLong(@NotNull String path, long def) { try { return Long.parseLong(getString(path)); } catch (Exception ex) { @@ -136,7 +136,7 @@ public long getLong(@Nonnull String path, long def) { } @Override - public int getInt(@Nonnull String path, int def) { + public int getInt(@NotNull String path, int def) { try { return Integer.parseInt(getString(path)); } catch (Exception ex) { @@ -145,7 +145,7 @@ public int getInt(@Nonnull String path, int def) { } @Override - public short getShort(@Nonnull String path, short def) { + public short getShort(@NotNull String path, short def) { try { return Short.parseShort(getString(path)); } catch (Exception ex) { @@ -154,7 +154,7 @@ public short getShort(@Nonnull String path, short def) { } @Override - public byte getByte(@Nonnull String path, byte def) { + public byte getByte(@NotNull String path, byte def) { try { return Byte.parseByte(getString(path)); } catch (Exception ex) { @@ -163,7 +163,7 @@ public byte getByte(@Nonnull String path, byte def) { } @Override - public float getFloat(@Nonnull String path, float def) { + public float getFloat(@NotNull String path, float def) { try { return Float.parseFloat(getString(path)); } catch (Exception ex) { @@ -172,7 +172,7 @@ public float getFloat(@Nonnull String path, float def) { } @Override - public double getDouble(@Nonnull String path, double def) { + public double getDouble(@NotNull String path, double def) { try { return Double.parseDouble(getString(path)); } catch (Exception ex) { @@ -181,7 +181,7 @@ public double getDouble(@Nonnull String path, double def) { } @Override - public boolean getBoolean(@Nonnull String path, boolean def) { + public boolean getBoolean(@NotNull String path, boolean def) { try { if (!contains(path)) return def; switch (getString(path).toLowerCase()) { @@ -196,9 +196,9 @@ public boolean getBoolean(@Nonnull String path, boolean def) { } } - @Nonnull + @NotNull @Override - public List getStringList(@Nonnull String path) { + public List getStringList(@NotNull String path) { Object object = getObject(path); if (object == null) return Collections.emptyList(); if (object instanceof Iterable) @@ -210,7 +210,7 @@ public List getStringList(@Nonnull String path) { @Nullable @Override - public UUID getUUID(@Nonnull String path) { + public UUID getUUID(@NotNull String path) { try { Object object = getObject(path); if (object instanceof UUID) return (UUID) object; @@ -222,7 +222,7 @@ public UUID getUUID(@Nonnull String path) { @Nullable @Override - public Date getDate(@Nonnull String path) { + public Date getDate(@NotNull String path) { Object object = getObject(path); if (object instanceof String) return PropertyHelper.parseDate((String) object); if (object instanceof Date) return (Date) object; @@ -231,7 +231,7 @@ public Date getDate(@Nonnull String path) { @Nullable @Override - public OffsetDateTime getDateTime(@Nonnull String path) { + public OffsetDateTime getDateTime(@NotNull String path) { Object object = getObject(path); if (object instanceof CharSequence) return OffsetDateTime.parse((CharSequence) object); if (object instanceof OffsetDateTime) return (OffsetDateTime) object; @@ -240,7 +240,7 @@ public OffsetDateTime getDateTime(@Nonnull String path) { @Nullable @Override - public Color getColor(@Nonnull String path) { + public Color getColor(@NotNull String path) { Object object = getObject(path); if (object instanceof Color) return (Color) object; if (object instanceof String) return Color.decode((String) object); @@ -248,24 +248,24 @@ public Color getColor(@Nonnull String path) { } @Override - public boolean isList(@Nonnull String path) { + public boolean isList(@NotNull String path) { Object value = values.get(path); return value instanceof Iterable || (value != null && value.getClass().isArray()); } @Override - public boolean isObject(@Nonnull String path) { + public boolean isObject(@NotNull String path) { return !isDocument(path) && !isList(path); } @Override - public boolean isDocument(@Nonnull String path) { + public boolean isDocument(@NotNull String path) { Object value = values.get(path); return value instanceof Map || value instanceof Document; } @Override - public boolean contains(@Nonnull String path) { + public boolean contains(@NotNull String path) { return values.containsKey(path); } @@ -274,20 +274,20 @@ public int size() { return values.size(); } - @Nonnull + @NotNull @Override public Map values() { return Collections.unmodifiableMap(values); } - @Nonnull + @NotNull @Override public Collection keys() { return values.keySet(); } @Override - public void forEach(@Nonnull BiConsumer action) { + public void forEach(@NotNull BiConsumer action) { values.forEach(action); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java index 67086b69e..02c108acb 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/PropertiesDocument.java @@ -5,9 +5,9 @@ import net.codingarea.commons.common.config.PropertyHelper; import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.commons.common.misc.PropertiesUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.awt.*; import java.io.File; import java.io.IOException; @@ -30,53 +30,53 @@ public PropertiesDocument(@Nullable Properties properties) { this.properties = properties == null ? new Properties() : properties; } - public PropertiesDocument(@Nonnull File file) throws IOException { + public PropertiesDocument(@NotNull File file) throws IOException { properties = new Properties(); properties.load(FileUtils.newBufferedReader(file)); } - @Nonnull + @NotNull @Override - public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + public Document getDocument0(@NotNull String path, @NotNull Document root, @Nullable Document parent) { throw new UnsupportedOperationException("PropertiesDocument.getDocument(String)"); } - @Nonnull + @NotNull @Override - public List getDocumentList(@Nonnull String path) { + public List getDocumentList(@NotNull String path) { throw new UnsupportedOperationException("PropertiesDocument.getDocumentList(String)"); } - @Nonnull + @NotNull @Override - public List getStringList(@Nonnull String path) { + public List getStringList(@NotNull String path) { throw new UnsupportedOperationException("PropertiesDocument.getList(String)"); } @Nullable @Override - public Object getObject(@Nonnull String path) { + public Object getObject(@NotNull String path) { return properties.get(path); } @Override - public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + public T getInstance(@NotNull String path, @NotNull Class classOfT) { return classOfT.cast(getObject(path)); } @Override - public T toInstanceOf(@Nonnull Class classOfT) { + public T toInstanceOf(@NotNull Class classOfT) { return copyJson().toInstanceOf(classOfT); } @Nullable @Override - public String getString(@Nonnull String path) { + public String getString(@NotNull String path) { return properties.getProperty(path); } @Override - public long getLong(@Nonnull String path, long def) { + public long getLong(@NotNull String path, long def) { try { return Long.parseLong(getString(path)); } catch (Exception ex) { @@ -85,7 +85,7 @@ public long getLong(@Nonnull String path, long def) { } @Override - public int getInt(@Nonnull String path, int def) { + public int getInt(@NotNull String path, int def) { try { return Integer.parseInt(getString(path)); } catch (Exception ex) { @@ -94,7 +94,7 @@ public int getInt(@Nonnull String path, int def) { } @Override - public short getShort(@Nonnull String path, short def) { + public short getShort(@NotNull String path, short def) { try { return Short.parseShort(getString(path)); } catch (Exception ex) { @@ -103,7 +103,7 @@ public short getShort(@Nonnull String path, short def) { } @Override - public byte getByte(@Nonnull String path, byte def) { + public byte getByte(@NotNull String path, byte def) { try { return Byte.parseByte(getString(path)); } catch (Exception ex) { @@ -112,7 +112,7 @@ public byte getByte(@Nonnull String path, byte def) { } @Override - public float getFloat(@Nonnull String path, float def) { + public float getFloat(@NotNull String path, float def) { try { return Float.parseFloat(getString(path)); } catch (Exception ex) { @@ -121,7 +121,7 @@ public float getFloat(@Nonnull String path, float def) { } @Override - public double getDouble(@Nonnull String path, double def) { + public double getDouble(@NotNull String path, double def) { try { return Double.parseDouble(getString(path)); } catch (Exception ex) { @@ -130,14 +130,14 @@ public double getDouble(@Nonnull String path, double def) { } @Override - public boolean getBoolean(@Nonnull String path, boolean def) { + public boolean getBoolean(@NotNull String path, boolean def) { if (!contains(path)) return def; return Boolean.parseBoolean(getString(path)); } @Nullable @Override - public UUID getUUID(@Nonnull String path) { + public UUID getUUID(@NotNull String path) { try { return UUID.fromString(getString(path)); } catch (Exception ex) { @@ -147,13 +147,13 @@ public UUID getUUID(@Nonnull String path) { @Nullable @Override - public Date getDate(@Nonnull String path) { + public Date getDate(@NotNull String path) { return PropertyHelper.parseDate(getString(path)); } @Nullable @Override - public OffsetDateTime getDateTime(@Nonnull String path) { + public OffsetDateTime getDateTime(@NotNull String path) { try { return OffsetDateTime.parse(getString(path)); } catch (Exception ex) { @@ -163,14 +163,14 @@ public OffsetDateTime getDateTime(@Nonnull String path) { @Nullable @Override - public Color getColor(@Nonnull String path) { + public Color getColor(@NotNull String path) { String string = getString(path); return string == null ? null : Color.decode(string); } @Nullable @Override - public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + public > E getEnum(@NotNull String path, @NotNull Class classOfEnum) { try { String name = getString(path); if (name == null) return null; @@ -181,22 +181,22 @@ public > E getEnum(@Nonnull String path, @Nonnull Class cla } @Override - public boolean contains(@Nonnull String path) { + public boolean contains(@NotNull String path) { return properties.containsKey(path); } @Override - public boolean isList(@Nonnull String path) { + public boolean isList(@NotNull String path) { return false; } @Override - public boolean isObject(@Nonnull String path) { + public boolean isObject(@NotNull String path) { return true; } @Override - public boolean isDocument(@Nonnull String path) { + public boolean isDocument(@NotNull String path) { return false; } @@ -205,7 +205,7 @@ public int size() { return properties.size(); } - @Nonnull + @NotNull @Override public Map values() { Map map = new LinkedHashMap<>(); @@ -215,19 +215,19 @@ public Map values() { return map; } - @Nonnull + @NotNull @Override public Collection keys() { return properties.stringPropertyNames(); } @Override - public void forEach(@Nonnull BiConsumer action) { + public void forEach(@NotNull BiConsumer action) { values().forEach(action); } @Override - public void set0(@Nonnull String path, @Nullable Object value) { + public void set0(@NotNull String path, @Nullable Object value) { final String asString; if (value instanceof Color) { asString = Colors.asHex((Color) value); @@ -244,33 +244,33 @@ public void clear0() { } @Override - public void remove0(@Nonnull String path) { + public void remove0(@NotNull String path) { properties.remove(path); } @Override - public void write(@Nonnull Writer writer) throws IOException { + public void write(@NotNull Writer writer) throws IOException { properties.store(writer, null); } - @Nonnull + @NotNull public Properties getProperties() { return properties; } - @Nonnull + @NotNull @Override public String toJson() { return copyJson().toJson(); } - @Nonnull + @NotNull @Override public String toPrettyJson() { return copyJson().toPrettyJson(); } - @Nonnull + @NotNull @Override public Document copyJson() { Map map = new HashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java index f7ec8d1cf..8a6bc53ad 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlDocument.java @@ -5,14 +5,14 @@ import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConstructor; import org.bukkit.configuration.file.YamlRepresenter; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.representer.Representer; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.awt.*; import java.io.File; import java.io.IOException; @@ -31,66 +31,66 @@ public YamlDocument() { this.config = new YamlConfiguration(); } - public YamlDocument(@Nonnull ConfigurationSection config) { + public YamlDocument(@NotNull ConfigurationSection config) { this.config = config; } - public YamlDocument(@Nonnull ConfigurationSection config, @Nonnull Document root, @Nullable Document parent) { + public YamlDocument(@NotNull ConfigurationSection config, @NotNull Document root, @Nullable Document parent) { super(root, parent); this.config = config; } - public YamlDocument(@Nonnull File file) { + public YamlDocument(@NotNull File file) { this(YamlConfiguration.loadConfiguration(file)); } @Nullable @Override - public String getString(@Nonnull String path) { + public String getString(@NotNull String path) { return config.getString(path); } - @Nonnull + @NotNull @Override - public String getString(@Nonnull String path, @Nonnull String def) { + public String getString(@NotNull String path, @NotNull String def) { String string = config.getString(path, def); return string == null ? def : string; } @Nullable @Override - public Object getObject(@Nonnull String path) { + public Object getObject(@NotNull String path) { return config.get(path); } - @Nonnull + @NotNull @Override - public Object getObject(@Nonnull String path, @Nonnull Object def) { + public Object getObject(@NotNull String path, @NotNull Object def) { Object value = config.get(path, def); return value == null ? def : value; } @Override - public T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + public T getInstance(@NotNull String path, @NotNull Class classOfT) { return copyJson().getInstance(path, classOfT); } @Override - public T toInstanceOf(@Nonnull Class classOfT) { + public T toInstanceOf(@NotNull Class classOfT) { return copyJson().toInstanceOf(classOfT); } - @Nonnull + @NotNull @Override - public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + public Document getDocument0(@NotNull String path, @NotNull Document root, @Nullable Document parent) { ConfigurationSection section = config.getConfigurationSection(path); if (section == null) section = config.createSection(path); return new YamlDocument(section, root, parent); } - @Nonnull + @NotNull @Override - public List getDocumentList(@Nonnull String path) { + public List getDocumentList(@NotNull String path) { List> maps = config.getMapList(path); List documents = new ArrayList<>(maps.size()); for (Map map : maps) { @@ -100,52 +100,52 @@ public List getDocumentList(@Nonnull String path) { } @Override - public long getLong(@Nonnull String path) { + public long getLong(@NotNull String path) { return config.getLong(path); } @Override - public long getLong(@Nonnull String path, long def) { + public long getLong(@NotNull String path, long def) { return config.getLong(path, def); } @Override - public int getInt(@Nonnull String path) { + public int getInt(@NotNull String path) { return config.getInt(path); } @Override - public int getInt(@Nonnull String path, int def) { + public int getInt(@NotNull String path, int def) { return config.getInt(path, def); } @Override - public short getShort(@Nonnull String path) { + public short getShort(@NotNull String path) { return (short) config.getInt(path); } @Override - public short getShort(@Nonnull String path, short def) { + public short getShort(@NotNull String path, short def) { return (short) config.getInt(path, def); } @Override - public byte getByte(@Nonnull String path) { + public byte getByte(@NotNull String path) { return (byte) config.getInt(path); } @Override - public byte getByte(@Nonnull String path, byte def) { + public byte getByte(@NotNull String path, byte def) { return (byte) config.getInt(path, def); } @Override - public char getChar(@Nonnull String path) { + public char getChar(@NotNull String path) { return getChar(path, (char) 0); } @Override - public char getChar(@Nonnull String path, char def) { + public char getChar(@NotNull String path, char def) { try { return getString(path).charAt(0); } catch (NullPointerException | StringIndexOutOfBoundsException ex) { @@ -154,44 +154,44 @@ public char getChar(@Nonnull String path, char def) { } @Override - public double getDouble(@Nonnull String path) { + public double getDouble(@NotNull String path) { return config.getDouble(path); } @Override - public double getDouble(@Nonnull String path, double def) { + public double getDouble(@NotNull String path, double def) { return config.getDouble(path, def); } @Override - public float getFloat(@Nonnull String path) { + public float getFloat(@NotNull String path) { return (float) config.getDouble(path); } @Override - public float getFloat(@Nonnull String path, float def) { + public float getFloat(@NotNull String path, float def) { return (float) config.getDouble(path, def); } @Override - public boolean getBoolean(@Nonnull String path) { + public boolean getBoolean(@NotNull String path) { return config.getBoolean(path); } @Override - public boolean getBoolean(@Nonnull String path, boolean def) { + public boolean getBoolean(@NotNull String path, boolean def) { return config.getBoolean(path, def); } - @Nonnull + @NotNull @Override - public List getStringList(@Nonnull String path) { + public List getStringList(@NotNull String path) { return config.getStringList(path); } @Nullable @Override - public UUID getUUID(@Nonnull String path) { + public UUID getUUID(@NotNull String path) { try { return UUID.fromString(getString(path)); } catch (Exception ex) { @@ -201,7 +201,7 @@ public UUID getUUID(@Nonnull String path) { @Nullable @Override - public Date getDate(@Nonnull String path) { + public Date getDate(@NotNull String path) { try { return DateFormat.getDateTimeInstance().parse(path); } catch (Exception ex) { @@ -211,7 +211,7 @@ public Date getDate(@Nonnull String path) { @Nullable @Override - public OffsetDateTime getDateTime(@Nonnull String path) { + public OffsetDateTime getDateTime(@NotNull String path) { try { return OffsetDateTime.parse(getString(path)); } catch (Exception ex) { @@ -221,7 +221,7 @@ public OffsetDateTime getDateTime(@Nonnull String path) { @Nullable @Override - public Color getColor(@Nonnull String path) { + public Color getColor(@NotNull String path) { try { return Color.decode(getString(path)); } catch (Exception ex) { @@ -231,7 +231,7 @@ public Color getColor(@Nonnull String path) { @Nullable @Override - public > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + public > E getEnum(@NotNull String path, @NotNull Class classOfEnum) { try { String name = getString(path); if (name == null) return null; @@ -242,22 +242,22 @@ public > E getEnum(@Nonnull String path, @Nonnull Class cla } @Override - public boolean isList(@Nonnull String path) { + public boolean isList(@NotNull String path) { return config.isList(path); } @Override - public boolean isObject(@Nonnull String path) { + public boolean isObject(@NotNull String path) { return !isDocument(path) && !isList(path); } @Override - public boolean isDocument(@Nonnull String path) { + public boolean isDocument(@NotNull String path) { return config.get(path) instanceof ConfigurationSection; } @Override - public boolean contains(@Nonnull String path) { + public boolean contains(@NotNull String path) { return config.contains(path, true); } @@ -267,7 +267,7 @@ public int size() { } @Override - public void set0(@Nonnull String path, @Nullable Object value) { + public void set0(@NotNull String path, @Nullable Object value) { if (value instanceof Enum) { Enum enun = (Enum) value; value = enun.name(); @@ -276,7 +276,7 @@ public void set0(@Nonnull String path, @Nullable Object value) { } @Override - public void remove0(@Nonnull String path) { + public void remove0(@NotNull String path) { config.set(path, null); } @@ -287,20 +287,20 @@ public void clear0() { } } - @Nonnull + @NotNull @Override public Map values() { return config.getValues(true); } - @Nonnull + @NotNull @Override public Collection keys() { return config.getKeys(false); } @Override - public void forEach(@Nonnull BiConsumer action) { + public void forEach(@NotNull BiConsumer action) { values().forEach(action); } @@ -325,23 +325,23 @@ public String toString() { } @Override - public void write(@Nonnull Writer writer) throws IOException { + public void write(@NotNull Writer writer) throws IOException { writer.write(toString()); } - @Nonnull + @NotNull @Override public Document copyJson() { return new GsonDocument(values()); } - @Nonnull + @NotNull @Override public String toJson() { return copyJson().toJson(); } - @Nonnull + @NotNull @Override public String toPrettyJson() { return copyJson().toPrettyJson(); diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java index f4252eb6f..3dd53705c 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/BukkitReflectionSerializableTypeAdapter.java @@ -8,8 +8,8 @@ import com.google.gson.stream.JsonWriter; import net.codingarea.commons.common.misc.BukkitReflectionSerializationUtils; import net.codingarea.commons.common.misc.GsonUtils; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.io.IOException; import java.util.Map; import java.util.Optional; @@ -19,7 +19,7 @@ public class BukkitReflectionSerializableTypeAdapter implements GsonTypeAdapter< public static final String ALTERNATE_KEY = "classOfType", KEY = "=="; @Override - public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Object object) throws IOException { + public void write(@NotNull Gson gson, @NotNull JsonWriter writer, @NotNull Object object) throws IOException { Map map = BukkitReflectionSerializationUtils.serializeObject(object); if (map == null) return; @@ -32,7 +32,7 @@ public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Objec } @Override - public Object read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + public Object read(@NotNull Gson gson, @NotNull JsonReader reader) throws IOException { JsonElement element = TypeAdapters.JSON_ELEMENT.read(reader); if (element == null || !element.isJsonObject()) return null; @@ -51,7 +51,7 @@ public Object read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOExce } - private JsonElement findClassContainer(@Nonnull JsonObject json) { + private JsonElement findClassContainer(@NotNull JsonObject json) { if (json.has(ALTERNATE_KEY)) return json.get(ALTERNATE_KEY); return json.get(KEY); diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java index 01c511c19..21528fdf3 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ClassTypeAdapter.java @@ -4,19 +4,19 @@ import com.google.gson.internal.bind.TypeAdapters; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.io.IOException; public class ClassTypeAdapter implements GsonTypeAdapter> { @Override - public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Class object) throws IOException { + public void write(@NotNull Gson gson, @NotNull JsonWriter writer, @NotNull Class object) throws IOException { TypeAdapters.STRING.write(writer, object.getName()); } @Override - public Class read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + public Class read(@NotNull Gson gson, @NotNull JsonReader reader) throws IOException { try { String value = reader.nextString(); diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java index 9dc2bb966..377ad1957 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/ColorTypeAdapter.java @@ -5,20 +5,20 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import net.codingarea.commons.common.collection.Colors; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.awt.*; import java.io.IOException; public class ColorTypeAdapter implements GsonTypeAdapter { @Override - public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Color color) throws IOException { + public void write(@NotNull Gson gson, @NotNull JsonWriter writer, @NotNull Color color) throws IOException { TypeAdapters.STRING.write(writer, Colors.asHex(color)); } @Override - public Color read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + public Color read(@NotNull Gson gson, @NotNull JsonReader reader) throws IOException { String value = TypeAdapters.STRING.read(reader); if (value == null) return null; return Color.decode(value); diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java index ab4a111a6..436b8d1e7 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/DocumentTypeAdapter.java @@ -7,14 +7,14 @@ import com.google.gson.stream.JsonWriter; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.document.GsonDocument; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.io.IOException; public class DocumentTypeAdapter implements GsonTypeAdapter { @Override - public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Document document) throws IOException { + public void write(@NotNull Gson gson, @NotNull JsonWriter writer, @NotNull Document document) throws IOException { if (document instanceof GsonDocument) { GsonDocument gsonDocument = (GsonDocument) document; TypeAdapters.JSON_ELEMENT.write(writer, gsonDocument.getJsonObject()); @@ -34,7 +34,7 @@ public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Docum } @Override - public Document read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + public Document read(@NotNull Gson gson, @NotNull JsonReader reader) throws IOException { JsonElement jsonElement = TypeAdapters.JSON_ELEMENT.read(reader); if (jsonElement != null && jsonElement.isJsonObject()) { return new GsonDocument(jsonElement.getAsJsonObject()); diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java index 147b299f9..6a30c499f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/GsonTypeAdapter.java @@ -6,19 +6,19 @@ import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.io.IOException; import java.util.function.Predicate; @SuppressWarnings("unchecked") public interface GsonTypeAdapter { - void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull T object) throws IOException; + void write(@NotNull Gson gson, @NotNull JsonWriter writer, @NotNull T object) throws IOException; - T read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException; + T read(@NotNull Gson gson, @NotNull JsonReader reader) throws IOException; - default TypeAdapter toTypeAdapter(@Nonnull Gson gson) { + default TypeAdapter toTypeAdapter(@NotNull Gson gson) { return new TypeAdapter() { @Override public void write(JsonWriter writer, T object) throws IOException { @@ -36,8 +36,8 @@ public T read(JsonReader reader) throws IOException { }; } - @Nonnull - static TypeAdapterFactory newTypeHierarchyFactory(@Nonnull Class clazz, @Nonnull GsonTypeAdapter adapter) { + @NotNull + static TypeAdapterFactory newTypeHierarchyFactory(@NotNull Class clazz, @NotNull GsonTypeAdapter adapter) { return new TypeAdapterFactory() { @Override public TypeAdapter create(Gson gson, TypeToken token) { @@ -49,8 +49,8 @@ public TypeAdapter create(Gson gson, TypeToken token) { }; } - @Nonnull - static TypeAdapterFactory newPredictableFactory(@Nonnull Predicate> predicate, @Nonnull GsonTypeAdapter adapter) { + @NotNull + static TypeAdapterFactory newPredictableFactory(@NotNull Predicate> predicate, @NotNull GsonTypeAdapter adapter) { return new TypeAdapterFactory() { @Override public TypeAdapter create(Gson gson, TypeToken type) { diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java index 0b3deebc2..b2b14e079 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/gson/PairTypeAdapter.java @@ -8,14 +8,14 @@ import net.codingarea.commons.common.collection.pair.Quadro; import net.codingarea.commons.common.collection.pair.Triple; import net.codingarea.commons.common.collection.pair.Tuple; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.io.IOException; public class PairTypeAdapter implements GsonTypeAdapter { @Override - public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Pair object) throws IOException { + public void write(@NotNull Gson gson, @NotNull JsonWriter writer, @NotNull Pair object) throws IOException { Object[] values = object.values(); JsonArray array = new JsonArray(values.length); // TODO fix(deps) version ambiguity for (Object value : values) { @@ -24,7 +24,7 @@ public void write(@Nonnull Gson gson, @Nonnull JsonWriter writer, @Nonnull Pair } @Override - public Pair read(@Nonnull Gson gson, @Nonnull JsonReader reader) throws IOException { + public Pair read(@NotNull Gson gson, @NotNull JsonReader reader) throws IOException { JsonArray array = gson.fromJson(reader, JsonArray.class); int size = array.size(); switch (size) { diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java index 11dd71c28..cf06a143e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/readonly/ReadOnlyDocumentWrapper.java @@ -2,14 +2,13 @@ import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.document.wrapper.WrappedDocument; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public final class ReadOnlyDocumentWrapper implements WrappedDocument { private final Document document; - public ReadOnlyDocumentWrapper(@Nonnull Document document) { + public ReadOnlyDocumentWrapper(@NotNull Document document) { this.document = document; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java index 976232f9b..6170f8fb8 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/FileDocumentWrapper.java @@ -2,9 +2,9 @@ import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.FileDocument; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.io.File; import java.nio.file.Path; @@ -13,7 +13,7 @@ public class FileDocumentWrapper implements WrappedDocument, FileD protected final Document document; protected final File file; - public FileDocumentWrapper(@Nonnull File file, @Nonnull Document document) { + public FileDocumentWrapper(@NotNull File file, @NotNull Document document) { this.file = file; this.document = document; } @@ -23,39 +23,39 @@ public Document getWrappedDocument() { return document; } - @Nonnull + @NotNull @Override public File getFile() { return file; } - @Nonnull + @NotNull @Override public Path getPath() { return file.toPath(); } - @Nonnull + @NotNull @Override - public FileDocument set(@Nonnull String path, @Nullable Object value) { + public FileDocument set(@NotNull String path, @Nullable Object value) { return WrappedDocument.super.set(path, value); } - @Nonnull + @NotNull @Override - public FileDocument set(@Nonnull Object value) { + public FileDocument set(@NotNull Object value) { return WrappedDocument.super.set(value); } - @Nonnull + @NotNull @Override public FileDocument clear() { return WrappedDocument.super.clear(); } - @Nonnull + @NotNull @Override - public FileDocument remove(@Nonnull String path) { + public FileDocument remove(@NotNull String path) { return WrappedDocument.super.remove(path); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java index 03ab050c5..37d94e1af 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/wrapper/WrappedDocument.java @@ -4,9 +4,9 @@ import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.Propertyable; import net.codingarea.commons.common.version.Version; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.awt.*; import java.io.File; import java.io.IOException; @@ -28,390 +28,390 @@ default boolean isReadonly() { return getWrappedDocument().isReadonly(); } - @Nonnull + @NotNull @Override - default Document getDocument(@Nonnull String path) { + default Document getDocument(@NotNull String path) { return getWrappedDocument().getDocument(path); } - @Nonnull + @NotNull @Override - default List getDocumentList(@Nonnull String path) { + default List getDocumentList(@NotNull String path) { return getWrappedDocument().getDocumentList(path); } - @Nonnull + @NotNull @Override - default List getSerializableList(@Nonnull String path, @Nonnull Class classOfT) { + default List getSerializableList(@NotNull String path, @NotNull Class classOfT) { return getWrappedDocument().getSerializableList(path, classOfT); } - @Nonnull + @NotNull @Override - default D set(@Nonnull String path, @Nullable Object value) { + default D set(@NotNull String path, @Nullable Object value) { getWrappedDocument().set(path, value); return self(); } - @Nonnull + @NotNull @Override - default D set(@Nonnull Object value) { + default D set(@NotNull Object value) { getWrappedDocument().set(value); return self(); } - @Nonnull + @NotNull @Override default D clear() { getWrappedDocument().clear(); return self(); } - @Nonnull + @NotNull @Override - default D remove(@Nonnull String path) { + default D remove(@NotNull String path) { getWrappedDocument().remove(path); return self(); } @Override - default void write(@Nonnull Writer writer) throws IOException { + default void write(@NotNull Writer writer) throws IOException { getWrappedDocument().write(writer); } @Override - default void saveToFile(@Nonnull File file) throws IOException { + default void saveToFile(@NotNull File file) throws IOException { getWrappedDocument().saveToFile(file); } - @Nonnull + @NotNull @Override default String toJson() { return getWrappedDocument().toJson(); } - @Nonnull + @NotNull @Override default String toPrettyJson() { return getWrappedDocument().toPrettyJson(); } @Override - default T getInstance(@Nonnull String path, @Nonnull Class classOfT) { + default T getInstance(@NotNull String path, @NotNull Class classOfT) { return getWrappedDocument().getInstance(path, classOfT); } @Override - default T toInstanceOf(@Nonnull Class classOfT) { + default T toInstanceOf(@NotNull Class classOfT) { return getWrappedDocument().toInstanceOf(classOfT); } @Nullable @Override - default Object getObject(@Nonnull String path) { + default Object getObject(@NotNull String path) { return getWrappedDocument().getObject(path); } - @Nonnull + @NotNull @Override - default Object getObject(@Nonnull String path, @Nonnull Object def) { + default Object getObject(@NotNull String path, @NotNull Object def) { return getWrappedDocument().getObject(path, def); } - @Nonnull + @NotNull @Override - default Optional getOptional(@Nonnull String key, @Nonnull BiFunction extractor) { + default Optional getOptional(@NotNull String key, @NotNull BiFunction extractor) { return getWrappedDocument().getOptional(key, extractor); } @Nullable @Override - default String getString(@Nonnull String path) { + default String getString(@NotNull String path) { return getWrappedDocument().getString(path); } - @Nonnull + @NotNull @Override - default String getString(@Nonnull String path, @Nonnull String def) { + default String getString(@NotNull String path, @NotNull String def) { return getWrappedDocument().getString(path, def); } @Override - default char getChar(@Nonnull String path) { + default char getChar(@NotNull String path) { return getWrappedDocument().getChar(path); } @Override - default char getChar(@Nonnull String path, char def) { + default char getChar(@NotNull String path, char def) { return getWrappedDocument().getChar(path, def); } @Override - default long getLong(@Nonnull String path) { + default long getLong(@NotNull String path) { return getWrappedDocument().getLong(path); } @Override - default long getLong(@Nonnull String path, long def) { + default long getLong(@NotNull String path, long def) { return getWrappedDocument().getLong(path, def); } @Override - default int getInt(@Nonnull String path) { + default int getInt(@NotNull String path) { return getWrappedDocument().getInt(path); } @Override - default int getInt(@Nonnull String path, int def) { + default int getInt(@NotNull String path, int def) { return getWrappedDocument().getInt(path, def); } @Override - default short getShort(@Nonnull String path) { + default short getShort(@NotNull String path) { return getWrappedDocument().getShort(path); } @Override - default short getShort(@Nonnull String path, short def) { + default short getShort(@NotNull String path, short def) { return getWrappedDocument().getShort(path, def); } @Override - default byte getByte(@Nonnull String path) { + default byte getByte(@NotNull String path) { return getWrappedDocument().getByte(path); } @Override - default byte getByte(@Nonnull String path, byte def) { + default byte getByte(@NotNull String path, byte def) { return getWrappedDocument().getByte(path, def); } @Override - default float getFloat(@Nonnull String path) { + default float getFloat(@NotNull String path) { return getWrappedDocument().getFloat(path); } @Override - default float getFloat(@Nonnull String path, float def) { + default float getFloat(@NotNull String path, float def) { return getWrappedDocument().getFloat(path, def); } @Override - default double getDouble(@Nonnull String path) { + default double getDouble(@NotNull String path) { return getWrappedDocument().getDouble(path); } @Override - default double getDouble(@Nonnull String path, double def) { + default double getDouble(@NotNull String path, double def) { return getWrappedDocument().getDouble(path, def); } @Override - default boolean getBoolean(@Nonnull String path) { + default boolean getBoolean(@NotNull String path) { return getWrappedDocument().getBoolean(path); } @Override - default boolean getBoolean(@Nonnull String path, boolean def) { + default boolean getBoolean(@NotNull String path, boolean def) { return getWrappedDocument().getBoolean(path, def); } - @Nonnull + @NotNull @Override - default List getStringList(@Nonnull String path) { + default List getStringList(@NotNull String path) { return getWrappedDocument().getStringList(path); } - @Nonnull + @NotNull @Override - default String[] getStringArray(@Nonnull String path) { + default String[] getStringArray(@NotNull String path) { return getWrappedDocument().getStringArray(path); } - @Nonnull + @NotNull @Override - default List mapList(@Nonnull String path, @Nonnull Function mapper) { + default List mapList(@NotNull String path, @NotNull Function mapper) { return getWrappedDocument().mapList(path, mapper); } - @Nonnull + @NotNull @Override - default > List getEnumList(@Nonnull String path, @Nonnull Class classOfEnum) { + default > List getEnumList(@NotNull String path, @NotNull Class classOfEnum) { return getWrappedDocument().getEnumList(path, classOfEnum); } - @Nonnull + @NotNull @Override - default List getUUIDList(@Nonnull String path) { + default List getUUIDList(@NotNull String path) { return getWrappedDocument().getUUIDList(path); } - @Nonnull + @NotNull @Override - default List getCharacterList(@Nonnull String path) { + default List getCharacterList(@NotNull String path) { return getWrappedDocument().getCharacterList(path); } - @Nonnull + @NotNull @Override - default List getByteList(@Nonnull String path) { + default List getByteList(@NotNull String path) { return getWrappedDocument().getByteList(path); } - @Nonnull + @NotNull @Override - default List getShortList(@Nonnull String path) { + default List getShortList(@NotNull String path) { return getWrappedDocument().getShortList(path); } - @Nonnull + @NotNull @Override - default List getIntegerList(@Nonnull String path) { + default List getIntegerList(@NotNull String path) { return getWrappedDocument().getIntegerList(path); } - @Nonnull + @NotNull @Override - default List getLongList(@Nonnull String path) { + default List getLongList(@NotNull String path) { return getWrappedDocument().getLongList(path); } - @Nonnull + @NotNull @Override - default List getFloatList(@Nonnull String path) { + default List getFloatList(@NotNull String path) { return getWrappedDocument().getFloatList(path); } - @Nonnull + @NotNull @Override - default List getDoubleList(@Nonnull String path) { + default List getDoubleList(@NotNull String path) { return getWrappedDocument().getDoubleList(path); } @Nullable @Override - default UUID getUUID(@Nonnull String path) { + default UUID getUUID(@NotNull String path) { return getWrappedDocument().getUUID(path); } - @Nonnull + @NotNull @Override - default UUID getUUID(@Nonnull String path, @Nonnull UUID def) { + default UUID getUUID(@NotNull String path, @NotNull UUID def) { return getWrappedDocument().getUUID(path, def); } @Nullable @Override - default Date getDate(@Nonnull String path) { + default Date getDate(@NotNull String path) { return getWrappedDocument().getDate(path); } - @Nonnull + @NotNull @Override - default Date getDate(@Nonnull String path, @Nonnull Date def) { + default Date getDate(@NotNull String path, @NotNull Date def) { return getWrappedDocument().getDate(path, def); } @Nullable @Override - default OffsetDateTime getDateTime(@Nonnull String path) { + default OffsetDateTime getDateTime(@NotNull String path) { return getWrappedDocument().getDateTime(path); } - @Nonnull + @NotNull @Override - default OffsetDateTime getDateTime(@Nonnull String path, @Nonnull OffsetDateTime def) { + default OffsetDateTime getDateTime(@NotNull String path, @NotNull OffsetDateTime def) { return getWrappedDocument().getDateTime(path, def); } @Nullable @Override - default Color getColor(@Nonnull String path) { + default Color getColor(@NotNull String path) { return getWrappedDocument().getColor(path); } - @Nonnull + @NotNull @Override - default Color getColor(@Nonnull String path, @Nonnull Color def) { + default Color getColor(@NotNull String path, @NotNull Color def) { return getWrappedDocument().getColor(path, def); } @Nullable @Override - default > E getEnum(@Nonnull String path, @Nonnull Class classOfEnum) { + default > E getEnum(@NotNull String path, @NotNull Class classOfEnum) { return getWrappedDocument().getEnum(path, classOfEnum); } - @Nonnull + @NotNull @Override - default > E getEnum(@Nonnull String path, @Nonnull E def) { + default > E getEnum(@NotNull String path, @NotNull E def) { return getWrappedDocument().getEnum(path, def); } @Nullable @Override - default T getSerializable(@Nonnull String path, @Nonnull Class classOfT) { + default T getSerializable(@NotNull String path, @NotNull Class classOfT) { return getWrappedDocument().getSerializable(path, classOfT); } - @Nonnull + @NotNull @Override - default T getSerializable(@Nonnull String path, @Nonnull T def) { + default T getSerializable(@NotNull String path, @NotNull T def) { return getWrappedDocument().getSerializable(path, def); } @Nullable @Override - default Class getClass(@Nonnull String path) { + default Class getClass(@NotNull String path) { return getWrappedDocument().getClass(path); } - @Nonnull + @NotNull @Override - default Class getClass(@Nonnull String path, @Nonnull Class def) { + default Class getClass(@NotNull String path, @NotNull Class def) { return getWrappedDocument().getClass(path, def); } @Nullable @Override - default Version getVersion(@Nonnull String path) { + default Version getVersion(@NotNull String path) { return getWrappedDocument().getVersion(path); } - @Nonnull + @NotNull @Override - default Version getVersion(@Nonnull String path, @Nonnull Version def) { + default Version getVersion(@NotNull String path, @NotNull Version def) { return getWrappedDocument().getVersion(path, def); } @Nullable @Override - default byte[] getBinary(@Nonnull String path) { + default byte[] getBinary(@NotNull String path) { return getWrappedDocument().getBinary(path); } @Override - default boolean contains(@Nonnull String path) { + default boolean contains(@NotNull String path) { return getWrappedDocument().contains(path); } @Override - default boolean hasChildren(@Nonnull String path) { + default boolean hasChildren(@NotNull String path) { return getWrappedDocument().hasChildren(path); } @Override - default boolean isObject(@Nonnull String path) { + default boolean isObject(@NotNull String path) { return getWrappedDocument().isObject(path); } @Override - default boolean isList(@Nonnull String path) { + default boolean isList(@NotNull String path) { return getWrappedDocument().isList(path); } @Override - default boolean isDocument(@Nonnull String path) { + default boolean isDocument(@NotNull String path) { return getWrappedDocument().isDocument(path); } @@ -425,66 +425,66 @@ default int size() { return getWrappedDocument().size(); } - @Nonnull + @NotNull @Override default Map values() { return getWrappedDocument().values(); } - @Nonnull + @NotNull @Override default Map valuesAsStrings() { return getWrappedDocument().valuesAsStrings(); } - @Nonnull + @NotNull @Override default Map children() { return getWrappedDocument().children(); } - @Nonnull + @NotNull @Override - default Map mapValues(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + default Map mapValues(@NotNull Function keyMapper, @NotNull Function valueMapper) { return getWrappedDocument().mapValues(keyMapper, valueMapper); } - @Nonnull + @NotNull @Override - default Map mapDocuments(@Nonnull Function keyMapper, @Nonnull Function valueMapper) { + default Map mapDocuments(@NotNull Function keyMapper, @NotNull Function valueMapper) { return getWrappedDocument().mapDocuments(keyMapper, valueMapper); } - @Nonnull + @NotNull @Override - default R mapDocument(@Nonnull String path, @Nonnull Function mapper) { + default R mapDocument(@NotNull String path, @NotNull Function mapper) { return getWrappedDocument().mapDocument(path, mapper); } @Nullable @Override - default R mapDocumentNullable(@Nonnull String path, @Nonnull Function mapper) { + default R mapDocumentNullable(@NotNull String path, @NotNull Function mapper) { return getWrappedDocument().mapDocumentNullable(path, mapper); } - @Nonnull + @NotNull @Override default Collection keys() { return getWrappedDocument().keys(); } - @Nonnull + @NotNull @Override default Set> entrySet() { return getWrappedDocument().entrySet(); } @Override - default void forEach(@Nonnull BiConsumer action) { + default void forEach(@NotNull BiConsumer action) { getWrappedDocument().forEach(action); } - @Nonnull + @NotNull @Override default Document readonly() { return getWrappedDocument().readonly(); @@ -496,7 +496,7 @@ default Document getParent() { return getWrappedDocument().getParent(); } - @Nonnull + @NotNull @Override default Document getRoot() { return getWrappedDocument().getRoot(); diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java b/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java index 07db92082..ee8cbb703 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/exceptions/ConfigReadOnlyException.java @@ -1,10 +1,10 @@ package net.codingarea.commons.common.config.exceptions; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public final class ConfigReadOnlyException extends IllegalStateException { - public ConfigReadOnlyException(@Nonnull String action) { + public ConfigReadOnlyException(@NotNull String action) { super("Config." + action); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java b/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java index 0adf55e34..b5da63a99 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/debug/TimingsHelper.java @@ -3,8 +3,8 @@ import net.codingarea.commons.common.collection.NumberFormatter; import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.misc.ReflectionUtils; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -16,11 +16,11 @@ public final class TimingsHelper { private TimingsHelper() { } - public static void start(@Nonnull String id) { + public static void start(@NotNull String id) { timings.put(id, System.currentTimeMillis()); } - public static void stop(@Nonnull String id) { + public static void stop(@NotNull String id) { Long start = timings.remove(id); if (start == null) { LOGGER.warn("Stopped timing {} which was not started before", id); @@ -31,7 +31,7 @@ public static void stop(@Nonnull String id) { LOGGER.debug("Finished timings '{}' within {}ms ({}s)", id, time, NumberFormatter.DOUBLE_FLOATING_POINT.format(time / 1000d)); } - public static void restart(@Nonnull String id) { + public static void restart(@NotNull String id) { stop(id); start(id); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java index f1d30ba76..66f755852 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java +++ b/plugin/src/main/java/net/codingarea/commons/common/discord/DiscordWebhook.java @@ -1,9 +1,9 @@ package net.codingarea.commons.common.discord; import net.codingarea.commons.common.config.Document; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import javax.net.ssl.HttpsURLConnection; import java.awt.*; import java.io.IOException; @@ -32,22 +32,22 @@ private DiscordWebhook() { * * @param url The webhook URL obtained in Discord */ - public DiscordWebhook(@Nonnull String url) { + public DiscordWebhook(@NotNull String url) { this.url = url; } - public DiscordWebhook(@Nonnull String url, @Nonnull String username) { + public DiscordWebhook(@NotNull String url, @NotNull String username) { this.url = url; this.username = username; } - public DiscordWebhook(@Nonnull String url, @Nonnull String username, @Nonnull String avatarUrl) { + public DiscordWebhook(@NotNull String url, @NotNull String username, @NotNull String avatarUrl) { this.url = url; this.username = username; this.avatarUrl = avatarUrl; } - public DiscordWebhook(@Nonnull String url, @Nonnull String username, @Nonnull String avatarUrl, @Nonnull String content, @Nonnull List embeds, boolean tts) { + public DiscordWebhook(@NotNull String url, @NotNull String username, @NotNull String avatarUrl, @NotNull String content, @NotNull List embeds, boolean tts) { this.url = url; this.username = username; this.avatarUrl = avatarUrl; @@ -56,37 +56,37 @@ public DiscordWebhook(@Nonnull String url, @Nonnull String username, @Nonnull St this.tts = tts; } - @Nonnull - public DiscordWebhook setUrl(@Nonnull String url) { + @NotNull + public DiscordWebhook setUrl(@NotNull String url) { this.url = url; return this; } - @Nonnull + @NotNull public DiscordWebhook setContent(@Nullable String content) { this.content = content; return this; } - @Nonnull + @NotNull public DiscordWebhook setUsername(@Nullable String username) { this.username = username; return this; } - @Nonnull + @NotNull public DiscordWebhook setAvatarUrl(@Nullable String avatarUrl) { this.avatarUrl = avatarUrl; return this; } - @Nonnull + @NotNull public DiscordWebhook setTts(boolean tts) { this.tts = tts; return this; } - @Nonnull + @NotNull public DiscordWebhook addEmbed(EmbedObject embed) { this.embeds.add(embed); return this; @@ -197,8 +197,8 @@ public void execute() throws IOException { connection.disconnect(); } - @Nonnull - public DiscordWebhook replaceEverywhere(@Nonnull String trigger, @Nonnull String replacement) { + @NotNull + public DiscordWebhook replaceEverywhere(@NotNull String trigger, @NotNull String replacement) { if (content != null) content = content.replace(trigger, replacement); if (username != null) username = username.replace(trigger, replacement); for (EmbedObject embed : embeds) { @@ -232,7 +232,7 @@ public EmbedObject() { public EmbedObject(@Nullable String title, @Nullable String description, @Nullable String url, @Nullable Color color, @Nullable Footer footer, @Nullable Thumbnail thumbnail, @Nullable Image image, @Nullable Author author, - @Nonnull List fields) { + @NotNull List fields) { this.title = title; this.description = description; this.url = url; @@ -280,55 +280,55 @@ public List getFields() { return fields; } - @Nonnull + @NotNull public EmbedObject setTitle(String title) { this.title = title; return this; } - @Nonnull + @NotNull public EmbedObject setDescription(String description) { this.description = description; return this; } - @Nonnull + @NotNull public EmbedObject setUrl(String url) { this.url = url; return this; } - @Nonnull + @NotNull public EmbedObject setColor(Color color) { this.color = color; return this; } - @Nonnull + @NotNull public EmbedObject setFooter(String text, String icon) { this.footer = new Footer(text, icon); return this; } - @Nonnull + @NotNull public EmbedObject setThumbnail(String url) { this.thumbnail = new Thumbnail(url); return this; } - @Nonnull + @NotNull public EmbedObject setImage(String url) { this.image = new Image(url); return this; } - @Nonnull + @NotNull public EmbedObject setAuthor(String name, String url, String icon) { this.author = new Author(name, url, icon); return this; } - @Nonnull + @NotNull public EmbedObject addField(String name, String value, boolean inline) { this.fields.add(new Field(name, value, inline)); return this; @@ -487,8 +487,8 @@ public DiscordWebhook clone() { return new DiscordWebhook(url, username, avatarUrl, content, clone(embeds, EmbedObject::clone), tts); } - @Nonnull - protected static List clone(@Nonnull Collection collection, @Nonnull Function cloner) { + @NotNull + protected static List clone(@NotNull Collection collection, @NotNull Function cloner) { List list = new ArrayList<>(collection.size()); for (T current : collection) { list.add(cloner.apply(current)); diff --git a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java index 3c7bff9a9..6b0a2640f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java +++ b/plugin/src/main/java/net/codingarea/commons/common/function/ExceptionallyFunction.java @@ -1,9 +1,8 @@ package net.codingarea.commons.common.function; import net.codingarea.commons.common.collection.WrappedException; +import org.jetbrains.annotations.NotNull; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; import java.util.function.Function; @FunctionalInterface @@ -20,8 +19,7 @@ default R apply(T t) { R applyExceptionally(T t) throws Exception; - @Nonnull - @CheckReturnValue + @NotNull static ExceptionallyFunction identity() { return t -> t; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java index 203aae04b..e54c2765a 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java @@ -12,11 +12,11 @@ import net.codingarea.commons.common.logging.lib.JavaILogger; import net.codingarea.commons.common.logging.lib.Slf4jILogger; import net.codingarea.commons.common.misc.ReflectionUtils; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.LoggerFactory; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.io.PrintStream; import java.nio.charset.StandardCharsets; import java.util.ServiceLoader; @@ -32,7 +32,7 @@ private static class Data { private boolean slf4j, slf4jApi; } - @Nonnull + @NotNull private static Data getData() { if (data == null) createData(); @@ -67,7 +67,7 @@ private static synchronized void createData() { data.slf4jApi = slf4jApi; } - @Nonnull + @NotNull public static ILoggerFactory getFactory() { if (factory == null) factory = getFallbackFactory(); @@ -75,7 +75,7 @@ public static ILoggerFactory getFactory() { return factory; } - @Nonnull + @NotNull private static ILoggerFactory getFallbackFactory() { return isSlf4jImplAvailable() ? new Slf4jLoggerFactory() : isSlf4jApiAvailable() ? new DefaultLoggerFactory(SimpleLogger::new) : @@ -95,119 +95,119 @@ static boolean isSlf4jApiAvailable() { return Holder.getData().slf4jApi; } - @Nonnull + @NotNull @CheckReturnValue static ILogger forName(@Nullable String name) { return getFactory().forName(name); } - @Nonnull + @NotNull @CheckReturnValue static ILogger forClass(@Nullable Class clazz) { return forName(clazz == null ? null : clazz.getSimpleName()); } - @Nonnull + @NotNull @CheckReturnValue - static ILogger forClassOf(@Nonnull Object object) { + static ILogger forClassOf(@NotNull Object object) { return forClass(object.getClass()); } - @Nonnull + @NotNull @CheckReturnValue static ILogger forThisClass() { return forClass(ReflectionUtils.getCaller()); } - @Nonnull + @NotNull @CheckReturnValue - static JavaILogger forJavaLogger(@Nonnull java.util.logging.Logger logger) { + static JavaILogger forJavaLogger(@NotNull java.util.logging.Logger logger) { return new JavaLoggerWrapper(logger); } - @Nonnull + @NotNull @CheckReturnValue - static ILogger forSlf4jLogger(@Nonnull org.slf4j.Logger logger) { + static ILogger forSlf4jLogger(@NotNull org.slf4j.Logger logger) { return logger instanceof ILogger ? (ILogger) logger : new Slf4jLoggerWrapper(logger); } - static void setFactory(@Nonnull ILoggerFactory factory) { + static void setFactory(@NotNull ILoggerFactory factory) { Preconditions.checkNotNull(factory); Holder.factory = factory; } - static void setConstantFactory(@Nonnull ILogger logger) { + static void setConstantFactory(@NotNull ILogger logger) { setFactory(new ConstantLoggerFactory(logger)); } - @Nonnull + @NotNull static ILoggerFactory getFactory() { return Holder.getFactory(); } - void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args); + void log(@NotNull LogLevel level, @Nullable String message, @NotNull Object... args); - default void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + default void log(@NotNull LogLevel level, @Nullable Object message, @NotNull Object... args) { log(level, String.valueOf(message), args); } - default void error(@Nullable String message, @Nonnull Object... args) { + default void error(@Nullable String message, @NotNull Object... args) { log(LogLevel.ERROR, message, args); } - default void error(@Nullable Object message, @Nonnull Object... args) { + default void error(@Nullable Object message, @NotNull Object... args) { log(LogLevel.ERROR, message, args); } - default void warn(@Nullable String message, @Nonnull Object... args) { + default void warn(@Nullable String message, @NotNull Object... args) { log(LogLevel.WARN, message, args); } - default void warn(@Nullable Object message, @Nonnull Object... args) { + default void warn(@Nullable Object message, @NotNull Object... args) { log(LogLevel.WARN, message, args); } - default void info(@Nullable String message, @Nonnull Object... args) { + default void info(@Nullable String message, @NotNull Object... args) { log(LogLevel.INFO, message, args); } - default void info(@Nullable Object message, @Nonnull Object... args) { + default void info(@Nullable Object message, @NotNull Object... args) { log(LogLevel.INFO, message, args); } - default void status(@Nullable String message, @Nonnull Object... args) { + default void status(@Nullable String message, @NotNull Object... args) { log(LogLevel.STATUS, message, args); } - default void status(@Nullable Object message, @Nonnull Object... args) { + default void status(@Nullable Object message, @NotNull Object... args) { log(LogLevel.STATUS, message, args); } - default void extended(@Nullable String message, @Nonnull Object... args) { + default void extended(@Nullable String message, @NotNull Object... args) { log(LogLevel.EXTENDED, message, args); } - default void extended(@Nullable Object message, @Nonnull Object... args) { + default void extended(@Nullable Object message, @NotNull Object... args) { log(LogLevel.EXTENDED, message, args); } - default void debug(@Nullable String message, @Nonnull Object... args) { + default void debug(@Nullable String message, @NotNull Object... args) { log(LogLevel.DEBUG, message, args); } - default void debug(@Nullable Object message, @Nonnull Object... args) { + default void debug(@Nullable Object message, @NotNull Object... args) { log(LogLevel.DEBUG, message, args); } - default void trace(@Nullable String message, @Nonnull Object... args) { + default void trace(@Nullable String message, @NotNull Object... args) { log(LogLevel.TRACE, message, args); } - default void trace(@Nullable Object message, @Nonnull Object... args) { + default void trace(@Nullable Object message, @NotNull Object... args) { log(LogLevel.TRACE, message, args); } - default boolean isLevelEnabled(@Nonnull LogLevel level) { + default boolean isLevelEnabled(@NotNull LogLevel level) { return level.isShownAtLoggerLevel(getMinLevel()); } @@ -235,13 +235,13 @@ default boolean isErrorEnabled() { return isLevelEnabled(LogLevel.ERROR); } - @Nonnull + @NotNull LogLevel getMinLevel(); - @Nonnull - ILogger setMinLevel(@Nonnull LogLevel level); + @NotNull + ILogger setMinLevel(@NotNull LogLevel level); - @Nonnull + @NotNull @CheckReturnValue default Slf4jILogger slf4j() { if (this instanceof Slf4jILogger) @@ -249,7 +249,7 @@ default Slf4jILogger slf4j() { throw new IllegalStateException(this.getClass().getName() + " cannot be converted to Slf4jILogger"); } - @Nonnull + @NotNull @CheckReturnValue default JavaILogger java() { if (this instanceof JavaILogger) @@ -257,9 +257,9 @@ default JavaILogger java() { throw new IllegalStateException(this.getClass().getName() + " cannot be converted to JavaILogger"); } - @Nonnull + @NotNull @CheckReturnValue - default PrintStream asPrintStream(@Nonnull LogLevel level) { + default PrintStream asPrintStream(@NotNull LogLevel level) { try { return new PrintStream(new LogOutputStream(this, level), true, StandardCharsets.UTF_8.name()); } catch (Exception ex) { @@ -267,9 +267,9 @@ default PrintStream asPrintStream(@Nonnull LogLevel level) { } } - @Nonnull + @NotNull @CheckReturnValue - static String formatMessage(@Nullable Object messageObject, @Nonnull Object... args) { + static String formatMessage(@Nullable Object messageObject, @NotNull Object... args) { StringBuilder message = new StringBuilder(String.valueOf(messageObject)); for (Object arg : args) { if (arg instanceof Throwable) continue; diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java index 25f4528cc..c695b6fbb 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/ILoggerFactory.java @@ -1,15 +1,15 @@ package net.codingarea.commons.common.logging; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public interface ILoggerFactory { - @Nonnull + @NotNull @CheckReturnValue ILogger forName(@Nullable String name); - void setDefaultLevel(@Nonnull LogLevel level); + void setDefaultLevel(@NotNull LogLevel level); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java index 13d78cecf..4e7d651fe 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogLevel.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.logging; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.util.logging.Level; public enum LogLevel { @@ -18,7 +19,7 @@ public enum LogLevel { private final int value; private final boolean highlighted; - LogLevel(int value, @Nonnull String uppercaseName, @Nonnull String lowercaseName, @Nonnull Level javaLevel, boolean highlighted) { + LogLevel(int value, @NotNull String uppercaseName, @NotNull String lowercaseName, @NotNull Level javaLevel, boolean highlighted) { this.uppercaseName = uppercaseName; this.lowercaseName = lowercaseName; this.javaLevel = javaLevel; @@ -26,12 +27,12 @@ public enum LogLevel { this.highlighted = highlighted; } - @Nonnull + @NotNull public Level getJavaUtilLevel() { return javaLevel; } - public boolean isShownAtLoggerLevel(@Nonnull LogLevel loggerLevel) { + public boolean isShownAtLoggerLevel(@NotNull LogLevel loggerLevel) { return this.getValue() >= loggerLevel.getValue(); } @@ -39,12 +40,12 @@ public int getValue() { return value; } - @Nonnull + @NotNull public String getLowerCaseName() { return lowercaseName; } - @Nonnull + @NotNull public String getUpperCaseName() { return uppercaseName; } @@ -53,8 +54,8 @@ public boolean isHighlighted() { return highlighted; } - @Nonnull - public static LogLevel fromJavaLevel(@Nonnull Level level) { + @NotNull + public static LogLevel fromJavaLevel(@NotNull Level level) { for (LogLevel logLevel : values()) { if (logLevel.getJavaUtilLevel().intValue() == level.intValue()) return logLevel; @@ -62,7 +63,7 @@ public static LogLevel fromJavaLevel(@Nonnull Level level) { return INFO; } - @Nonnull + @NotNull public static LogLevel fromValue(int value) { for (LogLevel level : values()) { if (level.getValue() == value) @@ -71,8 +72,8 @@ public static LogLevel fromValue(int value) { return INFO; } - @Nonnull - public static LogLevel fromName(@Nonnull String name) { + @NotNull + public static LogLevel fromName(@NotNull String name) { for (LogLevel level : values()) { if (level.getUpperCaseName().equalsIgnoreCase(name)) return level; diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java index de7b796a9..348809947 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LogOutputStream.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.logging; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -10,7 +11,7 @@ public class LogOutputStream extends ByteArrayOutputStream { private final ILogger logger; private final LogLevel level; - public LogOutputStream(@Nonnull ILogger logger, @Nonnull LogLevel level) { + public LogOutputStream(@NotNull ILogger logger, @NotNull LogLevel level) { this.logger = logger; this.level = level; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java b/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java index 54e721dae..2704e375c 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/LoggingApiUser.java @@ -1,38 +1,38 @@ package net.codingarea.commons.common.logging; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public interface LoggingApiUser { - @Nonnull + @NotNull ILogger getTargetLogger(); - default void error(@Nullable Object message, @Nonnull Object... args) { + default void error(@Nullable Object message, @NotNull Object... args) { getTargetLogger().error(message, args); } - default void warn(@Nullable Object message, @Nonnull Object... args) { + default void warn(@Nullable Object message, @NotNull Object... args) { getTargetLogger().warn(message, args); } - default void info(@Nullable Object message, @Nonnull Object... args) { + default void info(@Nullable Object message, @NotNull Object... args) { getTargetLogger().info(message, args); } - default void status(@Nullable Object message, @Nonnull Object... args) { + default void status(@Nullable Object message, @NotNull Object... args) { getTargetLogger().status(message, args); } - default void extended(@Nullable Object message, @Nonnull Object... args) { + default void extended(@Nullable Object message, @NotNull Object... args) { getTargetLogger().extended(message, args); } - default void debug(@Nullable Object message, @Nonnull Object... args) { + default void debug(@Nullable Object message, @NotNull Object... args) { getTargetLogger().debug(message, args); } - default void trace(@Nullable Object message, @Nonnull Object... args) { + default void trace(@Nullable Object message, @NotNull Object... args) { getTargetLogger().trace(message, args); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java index 37cde09d7..f21da6f0b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/WrappedILogger.java @@ -2,98 +2,98 @@ import net.codingarea.commons.common.logging.lib.JavaILogger; import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.io.PrintStream; public interface WrappedILogger extends ILogger { - @Nonnull + @NotNull ILogger getWrappedLogger(); @Override - default void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + default void log(@NotNull LogLevel level, @Nullable String message, @NotNull Object... args) { getWrappedLogger().log(level, message, args); } @Override - default void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + default void log(@NotNull LogLevel level, @Nullable Object message, @NotNull Object... args) { getWrappedLogger().log(level, message, args); } @Override - default void error(@Nullable String message, @Nonnull Object... args) { + default void error(@Nullable String message, @NotNull Object... args) { getWrappedLogger().error(message, args); } @Override - default void error(@Nullable Object message, @Nonnull Object... args) { + default void error(@Nullable Object message, @NotNull Object... args) { getWrappedLogger().error(message, args); } @Override - default void warn(@Nullable String message, @Nonnull Object... args) { + default void warn(@Nullable String message, @NotNull Object... args) { getWrappedLogger().warn(message, args); } @Override - default void warn(@Nullable Object message, @Nonnull Object... args) { + default void warn(@Nullable Object message, @NotNull Object... args) { getWrappedLogger().warn(message, args); } @Override - default void info(@Nullable String message, @Nonnull Object... args) { + default void info(@Nullable String message, @NotNull Object... args) { getWrappedLogger().info(message, args); } @Override - default void info(@Nullable Object message, @Nonnull Object... args) { + default void info(@Nullable Object message, @NotNull Object... args) { getWrappedLogger().info(message, args); } @Override - default void status(@Nullable String message, @Nonnull Object... args) { + default void status(@Nullable String message, @NotNull Object... args) { getWrappedLogger().status(message, args); } @Override - default void status(@Nullable Object message, @Nonnull Object... args) { + default void status(@Nullable Object message, @NotNull Object... args) { getWrappedLogger().status(message, args); } @Override - default void extended(@Nullable String message, @Nonnull Object... args) { + default void extended(@Nullable String message, @NotNull Object... args) { getWrappedLogger().extended(message, args); } @Override - default void extended(@Nullable Object message, @Nonnull Object... args) { + default void extended(@Nullable Object message, @NotNull Object... args) { getWrappedLogger().extended(message, args); } @Override - default void debug(@Nullable String message, @Nonnull Object... args) { + default void debug(@Nullable String message, @NotNull Object... args) { getWrappedLogger().debug(message, args); } @Override - default void debug(@Nullable Object message, @Nonnull Object... args) { + default void debug(@Nullable Object message, @NotNull Object... args) { getWrappedLogger().debug(message, args); } @Override - default void trace(@Nullable String message, @Nonnull Object... args) { + default void trace(@Nullable String message, @NotNull Object... args) { getWrappedLogger().trace(message, args); } @Override - default void trace(@Nullable Object message, @Nonnull Object... args) { + default void trace(@Nullable Object message, @NotNull Object... args) { getWrappedLogger().trace(message, args); } @Override - default boolean isLevelEnabled(@Nonnull LogLevel level) { + default boolean isLevelEnabled(@NotNull LogLevel level) { return getWrappedLogger().isLevelEnabled(level); } @@ -127,33 +127,33 @@ default boolean isErrorEnabled() { return getWrappedLogger().isErrorEnabled(); } - @Nonnull + @NotNull @Override default LogLevel getMinLevel() { return getWrappedLogger().getMinLevel(); } - @Nonnull + @NotNull @Override - default ILogger setMinLevel(@Nonnull LogLevel level) { + default ILogger setMinLevel(@NotNull LogLevel level) { return getWrappedLogger().setMinLevel(level); } - @Nonnull + @NotNull @Override default Slf4jILogger slf4j() { return getWrappedLogger().slf4j(); } - @Nonnull + @NotNull @Override default JavaILogger java() { return getWrappedLogger().java(); } - @Nonnull + @NotNull @Override - default PrintStream asPrintStream(@Nonnull LogLevel level) { + default PrintStream asPrintStream(@NotNull LogLevel level) { return getWrappedLogger().asPrintStream(level); } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java index b3386d795..22c999256 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledAsyncLogger.java @@ -2,8 +2,8 @@ import net.codingarea.commons.common.collection.NamedThreadFactory; import net.codingarea.commons.common.logging.LogLevel; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.concurrent.Executor; import java.util.concurrent.Executors; @@ -11,12 +11,12 @@ public class HandledAsyncLogger extends HandledLogger { protected final Executor executor = Executors.newSingleThreadExecutor(new NamedThreadFactory("AsyncLogTask")); - public HandledAsyncLogger(@Nonnull LogLevel initialLevel) { + public HandledAsyncLogger(@NotNull LogLevel initialLevel) { super(initialLevel); } @Override - protected void log0(@Nonnull LogEntry entry) { + protected void log0(@NotNull LogEntry entry) { executor.execute(() -> logNow(entry)); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java index 76b2b8f6b..7bb9db622 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledLogger.java @@ -2,9 +2,9 @@ import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.logging.LogLevel; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.time.Instant; import java.util.Arrays; import java.util.Collection; @@ -15,12 +15,12 @@ public abstract class HandledLogger implements ILogger { protected final Collection handlers = new CopyOnWriteArrayList<>(); protected LogLevel level; - public HandledLogger(@Nonnull LogLevel initialLevel) { + public HandledLogger(@NotNull LogLevel initialLevel) { this.level = initialLevel; } @Override - public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + public void log(@NotNull LogLevel level, @Nullable String message, @NotNull Object... args) { if (!level.isShownAtLoggerLevel(this.level)) return; Throwable exception = null; for (Object arg : args) { @@ -30,14 +30,14 @@ public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Obje log0(new LogEntry(Instant.now(), Thread.currentThread().getName(), ILogger.formatMessage(message, args), level, exception)); } - public void log(@Nonnull LogEntry entry) { + public void log(@NotNull LogEntry entry) { if (!entry.getLevel().isShownAtLoggerLevel(this.level)) return; log0(entry); } - protected abstract void log0(@Nonnull LogEntry entry); + protected abstract void log0(@NotNull LogEntry entry); - protected void logNow(@Nonnull LogEntry entry) { + protected void logNow(@NotNull LogEntry entry) { for (LogHandler handler : handlers) { try { handler.handle(entry); @@ -47,21 +47,21 @@ protected void logNow(@Nonnull LogEntry entry) { } } - @Nonnull - public HandledLogger addHandler(@Nonnull LogHandler... handler) { + @NotNull + public HandledLogger addHandler(@NotNull LogHandler... handler) { handlers.addAll(Arrays.asList(handler)); return this; } - @Nonnull + @NotNull @Override public LogLevel getMinLevel() { return level; } - @Nonnull + @NotNull @Override - public ILogger setMinLevel(@Nonnull LogLevel level) { + public ILogger setMinLevel(@NotNull LogLevel level) { this.level = level; return this; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java index 95b2de1fc..e4de76cdc 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/HandledSyncLogger.java @@ -1,17 +1,16 @@ package net.codingarea.commons.common.logging.handler; import net.codingarea.commons.common.logging.LogLevel; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class HandledSyncLogger extends HandledLogger { - public HandledSyncLogger(@Nonnull LogLevel initialLevel) { + public HandledSyncLogger(@NotNull LogLevel initialLevel) { super(initialLevel); } @Override - protected void log0(@Nonnull LogEntry entry) { + protected void log0(@NotNull LogEntry entry) { logNow(entry); } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java index 2c0b38f2c..22183919c 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogEntry.java @@ -1,9 +1,9 @@ package net.codingarea.commons.common.logging.handler; import net.codingarea.commons.common.logging.LogLevel; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.time.Instant; public class LogEntry { @@ -14,7 +14,7 @@ public class LogEntry { private LogLevel level; private Throwable exception; - public LogEntry(@Nonnull Instant timestamp, @Nonnull String threadName, @Nonnull String message, @Nonnull LogLevel level, @Nullable Throwable exception) { + public LogEntry(@NotNull Instant timestamp, @NotNull String threadName, @NotNull String message, @NotNull LogLevel level, @Nullable Throwable exception) { this.timestamp = timestamp; this.threadName = threadName; this.message = message; @@ -22,22 +22,22 @@ public LogEntry(@Nonnull Instant timestamp, @Nonnull String threadName, @Nonnull this.exception = exception; } - @Nonnull + @NotNull public Instant getTimestamp() { return timestamp; } - @Nonnull + @NotNull public String getThreadName() { return threadName; } - @Nonnull + @NotNull public String getMessage() { return message; } - @Nonnull + @NotNull public LogLevel getLevel() { return level; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java index 01f9f09ca..42016cdda 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/handler/LogHandler.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.logging.handler; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.text.DateFormat; import java.text.SimpleDateFormat; @@ -8,6 +9,6 @@ public interface LogHandler { DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss.SSS"); - void handle(@Nonnull LogEntry entry) throws Exception; + void handle(@NotNull LogEntry entry) throws Exception; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java index 49eb8665d..e1d176f25 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/BukkitLoggerWrapper.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.logging.internal; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.util.logging.Level; import java.util.logging.Logger; @@ -10,13 +11,13 @@ */ public class BukkitLoggerWrapper extends JavaLoggerWrapper { - public BukkitLoggerWrapper(@Nonnull Logger logger) { + public BukkitLoggerWrapper(@NotNull Logger logger) { super(logger); } - @Nonnull + @NotNull @Override - protected Level mapLevel(@Nonnull Level level) { + protected Level mapLevel(@NotNull Level level) { if (isLoggable(level) && level.intValue() < Level.INFO.intValue()) return Level.INFO; return level; diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java index eaf5a4d4d..39ad2d545 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/FallbackLogger.java @@ -2,10 +2,9 @@ import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.logging.LogLevel; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.io.PrintStream; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; @@ -26,7 +25,7 @@ public FallbackLogger() { } @Override - public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + public void log(@NotNull LogLevel level, @Nullable String message, @NotNull Object... args) { if (!isLevelEnabled(level)) return; stream.println(getLogMessage(level, ILogger.formatMessage(message, args), name)); for (Object arg : args) { @@ -35,22 +34,21 @@ public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Obje } } - @Nonnull + @NotNull @Override - public FallbackLogger setMinLevel(@Nonnull LogLevel level) { + public FallbackLogger setMinLevel(@NotNull LogLevel level) { this.level = level; return this; } - @Nonnull + @NotNull @Override public LogLevel getMinLevel() { return level; } - @Nonnull - @CheckReturnValue - public static String getLogMessage(@Nonnull LogLevel level, @Nonnull String message, @Nullable String name) { + @NotNull + public static String getLogMessage(@NotNull LogLevel level, @NotNull String message, @Nullable String name) { Thread thread = Thread.currentThread(); String threadName = thread.getName(); String time = OffsetDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss.SSS")); diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java index 43e5d6424..7fa76ac85 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/JavaLoggerWrapper.java @@ -3,9 +3,9 @@ import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.logging.LogLevel; import net.codingarea.commons.common.logging.lib.JavaILogger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ResourceBundle; import java.util.function.Supplier; import java.util.logging.*; @@ -14,7 +14,7 @@ public class JavaLoggerWrapper extends JavaILogger { protected final Logger logger; - public JavaLoggerWrapper(@Nonnull Logger logger) { + public JavaLoggerWrapper(@NotNull Logger logger) { super(null, null); this.logger = logger; } @@ -305,30 +305,30 @@ public String toString() { return logger.toString(); } - protected void mapLevel(@Nonnull LogRecord record) { + protected void mapLevel(@NotNull LogRecord record) { record.setLevel(mapLevel(record.getLevel())); } - @Nonnull - protected Level mapLevel(@Nonnull Level level) { + @NotNull + protected Level mapLevel(@NotNull Level level) { return level; } - @Nonnull + @NotNull @Override - public JavaILogger setMinLevel(@Nonnull LogLevel level) { + public JavaILogger setMinLevel(@NotNull LogLevel level) { setLevel(level.getJavaUtilLevel()); return this; } - @Nonnull + @NotNull @Override public LogLevel getMinLevel() { return LogLevel.fromJavaLevel(logger.getLevel()); } @Override - public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + public void log(@NotNull LogLevel level, @Nullable String message, @NotNull Object... args) { Throwable thrown = null; for (Object arg : args) { if (arg instanceof Throwable) @@ -338,57 +338,57 @@ public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Obje } @Override - public void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + public void log(@NotNull LogLevel level, @Nullable Object message, @NotNull Object... args) { log(level, String.valueOf(message), args); } @Override - public void error(@Nullable String message, @Nonnull Object... args) { + public void error(@Nullable String message, @NotNull Object... args) { log(LogLevel.ERROR, message, args); } @Override - public void error(@Nullable Object message, @Nonnull Object... args) { + public void error(@Nullable Object message, @NotNull Object... args) { log(LogLevel.ERROR, message, args); } @Override - public void warn(@Nullable String message, @Nonnull Object... args) { + public void warn(@Nullable String message, @NotNull Object... args) { log(LogLevel.WARN, message, args); } @Override - public void warn(@Nullable Object message, @Nonnull Object... args) { + public void warn(@Nullable Object message, @NotNull Object... args) { log(LogLevel.WARN, message, args); } @Override - public void info(@Nullable String message, @Nonnull Object... args) { + public void info(@Nullable String message, @NotNull Object... args) { log(LogLevel.INFO, message, args); } @Override - public void info(@Nullable Object message, @Nonnull Object... args) { + public void info(@Nullable Object message, @NotNull Object... args) { log(LogLevel.INFO, message, args); } @Override - public void status(@Nullable String message, @Nonnull Object... args) { + public void status(@Nullable String message, @NotNull Object... args) { log(LogLevel.STATUS, message, args); } @Override - public void status(@Nullable Object message, @Nonnull Object... args) { + public void status(@Nullable Object message, @NotNull Object... args) { log(LogLevel.STATUS, message, args); } @Override - public void debug(@Nullable String message, @Nonnull Object... args) { + public void debug(@Nullable String message, @NotNull Object... args) { log(LogLevel.DEBUG, message, args); } @Override - public void debug(@Nullable Object message, @Nonnull Object... args) { + public void debug(@Nullable Object message, @NotNull Object... args) { log(LogLevel.DEBUG, message, args); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java index 5fdc7351e..479d5a1b5 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/SimpleLogger.java @@ -2,11 +2,10 @@ import net.codingarea.commons.common.logging.LogLevel; import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Marker; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - public class SimpleLogger extends FallbackLogger implements Slf4jILogger { public SimpleLogger(@Nullable String name) { @@ -18,67 +17,67 @@ public SimpleLogger() { } @Override - public void log(@Nonnull LogLevel level, @Nullable Object message, @Nonnull Object... args) { + public void log(@NotNull LogLevel level, @Nullable Object message, @NotNull Object... args) { super.log(level, message, args); } @Override - public void error(@Nullable String message, @Nonnull Object... args) { + public void error(@Nullable String message, @NotNull Object... args) { super.error(message, args); } @Override - public void error(@Nullable Object message, @Nonnull Object... args) { + public void error(@Nullable Object message, @NotNull Object... args) { super.error(message, args); } @Override - public void warn(@Nullable String message, @Nonnull Object... args) { + public void warn(@Nullable String message, @NotNull Object... args) { super.warn(message, args); } @Override - public void warn(@Nullable Object message, @Nonnull Object... args) { + public void warn(@Nullable Object message, @NotNull Object... args) { super.warn(message, args); } @Override - public void info(@Nullable String message, @Nonnull Object... args) { + public void info(@Nullable String message, @NotNull Object... args) { super.info(message, args); } @Override - public void info(@Nullable Object message, @Nonnull Object... args) { + public void info(@Nullable Object message, @NotNull Object... args) { super.info(message, args); } @Override - public void status(@Nullable String message, @Nonnull Object... args) { + public void status(@Nullable String message, @NotNull Object... args) { super.status(message, args); } @Override - public void status(@Nullable Object message, @Nonnull Object... args) { + public void status(@Nullable Object message, @NotNull Object... args) { super.status(message, args); } @Override - public void debug(@Nullable String message, @Nonnull Object... args) { + public void debug(@Nullable String message, @NotNull Object... args) { super.debug(message, args); } @Override - public void debug(@Nullable Object message, @Nonnull Object... args) { + public void debug(@Nullable Object message, @NotNull Object... args) { super.debug(message, args); } @Override - public void trace(@Nullable String message, @Nonnull Object... args) { + public void trace(@Nullable String message, @NotNull Object... args) { super.trace(message, args); } @Override - public void trace(@Nullable Object message, @Nonnull Object... args) { + public void trace(@Nullable Object message, @NotNull Object... args) { super.trace(message, args); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java index 0462ffdbb..09727de4f 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jILoggerWrapper.java @@ -3,19 +3,18 @@ import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.logging.WrappedILogger; import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import org.jetbrains.annotations.NotNull; import org.slf4j.helpers.MarkerIgnoringBase; -import javax.annotation.Nonnull; - public class Slf4jILoggerWrapper extends MarkerIgnoringBase implements WrappedILogger, Slf4jILogger { private final ILogger logger; - public Slf4jILoggerWrapper(@Nonnull ILogger logger) { + public Slf4jILoggerWrapper(@NotNull ILogger logger) { this.logger = logger; } - @Nonnull + @NotNull @Override public ILogger getWrappedLogger() { return logger; diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java index 567dadc8d..4b6078e7e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/Slf4jLoggerWrapper.java @@ -3,17 +3,16 @@ import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.logging.LogLevel; import net.codingarea.commons.common.logging.lib.Slf4jILogger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.Marker; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - public class Slf4jLoggerWrapper implements Slf4jILogger { protected final Logger logger; - public Slf4jLoggerWrapper(@Nonnull Logger logger) { + public Slf4jLoggerWrapper(@NotNull Logger logger) { this.logger = logger; } @@ -283,7 +282,7 @@ public void error(String format, Object arg1, Object arg2) { } @Override - public void log(@Nonnull LogLevel level, @Nullable String message, @Nonnull Object... args) { + public void log(@NotNull LogLevel level, @Nullable String message, @NotNull Object... args) { switch (level) { case TRACE: trace(message, args); @@ -344,7 +343,7 @@ public void error(Marker marker, String msg, Throwable t) { logger.error(marker, msg, t); } - @Nonnull + @NotNull @Override public LogLevel getMinLevel() { if (logger.isTraceEnabled()) { @@ -360,9 +359,9 @@ public LogLevel getMinLevel() { } } - @Nonnull + @NotNull @Override - public ILogger setMinLevel(@Nonnull LogLevel level) { + public ILogger setMinLevel(@NotNull LogLevel level) { return this; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java index f073b4aa0..be9193791 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/ConstantLoggerFactory.java @@ -3,26 +3,25 @@ import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.logging.ILoggerFactory; import net.codingarea.commons.common.logging.LogLevel; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public class ConstantLoggerFactory implements ILoggerFactory { protected final ILogger logger; - public ConstantLoggerFactory(@Nonnull ILogger logger) { + public ConstantLoggerFactory(@NotNull ILogger logger) { this.logger = logger; } - @Nonnull + @NotNull @Override public ILogger forName(@Nullable String name) { return logger; } @Override - public void setDefaultLevel(@Nonnull LogLevel level) { + public void setDefaultLevel(@NotNull LogLevel level) { logger.setMinLevel(level); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java index 6ded66533..6224eea6c 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/DefaultLoggerFactory.java @@ -3,10 +3,10 @@ import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.logging.ILoggerFactory; import net.codingarea.commons.common.logging.LogLevel; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; @@ -17,11 +17,11 @@ public class DefaultLoggerFactory implements ILoggerFactory { protected final Function creator; protected LogLevel level = LogLevel.DEBUG; - public DefaultLoggerFactory(@Nonnull Function creator) { + public DefaultLoggerFactory(@NotNull Function creator) { this.creator = creator; } - @Nonnull + @NotNull @Override @CheckReturnValue public synchronized ILogger forName(@Nullable String name) { @@ -29,7 +29,7 @@ public synchronized ILogger forName(@Nullable String name) { } @Override - public void setDefaultLevel(@Nonnull LogLevel level) { + public void setDefaultLevel(@NotNull LogLevel level) { this.level = level; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java index 5357c563f..f2c75f1a3 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/internal/factory/Slf4jLoggerFactory.java @@ -3,14 +3,13 @@ import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.logging.ILoggerFactory; import net.codingarea.commons.common.logging.LogLevel; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.LoggerFactory; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - public class Slf4jLoggerFactory implements ILoggerFactory { - @Nonnull + @NotNull @Override public ILogger forName(@Nullable String name) { return ILogger.forSlf4jLogger( @@ -19,7 +18,7 @@ public ILogger forName(@Nullable String name) { } @Override - public void setDefaultLevel(@Nonnull LogLevel level) { + public void setDefaultLevel(@NotNull LogLevel level) { } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java index e6d559bb5..54f777bdf 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/JavaILogger.java @@ -2,8 +2,8 @@ import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.logging.LogLevel; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.logging.Logger; public abstract class JavaILogger extends Logger implements ILogger { @@ -12,8 +12,8 @@ protected JavaILogger(String name, String resourceBundleName) { super(name, resourceBundleName); } - @Nonnull + @NotNull @Override - public abstract JavaILogger setMinLevel(@Nonnull LogLevel level); + public abstract JavaILogger setMinLevel(@NotNull LogLevel level); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java index 123980c8f..ce5234273 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/lib/Slf4jILogger.java @@ -1,11 +1,10 @@ package net.codingarea.commons.common.logging.lib; import net.codingarea.commons.common.logging.ILogger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - public interface Slf4jILogger extends ILogger, Logger { @Override @@ -24,18 +23,18 @@ public interface Slf4jILogger extends ILogger, Logger { boolean isErrorEnabled(); @Override - void trace(@Nullable String message, @Nonnull Object... args); + void trace(@Nullable String message, @NotNull Object... args); @Override - void debug(@Nullable String message, @Nonnull Object... args); + void debug(@Nullable String message, @NotNull Object... args); @Override - void info(@Nullable String message, @Nonnull Object... args); + void info(@Nullable String message, @NotNull Object... args); @Override - void warn(@Nullable String message, @Nonnull Object... args); + void warn(@Nullable String message, @NotNull Object... args); @Override - void error(@Nullable String message, @Nonnull Object... args); + void error(@Nullable String message, @NotNull Object... args); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java index cba509034..ee340bf29 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/BukkitReflectionSerializationUtils.java @@ -1,9 +1,9 @@ package net.codingarea.commons.common.misc; import net.codingarea.commons.common.logging.ILogger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Map; @@ -15,7 +15,7 @@ private BukkitReflectionSerializationUtils() { protected static final ILogger logger = ILogger.forThisClass(); - public static boolean isSerializable(@Nonnull Class clazz) { + public static boolean isSerializable(@NotNull Class clazz) { try { clazz.getMethod("serialize"); return true; @@ -25,7 +25,7 @@ public static boolean isSerializable(@Nonnull Class clazz) { } @Nullable - public static Map serializeObject(@Nonnull Object object) { + public static Map serializeObject(@NotNull Object object) { Class classOfObject = object.getClass(); try { @@ -47,7 +47,7 @@ public static Map serializeObject(@Nonnull Object object) { @Nullable @SuppressWarnings("unchecked") - public static T deserializeObject(@Nonnull Map map, @Nullable Class classOfT) { + public static T deserializeObject(@NotNull Map map, @Nullable Class classOfT) { try { Class configurationSerializationClass = Class.forName("org.bukkit.configuration.serialization.ConfigurationSerialization"); @@ -79,8 +79,8 @@ public static T deserializeObject(@Nonnull Map map, @Nullabl } } - @Nonnull - public static String getSerializationName(@Nonnull Class clazz) { + @NotNull + public static String getSerializationName(@NotNull Class clazz) { for (Annotation annotation : clazz.getAnnotations()) { Class annotationType = annotation.annotationType(); Object value = ReflectionUtils.getAnnotationValue(annotation); diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java index 2efedc666..c7e6e2f9b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java @@ -4,10 +4,10 @@ import com.google.common.collect.ImmutableMap; import net.codingarea.commons.common.collection.WrappedException; import net.codingarea.commons.common.function.ExceptionallyConsumer; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.io.*; import java.net.URI; import java.nio.charset.StandardCharsets; @@ -43,86 +43,83 @@ public static void setTempDirectory(@Nullable Path tempDirectory) { FileUtils.tempDirectory = tempDirectory; } - @Nonnull - public static BufferedWriter newBufferedWriter(@Nonnull File file) throws IOException { + @NotNull + public static BufferedWriter newBufferedWriter(@NotNull File file) throws IOException { return newBufferedWriter(file.toPath()); } - @Nonnull - public static BufferedReader newBufferedReader(@Nonnull File file) throws IOException { + @NotNull + public static BufferedReader newBufferedReader(@NotNull File file) throws IOException { return newBufferedReader(file.toPath()); } - @Nonnull - public static BufferedWriter newBufferedWriter(@Nonnull Path file) throws IOException { + @NotNull + public static BufferedWriter newBufferedWriter(@NotNull Path file) throws IOException { return Files.newBufferedWriter(file, StandardCharsets.UTF_8); } - @Nonnull - public static BufferedReader newBufferedReader(@Nonnull Path file) throws IOException { + @NotNull + public static BufferedReader newBufferedReader(@NotNull Path file) throws IOException { return Files.newBufferedReader(file, StandardCharsets.UTF_8); } - @Nonnull - public static String getFileExtension(@Nonnull File file) { + @NotNull + public static String getFileExtension(@NotNull File file) { return getFileExtension(file.getName()); } - @Nonnull - public static String getFileExtension(@Nonnull Path file) { + @NotNull + public static String getFileExtension(@NotNull Path file) { return getFileExtension(file.toString()); } - @Nonnull - public static String getFileExtension(@Nonnull String filename) { + @NotNull + public static String getFileExtension(@NotNull String filename) { return StringUtils.getAfterLastIndex(filename, ".").toLowerCase(); } - @Nonnull - public static String getFileName(@Nonnull File file) { + @NotNull + public static String getFileName(@NotNull File file) { return getFileName(file.getName()); } - @Nonnull - public static String getFileName(@Nonnull Path file) { + @NotNull + public static String getFileName(@NotNull Path file) { return getFileName(file.toString()); } - @Nonnull - public static String getFileName(@Nonnull String filename) { + @NotNull + public static String getFileName(@NotNull String filename) { filename = stripFolders(filename); int index = filename.lastIndexOf('.'); if (index == -1) return filename; return filename.substring(0, index); } - @Nonnull - @CheckReturnValue - public static String getRealFileName(@Nonnull File file) { + @NotNull + public static String getRealFileName(@NotNull File file) { return getRealFileName(file.getName()); } - @Nonnull - @CheckReturnValue - public static String getRealFileName(@Nonnull Path file) { + @NotNull + public static String getRealFileName(@NotNull Path file) { return getRealFileName(file.toString()); } - @Nonnull - @CheckReturnValue - public static String getRealFileName(@Nonnull String filename) { + @NotNull + public static String getRealFileName(@NotNull String filename) { return stripFolders(filename); } - @Nonnull + @NotNull @CheckReturnValue - private static String stripFolders(@Nonnull String filename) { + private static String stripFolders(@NotNull String filename) { int index = filename.lastIndexOf(File.pathSeparator); if (index == -1) return filename; return filename.substring(index + 1); } - public static void createFilesIfNecessary(@Nonnull File file) throws IOException { + public static void createFilesIfNecessary(@NotNull File file) throws IOException { if (file.exists()) return; if (file.isDirectory()) { @@ -134,7 +131,7 @@ public static void createFilesIfNecessary(@Nonnull File file) throws IOException file.createNewFile(); } - public static void deleteWorldFolder(@Nonnull File path) { + public static void deleteWorldFolder(@NotNull File path) { if (path.exists()) { File[] files = path.listFiles(); if (files == null) return; @@ -169,7 +166,7 @@ public static byte[] toByteArray(@Nullable InputStream inputStream, byte[] buffe return null; } - public static void openZipFileSystem(@Nonnull Path path, @Nonnull ExceptionallyConsumer consumer) { + public static void openZipFileSystem(@NotNull Path path, @NotNull ExceptionallyConsumer consumer) { try (FileSystem fileSystem = FileSystems .newFileSystem(URI.create("jar:" + path.toUri()), ZIP_FILE_SYSTEM_PROPERTIES)) { consumer.accept(fileSystem); @@ -257,7 +254,7 @@ public static void delete(Path file) { FileUtils.deleteFile(file); } - public static long size(@Nonnull Path path) { + public static long size(@NotNull Path path) { try { return Files.size(path); } catch (IOException ex) { @@ -294,7 +291,7 @@ public static byte[] convert(Path... directories) { return emptyZipByteArray(); } - @Nonnull + @NotNull public static Path createTempFile() { if (tempDirectory != null) return createTempFile(UUID.randomUUID()); @@ -308,15 +305,15 @@ public static Path createTempFile() { } } - @Nonnull - public static Path createTempFile(@Nonnull UUID uuid) { + @NotNull + public static Path createTempFile(@NotNull UUID uuid) { Preconditions.checkNotNull(tempDirectory, "The temp directory cannot be null"); Path file = tempDirectory.resolve(uuid.toString()); createFile(file); return file; } - public static void setAttribute(@Nonnull Path path, @Nonnull String attribute, @Nullable Object value, @Nonnull LinkOption... options) { + public static void setAttribute(@NotNull Path path, @NotNull String attribute, @Nullable Object value, @NotNull LinkOption... options) { try { Files.setAttribute(path, attribute, value, options); } catch (IOException ex) { @@ -324,17 +321,17 @@ public static void setAttribute(@Nonnull Path path, @Nonnull String attribute, @ } } - public static void setHiddenAttribute(@Nonnull Path path, boolean hidden) { + public static void setHiddenAttribute(@NotNull Path path, boolean hidden) { setAttribute(path, "dos:hidden", hidden, LinkOption.NOFOLLOW_LINKS); } - @Nonnull - public static InputStream zipToStream(@Nonnull Path directory) throws IOException { + @NotNull + public static InputStream zipToStream(@NotNull Path directory) throws IOException { return zipToStream(directory, null); } - @Nonnull - public static InputStream zipToStream(@Nonnull Path directory, @Nullable Predicate fileFilter) throws IOException { + @NotNull + public static InputStream zipToStream(@NotNull Path directory, @Nullable Predicate fileFilter) throws IOException { Path target = createTempFile(); zipToFile(directory, target, path -> !target.equals(path) && (fileFilter == null || fileFilter.test(path))); return Files.newInputStream(target, StandardOpenOption.DELETE_ON_CLOSE, LinkOption.NOFOLLOW_LINKS); @@ -554,8 +551,8 @@ private static void ensureChild(Path root, Path child) { } } - @Nonnull - public static Stream list(@Nonnull Path directory) { + @NotNull + public static Stream list(@NotNull Path directory) { try { return Files.list(directory); } catch (IOException ex) { diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java index bade80ed0..4a0f37c34 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java @@ -1,9 +1,9 @@ package net.codingarea.commons.common.misc; import com.google.gson.*; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -46,22 +46,22 @@ public static String convertJsonElementToString(@Nullable JsonElement element) { return element.toString(); } - @Nonnull - public static Map convertJsonObjectToMap(@Nonnull JsonObject object) { + @NotNull + public static Map convertJsonObjectToMap(@NotNull JsonObject object) { Map map = new LinkedHashMap<>(); convertJsonObjectToMap(object, map); return map; } - public static void convertJsonObjectToMap(@Nonnull JsonObject object, @Nonnull Map map) { + public static void convertJsonObjectToMap(@NotNull JsonObject object, @NotNull Map map) { for (Entry entry : object.entrySet()) { map.put(entry.getKey(), unpackJsonElement(entry.getValue())); } } - @Nonnull - public static List convertJsonArrayToStringList(@Nonnull JsonArray array) { + @NotNull + public static List convertJsonArrayToStringList(@NotNull JsonArray array) { List list = new ArrayList<>(array.size()); for (JsonElement element : array) { list.add(convertJsonElementToString(element)); @@ -69,8 +69,8 @@ public static List convertJsonArrayToStringList(@Nonnull JsonArray array return list; } - @Nonnull - public static String[] convertJsonArrayToStringArray(@Nonnull JsonArray array) { + @NotNull + public static String[] convertJsonArrayToStringArray(@NotNull JsonArray array) { String[] list = new String[array.size()]; for (int i = 0; i < array.size(); i++) { list[i] = convertJsonElementToString(array.get(i)); @@ -78,21 +78,21 @@ public static String[] convertJsonArrayToStringArray(@Nonnull JsonArray array) { return list; } - @Nonnull - public static JsonArray convertIterableToJsonArray(@Nonnull Gson gson, @Nonnull Iterable iterable) { + @NotNull + public static JsonArray convertIterableToJsonArray(@NotNull Gson gson, @NotNull Iterable iterable) { JsonArray array = new JsonArray(); iterable.forEach(object -> array.add(gson.toJsonTree(object))); return array; } - @Nonnull - public static JsonArray convertArrayToJsonArray(@Nonnull Gson gson, @Nonnull Object array) { + @NotNull + public static JsonArray convertArrayToJsonArray(@NotNull Gson gson, @NotNull Object array) { JsonArray jsonArray = new JsonArray(); ReflectionUtils.forEachInArray(array, object -> jsonArray.add(gson.toJsonTree(object))); return jsonArray; } - public static void setDocumentProperties(@Nonnull Gson gson, @Nonnull JsonObject object, @Nonnull Map values) { + public static void setDocumentProperties(@NotNull Gson gson, @NotNull JsonObject object, @NotNull Map values) { for (Entry entry : values.entrySet()) { Object value = entry.getValue(); @@ -116,7 +116,7 @@ public static void setDocumentProperties(@Nonnull Gson gson, @Nonnull JsonObject } } - public static int getSize(@Nonnull JsonObject object) { + public static int getSize(@NotNull JsonObject object) { try { return object.size(); } catch (NoSuchMethodError ignored) { diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java index 3fed7ad6b..88909c390 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ImageUtils.java @@ -1,10 +1,10 @@ package net.codingarea.commons.common.misc; import net.codingarea.commons.common.collection.IOUtils; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import javax.imageio.ImageIO; import java.awt.*; import java.awt.font.TextLayout; @@ -23,7 +23,7 @@ private ImageUtils() { * @param height The y-position of the text * @return The width of the text added in pixels */ - public static int addCenteredText(@Nonnull Graphics2D graphics, @Nonnull String text, int height) { + public static int addCenteredText(@NotNull Graphics2D graphics, @NotNull String text, int height) { TextLayout layout = getTextLayout(graphics, text); int lineWidth = (int) layout.getBounds().getWidth(); graphics.drawString(text, graphics.getDeviceConfiguration().getBounds().width / 2 - lineWidth / 2, height); @@ -34,7 +34,7 @@ public static int addCenteredText(@Nonnull Graphics2D graphics, @Nonnull String /** * @return The ending position of the text */ - public static int addText(@Nonnull Graphics2D graphics, @Nonnull String text, int height, int x) { + public static int addText(@NotNull Graphics2D graphics, @NotNull String text, int height, int x) { TextLayout layout = getTextLayout(graphics, text); graphics.drawString(text, x, height); return (int) (x + layout.getBounds().getWidth()); @@ -43,7 +43,7 @@ public static int addText(@Nonnull Graphics2D graphics, @Nonnull String text, in /** * @return Returns where the text has started */ - public static int addTextEndingAt(@Nonnull Graphics2D graphics, @Nonnull String text, int height, int endX) { + public static int addTextEndingAt(@NotNull Graphics2D graphics, @NotNull String text, int height, int endX) { TextLayout layout = getTextLayout(graphics, text); int position = (int) (endX - layout.getBounds().getWidth()); graphics.drawString(text, position, height); @@ -53,7 +53,7 @@ public static int addTextEndingAt(@Nonnull Graphics2D graphics, @Nonnull String /** * @param height The y-position of the text */ - public static void addTextEndingAtMid(@Nonnull Graphics2D graphics, @Nonnull String text, int height) { + public static void addTextEndingAtMid(@NotNull Graphics2D graphics, @NotNull String text, int height) { TextLayout layout = getTextLayout(graphics, text); int lineWidth = (int) layout.getBounds().getWidth(); graphics.drawString(text, graphics.getClipBounds().width / 2 - lineWidth, height); @@ -65,26 +65,26 @@ public static void addTextEndingAtMid(@Nonnull Graphics2D graphics, @Nonnull Str * @param url The URL the image is stored to * @throws IOException When something goes wrong while connecting or reading the image */ - public static BufferedImage loadUrl(@Nonnull String url) throws IOException { + public static BufferedImage loadUrl(@NotNull String url) throws IOException { URLConnection connection = IOUtils.createConnection(url); return ImageIO.read(connection.getInputStream()); } - public static BufferedImage loadResource(@Nonnull String path) throws IOException { + public static BufferedImage loadResource(@NotNull String path) throws IOException { InputStream stream = ImageUtils.class.getClassLoader().getResourceAsStream(path); return ImageIO.read(stream); } - public static BufferedImage loadFile(@Nonnull File file) throws IOException { + public static BufferedImage loadFile(@NotNull File file) throws IOException { return ImageIO.read(file); } - @Nonnull - public static TextLayout getTextLayout(@Nonnull Graphics2D graphics, @Nonnull String text) { + @NotNull + public static TextLayout getTextLayout(@NotNull Graphics2D graphics, @NotNull String text) { return new TextLayout(text, graphics.getFont(), graphics.getFontRenderContext()); } - public static void darkenImage(@Nonnull BufferedImage image) { + public static void darkenImage(@NotNull BufferedImage image) { for (int i = 0; i < image.getWidth(); i++) { for (int j = 0; j < image.getHeight(); j++) { image.setRGB(i, j, new Color(image.getRGB(i, j)).darker().getRGB()); @@ -92,9 +92,9 @@ public static void darkenImage(@Nonnull BufferedImage image) { } } - @Nonnull + @NotNull @CheckReturnValue - public static BufferedImage replaceTransparency(@Nonnull BufferedImage image, @Nullable Color replacementColor) { + public static BufferedImage replaceTransparency(@NotNull BufferedImage image, @Nullable Color replacementColor) { if (replacementColor == null) replacementColor = new Color(0, 0, 0, 0); BufferedImage created = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = created.createGraphics(); diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java index 5db7e5452..3d5d09c71 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/PropertiesUtils.java @@ -1,6 +1,7 @@ package net.codingarea.commons.common.misc; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.util.Map; import java.util.Map.Entry; import java.util.Properties; @@ -10,7 +11,7 @@ public final class PropertiesUtils { private PropertiesUtils() { } - public static void setProperties(@Nonnull Properties properties, @Nonnull Map map) { + public static void setProperties(@NotNull Properties properties, @NotNull Map map) { for (Entry entry : properties.entrySet()) { map.put((String) entry.getKey(), entry.getValue()); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java index 6af4038bc..d27ccb443 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java @@ -3,10 +3,10 @@ import net.codingarea.commons.common.collection.ArrayWalker; import net.codingarea.commons.common.collection.ClassWalker; import net.codingarea.commons.common.collection.WrappedException; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Field; @@ -22,8 +22,8 @@ public final class ReflectionUtils { private ReflectionUtils() { } - @Nonnull - public static Collection getPublicMethodsAnnotatedWith(@Nonnull Class clazz, @Nonnull Class classOfAnnotation) { + @NotNull + public static Collection getPublicMethodsAnnotatedWith(@NotNull Class clazz, @NotNull Class classOfAnnotation) { List annotatedMethods = new ArrayList<>(); for (Method method : clazz.getMethods()) { if (!method.isAnnotationPresent(classOfAnnotation)) continue; @@ -32,8 +32,8 @@ public static Collection getPublicMethodsAnnotatedWith(@Nonnull Class return annotatedMethods; } - @Nonnull - public static Collection getMethodsAnnotatedWith(@Nonnull Class clazz, @Nonnull Class classOfAnnotation) { + @NotNull + public static Collection getMethodsAnnotatedWith(@NotNull Class clazz, @NotNull Class classOfAnnotation) { List annotatedMethods = new ArrayList<>(); for (Class currentClass : ClassWalker.walk(clazz)) { for (Method method : currentClass.getDeclaredMethods()) { @@ -44,8 +44,8 @@ public static Collection getMethodsAnnotatedWith(@Nonnull Class clazz return annotatedMethods; } - @Nonnull - public static Method getInheritedPrivateMethod(@Nonnull Class clazz, @Nonnull String name, @Nonnull Class... parameterTypes) throws NoSuchMethodException { + @NotNull + public static Method getInheritedPrivateMethod(@NotNull Class clazz, @NotNull String name, @NotNull Class... parameterTypes) throws NoSuchMethodException { for (Class current : ClassWalker.walk(clazz)) { try { return current.getDeclaredMethod(name, parameterTypes); @@ -56,8 +56,8 @@ public static Method getInheritedPrivateMethod(@Nonnull Class clazz, @Nonnull throw new NoSuchMethodException(name); } - @Nonnull - public static Field getInheritedPrivateField(@Nonnull Class clazz, @Nonnull String name) throws NoSuchFieldException { + @NotNull + public static Field getInheritedPrivateField(@NotNull Class clazz, @NotNull String name) throws NoSuchFieldException { for (Class current : ClassWalker.walk(clazz)) { try { return current.getDeclaredField(name); @@ -72,8 +72,8 @@ public static Field getInheritedPrivateField(@Nonnull Class clazz, @Nonnull S * @param classOfEnum The class containing the enum constants * @return The first enum found by the given names */ - @Nonnull - public static > E getFirstEnumByNames(@Nonnull Class classOfEnum, @Nonnull String... names) { + @NotNull + public static > E getFirstEnumByNames(@NotNull Class classOfEnum, @NotNull String... names) { for (String name : names) { try { return Enum.valueOf(classOfEnum, name); @@ -94,17 +94,16 @@ public static > E getFirstEnumByNames(@Nonnull Class classO * @see Array#getLength(Object) * @see Array#get(Object, int) */ - public static void forEachInArray(@Nonnull Object array, @Nonnull Consumer action) { + public static void forEachInArray(@NotNull Object array, @NotNull Consumer action) { ReflectionUtils.iterableArray(array).forEach(action); } - @Nonnull + @NotNull @CheckReturnValue - public static Iterable iterableArray(@Nonnull Object array) { + public static Iterable iterableArray(@NotNull Object array) { return ArrayWalker.walk(array); } - @CheckReturnValue public static Class getCaller() { return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE) .walk(stream -> stream @@ -115,7 +114,7 @@ public static Class getCaller() { ); } - @Nonnull + @NotNull public static String getCallerName() { StackTraceElement[] trace = Thread.currentThread().getStackTrace(); StackTraceElement element = trace[3]; @@ -129,8 +128,8 @@ public static String getCallerName() { * * @see Class#getField(String) */ - @Nonnull - public static Field getEnumAsField(@Nonnull Enum enun) { + @NotNull + public static Field getEnumAsField(@NotNull Enum enun) { Class classOfEnum = enun.getClass(); try { @@ -143,8 +142,8 @@ public static Field getEnumAsField(@Nonnull Enum enun) { /** * @see Field#getAnnotations() */ - @Nonnull - public static > Annotation[] getEnumAnnotations(@Nonnull E enun) { + @NotNull + public static > Annotation[] getEnumAnnotations(@NotNull E enun) { Field field = getEnumAsField(enun); return field.getAnnotations(); } @@ -153,13 +152,13 @@ public static > Annotation[] getEnumAnnotations(@Nonnull E enu * @return Returns {@code null} if no annotation of this class is present * @see Field#getAnnotation(Class) */ - public static , A extends Annotation> A getEnumAnnotation(@Nonnull E enun, Class classOfAnnotation) { + public static , A extends Annotation> A getEnumAnnotation(@NotNull E enun, Class classOfAnnotation) { Field field = getEnumAsField(enun); return field.getAnnotation(classOfAnnotation); } @Nullable - public static > E getEnumOrNull(@Nullable String name, @Nonnull Class classOfEnum) { + public static > E getEnumOrNull(@Nullable String name, @NotNull Class classOfEnum) { try { if (name == null) return null; return Enum.valueOf(classOfEnum, name); @@ -181,7 +180,7 @@ public static Class getClassOrNull(@Nullable String name) { @Nullable @SuppressWarnings("unchecked") - public static Class getClassOrNull(@Nullable String name, boolean initialize, @Nonnull ClassLoader classLoader) { + public static Class getClassOrNull(@Nullable String name, boolean initialize, @NotNull ClassLoader classLoader) { try { if (name == null) return null; return (Class) Class.forName(name, initialize, classLoader); @@ -192,7 +191,7 @@ public static Class getClassOrNull(@Nullable String name, boolean initial @Nullable @SuppressWarnings("unchecked") - public static T invokeMethodOrNull(@Nullable Object instance, @Nonnull Method method) { + public static T invokeMethodOrNull(@Nullable Object instance, @NotNull Method method) { try { if (!method.isAccessible()) method.setAccessible(true); return (T) method.invoke(instance); @@ -202,7 +201,7 @@ public static T invokeMethodOrNull(@Nullable Object instance, @Nonnull Metho } @Nullable - public static T invokeStaticMethodOrNull(@Nonnull Class clazz, @Nonnull String method) { + public static T invokeStaticMethodOrNull(@NotNull Class clazz, @NotNull String method) { try { return invokeMethodOrNull(null, clazz.getMethod(method)); } catch (NoSuchMethodException ex) { @@ -211,7 +210,7 @@ public static T invokeStaticMethodOrNull(@Nonnull Class clazz, @Nonnull S } @Nullable - public static T invokeMethodOrNull(@Nonnull Object instance, @Nonnull String method) { + public static T invokeMethodOrNull(@NotNull Object instance, @NotNull String method) { try { return invokeMethodOrNull(instance, instance.getClass().getDeclaredMethod(method)); } catch (NoSuchMethodException ex) { @@ -220,12 +219,12 @@ public static T invokeMethodOrNull(@Nonnull Object instance, @Nonnull String } @Nullable - public static T getAnnotationValue(@Nonnull Annotation annotation) { + public static T getAnnotationValue(@NotNull Annotation annotation) { return invokeMethodOrNull(annotation, "value"); } @Nullable - public static > E getEnumByAlternateNames(@Nonnull Class classOfE, @Nonnull String input) { + public static > E getEnumByAlternateNames(@NotNull Class classOfE, @NotNull String input) { E[] values = invokeStaticMethodOrNull(classOfE, "values"); String[] methodNames = {"getName", "getNames", "getAlias", "getAliases", "getKey", "getKeys", "name", "toString", "ordinal", "getId", "id"}; for (E value : values) { @@ -238,7 +237,7 @@ public static > E getEnumByAlternateNames(@Nonnull Class cl return null; } - private static boolean check(@Nonnull String input, @Nullable Object value) { + private static boolean check(@NotNull String input, @Nullable Object value) { if (value == null) return false; if (value.getClass().isArray()) { for (Object key : iterableArray(value)) { diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java index e737ce0ec..eb0487614 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/SimpleCollectionUtils.java @@ -1,10 +1,9 @@ package net.codingarea.commons.common.misc; import net.codingarea.commons.common.logging.ILogger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.*; import java.util.Map.Entry; import java.util.function.Function; @@ -30,10 +29,9 @@ public static void disableErrorLogging() { * * @deprecated Unsafe because of strings containing , or = */ - @Nonnull + @NotNull @Deprecated - @CheckReturnValue - public static String convertMapToString(@Nonnull Map map, @Nonnull Function key, @Nonnull Function value) { + public static String convertMapToString(@NotNull Map map, @NotNull Function key, @NotNull Function value) { StringBuilder builder = new StringBuilder(); for (Entry entry : map.entrySet()) { if (builder.length() != 0) builder.append(REGEX_1); @@ -50,10 +48,9 @@ public static String convertMapToString(@Nonnull Map map, @Nonnull * * @deprecated Unsafe because of strings containing , or = */ - @Nonnull + @NotNull @Deprecated - @CheckReturnValue - public static Map convertStringToMap(@Nullable String string, @Nonnull Function key, @Nonnull Function value) { + public static Map convertStringToMap(@Nullable String string, @NotNull Function key, @NotNull Function value) { Map map = new HashMap<>(); if (string == null) return map; @@ -81,11 +78,10 @@ public static Map convertStringToMap(@Nullable String string, @Nonn } - @Nonnull - @CheckReturnValue - public static Map convertMap(@Nonnull Map map, - @Nonnull Function keyMapper, - @Nonnull Function valueMapper) { + @NotNull + public static Map convertMap(@NotNull Map map, + @NotNull Function keyMapper, + @NotNull Function valueMapper) { Map result = new HashMap<>(); map.forEach((key, value) -> { try { @@ -98,10 +94,9 @@ public static Map convertMap(@Nonnull Map List convert(@Nonnull Collection collection, - @Nonnull Function mapper) { + @NotNull + public static List convert(@NotNull Collection collection, + @NotNull Function mapper) { List result = new ArrayList<>(collection.size()); collection.forEach(value -> { try { @@ -114,7 +109,7 @@ public static List convert(@Nonnull Collection collection, return result; } - public static V getMostFrequentValue(@Nonnull Map map) { + public static V getMostFrequentValue(@NotNull Map map) { Collection values = map.values(); List list = new ArrayList<>(values); Set set = new HashSet<>(values); @@ -133,7 +128,7 @@ public static V getMostFrequentValue(@Nonnull Map map) { } @SafeVarargs - public static Set setOf(@Nonnull Collection... collections) { + public static Set setOf(@NotNull Collection... collections) { Set set = new HashSet<>(); for (Collection collection : collections) { set.addAll(collection); diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java index 3ad7f7e18..457755a5d 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java @@ -2,9 +2,9 @@ import net.codingarea.commons.common.collection.WrappedException; import net.codingarea.commons.common.logging.ILogger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Optional; import java.util.concurrent.Callable; import java.util.function.Function; @@ -17,13 +17,13 @@ public final class StringUtils { private StringUtils() { } - @Nonnull - public static String getEnumName(@Nonnull Enum enun) { + @NotNull + public static String getEnumName(@NotNull Enum enun) { return getEnumName(enun.name()); } - @Nonnull - public static String getEnumName(@Nonnull String name) { + @NotNull + public static String getEnumName(@NotNull String name) { StringBuilder builder = new StringBuilder(); boolean nextUpperCase = true; for (char letter : name.toCharArray()) { @@ -39,8 +39,8 @@ public static String getEnumName(@Nonnull String name) { return builder.toString(); } - @Nonnull - public static String format(@Nonnull String sequence, @Nonnull Object... args) { + @NotNull + public static String format(@NotNull String sequence, @NotNull Object... args) { char start = '{', end = '}'; boolean inArgument = false; StringBuilder argument = new StringBuilder(); @@ -79,16 +79,16 @@ public static String format(@Nonnull String sequence, @Nonnull Object... args) { return builder.toString(); } - @Nonnull - public static String getAfterLastIndex(@Nonnull String input, @Nonnull String separator) { + @NotNull + public static String getAfterLastIndex(@NotNull String input, @NotNull String separator) { return Optional.of(input) .filter(name -> name.contains(separator)) .map(name -> name.substring(name.lastIndexOf(separator) + separator.length())) .orElse(""); } - @Nonnull - public static String[] format(@Nonnull String[] array, @Nonnull Object... args) { + @NotNull + public static String[] format(@NotNull String[] array, @NotNull Object... args) { String[] result = new String[array.length]; for (int i = 0; i < array.length; i++) { result[i] = format(array[i], args); @@ -96,8 +96,8 @@ public static String[] format(@Nonnull String[] array, @Nonnull Object... args) return result; } - @Nonnull - public static String getArrayAsString(@Nonnull String[] array, @Nonnull String separator) { + @NotNull + public static String getArrayAsString(@NotNull String[] array, @NotNull String separator) { StringBuilder builder = new StringBuilder(); for (String string : array) { if (builder.length() != 0) builder.append(separator); @@ -106,13 +106,13 @@ public static String getArrayAsString(@Nonnull String[] array, @Nonnull String s return builder.toString(); } - @Nonnull - public static String[] getStringAsArray(@Nonnull String string) { + @NotNull + public static String[] getStringAsArray(@NotNull String string) { return string.split("\n"); } - @Nonnull - public static String getIterableAsString(@Nonnull Iterable iterable, @Nonnull String separator, @Nonnull Function mapper) { + @NotNull + public static String getIterableAsString(@NotNull Iterable iterable, @NotNull String separator, @NotNull Function mapper) { StringBuilder builder = new StringBuilder(); for (T t : iterable) { if (builder.length() > 0) builder.append(separator); @@ -122,7 +122,7 @@ public static String getIterableAsString(@Nonnull Iterable iterable, @Non return builder.toString(); } - @Nonnull + @NotNull public static String repeat(@Nullable Object sequence, int amount) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < amount; i++) builder.append(sequence); @@ -146,7 +146,7 @@ private static int getMultiplier(char c) { } } - public static long parseSeconds(@Nonnull String input) { + public static long parseSeconds(@NotNull String input) { if (input.toLowerCase().startsWith("perm")) return -1; long current = 0; long seconds = 0; @@ -165,7 +165,7 @@ public static long parseSeconds(@Nonnull String input) { return seconds; } - public static boolean isNumber(@Nonnull String sequence) { + public static boolean isNumber(@NotNull String sequence) { try { Double.parseDouble(sequence); return true; @@ -174,7 +174,7 @@ public static boolean isNumber(@Nonnull String sequence) { } } - private static int indexOf(@Nonnull String string, @Nonnull String pattern, int occurrenceIndex) { + private static int indexOf(@NotNull String string, @NotNull String pattern, int occurrenceIndex) { int lastIndex = 0; for (int currentLayer = 0; currentLayer <= occurrenceIndex; currentLayer++) { int index = string.indexOf(pattern, (lastIndex > 0) ? lastIndex + 1 : 0); diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/Version.java b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java index a8cd6c818..2b858d9da 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/Version.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java @@ -1,45 +1,40 @@ package net.codingarea.commons.common.version; import net.codingarea.commons.common.annotations.Since; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.*; public interface Version { - @Nonnegative int getMajor(); - @Nonnegative int getMinor(); - @Nonnegative int getRevision(); - default boolean isNewerThan(@Nonnull Version other) { + default boolean isNewerThan(@NotNull Version other) { return this.intValue() > other.intValue(); } - default boolean isNewerOrEqualThan(@Nonnull Version other) { + default boolean isNewerOrEqualThan(@NotNull Version other) { return this.intValue() >= other.intValue(); } - default boolean isOlderThan(@Nonnull Version other) { + default boolean isOlderThan(@NotNull Version other) { return this.intValue() < other.intValue(); } - default boolean isOlderOrEqualThan(@Nonnull Version other) { + default boolean isOlderOrEqualThan(@NotNull Version other) { return this.intValue() <= other.intValue(); } - default boolean equals(@Nonnull Version other) { + default boolean equals(@NotNull Version other) { return this.intValue() == other.intValue(); } - @Nonnull + @NotNull default String format() { int revision = getRevision(); return revision > 0 ? String.format("%s.%s.%s", getMajor(), getMinor(), revision) @@ -60,33 +55,28 @@ default int intValue() { + major * 10000; } - @Nonnull - @CheckReturnValue + @NotNull static Version parse(@Nullable String input) { return parse(input, new VersionInfo(1, 0, 0)); } - @CheckReturnValue static Version parse(@Nullable String input, Version def) { return VersionInfo.parse(input, def); } - @Nonnull - @CheckReturnValue + @NotNull static Version parseExceptionally(@Nullable String input) { return VersionInfo.parseExceptionally(input); } - @Nonnull - @CheckReturnValue - static Version getAnnotatedSince(@Nonnull Object object) { + @NotNull + static Version getAnnotatedSince(@NotNull Object object) { if (!object.getClass().isAnnotationPresent(Since.class)) return new VersionInfo(1, 0, 0); return parse(object.getClass().getAnnotation(Since.class).value()); } - @Nonnull - @CheckReturnValue - static V findNearest(@Nonnull Version target, @Nonnull V[] sortedVersionsArray) { + @NotNull + static V findNearest(@NotNull Version target, @NotNull V[] sortedVersionsArray) { List versions = new ArrayList<>(Arrays.asList(sortedVersionsArray)); Collections.reverse(versions); for (V version : versions) { @@ -96,8 +86,7 @@ static V findNearest(@Nonnull Version target, @Nonnull V[] s throw new IllegalArgumentException("No version found for '" + target + "'"); } - @Nonnull - @CheckReturnValue + @NotNull static Comparator comparator() { return new VersionComparator(); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java index 7027fbf7c..71dcd75e5 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java @@ -1,12 +1,13 @@ package net.codingarea.commons.common.version; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.util.Comparator; public class VersionComparator implements Comparator { @Override - public int compare(@Nonnull Version v1, @Nonnull Version v2) { + public int compare(@NotNull Version v1, @NotNull Version v2) { return v1.equals(v2) ? 0 : v1.isNewerThan(v2) ? 1 : -1; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java index aeb0d88a6..16443488b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java @@ -1,8 +1,8 @@ package net.codingarea.commons.common.version; import net.codingarea.commons.common.logging.ILogger; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nullable; import java.util.Objects; public class VersionInfo implements Version { diff --git a/plugin/src/main/java/net/codingarea/commons/database/Database.java b/plugin/src/main/java/net/codingarea/commons/database/Database.java index 067656d59..36e01e076 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/Database.java +++ b/plugin/src/main/java/net/codingarea/commons/database/Database.java @@ -6,21 +6,20 @@ import net.codingarea.commons.database.exceptions.DatabaseAlreadyConnectedException; import net.codingarea.commons.database.exceptions.DatabaseConnectionClosedException; import net.codingarea.commons.database.exceptions.DatabaseException; - -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; public interface Database { ILogger LOGGER = ILogger.forThisClass(); - @Nonnull + @NotNull @CheckReturnValue static Database empty() { return new EmptyDatabase(true); } - @Nonnull + @NotNull @CheckReturnValue static Database unsupported() { return new EmptyDatabase(false); @@ -60,48 +59,48 @@ static Database unsupported() { */ boolean disconnectSafely(); - void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException; + void createTable(@NotNull String name, @NotNull SQLColumn... columns) throws DatabaseException; - void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns); + void createTableSafely(@NotNull String name, @NotNull SQLColumn... columns); - @Nonnull - default Task createTableAsync(@Nonnull String name, @Nonnull SQLColumn... columns) { + @NotNull + default Task createTableAsync(@NotNull String name, @NotNull SQLColumn... columns) { return Task.asyncRunExceptionally(() -> createTable(name, columns)); } - @Nonnull + @NotNull @CheckReturnValue DatabaseListTables listTables(); - @Nonnull + @NotNull @CheckReturnValue - DatabaseCountEntries countEntries(@Nonnull String table); + DatabaseCountEntries countEntries(@NotNull String table); - @Nonnull + @NotNull @CheckReturnValue - DatabaseQuery query(@Nonnull String table); + DatabaseQuery query(@NotNull String table); - @Nonnull + @NotNull @CheckReturnValue - DatabaseUpdate update(@Nonnull String table); + DatabaseUpdate update(@NotNull String table); - @Nonnull + @NotNull @CheckReturnValue - DatabaseInsertion insert(@Nonnull String table); + DatabaseInsertion insert(@NotNull String table); - @Nonnull + @NotNull @CheckReturnValue - DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table); + DatabaseInsertionOrUpdate insertOrUpdate(@NotNull String table); - @Nonnull + @NotNull @CheckReturnValue - DatabaseDeletion delete(@Nonnull String table); + DatabaseDeletion delete(@NotNull String table); - @Nonnull + @NotNull @CheckReturnValue - SpecificDatabase getSpecificDatabase(@Nonnull String name); + SpecificDatabase getSpecificDatabase(@NotNull String name); - @Nonnull + @NotNull DatabaseConfig getConfig(); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java index 57e1e3498..02c37dca8 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java +++ b/plugin/src/main/java/net/codingarea/commons/database/DatabaseConfig.java @@ -1,8 +1,7 @@ package net.codingarea.commons.database; import net.codingarea.commons.common.config.Propertyable; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public final class DatabaseConfig { @@ -46,7 +45,7 @@ public DatabaseConfig(String host, String database, String authDatabase, String this.file = file; } - public DatabaseConfig(@Nonnull Propertyable config) { + public DatabaseConfig(@NotNull Propertyable config) { this( config.getString("host"), config.getString("database"), diff --git a/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java index 9f0095658..ba73ac5b9 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/EmptyDatabase.java @@ -5,9 +5,9 @@ import net.codingarea.commons.database.abstraction.DefaultSpecificDatabase; import net.codingarea.commons.database.action.*; import net.codingarea.commons.database.exceptions.DatabaseException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Collections; import java.util.List; @@ -23,7 +23,7 @@ public boolean isSilent() { return silent; } - protected void exception(@Nonnull String message) { + protected void exception(@NotNull String message) { throw new UnsupportedOperationException(message); } @@ -55,16 +55,16 @@ public boolean disconnectSafely() { } @Override - public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { + public void createTable(@NotNull String name, @NotNull SQLColumn... columns) throws DatabaseException { if (!silent) exception("Cannot create tables from a NOP Database"); } @Override - public void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns) { + public void createTableSafely(@NotNull String name, @NotNull SQLColumn... columns) { } - @Nonnull + @NotNull @Override public DatabaseListTables listTables() { if (!silent) @@ -73,67 +73,67 @@ public DatabaseListTables listTables() { return new EmptyListTables(); } - @Nonnull + @NotNull @Override - public DatabaseCountEntries countEntries(@Nonnull String table) { + public DatabaseCountEntries countEntries(@NotNull String table) { if (!silent) exception("Cannot count entries of a NOP Database"); return new EmptyCountEntries(); } - @Nonnull + @NotNull @Override - public DatabaseQuery query(@Nonnull String table) { + public DatabaseQuery query(@NotNull String table) { if (!silent) exception("Cannot query in a NOP Database"); return new EmptyDatabaseQuery(); } - @Nonnull + @NotNull @Override - public DatabaseUpdate update(@Nonnull String table) { + public DatabaseUpdate update(@NotNull String table) { if (!silent) exception("Cannot update in a NOP Database"); return new EmptyVoidAction(); } - @Nonnull + @NotNull @Override - public DatabaseInsertion insert(@Nonnull String table) { + public DatabaseInsertion insert(@NotNull String table) { if (!silent) exception("Cannot insert into a NOP Database"); return new EmptyVoidAction(); } - @Nonnull + @NotNull @Override - public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { + public DatabaseInsertionOrUpdate insertOrUpdate(@NotNull String table) { if (!silent) exception("Cannot inset or update into a NOP Database"); return new EmptyVoidAction(); } - @Nonnull + @NotNull @Override - public DatabaseDeletion delete(@Nonnull String table) { + public DatabaseDeletion delete(@NotNull String table) { if (!silent) exception("Cannot delete from a NOP Database"); return new EmptyVoidAction(); } - @Nonnull + @NotNull @Override - public SpecificDatabase getSpecificDatabase(@Nonnull String name) { + public SpecificDatabase getSpecificDatabase(@NotNull String name) { return new DefaultSpecificDatabase(this, name); } - @Nonnull + @NotNull @Override public DatabaseConfig getConfig() { throw new UnsupportedOperationException(); @@ -146,55 +146,55 @@ public String toString() { public static class EmptyDatabaseQuery implements DatabaseQuery { - @Nonnull + @NotNull @Override - public DatabaseQuery where(@Nonnull String field, @Nullable Object object) { + public DatabaseQuery where(@NotNull String field, @Nullable Object object) { return this; } - @Nonnull + @NotNull @Override - public DatabaseQuery where(@Nonnull String field, @Nullable Number value) { + public DatabaseQuery where(@NotNull String field, @Nullable Number value) { return this; } - @Nonnull + @NotNull @Override - public DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + public DatabaseQuery where(@NotNull String field, @Nullable String value, boolean ignoreCase) { return this; } - @Nonnull + @NotNull @Override - public DatabaseQuery where(@Nonnull String field, @Nullable String value) { + public DatabaseQuery where(@NotNull String field, @Nullable String value) { return this; } - @Nonnull + @NotNull @Override - public DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value) { + public DatabaseQuery whereNot(@NotNull String field, @Nullable Object value) { return this; } - @Nonnull + @NotNull @Override - public DatabaseQuery select(@Nonnull String... selection) { + public DatabaseQuery select(@NotNull String... selection) { return this; } - @Nonnull + @NotNull @Override - public DatabaseQuery orderBy(@Nonnull String field, @Nonnull Order order) { + public DatabaseQuery orderBy(@NotNull String field, @NotNull Order order) { return this; } - @Nonnull + @NotNull @Override public ExecutedQuery execute() throws DatabaseException { return new DefaultExecutedQuery(Collections.emptyList()); } - @Nonnull + @NotNull @Override public Task executeAsync() { return Task.syncCall(this::execute); @@ -204,39 +204,39 @@ public Task executeAsync() { public static class EmptyVoidAction implements DatabaseDeletion, DatabaseInsertion, DatabaseUpdate, DatabaseInsertionOrUpdate { - @Nonnull + @NotNull @Override - public EmptyVoidAction where(@Nonnull String field, @Nullable Object value) { + public EmptyVoidAction where(@NotNull String field, @Nullable Object value) { return this; } - @Nonnull + @NotNull @Override - public EmptyVoidAction where(@Nonnull String field, @Nullable Number value) { + public EmptyVoidAction where(@NotNull String field, @Nullable Number value) { return this; } - @Nonnull + @NotNull @Override - public EmptyVoidAction where(@Nonnull String field, @Nullable String value, boolean ignoreCase) { + public EmptyVoidAction where(@NotNull String field, @Nullable String value, boolean ignoreCase) { return this; } - @Nonnull + @NotNull @Override - public EmptyVoidAction where(@Nonnull String field, @Nullable String value) { + public EmptyVoidAction where(@NotNull String field, @Nullable String value) { return this; } - @Nonnull + @NotNull @Override - public EmptyVoidAction whereNot(@Nonnull String field, @Nullable Object value) { + public EmptyVoidAction whereNot(@NotNull String field, @Nullable Object value) { return this; } - @Nonnull + @NotNull @Override - public EmptyVoidAction set(@Nonnull String field, @Nullable Object value) { + public EmptyVoidAction set(@NotNull String field, @Nullable Object value) { return this; } @@ -245,7 +245,7 @@ public Void execute() throws DatabaseException { return null; } - @Nonnull + @NotNull @Override public Task executeAsync() { return Task.completedVoid(); @@ -255,13 +255,13 @@ public Task executeAsync() { public static class EmptyCountEntries implements DatabaseCountEntries { - @Nonnull + @NotNull @Override public Long execute() throws DatabaseException { return 0L; } - @Nonnull + @NotNull @Override public Task executeAsync() { return Task.completed(0L); @@ -271,13 +271,13 @@ public Task executeAsync() { public static class EmptyListTables implements DatabaseListTables { - @Nonnull + @NotNull @Override public List execute() throws DatabaseException { return Collections.emptyList(); } - @Nonnull + @NotNull @Override public Task> executeAsync() { return Task.completed(Collections.emptyList()); diff --git a/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java b/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java index 07987b629..4b6e33d93 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java +++ b/plugin/src/main/java/net/codingarea/commons/database/SQLColumn.java @@ -2,10 +2,9 @@ import net.codingarea.commons.common.misc.ReflectionUtils; import net.codingarea.commons.common.misc.StringUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Arrays; public final class SQLColumn { @@ -113,7 +112,7 @@ public enum Type { private final String type; private final String param; - public SQLColumn(@Nonnull String name, @Nonnull String type, @Nullable String param) { + public SQLColumn(@NotNull String name, @NotNull String type, @Nullable String param) { if (name.contains(" ")) throw new IllegalArgumentException("Column name cannot contain spaces"); if (type.contains(" ")) throw new IllegalArgumentException("Column type cannot contain spaces"); @@ -122,44 +121,44 @@ public SQLColumn(@Nonnull String name, @Nonnull String type, @Nullable String pa this.param = param; } - public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnegative int size) { + public SQLColumn(@NotNull String name, @NotNull String type, int size) { this(name, type, String.valueOf(size)); } - public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnegative int size, @Nonnegative int d) { + public SQLColumn(@NotNull String name, @NotNull String type, int size, int d) { this(name, type, String.valueOf(size), String.valueOf(d)); } - public SQLColumn(@Nonnull String name, @Nonnull String type, @Nonnull String... params) { + public SQLColumn(@NotNull String name, @NotNull String type, @NotNull String... params) { this(name, type, StringUtils.getArrayAsString(params, ", ")); } - public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nullable String param) { + public SQLColumn(@NotNull String name, @NotNull Type type, @Nullable String param) { this(name, type.name(), param); } - public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnegative int size) { + public SQLColumn(@NotNull String name, @NotNull Type type, int size) { this(name, type.name(), size); } - public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnegative int size, @Nonnegative int d) { + public SQLColumn(@NotNull String name, @NotNull Type type, int size, int d) { this(name, type.name(), size, d); } - public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnull String... params) { + public SQLColumn(@NotNull String name, @NotNull Type type, @NotNull String... params) { this(name, type.name(), params); } - public SQLColumn(@Nonnull String name, @Nonnull Type type, @Nonnull Type... types) { + public SQLColumn(@NotNull String name, @NotNull Type type, @NotNull Type... types) { this(name, type, Arrays.stream(types).map(Type::name).toArray(String[]::new)); } - @Nonnull + @NotNull public String getName() { return name; } - @Nonnull + @NotNull public String getType() { return type; } diff --git a/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java b/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java index 6889f896a..07290b9a0 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java +++ b/plugin/src/main/java/net/codingarea/commons/database/SimpleDatabaseTypeResolver.java @@ -1,9 +1,9 @@ package net.codingarea.commons.database; import net.codingarea.commons.common.misc.ReflectionUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; @@ -21,20 +21,20 @@ private SimpleDatabaseTypeResolver() { } @Nullable - public static Class findDatabaseType(@Nonnull String name) { + public static Class findDatabaseType(@NotNull String name) { return ReflectionUtils.getClassOrNull(registry.get(name)); } @Nullable - public static Class findDatabaseType(@Nonnull String name, boolean initialize, @Nonnull ClassLoader classLoader) { + public static Class findDatabaseType(@NotNull String name, boolean initialize, @NotNull ClassLoader classLoader) { return ReflectionUtils.getClassOrNull(registry.get(name), initialize, classLoader); } - public static void registerType(@Nonnull String name, @Nonnull String className) { + public static void registerType(@NotNull String name, @NotNull String className) { registry.put(name, className); } - public static void registerType(@Nonnull String name, @Nonnull Class databaseClass) { + public static void registerType(@NotNull String name, @NotNull Class databaseClass) { registerType(name, databaseClass.getName()); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java index f65f869cc..fbd2d744e 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/SpecificDatabase.java @@ -1,9 +1,8 @@ package net.codingarea.commons.database; import net.codingarea.commons.database.action.*; - -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; /** * Represents a table/collection of a database @@ -15,52 +14,52 @@ public interface SpecificDatabase { boolean isConnected(); - @Nonnull + @NotNull String getName(); /** * @see Database#countEntries(String) */ - @Nonnull + @NotNull @CheckReturnValue DatabaseCountEntries countEntries(); /** * @see Database#query(String) */ - @Nonnull + @NotNull @CheckReturnValue DatabaseQuery query(); /** * @see Database#update(String) */ - @Nonnull + @NotNull @CheckReturnValue DatabaseUpdate update(); /** * @see Database#insert(String) */ - @Nonnull + @NotNull @CheckReturnValue DatabaseInsertion insert(); /** * @see Database#insertOrUpdate(String) */ - @Nonnull + @NotNull @CheckReturnValue DatabaseInsertionOrUpdate insertOrUpdate(); /** * @see Database#delete(String) */ - @Nonnull + @NotNull @CheckReturnValue DatabaseDeletion delete(); - @Nonnull + @NotNull Database getParent(); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java index 62aa6846b..f346a9a3a 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java @@ -7,14 +7,13 @@ import net.codingarea.commons.database.exceptions.DatabaseAlreadyConnectedException; import net.codingarea.commons.database.exceptions.DatabaseConnectionClosedException; import net.codingarea.commons.database.exceptions.DatabaseException; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public abstract class AbstractDatabase implements Database { protected final DatabaseConfig config; - public AbstractDatabase(@Nonnull DatabaseConfig config) { + public AbstractDatabase(@NotNull DatabaseConfig config) { this.config = config; } @@ -68,7 +67,7 @@ public void connect() throws DatabaseException { protected abstract void connect0() throws Exception; @Override - public void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... columns) { + public void createTableSafely(@NotNull String name, @NotNull SQLColumn... columns) { try { createTable(name, columns); } catch (DatabaseException ex) { @@ -76,13 +75,13 @@ public void createTableSafely(@Nonnull String name, @Nonnull SQLColumn... column } } - @Nonnull + @NotNull @Override - public SpecificDatabase getSpecificDatabase(@Nonnull String name) { + public SpecificDatabase getSpecificDatabase(@NotNull String name) { return new DefaultSpecificDatabase(this, name); } - @Nonnull + @NotNull @Override public DatabaseConfig getConfig() { return config; diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java index 01f649efd..2a7695026 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultExecutedQuery.java @@ -2,8 +2,8 @@ import net.codingarea.commons.common.config.Document; import net.codingarea.commons.database.action.ExecutedQuery; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.io.PrintStream; import java.util.*; import java.util.function.IntFunction; @@ -14,40 +14,40 @@ public class DefaultExecutedQuery implements ExecutedQuery { protected final List results; - public DefaultExecutedQuery(@Nonnull List results) { + public DefaultExecutedQuery(@NotNull List results) { this.results = results; } - @Nonnull + @NotNull @Override public Optional first() { if (results.isEmpty()) return Optional.empty(); return Optional.ofNullable(results.get(0)); } - @Nonnull + @NotNull @Override public Optional get(int index) { if (index >= results.size()) return Optional.empty(); return Optional.ofNullable(results.get(index)); } - @Nonnull + @NotNull @Override public Stream all() { return results.stream(); } - @Nonnull + @NotNull @Override - public > C toCollection(@Nonnull C collection) { + public > C toCollection(@NotNull C collection) { collection.addAll(results); return collection; } - @Nonnull + @NotNull @Override - public Document[] toArray(@Nonnull IntFunction arraySupplier) { + public Document[] toArray(@NotNull IntFunction arraySupplier) { Document[] array = arraySupplier.apply(size()); for (int i = 0; i < size(); i++) { array[i] = results.get(i); @@ -56,7 +56,7 @@ public Document[] toArray(@Nonnull IntFunction arraySupplier) { } @Override - public int index(@Nonnull Predicate filter) { + public int index(@NotNull Predicate filter) { int index = 0; for (Document result : results) { if (filter.test(result)) @@ -82,7 +82,7 @@ public int size() { } @Override - public void print(@Nonnull PrintStream out) { + public void print(@NotNull PrintStream out) { if (results.isEmpty()) { out.println(""); return; diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java index bd5c88b58..bce699996 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/DefaultSpecificDatabase.java @@ -3,8 +3,8 @@ import net.codingarea.commons.database.Database; import net.codingarea.commons.database.SpecificDatabase; import net.codingarea.commons.database.action.*; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.Objects; public class DefaultSpecificDatabase implements SpecificDatabase { @@ -12,7 +12,7 @@ public class DefaultSpecificDatabase implements SpecificDatabase { protected final Database parent; protected final String name; - public DefaultSpecificDatabase(@Nonnull Database parent, @Nonnull String name) { + public DefaultSpecificDatabase(@NotNull Database parent, @NotNull String name) { this.parent = parent; this.name = name; } @@ -22,49 +22,49 @@ public boolean isConnected() { return parent.isConnected(); } - @Nonnull + @NotNull @Override public String getName() { return name; } - @Nonnull + @NotNull @Override public DatabaseCountEntries countEntries() { return parent.countEntries(name); } - @Nonnull + @NotNull @Override public DatabaseQuery query() { return parent.query(name); } - @Nonnull + @NotNull @Override public DatabaseUpdate update() { return parent.update(name); } - @Nonnull + @NotNull @Override public DatabaseInsertion insert() { return parent.insert(name); } - @Nonnull + @NotNull @Override public DatabaseInsertionOrUpdate insertOrUpdate() { return parent.insertOrUpdate(name); } - @Nonnull + @NotNull @Override public DatabaseDeletion delete() { return parent.delete(name); } - @Nonnull + @NotNull @Override public Database getParent() { return parent; diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java b/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java index 638b0d965..70f5239c6 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java +++ b/plugin/src/main/java/net/codingarea/commons/database/access/CachedDatabaseAccess.java @@ -4,9 +4,9 @@ import net.codingarea.commons.common.config.Propertyable; import net.codingarea.commons.database.Database; import net.codingarea.commons.database.exceptions.DatabaseException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; @@ -16,13 +16,13 @@ public class CachedDatabaseAccess extends DirectDatabaseAccess { protected final Map cache = new ConcurrentHashMap<>(); - public CachedDatabaseAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config, @Nonnull BiFunction mapper) { + public CachedDatabaseAccess(@NotNull Database database, @NotNull DatabaseAccessConfig config, @NotNull BiFunction mapper) { super(database, config, mapper); } @Nullable @Override - public V getValue(@Nonnull String key) throws DatabaseException { + public V getValue(@NotNull String key) throws DatabaseException { V value = cache.get(key); if (value != null) return value; @@ -31,9 +31,9 @@ public V getValue(@Nonnull String key) throws DatabaseException { return value; } - @Nonnull + @NotNull @Override - public V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException { + public V getValue(@NotNull String key, @NotNull V def) throws DatabaseException { V value = cache.get(key); if (value != null) return value; @@ -42,9 +42,9 @@ public V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException return value; } - @Nonnull + @NotNull @Override - public Optional getValueOptional(@Nonnull String key) throws DatabaseException { + public Optional getValueOptional(@NotNull String key) throws DatabaseException { V cached = cache.get(key); if (cached != null) return Optional.of(cached); @@ -52,33 +52,33 @@ public Optional getValueOptional(@Nonnull String key) throws DatabaseExceptio } @Override - public void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException { + public void setValue(@NotNull String key, @Nullable V value) throws DatabaseException { cache.put(key, value); super.setValue(key, value); } - @Nonnull - public static CachedDatabaseAccess newStringAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + @NotNull + public static CachedDatabaseAccess newStringAccess(@NotNull Database database, @NotNull DatabaseAccessConfig config) { return new CachedDatabaseAccess<>(database, config, Propertyable::getString); } - @Nonnull - public static CachedDatabaseAccess newIntAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + @NotNull + public static CachedDatabaseAccess newIntAccess(@NotNull Database database, @NotNull DatabaseAccessConfig config) { return new CachedDatabaseAccess<>(database, config, Propertyable::getInt); } - @Nonnull - public static CachedDatabaseAccess newLongAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + @NotNull + public static CachedDatabaseAccess newLongAccess(@NotNull Database database, @NotNull DatabaseAccessConfig config) { return new CachedDatabaseAccess<>(database, config, Propertyable::getLong); } - @Nonnull - public static CachedDatabaseAccess newDoubleAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + @NotNull + public static CachedDatabaseAccess newDoubleAccess(@NotNull Database database, @NotNull DatabaseAccessConfig config) { return new CachedDatabaseAccess<>(database, config, Propertyable::getDouble); } - @Nonnull - public static CachedDatabaseAccess newDocumentAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config) { + @NotNull + public static CachedDatabaseAccess newDocumentAccess(@NotNull Database database, @NotNull DatabaseAccessConfig config) { return new CachedDatabaseAccess<>(database, config, Document::getDocument); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java index 0870dfb8d..73f2119e7 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java +++ b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccess.java @@ -2,32 +2,32 @@ import net.codingarea.commons.database.Database; import net.codingarea.commons.database.exceptions.DatabaseException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Optional; public interface DatabaseAccess { @Nullable - V getValue(@Nonnull String key) throws DatabaseException; + V getValue(@NotNull String key) throws DatabaseException; - @Nonnull - V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException; + @NotNull + V getValue(@NotNull String key, @NotNull V def) throws DatabaseException; - @Nonnull - Optional getValueOptional(@Nonnull String key) throws DatabaseException; + @NotNull + Optional getValueOptional(@NotNull String key) throws DatabaseException; - void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException; + void setValue(@NotNull String key, @Nullable V value) throws DatabaseException; - default boolean hasValue(@Nonnull String key) throws DatabaseException { + default boolean hasValue(@NotNull String key) throws DatabaseException { return getValueOptional(key).isPresent(); } - @Nonnull + @NotNull Database getDatabase(); - @Nonnull + @NotNull DatabaseAccessConfig getConfig(); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java index edbaae624..33723d81b 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java +++ b/plugin/src/main/java/net/codingarea/commons/database/access/DatabaseAccessConfig.java @@ -1,6 +1,6 @@ package net.codingarea.commons.database.access; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public final class DatabaseAccessConfig { @@ -8,23 +8,23 @@ public final class DatabaseAccessConfig { private final String keyField; private final String valueField; - public DatabaseAccessConfig(@Nonnull String table, @Nonnull String keyField, @Nonnull String valueField) { + public DatabaseAccessConfig(@NotNull String table, @NotNull String keyField, @NotNull String valueField) { this.table = table; this.keyField = keyField; this.valueField = valueField; } - @Nonnull + @NotNull public String getTable() { return table; } - @Nonnull + @NotNull public String getKeyField() { return keyField; } - @Nonnull + @NotNull public String getValueField() { return valueField; } diff --git a/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java b/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java index 902b1b6e3..f6343fdae 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java +++ b/plugin/src/main/java/net/codingarea/commons/database/access/DirectDatabaseAccess.java @@ -3,9 +3,9 @@ import net.codingarea.commons.common.config.Document; import net.codingarea.commons.database.Database; import net.codingarea.commons.database.exceptions.DatabaseException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Optional; import java.util.function.BiFunction; @@ -15,7 +15,7 @@ public class DirectDatabaseAccess implements DatabaseAccess { protected final DatabaseAccessConfig config; protected final BiFunction mapper; - public DirectDatabaseAccess(@Nonnull Database database, @Nonnull DatabaseAccessConfig config, @Nonnull BiFunction mapper) { + public DirectDatabaseAccess(@NotNull Database database, @NotNull DatabaseAccessConfig config, @NotNull BiFunction mapper) { this.database = database; this.config = config; this.mapper = mapper; @@ -23,24 +23,24 @@ public DirectDatabaseAccess(@Nonnull Database database, @Nonnull DatabaseAccessC @Nullable @Override - public V getValue(@Nonnull String key) throws DatabaseException { + public V getValue(@NotNull String key) throws DatabaseException { return getValue0(key).orElse(null); } - @Nonnull + @NotNull @Override - public V getValue(@Nonnull String key, @Nonnull V def) throws DatabaseException { + public V getValue(@NotNull String key, @NotNull V def) throws DatabaseException { return getValue0(key).orElse(def); } - @Nonnull + @NotNull @Override - public Optional getValueOptional(@Nonnull String key) throws DatabaseException { + public Optional getValueOptional(@NotNull String key) throws DatabaseException { return getValue0(key); } - @Nonnull - protected Optional getValue0(@Nonnull String key) throws DatabaseException { + @NotNull + protected Optional getValue0(@NotNull String key) throws DatabaseException { return database.query(config.getTable()) .where(config.getKeyField(), key) .execute().first() @@ -48,20 +48,20 @@ protected Optional getValue0(@Nonnull String key) throws DatabaseException { } @Override - public void setValue(@Nonnull String key, @Nullable V value) throws DatabaseException { + public void setValue(@NotNull String key, @Nullable V value) throws DatabaseException { database.insertOrUpdate(config.getTable()) .set(config.getValueField(), value) .where(config.getKeyField(), key) .execute(); } - @Nonnull + @NotNull @Override public Database getDatabase() { return database; } - @Nonnull + @NotNull @Override public DatabaseAccessConfig getConfig() { return config; diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java index b2f0fde7f..06aec7d25 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseAction.java @@ -7,8 +7,7 @@ import net.codingarea.commons.database.exceptions.DatabaseConnectionClosedException; import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.commons.database.exceptions.UnsignedDatabaseException; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; /** * Some action which will be executed on a database. @@ -67,7 +66,7 @@ default R executeUnsigned() { * * @return a new {@link Task} which will be completed when the action was executed */ - @Nonnull + @NotNull default Task executeAsync() { return Task.asyncCall(this::execute); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java index 67206e3be..62fba9626 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseCountEntries.java @@ -3,9 +3,7 @@ import net.codingarea.commons.database.Database; import net.codingarea.commons.database.SpecificDatabase; import net.codingarea.commons.database.exceptions.DatabaseException; - -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; /** * @see Database#countEntries(String) @@ -13,9 +11,8 @@ */ public interface DatabaseCountEntries extends DatabaseAction { - @Nonnull + @NotNull @Override - @Nonnegative Long execute() throws DatabaseException; } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java index 1f02e8392..54f8354eb 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseDeletion.java @@ -4,10 +4,9 @@ import net.codingarea.commons.database.SpecificDatabase; import net.codingarea.commons.database.action.hierarchy.WhereAction; import net.codingarea.commons.database.exceptions.DatabaseException; - -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; /** * @see Database#delete(String) @@ -15,25 +14,25 @@ */ public interface DatabaseDeletion extends DatabaseAction, WhereAction { - @Nonnull + @NotNull @CheckReturnValue - DatabaseDeletion where(@Nonnull String field, @Nullable Object value); + DatabaseDeletion where(@NotNull String field, @Nullable Object value); - @Nonnull + @NotNull @CheckReturnValue - DatabaseDeletion where(@Nonnull String field, @Nullable Number value); + DatabaseDeletion where(@NotNull String field, @Nullable Number value); - @Nonnull + @NotNull @CheckReturnValue - DatabaseDeletion where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + DatabaseDeletion where(@NotNull String field, @Nullable String value, boolean ignoreCase); - @Nonnull + @NotNull @CheckReturnValue - DatabaseDeletion where(@Nonnull String field, @Nullable String value); + DatabaseDeletion where(@NotNull String field, @Nullable String value); - @Nonnull + @NotNull @CheckReturnValue - DatabaseDeletion whereNot(@Nonnull String field, @Nullable Object value); + DatabaseDeletion whereNot(@NotNull String field, @Nullable Object value); @Nullable @Override diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java index 2feb77399..b7c89a1cf 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertion.java @@ -4,10 +4,9 @@ import net.codingarea.commons.database.SpecificDatabase; import net.codingarea.commons.database.action.hierarchy.SetAction; import net.codingarea.commons.database.exceptions.DatabaseException; - -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; /** * @see Database#insert(String) @@ -15,9 +14,9 @@ */ public interface DatabaseInsertion extends DatabaseAction, SetAction { - @Nonnull + @NotNull @CheckReturnValue - DatabaseInsertion set(@Nonnull String field, @Nullable Object value); + DatabaseInsertion set(@NotNull String field, @Nullable Object value); @Nullable @Override diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java index c97385028..2844237b0 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseInsertionOrUpdate.java @@ -3,10 +3,9 @@ import net.codingarea.commons.database.Database; import net.codingarea.commons.database.SpecificDatabase; import net.codingarea.commons.database.exceptions.DatabaseException; - -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; /** * @see Database#insertOrUpdate(String) @@ -14,29 +13,29 @@ */ public interface DatabaseInsertionOrUpdate extends DatabaseUpdate, DatabaseInsertion { - @Nonnull + @NotNull @CheckReturnValue - DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Object value); + DatabaseInsertionOrUpdate where(@NotNull String field, @Nullable Object value); - @Nonnull + @NotNull @CheckReturnValue - DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable Number value); + DatabaseInsertionOrUpdate where(@NotNull String field, @Nullable Number value); - @Nonnull + @NotNull @CheckReturnValue - DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + DatabaseInsertionOrUpdate where(@NotNull String field, @Nullable String value, boolean ignoreCase); - @Nonnull + @NotNull @CheckReturnValue - DatabaseInsertionOrUpdate where(@Nonnull String field, @Nullable String value); + DatabaseInsertionOrUpdate where(@NotNull String field, @Nullable String value); - @Nonnull + @NotNull @Override - DatabaseInsertionOrUpdate whereNot(@Nonnull String field, @Nullable Object value); + DatabaseInsertionOrUpdate whereNot(@NotNull String field, @Nullable Object value); - @Nonnull + @NotNull @Override - DatabaseInsertionOrUpdate set(@Nonnull String field, @Nullable Object value); + DatabaseInsertionOrUpdate set(@NotNull String field, @Nullable Object value); @Nullable @Override diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java index 27ac72e78..5e9fc6458 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseListTables.java @@ -2,8 +2,8 @@ import net.codingarea.commons.database.Database; import net.codingarea.commons.database.exceptions.DatabaseException; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.util.List; /** @@ -11,7 +11,7 @@ */ public interface DatabaseListTables extends DatabaseAction> { - @Nonnull + @NotNull @Override List execute() throws DatabaseException; diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java index 8cf667d39..2a624de91 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseQuery.java @@ -6,10 +6,9 @@ import net.codingarea.commons.database.action.hierarchy.OrderedAction; import net.codingarea.commons.database.action.hierarchy.WhereAction; import net.codingarea.commons.database.exceptions.DatabaseException; - -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; /** * @see Database#query(String) @@ -17,37 +16,36 @@ */ public interface DatabaseQuery extends DatabaseAction, WhereAction, OrderedAction { - @Nonnull + @NotNull @CheckReturnValue - DatabaseQuery where(@Nonnull String field, @Nullable Object object); + DatabaseQuery where(@NotNull String field, @Nullable Object object); - @Nonnull + @NotNull @CheckReturnValue - DatabaseQuery where(@Nonnull String field, @Nullable Number value); + DatabaseQuery where(@NotNull String field, @Nullable Number value); - @Nonnull + @NotNull @CheckReturnValue - DatabaseQuery where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + DatabaseQuery where(@NotNull String field, @Nullable String value, boolean ignoreCase); - @Nonnull + @NotNull @CheckReturnValue - DatabaseQuery where(@Nonnull String field, @Nullable String value); + DatabaseQuery where(@NotNull String field, @Nullable String value); - @Nonnull + @NotNull @CheckReturnValue - DatabaseQuery whereNot(@Nonnull String field, @Nullable Object value); + DatabaseQuery whereNot(@NotNull String field, @Nullable Object value); - @Nonnull + @NotNull @CheckReturnValue - DatabaseQuery select(@Nonnull String... selection); + DatabaseQuery select(@NotNull String... selection); - @Nonnull + @NotNull @CheckReturnValue - DatabaseQuery orderBy(@Nonnull String field, @Nonnull Order order); + DatabaseQuery orderBy(@NotNull String field, @NotNull Order order); - @Nonnull + @NotNull @Override - @CheckReturnValue ExecutedQuery execute() throws DatabaseException; } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java index d39831207..bc7bc1732 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/DatabaseUpdate.java @@ -5,10 +5,9 @@ import net.codingarea.commons.database.action.hierarchy.SetAction; import net.codingarea.commons.database.action.hierarchy.WhereAction; import net.codingarea.commons.database.exceptions.DatabaseException; - -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; /** * @see Database#update(String) @@ -16,29 +15,29 @@ */ public interface DatabaseUpdate extends DatabaseAction, WhereAction, SetAction { - @Nonnull + @NotNull @CheckReturnValue - DatabaseUpdate where(@Nonnull String field, @Nullable Object value); + DatabaseUpdate where(@NotNull String field, @Nullable Object value); - @Nonnull + @NotNull @CheckReturnValue - DatabaseUpdate where(@Nonnull String field, @Nullable Number value); + DatabaseUpdate where(@NotNull String field, @Nullable Number value); - @Nonnull + @NotNull @CheckReturnValue - DatabaseUpdate where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + DatabaseUpdate where(@NotNull String field, @Nullable String value, boolean ignoreCase); - @Nonnull + @NotNull @CheckReturnValue - DatabaseUpdate where(@Nonnull String field, @Nullable String value); + DatabaseUpdate where(@NotNull String field, @Nullable String value); - @Nonnull + @NotNull @CheckReturnValue - DatabaseUpdate whereNot(@Nonnull String field, @Nullable Object value); + DatabaseUpdate whereNot(@NotNull String field, @Nullable Object value); - @Nonnull + @NotNull @CheckReturnValue - DatabaseUpdate set(@Nonnull String field, @Nullable Object value); + DatabaseUpdate set(@NotNull String field, @Nullable Object value); @Nullable @Override diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java b/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java index 70520483c..f1a57ace1 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/ExecutedQuery.java @@ -3,9 +3,9 @@ import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.logging.LogLevel; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; import java.io.PrintStream; import java.util.*; import java.util.function.IntFunction; @@ -17,55 +17,55 @@ */ public interface ExecutedQuery extends Iterable { - @Nonnull + @NotNull @CheckReturnValue Optional first(); - @Nonnull + @NotNull @CheckReturnValue default Document firstOrEmpty() { return first().orElse(Document.empty()); } - @Nonnull + @NotNull @CheckReturnValue Optional get(int index); - @Nonnull + @NotNull @CheckReturnValue default Document getOrEmpty(int index) { return get(index).orElse(Document.empty()); } - @Nonnull + @NotNull @CheckReturnValue Stream all(); - @Nonnull + @NotNull @CheckReturnValue default List toList() { return toCollection((IntFunction>) ArrayList::new); } - @Nonnull + @NotNull @CheckReturnValue default Set toSet() { return toCollection((IntFunction>) HashSet::new); } - @Nonnull - > C toCollection(@Nonnull C collection); + @NotNull + > C toCollection(@NotNull C collection); - @Nonnull + @NotNull @CheckReturnValue - default > C toCollection(@Nonnull IntFunction collectionSupplier) { + default > C toCollection(@NotNull IntFunction collectionSupplier) { return toCollection(collectionSupplier.apply(size())); } - @Nonnull - Document[] toArray(@Nonnull IntFunction arraySupplier); + @NotNull + Document[] toArray(@NotNull IntFunction arraySupplier); - int index(@Nonnull Predicate filter); + int index(@NotNull Predicate filter); boolean isEmpty(); @@ -73,9 +73,9 @@ default > C toCollection(@Nonnull IntFunc int size(); - void print(@Nonnull PrintStream out); + void print(@NotNull PrintStream out); - default void print(@Nonnull ILogger logger) { + default void print(@NotNull ILogger logger) { print(logger.asPrintStream(LogLevel.INFO)); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java index 7f7446830..0af709217 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/OrderedAction.java @@ -1,13 +1,12 @@ package net.codingarea.commons.database.action.hierarchy; import net.codingarea.commons.database.Order; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public interface OrderedAction { @Nullable - OrderedAction orderBy(@Nonnull String field, @Nonnull Order order); + OrderedAction orderBy(@NotNull String field, @NotNull Order order); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java index c22e7970f..aff2b7354 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/SetAction.java @@ -1,11 +1,11 @@ package net.codingarea.commons.database.action.hierarchy; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public interface SetAction { - @Nonnull - SetAction set(@Nonnull String field, @Nullable Object value); + @NotNull + SetAction set(@NotNull String field, @Nullable Object value); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java index 6df5c791b..a480501c3 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java +++ b/plugin/src/main/java/net/codingarea/commons/database/action/hierarchy/WhereAction.java @@ -1,29 +1,29 @@ package net.codingarea.commons.database.action.hierarchy; -import javax.annotation.CheckReturnValue; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public interface WhereAction { - @Nonnull + @NotNull @CheckReturnValue - WhereAction where(@Nonnull String field, @Nullable Object value); + WhereAction where(@NotNull String field, @Nullable Object value); - @Nonnull + @NotNull @CheckReturnValue - WhereAction where(@Nonnull String field, @Nullable Number value); + WhereAction where(@NotNull String field, @Nullable Number value); - @Nonnull + @NotNull @CheckReturnValue - WhereAction where(@Nonnull String field, @Nullable String value, boolean ignoreCase); + WhereAction where(@NotNull String field, @Nullable String value, boolean ignoreCase); - @Nonnull + @NotNull @CheckReturnValue - WhereAction where(@Nonnull String field, @Nullable String value); + WhereAction where(@NotNull String field, @Nullable String value); - @Nonnull + @NotNull @CheckReturnValue - WhereAction whereNot(@Nonnull String field, @Nullable Object value); + WhereAction whereNot(@NotNull String field, @Nullable Object value); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java index 49722e7e7..937c6e2e4 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseException.java @@ -1,8 +1,7 @@ package net.codingarea.commons.database.exceptions; import net.codingarea.commons.database.action.DatabaseAction; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; /** * @see DatabaseAlreadyConnectedException @@ -16,15 +15,15 @@ protected DatabaseException() { super(); } - public DatabaseException(@Nonnull String message) { + public DatabaseException(@NotNull String message) { super(message); } - public DatabaseException(@Nonnull Throwable cause) { + public DatabaseException(@NotNull Throwable cause) { super(cause); } - public DatabaseException(@Nonnull String message, @Nonnull Throwable cause) { + public DatabaseException(@NotNull String message, @NotNull Throwable cause) { super(message, cause); } } diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java index 5aa24fd12..34d61d981 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/DatabaseUnsupportedFeatureException.java @@ -1,13 +1,13 @@ package net.codingarea.commons.database.exceptions; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class DatabaseUnsupportedFeatureException extends DatabaseException { public DatabaseUnsupportedFeatureException() { } - public DatabaseUnsupportedFeatureException(@Nonnull String message) { + public DatabaseUnsupportedFeatureException(@NotNull String message) { super(message); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java b/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java index c9137b8b5..f9bc55a96 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java +++ b/plugin/src/main/java/net/codingarea/commons/database/exceptions/UnsignedDatabaseException.java @@ -2,8 +2,7 @@ import net.codingarea.commons.common.collection.WrappedException; import net.codingarea.commons.database.action.DatabaseAction; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; /** * @see DatabaseException @@ -11,11 +10,11 @@ */ public class UnsignedDatabaseException extends WrappedException { - public UnsignedDatabaseException(@Nonnull DatabaseException cause) { + public UnsignedDatabaseException(@NotNull DatabaseException cause) { super(cause); } - @Nonnull + @NotNull @Override public DatabaseException getCause() { return (DatabaseException) super.getCause(); diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java index 19551869f..a31562e3c 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/AbstractSQLDatabase.java @@ -12,8 +12,8 @@ import net.codingarea.commons.database.sql.abstraction.query.SQLQuery; import net.codingarea.commons.database.sql.abstraction.update.SQLUpdate; import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; @@ -24,7 +24,7 @@ public abstract class AbstractSQLDatabase extends AbstractDatabase { protected Connection connection; - public AbstractSQLDatabase(@Nonnull DatabaseConfig config) { + public AbstractSQLDatabase(@NotNull DatabaseConfig config) { super(config); } @@ -54,7 +54,7 @@ public boolean isConnected() { } @Override - public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) throws DatabaseException { + public void createTable(@NotNull String name, @NotNull SQLColumn... columns) throws DatabaseException { try { StringBuilder command = new StringBuilder(); command.append("CREATE TABLE IF NOT EXISTS `"); @@ -77,54 +77,54 @@ public void createTable(@Nonnull String name, @Nonnull SQLColumn... columns) thr } } - @Nonnull + @NotNull @Override - public DatabaseCountEntries countEntries(@Nonnull String table) { + public DatabaseCountEntries countEntries(@NotNull String table) { return new SQLCountEntries(this, table); } - @Nonnull + @NotNull @Override - public DatabaseQuery query(@Nonnull String table) { + public DatabaseQuery query(@NotNull String table) { return new SQLQuery(this, table); } - @Nonnull - public DatabaseQuery query(@Nonnull String table, @Nonnull Map where) { + @NotNull + public DatabaseQuery query(@NotNull String table, @NotNull Map where) { return new SQLQuery(this, table, where); } - @Nonnull + @NotNull @Override - public DatabaseUpdate update(@Nonnull String table) { + public DatabaseUpdate update(@NotNull String table) { return new SQLUpdate(this, table); } - @Nonnull + @NotNull @Override - public DatabaseInsertion insert(@Nonnull String table) { + public DatabaseInsertion insert(@NotNull String table) { return new SQLInsertion(this, table); } - @Nonnull - public DatabaseInsertion insert(@Nonnull String table, @Nonnull Map values) { + @NotNull + public DatabaseInsertion insert(@NotNull String table, @NotNull Map values) { return new SQLInsertion(this, table, values); } - @Nonnull + @NotNull @Override - public DatabaseInsertionOrUpdate insertOrUpdate(@Nonnull String table) { + public DatabaseInsertionOrUpdate insertOrUpdate(@NotNull String table) { return new SQLInsertionOrUpdate(this, table); } - @Nonnull + @NotNull @Override - public DatabaseDeletion delete(@Nonnull String table) { + public DatabaseDeletion delete(@NotNull String table) { return new SQLDeletion(this, table); } - @Nonnull - public PreparedStatement prepare(@Nonnull CharSequence command, @Nonnull Object... args) throws SQLException, DatabaseException { + @NotNull + public PreparedStatement prepare(@NotNull CharSequence command, @NotNull Object... args) throws SQLException, DatabaseException { checkConnection(); PreparedStatement statement = connection.prepareStatement(command.toString()); SQLHelper.fillParams(statement, args); diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java index e53c76cbd..0215be104 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/SQLHelper.java @@ -3,9 +3,9 @@ import net.codingarea.commons.common.config.Json; import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.commons.common.misc.GsonUtils; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Map; @@ -15,7 +15,7 @@ public final class SQLHelper { private SQLHelper() { } - public static void fillParams(@Nonnull PreparedStatement statement, @Nonnull Object... params) throws SQLException { + public static void fillParams(@NotNull PreparedStatement statement, @NotNull Object... params) throws SQLException { for (int i = 0; i < params.length; i++) { Object param = serializeObject(params[i]); statement.setObject(i + 1 /* in sql we count from 1 */, param); diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java index a0100ab1e..d9af09800 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/count/SQLCountEntries.java @@ -3,8 +3,8 @@ import net.codingarea.commons.database.action.DatabaseCountEntries; import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Objects; @@ -14,12 +14,12 @@ public class SQLCountEntries implements DatabaseCountEntries { protected final AbstractSQLDatabase database; protected final String table; - public SQLCountEntries(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + public SQLCountEntries(@NotNull AbstractSQLDatabase database, @NotNull String table) { this.database = database; this.table = table; } - @Nonnull + @NotNull @Override public Long execute() throws DatabaseException { try { diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java index 14a3239c5..c5aec36eb 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/deletion/SQLDeletion.java @@ -6,9 +6,9 @@ import net.codingarea.commons.database.sql.abstraction.where.ObjectWhere; import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; import net.codingarea.commons.database.sql.abstraction.where.StringIgnoreCaseWhere; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.*; @@ -20,47 +20,47 @@ public class SQLDeletion implements DatabaseDeletion { protected final String table; protected final Map where = new HashMap<>(); - public SQLDeletion(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + public SQLDeletion(@NotNull AbstractSQLDatabase database, @NotNull String table) { this.database = database; this.table = table; } - @Nonnull + @NotNull @Override - public DatabaseDeletion where(@Nonnull String column, @Nullable Object value) { + public DatabaseDeletion where(@NotNull String column, @Nullable Object value) { where.put(column, new ObjectWhere(column, value, "=")); return this; } - @Nonnull + @NotNull @Override - public DatabaseDeletion where(@Nonnull String column, @Nullable Number value) { + public DatabaseDeletion where(@NotNull String column, @Nullable Number value) { return where(column, (Object) value); } - @Nonnull + @NotNull @Override - public DatabaseDeletion where(@Nonnull String column, @Nullable String value) { + public DatabaseDeletion where(@NotNull String column, @Nullable String value) { return where(column, (Object) value); } - @Nonnull + @NotNull @Override - public DatabaseDeletion where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + public DatabaseDeletion where(@NotNull String column, @Nullable String value, boolean ignoreCase) { if (!ignoreCase) return where(column, value); if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); where.put(column, new StringIgnoreCaseWhere(column, value)); return this; } - @Nonnull + @NotNull @Override - public DatabaseDeletion whereNot(@Nonnull String column, @Nullable Object value) { + public DatabaseDeletion whereNot(@NotNull String column, @Nullable Object value) { where.put(column, new ObjectWhere(column, value, "!=")); return this; } - @Nonnull + @NotNull protected PreparedStatement prepare() throws SQLException, DatabaseException { StringBuilder command = new StringBuilder(); List args = new ArrayList<>(); diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java index a2b397b48..a9ae2a2f6 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertion/SQLInsertion.java @@ -3,9 +3,9 @@ import net.codingarea.commons.database.action.DatabaseInsertion; import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.*; @@ -16,26 +16,26 @@ public class SQLInsertion implements DatabaseInsertion { protected final AbstractSQLDatabase database; protected final String table; - public SQLInsertion(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + public SQLInsertion(@NotNull AbstractSQLDatabase database, @NotNull String table) { this.database = database; this.table = table; this.values = new HashMap<>(); } - public SQLInsertion(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map values) { + public SQLInsertion(@NotNull AbstractSQLDatabase database, @NotNull String table, @NotNull Map values) { this.database = database; this.table = table; this.values = values; } - @Nonnull + @NotNull @Override - public DatabaseInsertion set(@Nonnull String field, @Nullable Object value) { + public DatabaseInsertion set(@NotNull String field, @Nullable Object value) { values.put(field, value); return this; } - @Nonnull + @NotNull protected PreparedStatement prepare() throws SQLException, DatabaseException { if (values.isEmpty()) throw new IllegalArgumentException("Cannot insert nothing"); diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java index 348a51d3d..32c5572e8 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/insertorupdate/SQLInsertionOrUpdate.java @@ -5,57 +5,57 @@ import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; import net.codingarea.commons.database.sql.abstraction.update.SQLUpdate; import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public class SQLInsertionOrUpdate extends SQLUpdate implements DatabaseInsertionOrUpdate { - public SQLInsertionOrUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + public SQLInsertionOrUpdate(@NotNull AbstractSQLDatabase database, @NotNull String table) { super(database, table); } - @Nonnull + @NotNull @Override - public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable Object value) { + public DatabaseInsertionOrUpdate where(@NotNull String column, @Nullable Object value) { super.where(column, value); return this; } - @Nonnull + @NotNull @Override - public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable Number value) { + public DatabaseInsertionOrUpdate where(@NotNull String column, @Nullable Number value) { super.where(column, value); return this; } - @Nonnull + @NotNull @Override - public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + public DatabaseInsertionOrUpdate where(@NotNull String column, @Nullable String value, boolean ignoreCase) { super.where(column, value); return this; } - @Nonnull + @NotNull @Override - public DatabaseInsertionOrUpdate where(@Nonnull String column, @Nullable String value) { + public DatabaseInsertionOrUpdate where(@NotNull String column, @Nullable String value) { super.where(column, value); return this; } - @Nonnull + @NotNull @Override - public DatabaseInsertionOrUpdate whereNot(@Nonnull String column, @Nullable Object value) { + public DatabaseInsertionOrUpdate whereNot(@NotNull String column, @Nullable Object value) { super.whereNot(column, value); return this; } - @Nonnull + @NotNull @Override - public DatabaseInsertionOrUpdate set(@Nonnull String column, @Nullable Object value) { + public DatabaseInsertionOrUpdate set(@NotNull String column, @Nullable Object value) { super.set(column, value); return this; } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java index 814a05b7f..b2980e44d 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLQuery.java @@ -10,9 +10,9 @@ import net.codingarea.commons.database.sql.abstraction.where.ObjectWhere; import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; import net.codingarea.commons.database.sql.abstraction.where.StringIgnoreCaseWhere; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; @@ -29,70 +29,70 @@ public class SQLQuery implements DatabaseQuery { protected String orderBy; protected Order order; - public SQLQuery(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + public SQLQuery(@NotNull AbstractSQLDatabase database, @NotNull String table) { this.database = database; this.table = table; this.where = new HashMap<>(); } - public SQLQuery(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map where) { + public SQLQuery(@NotNull AbstractSQLDatabase database, @NotNull String table, @NotNull Map where) { this.database = database; this.table = table; this.where = where; } - @Nonnull + @NotNull @Override - public DatabaseQuery where(@Nonnull String column, @Nullable Object object) { + public DatabaseQuery where(@NotNull String column, @Nullable Object object) { where.put(column, new ObjectWhere(column, object, "=")); return this; } - @Nonnull + @NotNull @Override - public DatabaseQuery where(@Nonnull String column, @Nullable Number value) { + public DatabaseQuery where(@NotNull String column, @Nullable Number value) { return where(column, (Object) value); } - @Nonnull + @NotNull @Override - public DatabaseQuery where(@Nonnull String column, @Nullable String value) { + public DatabaseQuery where(@NotNull String column, @Nullable String value) { return where(column, (Object) value); } - @Nonnull + @NotNull @Override - public DatabaseQuery where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + public DatabaseQuery where(@NotNull String column, @Nullable String value, boolean ignoreCase) { if (!ignoreCase) return where(column, value); if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); where.put(column, new StringIgnoreCaseWhere(column, value)); return this; } - @Nonnull + @NotNull @Override - public DatabaseQuery whereNot(@Nonnull String column, @Nullable Object object) { + public DatabaseQuery whereNot(@NotNull String column, @Nullable Object object) { where.put(column, new ObjectWhere(column, object, "!=")); return this; } - @Nonnull + @NotNull @Override - public DatabaseQuery orderBy(@Nonnull String column, @Nonnull Order order) { + public DatabaseQuery orderBy(@NotNull String column, @NotNull Order order) { this.orderBy = column; this.order = order; return this; } - @Nonnull + @NotNull @Override - public DatabaseQuery select(@Nonnull String... selection) { + public DatabaseQuery select(@NotNull String... selection) { if (selection.length == 0) throw new IllegalArgumentException("Cannot select noting"); this.selection = selection; return this; } - @Nonnull + @NotNull protected PreparedStatement prepare() throws SQLException, DatabaseException { StringBuilder command = new StringBuilder(); List args = new LinkedList<>(); @@ -128,7 +128,7 @@ protected PreparedStatement prepare() throws SQLException, DatabaseException { return database.prepare(command.toString(), args.toArray()); } - @Nonnull + @NotNull @Override public ExecutedQuery execute() throws DatabaseException { try { @@ -140,8 +140,8 @@ public ExecutedQuery execute() throws DatabaseException { } } - @Nonnull - private ExecutedQuery createExecutedQuery(@Nonnull ResultSet result) throws SQLException { + @NotNull + private ExecutedQuery createExecutedQuery(@NotNull ResultSet result) throws SQLException { List results = new ArrayList<>(); ResultSetMetaData data = result.getMetaData(); while (result.next()) { diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java index 9077b8a92..2f9937c2d 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/query/SQLResult.java @@ -4,20 +4,20 @@ import net.codingarea.commons.common.config.document.EmptyDocument; import net.codingarea.commons.common.config.document.GsonDocument; import net.codingarea.commons.common.config.document.MapDocument; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Map; public final class SQLResult extends MapDocument { - public SQLResult(@Nonnull Map values) { + public SQLResult(@NotNull Map values) { super(values); } - @Nonnull + @NotNull @Override - public Document getDocument0(@Nonnull String path, @Nonnull Document root, @Nullable Document parent) { + public Document getDocument0(@NotNull String path, @NotNull Document root, @Nullable Document parent) { try { return new GsonDocument(getString(path), this, this).readonly(); } catch (Exception ex) { diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java index 7f2326334..adaae19dd 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/update/SQLUpdate.java @@ -6,9 +6,9 @@ import net.codingarea.commons.database.sql.abstraction.where.ObjectWhere; import net.codingarea.commons.database.sql.abstraction.where.SQLWhere; import net.codingarea.commons.database.sql.abstraction.where.StringIgnoreCaseWhere; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.*; @@ -21,63 +21,63 @@ public class SQLUpdate implements DatabaseUpdate { protected final Map where; protected final Map values; - public SQLUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table) { + public SQLUpdate(@NotNull AbstractSQLDatabase database, @NotNull String table) { this.database = database; this.table = table; this.where = new HashMap<>(); this.values = new HashMap<>(); } - public SQLUpdate(@Nonnull AbstractSQLDatabase database, @Nonnull String table, @Nonnull Map where, @Nonnull Map values) { + public SQLUpdate(@NotNull AbstractSQLDatabase database, @NotNull String table, @NotNull Map where, @NotNull Map values) { this.database = database; this.table = table; this.where = where; this.values = values; } - @Nonnull + @NotNull @Override - public DatabaseUpdate where(@Nonnull String column, @Nullable Object value) { + public DatabaseUpdate where(@NotNull String column, @Nullable Object value) { where.put(column, new ObjectWhere(column, value, "=")); return this; } - @Nonnull + @NotNull @Override - public DatabaseUpdate where(@Nonnull String column, @Nullable Number value) { + public DatabaseUpdate where(@NotNull String column, @Nullable Number value) { return where(column, (Object) value); } - @Nonnull + @NotNull @Override - public DatabaseUpdate where(@Nonnull String column, @Nullable String value) { + public DatabaseUpdate where(@NotNull String column, @Nullable String value) { return where(column, (Object) value); } - @Nonnull + @NotNull @Override - public DatabaseUpdate where(@Nonnull String column, @Nullable String value, boolean ignoreCase) { + public DatabaseUpdate where(@NotNull String column, @Nullable String value, boolean ignoreCase) { if (!ignoreCase) return where(column, value); if (value == null) throw new NullPointerException("Cannot use where ignore case with null value"); where.put(column, new StringIgnoreCaseWhere(column, value)); return this; } - @Nonnull + @NotNull @Override - public DatabaseUpdate whereNot(@Nonnull String column, @Nullable Object value) { + public DatabaseUpdate whereNot(@NotNull String column, @Nullable Object value) { where.put(column, new ObjectWhere(column, value, "!=")); return this; } - @Nonnull + @NotNull @Override - public DatabaseUpdate set(@Nonnull String column, @Nullable Object value) { + public DatabaseUpdate set(@NotNull String column, @Nullable Object value) { values.put(column, value); return this; } - @Nonnull + @NotNull protected PreparedStatement prepare() throws SQLException, DatabaseException { if (values.isEmpty()) throw new IllegalArgumentException("Can't update nothing"); diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java index 3ea51faf7..14e41d9fb 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/ObjectWhere.java @@ -1,7 +1,8 @@ package net.codingarea.commons.database.sql.abstraction.where; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + import java.util.Objects; public class ObjectWhere implements SQLWhere { @@ -10,19 +11,19 @@ public class ObjectWhere implements SQLWhere { protected final Object value; protected final String comparator; - public ObjectWhere(@Nonnull String column, @Nullable Object value, @Nonnull String comparator) { + public ObjectWhere(@NotNull String column, @Nullable Object value, @NotNull String comparator) { this.column = column; this.value = value; this.comparator = comparator; } - @Nonnull + @NotNull @Override public Object[] getArgs() { return new Object[]{value}; } - @Nonnull + @NotNull @Override public String getAsSQLString() { return String.format("`%s` %s ?", column, comparator); diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java index f1ad961e9..61cfe31e1 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/SQLWhere.java @@ -1,13 +1,13 @@ package net.codingarea.commons.database.sql.abstraction.where; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public interface SQLWhere { - @Nonnull + @NotNull Object[] getArgs(); - @Nonnull + @NotNull String getAsSQLString(); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java index efe4efe88..388c6cdaf 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/abstraction/where/StringIgnoreCaseWhere.java @@ -1,6 +1,7 @@ package net.codingarea.commons.database.sql.abstraction.where; -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; + import java.util.Objects; public class StringIgnoreCaseWhere implements SQLWhere { @@ -8,18 +9,18 @@ public class StringIgnoreCaseWhere implements SQLWhere { protected final String column; protected final String value; - public StringIgnoreCaseWhere(@Nonnull String column, @Nonnull String value) { + public StringIgnoreCaseWhere(@NotNull String column, @NotNull String value) { this.column = column; this.value = value; } - @Nonnull + @NotNull @Override public Object[] getArgs() { return new Object[]{value}; } - @Nonnull + @NotNull @Override public String getAsSQLString() { return String.format("LOWER(%s) = LOWER(?)", column); diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java index 4f4ee4c54..91ecfece6 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/MySQLDatabase.java @@ -4,8 +4,7 @@ import net.codingarea.commons.database.action.DatabaseListTables; import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; import net.codingarea.commons.database.sql.mysql.list.MySQLListTables; - -import javax.annotation.Nonnull; +import org.jetbrains.annotations.NotNull; public class MySQLDatabase extends AbstractSQLDatabase { @@ -17,17 +16,17 @@ public class MySQLDatabase extends AbstractSQLDatabase { } } - public MySQLDatabase(@Nonnull DatabaseConfig config) { + public MySQLDatabase(@NotNull DatabaseConfig config) { super(config); } - @Nonnull + @NotNull @Override protected String createUrl() { return "jdbc:mysql://" + config.getHost() + (config.isPortSet() ? ":" + config.getPort() : "") + "/" + config.getDatabase(); } - @Nonnull + @NotNull @Override public DatabaseListTables listTables() { return new MySQLListTables(this); diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java index 23a77bcc9..5647ec6f1 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/mysql/list/MySQLListTables.java @@ -3,8 +3,8 @@ import net.codingarea.commons.database.action.DatabaseListTables; import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; @@ -14,11 +14,11 @@ public class MySQLListTables implements DatabaseListTables { protected final AbstractSQLDatabase database; - public MySQLListTables(@Nonnull AbstractSQLDatabase database) { + public MySQLListTables(@NotNull AbstractSQLDatabase database) { this.database = database; } - @Nonnull + @NotNull @Override public List execute() throws DatabaseException { try { diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java index 183e8da35..34c849621 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/SQLiteDatabase.java @@ -6,8 +6,8 @@ import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; import net.codingarea.commons.database.sql.sqlite.list.SQLiteListTables; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.io.File; import java.io.IOException; @@ -23,7 +23,7 @@ public class SQLiteDatabase extends AbstractSQLDatabase { protected final File file; - public SQLiteDatabase(@Nonnull DatabaseConfig config) { + public SQLiteDatabase(@NotNull DatabaseConfig config) { super(config); file = new File(config.getFile()); } @@ -44,7 +44,7 @@ protected String createUrl() { return "jdbc:sqlite:" + file; } - @Nonnull + @NotNull @Override public DatabaseListTables listTables() { return new SQLiteListTables(this); diff --git a/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java index 1ac41caf8..2150a80b9 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java +++ b/plugin/src/main/java/net/codingarea/commons/database/sql/sqlite/list/SQLiteListTables.java @@ -3,8 +3,8 @@ import net.codingarea.commons.database.action.DatabaseListTables; import net.codingarea.commons.database.exceptions.DatabaseException; import net.codingarea.commons.database.sql.abstraction.AbstractSQLDatabase; +import org.jetbrains.annotations.NotNull; -import javax.annotation.Nonnull; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; @@ -14,11 +14,11 @@ public class SQLiteListTables implements DatabaseListTables { protected final AbstractSQLDatabase database; - public SQLiteListTables(@Nonnull AbstractSQLDatabase database) { + public SQLiteListTables(@NotNull AbstractSQLDatabase database) { this.database = database; } - @Nonnull + @NotNull @Override public List execute() throws DatabaseException { try { From 527e20869b1c2ee2ccc89765a0e40f9bf00d7f1d Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Sun, 31 May 2026 18:37:43 +0200 Subject: [PATCH 076/119] fix: remove redundant accessors Delete explicit getPlayer() and getInventory() methods from ChallengeMenuClickInfo (provided by superclass). Because this change was excluded from the previous annotation migration, the reference to Nonnull was not replaced with NotNull resulting in build failure. --- .../management/menu/info/ChallengeMenuClickInfo.java | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java index 96298fefc..419748c40 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/info/ChallengeMenuClickInfo.java @@ -28,14 +28,4 @@ public boolean isLowerItemClick() { return !upperItem; } - @Nonnull - public Player getPlayer() { - return player; - } - - @Nonnull - public Inventory getInventory() { - return inventory; - } - } From 320e7238133486c0af28dcb504d967feeaf291e0 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Sun, 31 May 2026 20:05:39 +0200 Subject: [PATCH 077/119] fix: timer menu inv list, language loader config - timer menu generator created dummy inventories as it kept adding inventories to a list while only using first two - discussion: reason for timer menu generator not using MultiPageMenuGenerator? - language loader migration function (probably) did not return correct read config doc --- .../challenges/plugin/content/loader/LanguageLoader.java | 2 +- .../menu/generator/implementation/TimerMenuGenerator.java | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index 3a0c3ddd3..2a043ed10 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -41,7 +41,7 @@ public Document getLanguageProperties() { try { FileUtils.createFilesIfNecessary(getLanguagePropertiesFile()); - FileDocument document = FileDocument.readPropertiesFile(getLanguagePropertiesFile()); + return FileDocument.readPropertiesFile(getLanguagePropertiesFile()); } catch (Exception e) { Logger.error("Could not read language properties", e); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java index 2331aaefb..832938d1f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java @@ -28,7 +28,7 @@ import java.util.ArrayList; import java.util.List; -public class TimerMenuGenerator extends MenuGenerator { +public class TimerMenuGenerator extends MenuGenerator { // TODO discussion: reason for not using MultiPageMenuGenerator public static final int SIZE = 5 * 9; public static final int[] NAVIGATION_SLOTS = {36, 44}; @@ -79,7 +79,7 @@ public void updateSecondPage() { inventory.setItem(SECOND_SLOTS[1], getTimeItem(seconds, Message.forName("second"), Message.forName("seconds"))); } - private void setTimeNavigation(@NotNull int[] slots, @NotNull Message singular, @NotNull Message plural) { + private void setTimeNavigation(int[] slots, @NotNull Message singular, @NotNull Message plural) { Inventory inventory = inventories.get(1); inventory.setItem(slots[0], getNavigationItem(true, singular, plural)); inventory.setItem(slots[2], getNavigationItem(false, singular, plural)); @@ -122,6 +122,7 @@ private void setNavigation() { @Override public void generateInventories() { + inventories.clear(); createNewInventory(0); createNewInventory(1); setNavigation(); From d34dd81ec00dde22806ce6504008f59b5e35de45 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Sun, 31 May 2026 20:06:13 +0200 Subject: [PATCH 078/119] chore: bundle extracted cloud support modules in shaded jar --- plugin/build.gradle.kts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index 4d8c10bf2..ed5e2ae27 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -38,6 +38,11 @@ tasks { dependencies { // TODO adopted from maven shade configuration, check necessity include(dependency("net.kyori:adventure-api")) + + // TODO abstract to register dynamically + include(project(":cloud-support:api")) + include(project(":cloud-support:cloudnet2")) + include(project(":cloud-support:cloudnet3")) } } From 48b250300856c96898438ee85b49aba40b39c6cf Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Sun, 31 May 2026 20:56:45 +0200 Subject: [PATCH 079/119] chore: extract cloudnet repository to unique module --- build.gradle.kts | 2 -- cloud-support/cloudnet2/build.gradle.kts | 5 +++++ cloud-support/cloudnet3/build.gradle.kts | 5 +++++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index cb6d678ae..456ce60ca 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -9,8 +9,6 @@ allprojects { maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/") maven("https://libraries.minecraft.net/") maven("https://jitpack.io") - // legacy cloudnet 3 repository, officially "https://repo.cloudnetservice.eu/repository/releases/" - maven("https://repo.cloudnetservice.eu/releases/") } } diff --git a/cloud-support/cloudnet2/build.gradle.kts b/cloud-support/cloudnet2/build.gradle.kts index 487ef394e..54b2d665c 100644 --- a/cloud-support/cloudnet2/build.gradle.kts +++ b/cloud-support/cloudnet2/build.gradle.kts @@ -8,6 +8,11 @@ dependencies { compileOnly(project(":cloud-support:api")) } +repositories { + // legacy cloudnet 3 repository, officially "https://repo.cloudnetservice.eu/repository/releases/" + maven("https://repo.cloudnetservice.eu/releases/") +} + tasks { jar { archiveClassifier = "plain" diff --git a/cloud-support/cloudnet3/build.gradle.kts b/cloud-support/cloudnet3/build.gradle.kts index 915680d7f..13f24927f 100644 --- a/cloud-support/cloudnet3/build.gradle.kts +++ b/cloud-support/cloudnet3/build.gradle.kts @@ -9,6 +9,11 @@ dependencies { compileOnly(project(":cloud-support:api")) } +repositories { + // legacy cloudnet 3 repository, officially "https://repo.cloudnetservice.eu/repository/releases/" + maven("https://repo.cloudnetservice.eu/releases/") +} + tasks { jar { archiveClassifier = "plain" From 343655d07f1f78922d78bfb860a1b7911a56fee9 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Sun, 31 May 2026 23:02:54 +0200 Subject: [PATCH 080/119] fix: hide vanilla attributes --- .../bukkit/utils/item/ItemBuilder.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java index c3196bd4a..ac089d643 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java @@ -1,11 +1,16 @@ package net.codingarea.commons.bukkit.utils.item; +import net.codingarea.commons.bukkit.core.BukkitModule; import org.bukkit.Color; import org.bukkit.DyeColor; import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeModifier; import org.bukkit.block.banner.Pattern; import org.bukkit.block.banner.PatternType; import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.EquipmentSlotGroup; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.*; @@ -163,9 +168,30 @@ public ItemBuilder removeFlag(@NotNull ItemFlag... flags) { @NotNull public ItemBuilder hideAttributes() { + applyDummyAttributeModifier(); return addFlag(ItemFlag.values()); } + @SuppressWarnings({"UnstableApiUsage"}) + protected void applyDummyAttributeModifier() { + try { + // hacky fix to make paper hide damage attributes (only works with custom modifiers), "Vanilla behavior since 1.20.5" + // see https://github.com/PaperMC/Paper/issues/11224 + Attribute dummyAttribute = Attribute.LUCK; + Collection modifiers = getMeta().getAttributeModifiers(dummyAttribute); + + if (modifiers == null || modifiers.isEmpty()) { + meta.addAttributeModifier(dummyAttribute, new AttributeModifier( + new NamespacedKey(BukkitModule.getFirstInstance(), "dummy"), + 0, + AttributeModifier.Operation.ADD_NUMBER, + EquipmentSlotGroup.ANY + )); + } + } catch (Throwable ignored) { // defend against experimental api changes + } + } + @NotNull public ItemBuilder showAttributes() { return removeFlag(ItemFlag.values()); From 6c22abe9cfad01d898937806310280772a206cbf Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Mon, 1 Jun 2026 01:59:02 +0200 Subject: [PATCH 081/119] chore: bump spigot api to latest --- gradle/libs.versions.toml | 2 +- .../commons/bukkit/utils/misc/MinecraftVersion.java | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 089a524e3..4b20c7106 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,7 +1,7 @@ [versions] # minecraft -spigot = "1.21.4-R0.1-SNAPSHOT" +spigot = "26.1.2-R0.1-SNAPSHOT" authlib = "1.5.21" # utilities diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java index cfd43bccf..f63e5093d 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java @@ -41,6 +41,15 @@ public enum MinecraftVersion implements Version { V1_21_3, // 1.21.3 V1_21_4, // 1.21.4 V1_21_5, // 1.21.5 + V1_21_6, // 1.21.6 + V1_21_7, // 1.21.7 + V1_21_8, // 1.21.8 + V1_21_9, // 1.21.9 + V1_21_10, // 1.21.10 + V1_21_11, // 1.21.11 + V26_1, // 26.1 + V26_1_1, // 26.1.1 + V26_1_2, // 26.1.2 ; private final int major, minor, revision; From 9595ede8608c6c99db54cdc1fbf51c6362b47b6e Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Mon, 1 Jun 2026 02:00:59 +0200 Subject: [PATCH 082/119] feat: particle version compatibility --- .../implementation/goal/RaceGoal.java | 11 +- .../setting/RespawnSetting.java | 2 +- .../type/abstraction/HydraChallenge.java | 2 +- .../listener/PlayerConnectionListener.java | 2 +- .../plugin/utils/misc/ParticleUtils.java | 152 +++++++++++++----- 5 files changed, 121 insertions(+), 48 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java index 0e0916922..5d26a7da9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java @@ -112,13 +112,13 @@ public void onSecond() { Location relativeGoal = goal.clone(); relativeGoal.setY(player.getLocation().getY()); relativeGoal.add(0.5, 0, 0.5); - ParticleUtils.drawLine(player, player.getLocation(), relativeGoal, MinecraftNameWrapper.REDSTONE_DUST, new DustOptions( - Color.LIME, 1), 1, 0.5, 50); + ParticleUtils.drawLine(player, player.getLocation(), relativeGoal, MinecraftNameWrapper.REDSTONE_DUST, + new DustOptions(Color.LIME, 1), 1, 0.5, 50); if (player.getWorld() != goal.getWorld()) return; if (player.getLocation().distance(relativeGoal) > 20) return; - ParticleUtils.spawnParticleCircleAroundRadius(Challenges.getInstance(), relativeGoal, - MinecraftNameWrapper.INSTANT_EFFECT, 0.75, 0.5); + ParticleUtils.spawnParticleCylinderAroundRadius(Challenges.getInstance(), relativeGoal, + MinecraftNameWrapper.INSTANT_EFFECT, Color.WHITE, 0.75, 0.5); }); } @@ -132,7 +132,8 @@ public void onMove(PlayerMoveEvent event) { if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), goal)) { Message.forName("race-goal-reached").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); - ParticleUtils.spawnParticleCircleAroundRadius(Challenges.getInstance(), event.getTo(), MinecraftNameWrapper.ENTITY_EFFECT, 0.75, 2); + ParticleUtils.spawnParticleCylinderAroundRadius(Challenges.getInstance(), event.getTo(), + MinecraftNameWrapper.ENTITY_EFFECT, null, 0.75, 2); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java index d5d80f470..53124d94c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java @@ -50,7 +50,7 @@ public void onPlayerDeath(@NotNull PlayerDeathEvent event) { checkAllPlayersDead(); } - ParticleUtils.spawnUpGoingParticleCircle(Challenges.getInstance(), player.getLocation(), + ParticleUtils.spawnParticleCylinder(Challenges.getInstance(), player.getLocation(), MinecraftNameWrapper.WITCH_EFFECT, 17, 1, 2); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java index e14799978..67a9a2da6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java @@ -36,7 +36,7 @@ public void onEntityDamageByEntity(@NotNull EntityDeathByPlayerEvent event) { for (int i = 0; i < mobsCount; i++) { event.getEntity().getWorld().spawnEntity(event.getEntity().getLocation(), event.getEntityType()); } - ParticleUtils.spawnUpGoingParticleCircle(Challenges.getInstance(), event.getEntity().getLocation(), + ParticleUtils.spawnParticleCylinder(Challenges.getInstance(), event.getEntity().getLocation(), MinecraftNameWrapper.ENTITY_EFFECT, 2, 17, 1); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index eb607a322..df133833c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -46,7 +46,7 @@ public void onJoin(@NotNull PlayerJoinEvent event) { Player player = event.getPlayer(); player.getLocation().getChunk().load(true); - ParticleUtils.spawnUpGoingParticleCircle(Challenges.getInstance(), player.getLocation(), + ParticleUtils.spawnParticleCylinder(Challenges.getInstance(), player.getLocation(), MinecraftNameWrapper.ENTITY_EFFECT, 17, 1, 2); Challenges.getInstance().getScoreboardManager().handleJoin(player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java index bc23a9fd4..2b6496a88 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java @@ -1,34 +1,36 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.collection.IRandom; import org.bukkit.*; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.util.BoundingBox; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.lang.reflect.Constructor; +import java.lang.reflect.Parameter; import java.util.Objects; import java.util.function.BiConsumer; public final class ParticleUtils { - private static final IRandom iRandom = IRandom.create(); + private static final IRandom particleRandom = IRandom.create(); + private static final double cylinderParticleVerticalStep = 0.25; private ParticleUtils() { } - private static void spawnParticleCircle(@NotNull Location location, int points, double radius, @NotNull BiConsumer player) { - World world = location.getWorld(); + private static void spawnParticleCircle(@NotNull Location center, int points, double radius, @NotNull BiConsumer playParticle) { + World world = center.getWorld(); if (world == null) return; for (int i = 0; i < points; i++) { double angle = 2 * Math.PI * i / points; - Location point = location.clone().add(radius * Math.sin(angle), 0.0d, radius * Math.cos(angle)); - player.accept(world, point); + Location point = center.clone().add(radius * Math.sin(angle), 0.0d, radius * Math.cos(angle)); + playParticle.accept(world, point); } } @@ -40,53 +42,52 @@ public static void spawnParticleCircle(@NotNull Location location, @NotNull Part spawnParticleCircle(location, points, radius, (world, point) -> world.spawnParticle(particle, point, 1)); } - private static void spawnUpGoingParticleCircle(@NotNull JavaPlugin plugin, @NotNull Location location, int points, double radius, double height, @NotNull BiConsumer player) { - for (double y = 0, i = 0; y < height; y += .25, i++) { + private static void spawnParticleCylinder(@NotNull JavaPlugin plugin, @NotNull Location location, + int points, double radius, double height, + @NotNull BiConsumer playerParticle) { + for (double y = 0, i = 0; y < height; y += cylinderParticleVerticalStep, i++) { final double Y = y; Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { - spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, player); + spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, playerParticle); }, (long) i); } } - public static void spawnUpGoingParticleCircle(@NotNull JavaPlugin plugin, @NotNull Location location, @NotNull Effect effect, int points, double radius, double height) { - spawnUpGoingParticleCircle(plugin, location, points, radius, height, (world, point) -> world.playEffect(point, effect, 1)); + public static void spawnEffectCylinder(@NotNull JavaPlugin plugin, @NotNull Location location, + @NotNull Effect effect, int points, double radius, double height) { + spawnParticleCylinder(plugin, location, points, radius, height, (world, point) -> world.playEffect(point, effect, 1)); } - public static void spawnUpGoingParticleCircle(@NotNull JavaPlugin plugin, @NotNull Location location, @NotNull Particle particle, int points, double radius, double height) { - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_20_5)) { - for (double y = 0, i = 0; y < height; y += .25, i++) { - final double Y = y; - - Color color = Color.fromRGB( - iRandom.range(0, 255), - iRandom.range(0, 255), - iRandom.range(0, 255) - ); - - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { - if (particle == Particle.ENTITY_EFFECT) { - spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, (world, loc) -> world.spawnParticle(particle, loc, 1, color)); - } else { - spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, (world, loc) -> world.spawnParticle(particle, loc, 1)); - } - }, (long) i); - } - } else { - spawnUpGoingParticleCircle(plugin, location, points, radius, height, (world, point) -> world.spawnParticle(particle, point, 1)); - } + public static void spawnParticleCylinder(@NotNull JavaPlugin plugin, @NotNull Location location, + @NotNull Particle particle, + int points, double radius, double height) { + spawnParticleCylinder(plugin, location, particle, null, points, radius, height); } - public static void spawnParticleCircleAroundEntity(@NotNull JavaPlugin plugin, @NotNull Entity entity) { - spawnParticleCircleAroundBoundingBox(plugin, entity.getLocation(), MinecraftNameWrapper.INSTANT_EFFECT, entity.getBoundingBox(), 0.25); + public static void spawnParticleCylinder(@NotNull JavaPlugin plugin, @NotNull Location location, + @NotNull Particle particle, @Nullable Color overrideColor, + int points, double radius, double height) { + for (double y = 0, i = 0; y < height; y += .25, i++) { + final double Y = y; + + Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> spawnParticleCircle( + location.clone().add(0, Y, 0), points, radius, + (world, loc) -> doSpawnParticleWithData(loc, particle, 1, overrideColor) + ), (long) i); + } } - public static void spawnParticleCircleAroundBoundingBox(@NotNull JavaPlugin plugin, @NotNull Location location, @NotNull Particle particle, @NotNull BoundingBox box, double height) { - spawnParticleCircleAroundRadius(plugin, location, particle, box.getWidthX(), height); + public static void spawnParticleCircleAroundEntity(@NotNull JavaPlugin plugin, @NotNull Entity entity) { + // pre-1.20.5 INSTANT_EFFECT did not require particle data and was white by default + spawnParticleCylinderAroundRadius( + plugin, entity.getLocation(), MinecraftNameWrapper.INSTANT_EFFECT, Color.WHITE, + entity.getBoundingBox().getWidthX(), cylinderParticleVerticalStep); } - public static void spawnParticleCircleAroundRadius(@NotNull JavaPlugin plugin, @NotNull Location location, @NotNull Particle particle, double radius, double height) { - spawnUpGoingParticleCircle(plugin, location, particle, (int) (radius * 15), radius, height); + public static void spawnParticleCylinderAroundRadius(@NotNull JavaPlugin plugin, @NotNull Location location, + @NotNull Particle particle, @Nullable Color overrideColor, + double radius, double height) { + spawnParticleCylinder(plugin, location, particle, overrideColor, (int) (radius * 15), radius, height); } public static void drawLine(@NotNull Player player, @NotNull Location point1, @NotNull Location point2, @NotNull Particle particle, @Nullable Particle.DustOptions dustOptions, int count, double space, int max) { @@ -108,4 +109,75 @@ public static void drawLine(@NotNull Player player, @NotNull Location point1, @N } + /** + * ONLY SUPPORTS SELECTED PARTICLE TYPES NATIVELY. + * Adds version specific compatability as api implementation has changed by adding requirements for particle data + * types like colors etc., by adding them on the fly. + * As particle type names have also changed, use wrapped types for compatability. + * + * @param location location to spawn particle at (uses referenced world instance) + * @param particle particle type to spawn, note changed names and reference via name wrappers for compatability + * @param count particle count passed in bukkit call + * @param overrideColor some particles require a color, fallback to random color if null is passed + * and required by particle data type + * @see MinecraftNameWrapper + */ + public static void doSpawnParticleWithData(@NotNull Location location, @NotNull Particle particle, int count, @Nullable Color overrideColor) { + World world = location.getWorld(); + if (world == null) return; + + // Particle#getDataType was added in 1.9 so it should be safe to use + if (particle.getDataType() == Void.class) { // no data required + world.spawnParticle(particle, location, count); + return; + } + // ENTITY_EFFECT required no data type prior to 1.20.5 (now Color) + // INSTANT_EFFECT/SPELL_INSTANT required no data type prior to 1.20.5 (now Particle.Spell) + + Object data = null; + if (particle.getDataType() == Color.class) { // org.bukkit.Color not java.awt + data = (overrideColor != null) ? overrideColor : newRandomColor(); + } + // no native impl for Particle.Spell for compatibility reasons as it has been added for 1.20.5+ and marked as experimental + // (maybe impl in future by catching accessor errors) + + if (data != null) { + world.spawnParticle(particle, location, count, data); + return; + } + + try { + // fallback, slow reflection + Constructor constructor = particle.getDataType().getConstructors()[0]; + Parameter[] parameters = constructor.getParameters(); + Object[] dataParameters = new Object[parameters.length]; + for (int i = 0; i < parameters.length; i++) { + Class type = parameters[i].getType(); + if (type == int.class) { + dataParameters[i] = 1; // fallback (commonly "size") + } else if (type == float.class) { + dataParameters[i] = 1.0; // fallback (commonly "power") + } else if (type == Color.class) { + dataParameters[i] = (overrideColor != null) ? overrideColor : newRandomColor(); + } else { + // special parameter type not implemented for fallback here, can't provide data + return; + } + } + + data = constructor.newInstance(dataParameters); + world.spawnParticle(particle, location, count, data); + } catch (Throwable ex) { // compatability issues, also catch Error instances + Logger.warn("Unable to create particle {} with data type {}", particle, particle.getDataType(), ex); + } + } + + public static Color newRandomColor() { + return Color.fromRGB( + particleRandom.range(0, 255), + particleRandom.range(0, 255), + particleRandom.range(0, 255) + ); + } + } From 1ff27a3819247dcdcbce472c9c7ef272b8087129 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Mon, 1 Jun 2026 02:04:22 +0200 Subject: [PATCH 083/119] refactor: initial pass on gamerule compatibility, base64 lib - gamerules were renamed, adding compatibility via wrapper types - snake yaml lib removed, use built in java base64 lib for backpack en/decoding --- .../setting/ImmediateRespawnSetting.java | 6 +++--- .../setting/SplitHealthSetting.java | 11 ++++++++++- .../scheduler/timer/ChallengeTimer.java | 4 +++- .../plugin/management/server/WorldManager.java | 3 +-- .../bukkit/container/BukkitSerialization.java | 15 ++++++++++----- .../plugin/utils/misc/MinecraftNameWrapper.java | 9 +++++++++ 6 files changed, 36 insertions(+), 12 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java index 217f6362b..1c1c6e272 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java @@ -4,9 +4,9 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; -import org.bukkit.GameRule; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.event.EventHandler; @@ -36,7 +36,7 @@ protected void onEnable() { } try { for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.DO_IMMEDIATE_RESPAWN, true); + world.setGameRule(MinecraftNameWrapper.IMMEDIATE_RESPAWN, true); } } catch (NoSuchFieldError ignored) { respawnWithEvent = true; @@ -50,7 +50,7 @@ protected void onDisable() { } try { for (World world : Bukkit.getWorlds()) { - world.setGameRule(GameRule.DO_IMMEDIATE_RESPAWN, false); + world.setGameRule(MinecraftNameWrapper.IMMEDIATE_RESPAWN, false); } } catch (NoSuchFieldError ignored) { } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index 2ffd61e64..90a7771ea 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -94,7 +94,7 @@ public void setHealth(@NotNull Player player, @Nullable EntityDamageEvent damage } if (health <= 0 && damageEvent != null) { - currentPlayer.setLastDamageCause(damageEvent); + tryApplyLastDamageCause(currentPlayer, damageEvent); } currentPlayer.setHealth(health); @@ -102,4 +102,13 @@ public void setHealth(@NotNull Player player, @Nullable EntityDamageEvent damage } + @SuppressWarnings({"deprecation", "removal"}) + private void tryApplyLastDamageCause(Player player, EntityDamageEvent damageEvent) { + // marked for removal in api version 1.20.4 with no apparent replacement? + try { + player.setLastDamageCause(damageEvent); + } catch (Throwable ignored) { + } + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java index 2b7de378f..eae28ddf6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java @@ -14,6 +14,7 @@ import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.FileDocument; @@ -62,7 +63,8 @@ public void enable() { private void updateTimeRule() { for (World world : ChallengeAPI.getGameWorlds()) { - world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, !paused); + // overhaul post-1.21: DO_DAYLIGHT_CYCLE -> ADVANCE_TIME + world.setGameRule(MinecraftNameWrapper.DAYLIGHT_CYCLE, !paused); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java index 6daef66c3..4ffaf2982 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java @@ -154,8 +154,7 @@ private void loadExtraWorld() { disableGameRuleInFlatWorld("doDaylightCycle"); disableGameRuleInFlatWorld("disableRaids"); disableGameRuleInFlatWorld("mobGriefing"); - - } catch (Exception ex) { + } catch (Throwable ex) { Logger.error("Could not load extra world!", ex); Logger.error("Probably the server version or server system was changed and the old world is not compatible with it"); Logger.error("Please delete all worlds and try again!"); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java index 3de673ac2..d834629d8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/container/BukkitSerialization.java @@ -5,11 +5,11 @@ import org.bukkit.inventory.PlayerInventory; import org.bukkit.util.io.BukkitObjectInputStream; import org.bukkit.util.io.BukkitObjectOutputStream; -import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.util.Base64; public class BukkitSerialization { @@ -52,7 +52,9 @@ public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalSta // Serialize that array dataOutput.close(); - return Base64Coder.encodeLines(outputStream.toByteArray()); + + // org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder.encodeLines removed in 26.1 + return Base64.getEncoder().encodeToString(outputStream.toByteArray()); } catch (Exception e) { throw new IllegalStateException("Unable to save item stacks.", e); } @@ -83,7 +85,8 @@ public static String toBase64(Inventory inventory) throws IllegalStateException // Serialize that array dataOutput.close(); - return Base64Coder.encodeLines(outputStream.toByteArray()); + // org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder.encodeLines removed in 26.1 + return Base64.getEncoder().encodeToString(outputStream.toByteArray()); } catch (Exception e) { throw new IllegalStateException("Unable to save item stacks.", e); } @@ -104,7 +107,8 @@ public static String toBase64(Inventory inventory) throws IllegalStateException */ public static Inventory fromBase64(Inventory inventory, String data) throws IOException { try { - ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); + // org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder.decodeLines(data) removed in 26.1 + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data)); BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); // Read the serialized inventory @@ -131,7 +135,8 @@ public static Inventory fromBase64(Inventory inventory, String data) throws IOEx */ public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException { try { - ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); + // org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder.decodeLines(data) removed in 26.1 + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data)); BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); ItemStack[] items = new ItemStack[dataInput.readInt()]; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java index d12660961..d0aac4f35 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; import net.codingarea.commons.common.misc.ReflectionUtils; +import org.bukkit.GameRule; import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.enchantments.Enchantment; @@ -34,6 +35,9 @@ public class MinecraftNameWrapper { public static final Enchantment UNBREAKING = getEnchantByNames("DURABILITY", "UNBREAKING"); + public static final GameRule DAYLIGHT_CYCLE = getGameRuleByNames("DO_DAYLIGHT_CYCLE", "ADVANCE_TIME"); + public static final GameRule IMMEDIATE_RESPAWN = getGameRuleByNames("DO_IMMEDIATE_RESPAWN", "IMMEDIATE_RESPAWN"); + private MinecraftNameWrapper() { } @@ -62,6 +66,11 @@ private static Enchantment getEnchantByNames(@NotNull String... names) { return getFirstAttributeByNames(Enchantment.class, names); } + @NotNull + private static GameRule getGameRuleByNames(@NotNull String... names) { + return getFirstAttributeByNames(GameRule.class, names); + } + @SuppressWarnings("unchecked") @NotNull public static T getFirstAttributeByNames(@NotNull Class clazz, @NotNull String... names) { From 6c1cbea784e7f2a4e8d2d1949ab50c2ec0725e5b Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Mon, 1 Jun 2026 23:32:48 +0200 Subject: [PATCH 084/119] chore: apply local plugin build extension --- .gitignore | 1 + plugin/build.gradle.kts | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/.gitignore b/.gitignore index a4b9a33a4..4a4b80210 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ .idea/ *.iml **/dependency-reduced-pom.xml +**/local.gradle.kts # Test Sources **/src/test diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index ed5e2ae27..3d8eb8216 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -50,3 +50,8 @@ tasks { dependsOn(shadowJar) } } + +val localBuild = file("local.gradle.kts") +if (localBuild.exists()) { + apply(from = localBuild) +} From 38daac78da6892457b7de0e8812b0f6bce41050b Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Mon, 1 Jun 2026 23:55:57 +0200 Subject: [PATCH 085/119] fix: particle data compatibility --- .../challenge/extraworld/JumpAndRunChallenge.java | 7 ++----- .../plugin/utils/misc/ParticleUtils.java | 14 ++++++++------ 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java index 13a71d792..25095defa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java @@ -20,10 +20,7 @@ import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; +import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -208,7 +205,7 @@ public void loadGameState(@NotNull Document document) { public void spawnParticles() { if (targetBlock == null) return; ParticleUtils.spawnParticleCircle(targetBlock.getLocation().add(0.5, 1.05, 0.5), - MinecraftNameWrapper.INSTANT_EFFECT, 13, 0.35); + MinecraftNameWrapper.INSTANT_EFFECT, Color.WHITE, 13, 0.35); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java index 2b6496a88..1f2c539f2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java @@ -34,21 +34,21 @@ private static void spawnParticleCircle(@NotNull Location center, int points, do } } - public static void spawnParticleCircle(@NotNull Location location, @NotNull Effect particle, int points, double radius) { + public static void spawnEffectCircle(@NotNull Location location, @NotNull Effect particle, int points, double radius) { spawnParticleCircle(location, points, radius, (world, point) -> world.playEffect(point, particle, 1)); } - public static void spawnParticleCircle(@NotNull Location location, @NotNull Particle particle, int points, double radius) { - spawnParticleCircle(location, points, radius, (world, point) -> world.spawnParticle(particle, point, 1)); + public static void spawnParticleCircle(@NotNull Location location, @NotNull Particle particle, @Nullable Color overrideColor, int points, double radius) { + spawnParticleCircle(location, points, radius, (world, loc) -> doSpawnParticleWithData(loc, particle, 1, overrideColor)); } private static void spawnParticleCylinder(@NotNull JavaPlugin plugin, @NotNull Location location, int points, double radius, double height, - @NotNull BiConsumer playerParticle) { + @NotNull BiConsumer playParticle) { for (double y = 0, i = 0; y < height; y += cylinderParticleVerticalStep, i++) { final double Y = y; Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> { - spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, playerParticle); + spawnParticleCircle(location.clone().add(0, Y, 0), points, radius, playParticle); }, (long) i); } } @@ -156,7 +156,9 @@ public static void doSpawnParticleWithData(@NotNull Location location, @NotNull if (type == int.class) { dataParameters[i] = 1; // fallback (commonly "size") } else if (type == float.class) { - dataParameters[i] = 1.0; // fallback (commonly "power") + dataParameters[i] = 1.0f; // fallback (commonly "power") + } else if (type == double.class) { + dataParameters[i] = 1.0d; } else if (type == Color.class) { dataParameters[i] = (overrideColor != null) ? overrideColor : newRandomColor(); } else { From 9a96ae91be97af8295984ac20f0657250b6a24c1 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Tue, 2 Jun 2026 00:14:02 +0200 Subject: [PATCH 086/119] feat: compatibility for worlds, attributes, gamerules - minecraft made structural changes to their world system, the reset system/world manager had to be refactored - world reset now injects the new random/custom seed on startup into nms holder, as the new system has already read the level seed and would generate it again - alternatively we could switch to a "oscillating" approach where we would just generate a new world and use it as the default level - missing change: world names should now only include the level name without dimension suffix (version dependent!) - old attributes wrapper resulted in errors due to version incompatibility, replaced it as well as gamerules wrapper (special case raid gamerule!) --- .../action/impl/HealEntityAction.java | 3 +- .../challenge/ZeroHeartsChallenge.java | 6 +- .../challenge/quiz/QuizChallenge.java | 6 +- .../randomizer/RandomizedHPChallenge.java | 8 +- .../challenge/world/LoopChallenge.java | 4 +- .../goal/GetFullHealthGoal.java | 6 +- .../setting/MaxHealthSetting.java | 4 +- .../implementation/setting/OldPvPSetting.java | 4 +- .../setting/SplitHealthSetting.java | 4 +- .../management/server/GameWorldStorage.java | 3 +- .../management/server/WorldManager.java | 229 +++++++++--------- .../plugin/spigot/command/HealCommand.java | 4 +- .../utils/misc/MinecraftNameWrapper.java | 52 +++- .../bukkit/utils/misc/CompatibilityUtils.java | 3 - .../utils/wrapper/AttributeWrapper.java | 3 +- .../commons/common/misc/FileUtils.java | 2 +- 16 files changed, 186 insertions(+), 155 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java index d41647df9..597faf167 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java @@ -5,7 +5,6 @@ import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Entity; @@ -31,7 +30,7 @@ public void executeFor(Entity entity, Map subActions) { int amount = Integer.parseInt(subActions.get("amount")[0]); if (entity instanceof LivingEntity) { LivingEntity livingEntity = (LivingEntity) entity; - AttributeInstance attribute = livingEntity.getAttribute(AttributeWrapper.MAX_HEALTH); + AttributeInstance attribute = livingEntity.getAttribute(MinecraftNameWrapper.MAX_HEALTH); if (attribute == null) return; double newHealth = Math.min(livingEntity.getHealth() + amount, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index 96288f85f..dfc4fc60a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -8,8 +8,8 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -42,7 +42,7 @@ protected void onEnable() { }); bossbar.show(); Bukkit.getOnlinePlayers().forEach(player -> { - AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + AttributeInstance attribute = player.getAttribute(MinecraftNameWrapper.MAX_HEALTH); if (attribute == null) return; attribute.setBaseValue(0); }); @@ -68,7 +68,7 @@ protected void onValueChange() { @ScheduledTask(ticks = 20, async = false) public void onSecond() { broadcast(player -> { - AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + AttributeInstance attribute = player.getAttribute(MinecraftNameWrapper.MAX_HEALTH); if (attribute == null) return; attribute.setBaseValue(0); }); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index b4387bd8c..995ad121c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -12,11 +12,12 @@ import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.TriFunction; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; +import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.misc.StringUtils; @@ -44,6 +45,7 @@ import java.util.Map.Entry; import java.util.stream.Collectors; +@Since("2.4") public class QuizChallenge extends TimedChallenge implements PlayerCommand, TabCompleter { private static QuizChallenge instance; @@ -166,7 +168,7 @@ private void cancelQuestion() { SoundSample.BREAK.play(currentQuestionedPlayer); currentQuestion = null; - AttributeInstance attribute = currentQuestionedPlayer.getAttribute(AttributeWrapper.MAX_HEALTH); + AttributeInstance attribute = currentQuestionedPlayer.getAttribute(MinecraftNameWrapper.MAX_HEALTH); if (attribute == null) return; if (attribute.getBaseValue() == 2) { kill(currentQuestionedPlayer); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java index 17365b36f..12d08f908 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java @@ -8,7 +8,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; @@ -71,7 +71,7 @@ private void randomizeEntityHealth(@NotNull LivingEntity entity) { } int health = random.nextInt(getValue() * 100) + 1; entity.setHealth(health); - AttributeInstance attribute = entity.getAttribute(AttributeWrapper.MAX_HEALTH); + AttributeInstance attribute = entity.getAttribute(MinecraftNameWrapper.MAX_HEALTH); if (attribute == null) return; attribute.setBaseValue(health); } @@ -93,7 +93,7 @@ private void resetExistingEntityHealth() { double health = entityDefaultHealth.getOrDefault(type, getDefaultHealth(type)); entityDefaultHealth.put(type, health); - AttributeInstance attribute = entity.getAttribute(AttributeWrapper.MAX_HEALTH); + AttributeInstance attribute = entity.getAttribute(MinecraftNameWrapper.MAX_HEALTH); if (attribute == null) return; attribute.setBaseValue(health); entity.setHealth(health); @@ -106,7 +106,7 @@ private double getDefaultHealth(@NotNull EntityType entityType) { Entity entity = world.spawnEntity(new Location(world, 0, 0, 0), entityType); entity.remove(); if (!(entity instanceof LivingEntity)) return 0; - AttributeInstance attribute = ((LivingEntity) entity).getAttribute(AttributeWrapper.MAX_HEALTH); + AttributeInstance attribute = ((LivingEntity) entity).getAttribute(MinecraftNameWrapper.MAX_HEALTH); if (attribute == null) return 10; return attribute.getBaseValue(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index 0d983dcfb..435f78c6a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -12,9 +12,9 @@ import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.commons.common.annotations.Since; import org.bukkit.Location; import org.bukkit.Material; @@ -315,7 +315,7 @@ private boolean decreaseDurability() { private boolean isTool(@NotNull ItemStack itemStack) { if (itemStack.getItemMeta() != null) { try { - Attribute attribute = AttributeWrapper.MAX_HEALTH; + Attribute attribute = MinecraftNameWrapper.MAX_HEALTH; Collection attributeModifiers = itemStack.getItemMeta().getAttributeModifiers(attribute); return attributeModifiers == null || !attributeModifiers.isEmpty(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index 5513fd239..ea9bae95e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -8,7 +8,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -48,7 +48,7 @@ protected void onValueChange() { public void getWinnersOnEnd(@NotNull List winners) { for (Player player : Bukkit.getOnlinePlayers()) { if (ignorePlayer(player)) continue; - AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + AttributeInstance attribute = player.getAttribute(MinecraftNameWrapper.MAX_HEALTH); if (attribute != null) { if (player.getHealth() >= attribute.getBaseValue()) { winners.add(player); @@ -80,7 +80,7 @@ public void onHealthChange(EntityRegainHealthEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer((Player) event.getEntity())) return; Bukkit.getScheduler().runTask(plugin, () -> { - AttributeInstance attribute = ((Player) event.getEntity()).getAttribute(AttributeWrapper.MAX_HEALTH); + AttributeInstance attribute = ((Player) event.getEntity()).getAttribute(MinecraftNameWrapper.MAX_HEALTH); if (attribute != null && ((Player) event.getEntity()).getHealth() >= attribute.getBaseValue()) { ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index 4d36cc1ce..8058e04a3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -6,8 +6,8 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; import net.codingarea.commons.bukkit.utils.wrapper.MaterialWrapper; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.document.GsonDocument; @@ -72,7 +72,7 @@ public void onJoin(@NotNull PlayerJoinEvent event) { } private void updateHealth(Player player) { - AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + AttributeInstance attribute = player.getAttribute(MinecraftNameWrapper.MAX_HEALTH); if (attribute == null) return; // This should never happen because its a generic attribute, but just in case int newMaxHealth = getMaxHealth(player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java index 659f71666..94dc303db 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; @@ -67,7 +67,7 @@ public void onSweepDamage(@NotNull EntityDamageEvent event) { } protected void setAttackSpeed(@NotNull Player player, double value) { - AttributeInstance attribute = player.getAttribute(AttributeWrapper.ATTACK_SPEED); + AttributeInstance attribute = player.getAttribute(MinecraftNameWrapper.ATTACK_SPEED); if (attribute == null) return; attribute.setBaseValue(value); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index 90a7771ea..38b2ad2bb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -6,7 +6,7 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Material; @@ -87,7 +87,7 @@ public void setHealth(@NotNull Player player, @Nullable EntityDamageEvent damage if (currentPlayer.equals(player)) continue; double health = player.getHealth(); - AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + AttributeInstance attribute = player.getAttribute(MinecraftNameWrapper.MAX_HEALTH); if (attribute == null) return; if (health > attribute.getValue()) { health = attribute.getValue(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java index d4d18da94..8a92326ee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/GameWorldStorage.java @@ -81,8 +81,7 @@ public World getOrCreateVoidWorld() { } VoidMapGenerator generator = new VoidMapGenerator(); - voidWorld = new WorldCreator("void").type(WorldType.FLAT).generator( - generator).createWorld(); + voidWorld = new WorldCreator("void").type(WorldType.FLAT).generator(generator).createWorld(); worlds.add(voidWorld); return voidWorld; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java index 4ffaf2982..672b56eec 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java @@ -6,8 +6,12 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.bukkit.container.PlayerData; +import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.logging.Logger; +import net.codingarea.commons.common.collection.IRandom; +import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.FileDocument; import net.codingarea.commons.common.misc.FileUtils; @@ -19,17 +23,12 @@ import org.jetbrains.annotations.Nullable; import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.*; public final class WorldManager { - private static final String customSeedWorldPrefix = "pregenerated_"; private final boolean restartOnReset; @Getter private final boolean enableFreshReset; @@ -58,7 +57,7 @@ public WorldManager() { levelName = sessionConfig.getString("level-name", "world"); worlds = new String[]{ levelName, - levelName + "_nether", + levelName + "_nether", // TODO levelName + "_the_end" }; } @@ -91,53 +90,27 @@ public void prepareWorldReset(@Nullable CommandSender requestedBy, @Nullable Lon String kickMessage = Message.forName("server-reset").asString(requester); Bukkit.getOnlinePlayers().forEach(player -> player.kickPlayer(kickMessage)); - if (seed != null) { - generateCustomSeedWorlds(seed); - } - Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), this::stopServerNow, 3); - - } - - private void generateCustomSeedWorlds(long seed) { - - Logger.debug("Generating custom seed worlds with seed " + seed); - for (String name : worlds) { - - World world = Bukkit.getWorld(name); - if (world == null) { - Logger.error("Could not find world {}", name); - continue; - } - - String newWorldName = customSeedWorldPrefix + name; - File folder = new File(Bukkit.getWorldContainer(), newWorldName); - if (folder.exists()) FileUtils.deleteWorldFolder(folder); - - WorldCreator creator = new WorldCreator(newWorldName).seed(seed).environment(world.getEnvironment()); - creator.createWorld(); - - Logger.debug("Created custom seed world {}", newWorldName); - - } - } private void resetConfigs() { - FileDocument sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); sessionConfig.clear(); sessionConfig.set("reset", true); - sessionConfig.set("seed-reset", useCustomSeed); + sessionConfig.set("provided-custom-seed", useCustomSeed); + if (useCustomSeed) { + sessionConfig.set("custom-seed", customSeed); + } + if (!Bukkit.getWorlds().isEmpty()) { sessionConfig.set("level-name", ChallengeAPI.getGameWorld(Environment.NORMAL).getName()); + sessionConfig.set("old-seed", ChallengeAPI.getGameWorld(Environment.NORMAL).getSeed()); } sessionConfig.save(); FileDocument gamestateConfig = Challenges.getInstance().getConfigManager().getGamestateConfig(); gamestateConfig.clear(); gamestateConfig.save(); - } private void loadExtraWorld() { @@ -148,12 +121,9 @@ private void loadExtraWorld() { flatWorld = new WorldCreator("challenges-extra").type(WorldType.FLAT).generateStructures(false).createWorld(); if (flatWorld == null) return; flatWorld.setSpawnFlags(false, false); - disableGameRuleInFlatWorld("doMobSpawning"); - disableGameRuleInFlatWorld("doTraderSpawning"); - disableGameRuleInFlatWorld("doWeatherCycle"); - disableGameRuleInFlatWorld("doDaylightCycle"); - disableGameRuleInFlatWorld("disableRaids"); - disableGameRuleInFlatWorld("mobGriefing"); + applyGameRuleInFlatWorld(MinecraftNameWrapper.getDisableRaidsGameRulePair()); + disableGameRulesInFlatWorld(MinecraftNameWrapper.MOB_SPAWNING, MinecraftNameWrapper.WANDERING_TRADERS, + MinecraftNameWrapper.WEATHER_CYCLE, MinecraftNameWrapper.DAYLIGHT_CYCLE, GameRule.MOB_GRIEFING); } catch (Throwable ex) { Logger.error("Could not load extra world!", ex); Logger.error("Probably the server version or server system was changed and the old world is not compatible with it"); @@ -181,11 +151,15 @@ private void teleportPlayersOutOfExtraWorld() { } } - @SuppressWarnings("unchecked") - private void disableGameRuleInFlatWorld(@NotNull String name) { - GameRule gamerule = (GameRule) GameRule.getByName(name); - if (gamerule == null) return; - flatWorld.setGameRule(gamerule, false); + private void applyGameRuleInFlatWorld(Tuple, Boolean> gameRulePair) { + flatWorld.setGameRule(gameRulePair.getFirst(), gameRulePair.getSecond()); + } + + @SafeVarargs + private void disableGameRulesInFlatWorld(@NotNull GameRule... gameRules) { + for (GameRule gameRule : gameRules) { + flatWorld.setGameRule(gameRule, false); + } } private void executeWorldResetIfNecessary() { @@ -194,18 +168,23 @@ private void executeWorldResetIfNecessary() { } public void executeWorldReset() { - FileDocument sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); - boolean seedReset = sessionConfig.getBoolean("seed-reset"); - Logger.info("Deleting worlds.."); for (String world : worlds) { deleteWorld(world); - if (seedReset) { - copyPreGeneratedWorld(world); - } else { - deletePreGeneratedWorld(world); - } + } + + FileDocument sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); + boolean providedCustomSeed = sessionConfig.getBoolean("provided-custom-seed"); + long customSeed = sessionConfig.getLong("custom-seed"); + + if (sessionConfig.contains("old-seed")) { + long oldSeed = sessionConfig.getLong("old-seed"); + long newSeed = providedCustomSeed ? customSeed : this.useCustomSeed ? this.customSeed : IRandom.secure().nextLong(); + injectSeedViaReflection(String.valueOf(oldSeed), String.valueOf(newSeed)); + } else { + // this should never happen, probably old or corrupt session.json + Logger.warn("Could not find old level-seed session config for replacement!"); } for (String world : Challenges.getInstance().getGameWorldStorage().getCustomGeneratedGameWorlds()) { @@ -213,71 +192,93 @@ public void executeWorldReset() { } sessionConfig.set("reset", false); - sessionConfig.set("seed-reset", false); + sessionConfig.set("provided-custom-seed", false); sessionConfig.save(); - } - private void deleteWorld(@NotNull String name) { - File folder = new File(Bukkit.getWorldContainer(), name); - FileUtils.deleteWorldFolder(folder); - Logger.info("Deleted world {}", name); - } - - private void copyPreGeneratedWorld(@NotNull String name) { - File source = new File(Bukkit.getWorldContainer(), customSeedWorldPrefix + name); - if (!source.exists() || !source.isDirectory()) { - Logger.warn("Custom seed world '{}' does not exist!", name); - return; - } - - File target = new File(Bukkit.getWorldContainer(), name); + private void injectSeedViaReflection(String oldSeed, String newSeed) { + // before the world structure overhaul it was enough to just delete world data to trigger a regeneration + // with a new random seed. but after the overhaul the seed seemed to be already be read when onLoad injection + // takes place, therefore requiring the seed to be replaced in memory when sticking to world deletion on startup + // for easy plug-and-play. this also removes the need to pre-generate custom seed levels as the seed gets replaced. try { - copy(source, target); - Logger.debug("Copied pre generated custom seed world {}", name); - } catch (IOException ex) { - Logger.error("Unable to copy pre generated custom seed world {}", name, ex); - } - } - - private void deletePreGeneratedWorld(@NotNull String name) { - File source = new File(Bukkit.getWorldContainer(), customSeedWorldPrefix + name); - if (!source.exists() || !source.isDirectory()) return; - - FileUtils.deleteWorldFolder(source); - Logger.debug("Deleted pre generated custom seed world {}", name); - } - - public void copy(@NotNull File source, @NotNull File target) throws IOException { - if (source.isDirectory()) { - copyDirectory(source, target); - } else { - copyFile(source, target); + Object craftServer = Bukkit.getServer(); + Object dedicatedServer = ReflectionUtil.invokeMethod(craftServer, "getServer"); + if (dedicatedServer != null) { + injectSeedInto(dedicatedServer, oldSeed, newSeed, 6, new HashSet<>()); + } + } catch (Exception ex) { + Logger.warn("Failed to inject seed via reflection", ex); } } - private void copyDirectory(@NotNull File source, @NotNull File target) throws IOException { - if (!target.exists()) { - if (!target.mkdir()) { - return; + private void injectSeedInto(Object obj, String oldSeed, String newSeed, int depth, Set visited) { + if (obj == null || depth == 0) return; + if (!visited.add(System.identityHashCode(obj))) return; + // defend preemptively against obfuscation and impl changes: replace fields containing old seed with new one + // alternative: replacing correct field directly via reflection would be riskier and less future-proof + Class clazz = obj.getClass(); + while (clazz != null && clazz != Object.class) { + for (Field field : clazz.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers())) continue; + try { + field.setAccessible(true); + Object value = field.get(obj); + if (value == null) continue; + + if (value instanceof String) { + if (oldSeed.equals(value)) { + field.set(obj, newSeed); + Logger.debug("Injected string seed in " + clazz.getSimpleName() + "." + field.getName()); + } + } else if (field.getType() == long.class) { + try { + long oldL = Long.parseLong(oldSeed); + long newL = Long.parseLong(newSeed); + if ((long) value == oldL) { + field.setLong(obj, newL); + Logger.debug("Injected long seed in " + clazz.getSimpleName() + "." + field.getName()); + } + } catch (NumberFormatException ignored) { + } + } else if (value instanceof OptionalLong) { + try { + long oldL = Long.parseLong(oldSeed); + long newL = Long.parseLong(newSeed); + OptionalLong opt = (OptionalLong) value; + if (opt.isPresent() && opt.getAsLong() == oldL) { + field.set(obj, OptionalLong.of(newL)); + Logger.debug("Injected OptionalLong seed in " + clazz.getSimpleName() + "." + field.getName()); + } + } catch (NumberFormatException ignored) { + } + } else if (value instanceof Properties) { + Properties p = (Properties) value; + if (oldSeed.equals(p.getProperty("level-seed"))) { + p.setProperty("level-seed", newSeed); + Logger.debug("Injected seed in java.util.Properties"); + } + } else { + String name = value.getClass().getName(); + if (name.startsWith("net.minecraft") || name.startsWith("org.bukkit") || name.startsWith("com.destroystokyo")) { + injectSeedInto(value, oldSeed, newSeed, depth - 1, visited); + } else if (value instanceof Iterable) { + for (Object item : (Iterable) value) { + injectSeedInto(item, oldSeed, newSeed, depth - 1, visited); + } + } + } + } catch (Exception ignored) { + } } - } - - String[] list = source.list(); - if (list == null) return; - for (String child : list) { - if ("session.lock".equals(child)) continue; - copy(new File(source, child), new File(target, child)); + clazz = clazz.getSuperclass(); } } - private void copyFile(@NotNull File source, @NotNull File target) throws IOException { - try (InputStream in = Files.newInputStream(source.toPath()); OutputStream out = Files.newOutputStream(target.toPath())) { - byte[] buf = new byte[1024]; - int length; - while ((length = in.read(buf)) > 0) - out.write(buf, 0, length); - } + private void deleteWorld(@NotNull String name) { + File folder = new File(Bukkit.getWorldContainer(), name); + FileUtils.deleteWorldFolder(folder); + Logger.info("Deleted world {} (at: {}, world container: {})", name, folder, Bukkit.getWorldContainer()); } private void stopServerNow() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java index 381c8ef37..f6ce46c5d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java @@ -5,7 +5,7 @@ import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; -import net.codingarea.commons.bukkit.utils.wrapper.AttributeWrapper; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.attribute.AttributeInstance; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -37,7 +37,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { boolean otherPlayers = false; for (Player player : targets) { Message.forName("command-heal-healed").send(player, Prefix.CHALLENGES); - AttributeInstance attribute = player.getAttribute(AttributeWrapper.MAX_HEALTH); + AttributeInstance attribute = player.getAttribute(MinecraftNameWrapper.MAX_HEALTH); if (attribute == null) { player.setHealth(20); } else { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java index d0aac4f35..edcc58249 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java @@ -1,10 +1,12 @@ package net.codingarea.challenges.plugin.utils.misc; import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; +import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.commons.common.misc.ReflectionUtils; import org.bukkit.GameRule; import org.bukkit.Material; import org.bukkit.Particle; +import org.bukkit.attribute.Attribute; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.EntityType; import org.bukkit.potion.PotionEffectType; @@ -15,10 +17,10 @@ public class MinecraftNameWrapper { - public static final Material GREEN_DYE = getItemByNames("CACTUS_GREEN", "GREEN_DYE"); - public static final Material RED_DYE = getItemByNames("ROSE_RED", "RED_DYE"); - public static final Material YELLOW_DYE = getItemByNames("DANDELION_YELLOW", "YELLOW_DYE"); - public static final Material SIGN = getItemByNames("SIGN", "OAK_SIGN"); + public static final Material GREEN_DYE = getMaterialByNames("CACTUS_GREEN", "GREEN_DYE"); + public static final Material RED_DYE = getMaterialByNames("ROSE_RED", "RED_DYE"); + public static final Material YELLOW_DYE = getMaterialByNames("DANDELION_YELLOW", "YELLOW_DYE"); + public static final Material SIGN = getMaterialByNames("SIGN", "OAK_SIGN"); public static final EntityType FIREWORK = getEntityByNames("FIREWORK", "FIREWORK_ROCKET"); public static final EntityType SNOW_GOLEM = getEntityByNames("SNOWMAN", "SNOW_GOLEM"); @@ -35,14 +37,31 @@ public class MinecraftNameWrapper { public static final Enchantment UNBREAKING = getEnchantByNames("DURABILITY", "UNBREAKING"); + public static final Attribute MAX_HEALTH = getAttributeByNames("GENERIC_MAX_HEALTH", "MAX_HEALTH"); + public static final Attribute ATTACK_SPEED = getAttributeByNames("GENERIC_ATTACK_SPEED", "ATTACK_SPEED"); + + // replacement for wrapping via GameRule.getByName (marked for removal as of 1.21.11), + // access via namespace key would be a viable alternative public static final GameRule DAYLIGHT_CYCLE = getGameRuleByNames("DO_DAYLIGHT_CYCLE", "ADVANCE_TIME"); + public static final GameRule WEATHER_CYCLE = getGameRuleByNames("DO_WEATHER_CYCLE", "ADVANCE_WEATHER"); public static final GameRule IMMEDIATE_RESPAWN = getGameRuleByNames("DO_IMMEDIATE_RESPAWN", "IMMEDIATE_RESPAWN"); + public static final GameRule MOB_SPAWNING = getGameRuleByNames("DO_MOB_SPAWNING", "SPAWN_MOBS"); + public static final GameRule WANDERING_TRADERS = getGameRuleByNames("DO_TRADER_SPAWNING", "SPAWN_WANDERING_TRADERS"); + + // the game rule for toggling raids has been inverted from "disableRaids" to "raids" in the 1.21->26.1 update + public static final GameRule DISABLE_RAIDS = getFirstConstantByNamesOrNull(GameRule.class, "DISABLE_RAIDS"); + public static final GameRule ENABLE_RAIDS = getFirstConstantByNamesOrNull(GameRule.class, "RAIDS"); + + @NotNull + public static Tuple, Boolean> getDisableRaidsGameRulePair() { + return DISABLE_RAIDS != null ? Tuple.of(DISABLE_RAIDS, true) : Tuple.of(ENABLE_RAIDS, false); + } private MinecraftNameWrapper() { } @NotNull - private static Material getItemByNames(@NotNull String... names) { + private static Material getMaterialByNames(@NotNull String... names) { return ReflectionUtils.getFirstEnumByNames(Material.class, names); } @@ -58,22 +77,27 @@ private static Particle getParticleByNames(@NotNull String... names) { @NotNull private static PotionEffectType getPotionByNames(@NotNull String... names) { - return getFirstAttributeByNames(PotionEffectType.class, names); + return getFirstConstantByNames(PotionEffectType.class, names); } @NotNull private static Enchantment getEnchantByNames(@NotNull String... names) { - return getFirstAttributeByNames(Enchantment.class, names); + return getFirstConstantByNames(Enchantment.class, names); + } + + @NotNull + private static Attribute getAttributeByNames(@NotNull String... names) { + return getFirstConstantByNames(Attribute.class, names); } @NotNull private static GameRule getGameRuleByNames(@NotNull String... names) { - return getFirstAttributeByNames(GameRule.class, names); + return getFirstConstantByNames(GameRule.class, names); } - @SuppressWarnings("unchecked") @NotNull - public static T getFirstAttributeByNames(@NotNull Class clazz, @NotNull String... names) { + @SuppressWarnings("unchecked") + public static T getFirstConstantByNames(@NotNull Class clazz, @NotNull String... names) { for (String name : names) { try { Field field = ReflectionUtil.getField(clazz, name); @@ -84,4 +108,12 @@ public static T getFirstAttributeByNames(@NotNull Class clazz, @NotNull S throw new IllegalArgumentException("No attribute found in: " + clazz.getName() + " for " + Arrays.toString(names)); } + public static T getFirstConstantByNamesOrNull(@NotNull Class clazz, @NotNull String... names) { + try { + return getFirstConstantByNames(clazz, names); + } catch (IllegalArgumentException ex) { + return null; + } + } + } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java index bd88c6942..5bb4b39df 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java @@ -6,8 +6,6 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.jetbrains.annotations.NotNull; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -19,7 +17,6 @@ public class CompatibilityUtils { protected static final ILogger logger = ILogger.forThisClass(); - private static final Logger log = LoggerFactory.getLogger(CompatibilityUtils.class); private CompatibilityUtils() { } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java index ea2a13e3f..a35baf844 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java @@ -5,7 +5,8 @@ public class AttributeWrapper { - public static final Attribute MAX_HEALTH = wrap("MAX_HEALTH", "GENERIC_MAX_HEALTH"), + public static final Attribute + MAX_HEALTH = wrap("MAX_HEALTH", "GENERIC_MAX_HEALTH"), ATTACK_SPEED = wrap("ATTACK_SPEED", "GENERIC_ATTACK_SPEED"); public static Attribute wrap(String name, String legacyName) { diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java index c7e6e2f9b..1f1e33c7e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/FileUtils.java @@ -137,7 +137,7 @@ public static void deleteWorldFolder(@NotNull File path) { if (files == null) return; for (File currentFile : files) { if (currentFile.isDirectory()) { - // Don't delete directories or we'Ll minecraft won't create them again + // Don't delete directories or minecraft won't create them again deleteWorldFolder(currentFile); } else { if (currentFile.getName().equals("session.lock")) continue; // Don't delete or we'll get lots of exceptions From 7f01d1e1d43f6796163474a6e25a26afa7faac33 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Tue, 2 Jun 2026 13:55:57 +0200 Subject: [PATCH 087/119] fix: custom seed injection via server.properties - previously for pre-world-refactor: we pre generated the custom seed world before shutting down and copied it onLoad, removed this logic for easier cross-version-compatibility - newer version requires seed injection via reflection as seed has already been read from the world data (server.properties change has no effect) - older versions read seed from server.properties, no refl. injection necessary/effective --- .../management/server/WorldManager.java | 67 +++++++++++++------ 1 file changed, 46 insertions(+), 21 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java index 672b56eec..c873d768f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java @@ -32,13 +32,13 @@ public final class WorldManager { private final boolean restartOnReset; @Getter private final boolean enableFreshReset; - private final long customSeed; + private final long configCustomSeed; + private final boolean configUseCustomSeed; private final String levelName; private final String[] worlds; private final Map playerData = new HashMap<>(); @Getter private boolean shutdownBecauseOfReset = false; - private boolean useCustomSeed; private WorldSettings settings = new WorldSettings(); private World flatWorld; @Getter @@ -50,8 +50,8 @@ public WorldManager() { enableFreshReset = pluginConfig.getBoolean("enable-fresh-reset"); Document seedConfig = pluginConfig.getDocument("custom-seed"); - useCustomSeed = seedConfig.getBoolean("config"); - customSeed = seedConfig.getLong("seed"); + configUseCustomSeed = seedConfig.getBoolean("config"); + configCustomSeed = seedConfig.getLong("seed"); Document sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); levelName = sessionConfig.getString("level-name", "world"); @@ -71,12 +71,11 @@ public void enable() { } public void prepareWorldReset(@Nullable CommandSender requestedBy) { - prepareWorldReset(requestedBy, customSeed); + prepareWorldReset(requestedBy, configCustomSeed); } public void prepareWorldReset(@Nullable CommandSender requestedBy, @Nullable Long seed) { - if (seed == null && useCustomSeed) seed = customSeed; - if (seed != null) useCustomSeed = true; + if (seed == null && configUseCustomSeed) seed = configCustomSeed; shutdownBecauseOfReset = true; ChallengeAPI.pauseTimer(false); @@ -84,7 +83,7 @@ public void prepareWorldReset(@Nullable CommandSender requestedBy, @Nullable Lon // Stop all tasks to prevent them from overwriting configs Challenges.getInstance().getScheduler().stop(); - resetConfigs(); + resetConfigs(seed); String requester = requestedBy instanceof Player ? NameHelper.getName((Player) requestedBy) : "§4§lConsole"; String kickMessage = Message.forName("server-reset").asString(requester); @@ -93,18 +92,19 @@ public void prepareWorldReset(@Nullable CommandSender requestedBy, @Nullable Lon Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), this::stopServerNow, 3); } - private void resetConfigs() { + private void resetConfigs(@Nullable Long seed) { FileDocument sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); sessionConfig.clear(); sessionConfig.set("reset", true); - sessionConfig.set("provided-custom-seed", useCustomSeed); - if (useCustomSeed) { - sessionConfig.set("custom-seed", customSeed); + sessionConfig.set("provided-custom-seed", seed != null); + if (seed != null) { + sessionConfig.set("custom-seed", seed); } - if (!Bukkit.getWorlds().isEmpty()) { - sessionConfig.set("level-name", ChallengeAPI.getGameWorld(Environment.NORMAL).getName()); - sessionConfig.set("old-seed", ChallengeAPI.getGameWorld(Environment.NORMAL).getSeed()); + World world = ChallengeAPI.getGameWorld(Environment.NORMAL); + if (world != null) { + sessionConfig.set("level-name", world.getName()); + sessionConfig.set("old-seed", world.getSeed()); } sessionConfig.save(); @@ -174,17 +174,17 @@ public void executeWorldReset() { deleteWorld(world); } - FileDocument sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); - boolean providedCustomSeed = sessionConfig.getBoolean("provided-custom-seed"); - long customSeed = sessionConfig.getLong("custom-seed"); + long newSeed = getCustomSeedOrRandom(); + String newSeedString = String.valueOf(newSeed); + replaceServerPropertiesSeed(newSeedString); + FileDocument sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); if (sessionConfig.contains("old-seed")) { long oldSeed = sessionConfig.getLong("old-seed"); - long newSeed = providedCustomSeed ? customSeed : this.useCustomSeed ? this.customSeed : IRandom.secure().nextLong(); - injectSeedViaReflection(String.valueOf(oldSeed), String.valueOf(newSeed)); + injectSeedViaReflection(String.valueOf(oldSeed), newSeedString); } else { // this should never happen, probably old or corrupt session.json - Logger.warn("Could not find old level-seed session config for replacement!"); + Logger.warn("Could not find old level-seed in session config for reflection injection!"); } for (String world : Challenges.getInstance().getGameWorldStorage().getCustomGeneratedGameWorlds()) { @@ -196,6 +196,31 @@ public void executeWorldReset() { sessionConfig.save(); } + private long getCustomSeedOrRandom() { + FileDocument sessionConfig = Challenges.getInstance().getConfigManager().getSessionConfig(); + boolean providedCustomSeed = sessionConfig.getBoolean("provided-custom-seed"); + long customSeed = sessionConfig.getLong("custom-seed"); + + if (providedCustomSeed) return customSeed; + if (configUseCustomSeed) return configCustomSeed; + return IRandom.secure().nextLong(); + } + + private void replaceServerPropertiesSeed(String newSeed) { + // before the world structure overhaul we pre generated a custom seed world and copied it. injecting the level-seed + // into the server.properties works more seamlessly. versions after the update seem to have already read the seed + // before we replace it, requiring an injection via reflection and rendering this function ineffective + File serverPropertiesFile = new File("server.properties"); + if (!serverPropertiesFile.exists()) { + Logger.warn("Unable to find server.properties at {} for seed '{}' injection", serverPropertiesFile.getAbsolutePath(), newSeed); + return; + } + + FileDocument properties = FileDocument.readPropertiesFile(serverPropertiesFile); + properties.set("level-seed", newSeed); + properties.save(); + } + private void injectSeedViaReflection(String oldSeed, String newSeed) { // before the world structure overhaul it was enough to just delete world data to trigger a regeneration // with a new random seed. but after the overhaul the seed seemed to be already be read when onLoad injection From 473b239133448e7ce08c4fe379018c5bcbddc556 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Tue, 2 Jun 2026 13:58:12 +0200 Subject: [PATCH 088/119] fix: use inv CompatibilityUtils, attr/mats: MinecraftNameWrapper --- .../setting/MaxHealthSetting.java | 3 +-- .../utils/misc/MinecraftNameWrapper.java | 2 ++ .../commons/bukkit/core/BukkitModule.java | 8 +++---- .../bukkit/utils/misc/CompatibilityUtils.java | 17 +++++++++++++ .../utils/wrapper/AttributeWrapper.java | 24 ------------------- 5 files changed, 24 insertions(+), 30 deletions(-) delete mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index 8058e04a3..c467a56a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -8,7 +8,6 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.bukkit.utils.wrapper.MaterialWrapper; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.document.GsonDocument; import org.bukkit.attribute.AttributeInstance; @@ -34,7 +33,7 @@ public MaxHealthSetting() { @NotNull @Override public ItemBuilder createDisplayItem() { - return new ItemBuilder(MaterialWrapper.RED_DYE, Message.forName("item-max-health-setting")); + return new ItemBuilder(MinecraftNameWrapper.RED_DYE, Message.forName("item-max-health-setting")); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java index edcc58249..dc381025a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java @@ -11,6 +11,7 @@ import org.bukkit.entity.EntityType; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.lang.reflect.Field; import java.util.Arrays; @@ -108,6 +109,7 @@ public static T getFirstConstantByNames(@NotNull Class clazz, @NotNull St throw new IllegalArgumentException("No attribute found in: " + clazz.getName() + " for " + Arrays.toString(names)); } + @Nullable public static T getFirstConstantByNamesOrNull(@NotNull Class clazz, @NotNull String... names) { try { return getFirstConstantByNames(clazz, names); diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java index 069eac759..fa280521a 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java @@ -3,6 +3,7 @@ import com.google.common.base.Charsets; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.commons.bukkit.utils.menu.MenuPositionListener; +import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.commons.bukkit.utils.wrapper.ActionListener; import net.codingarea.commons.bukkit.utils.wrapper.SimpleEventExecutor; @@ -128,10 +129,9 @@ public final void onDisable() { executorService.shutdown(); for (Player player : Bukkit.getOnlinePlayers()) { - InventoryView view = player.getOpenInventory(); - Inventory inventory = view.getTopInventory(); - if (inventory.getHolder() == MenuPosition.HOLDER) - view.close(); + Inventory inventory = CompatibilityUtils.getTopInventory(player); + if (inventory != null && inventory.getHolder() == MenuPosition.HOLDER) + CompatibilityUtils.closeInventoryView(player); } if (error != null) diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java index 5bb4b39df..3e158dc6c 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/CompatibilityUtils.java @@ -44,4 +44,21 @@ public static Inventory getTopInventory(@NotNull InventoryClickEvent event) { return null; } } + + public static void closeInventoryView(@NotNull Player player) { + InventoryView view = player.getOpenInventory(); + + try { + view.close(); + return; + } catch (Throwable ignored) { + } + + try { + Method closeInventory = InventoryView.class.getMethod("close"); + closeInventory.invoke(view); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { + logger.error("Failed to close inventory", ex); + } + } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java deleted file mode 100644 index a35baf844..000000000 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/wrapper/AttributeWrapper.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.codingarea.commons.bukkit.utils.wrapper; - -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import org.bukkit.attribute.Attribute; - -public class AttributeWrapper { - - public static final Attribute - MAX_HEALTH = wrap("MAX_HEALTH", "GENERIC_MAX_HEALTH"), - ATTACK_SPEED = wrap("ATTACK_SPEED", "GENERIC_ATTACK_SPEED"); - - public static Attribute wrap(String name, String legacyName) { - return wrap(name, legacyName, MinecraftVersion.V1_21_2); - } - - public static Attribute wrap(String name, String legacyName, MinecraftVersion since) { - if (MinecraftVersion.current().isNewerOrEqualThan(since)) { - return Attribute.valueOf(name); - } else { - return Attribute.valueOf(legacyName); - } - } - -} From 2b0b36f1ec60b50ecdd34c9cda446f811b10be36 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Tue, 2 Jun 2026 19:29:29 +0200 Subject: [PATCH 089/119] fix: scoreboard race condition, concurrent timer pause - since 1d2b97b player challenge scoreboard objectives always have the same name; when the scoreboard was updated twice (e.g. because of the same trigger event) concurrently, it created a race condition where sometime the objective creation was sent twice to player resulting in a disconnect/crash in newer (only in newer minecraft versions?) - because team death and respawn setting call the same function on the same event but the timer state check was only on of them the timer pause was called twice concurrently which yielded a warning in the log; moved the check to prevent this - bukkit scoreboard api: current method is now deprecated, using new method with fallback to deprecated api for compatibility - force target item display via armor stand resulted in error when material is not an item (tested in 26.1.2) --- .../goal/forcebattle/targets/ForceTarget.java | 2 +- .../setting/RespawnSetting.java | 5 ++-- .../scoreboard/ChallengeScoreboard.java | 25 +++++++++++++++---- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java index dfa948547..7e7f2de90 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java @@ -39,7 +39,7 @@ public String toString() { } public void updateDisplayStand(@NotNull ArmorStand armorStand) { - if (target instanceof Material) { + if (target instanceof Material && ((Material) target).isItem()) { Objects.requireNonNull(armorStand.getEquipment()).setHelmet(new ItemStack((Material) target)); } else { Objects.requireNonNull(armorStand.getEquipment()).setHelmet(null); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java index 53124d94c..0331fbb61 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java @@ -46,8 +46,7 @@ public void onPlayerDeath(@NotNull PlayerDeathEvent event) { locationsBeforeRespawn.put(player, player.getLocation()); player.setGameMode(GameMode.SPECTATOR); - if (ChallengeAPI.isStarted()) - checkAllPlayersDead(); + checkAllPlayersDead(); } ParticleUtils.spawnParticleCylinder(Challenges.getInstance(), player.getLocation(), @@ -55,6 +54,8 @@ public void onPlayerDeath(@NotNull PlayerDeathEvent event) { } public void checkAllPlayersDead() { + if (ChallengeAPI.isPaused()) return; + int playersAlive = ChallengeAPI.getIngamePlayers().size(); if (playersAlive == 0) { ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_FAILED); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java index 6746930b0..b035ef668 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java @@ -8,6 +8,7 @@ import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import org.bukkit.scoreboard.Criteria; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Scoreboard; @@ -38,7 +39,10 @@ public void update() { } } - public void update(@NotNull Player player) { + public synchronized void update(@NotNull Player player) { + // synchronized method lock: prevent race condition resulting in client error/crash: by sending the objective + // with the same name at the same time twice as the name is constant (1d2b97b) + // java.lang.IllegalArgumentException: An objective with the name 'xxx' already exists! (client-side) if (!isShown()) { Logger.warn("Tried to update scoreboard which is not shown"); return; @@ -67,12 +71,12 @@ public void update(@NotNull Player player) { String name = String.valueOf(player.getUniqueId().hashCode()); // Unregister any old objective existing - Objective objective1 = scoreboard.getObjective(name); - if (objective1 != null) { - unregister(objective1); + Objective oldObjective = scoreboard.getObjective(name); + if (oldObjective != null) { + unregister(oldObjective); } - Objective objective = scoreboard.registerNewObjective(name, "dummy", String.valueOf(instance.getTitle())); + Objective objective = registerDummyObjective(scoreboard, name, String.valueOf(instance.getTitle())); int score = lines.size(); for (String line : lines) { if (line.isEmpty()) line = StringUtils.repeat(' ', score + 1); @@ -110,6 +114,17 @@ private void unregister(@Nullable Objective objective) { } } + @NotNull + @SuppressWarnings("deprecation") + private Objective registerDummyObjective(@NotNull Scoreboard scoreboard, @NotNull String name, @NotNull String displayName) { + try { + return scoreboard.registerNewObjective(name, Criteria.DUMMY, displayName); + } catch (Error ignored) { + // replacement not yet available in this version, use deprecated method + return scoreboard.registerNewObjective(name, "dummy", displayName); + } + } + @ToString public static final class ScoreboardInstance { From c3f82dc48d1023209e2d2a4657797e52b877ae82 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Wed, 3 Jun 2026 01:48:45 +0200 Subject: [PATCH 090/119] fix: reregister quiz challenge (conflicted) - the quiz challenge was corrupted by an incorrect merge conflict resolution (presumably in 8930698) - the challenge remains broken and still requires optimization --- language/files/de.json | 31 +++++++++++++++++++ language/files/en.json | 31 +++++++++++++++++++ .../challenges/ChallengeLoader.java | 2 ++ plugin/src/main/resources/plugin.yml | 3 ++ 4 files changed, 67 insertions(+) diff --git a/language/files/de.json b/language/files/de.json index db6acbadb..a489ac749 100644 --- a/language/files/de.json +++ b/language/files/de.json @@ -299,6 +299,37 @@ "Bist du etwa krank?", "Was geht denn jetzt ab" ], + + "quiz-how-to": "Schreibe deine Antwort mit §e/guess ", + + "quiz-right-answer": "§e{0} §7ist die §arichtige §7Antwort!", + "quiz-right-answer-other": "§e{0} §7hat die Frage §arichtig §7beantwortet", + + "quiz-wrong-answer": "§e{0} §7ist eine §cfalsche §7Antwort!", + "quiz-wrong-answer-other": "§e{0} §7hat die Frage §cfalsch beantwortet", + "quiz-time-up": "Die Zeit ist §cabgelaufen§7!", + "quiz-cancel": "Die Frage wurde §cabgebrochen§7!", + + "quiz-right-answer-was": "Die richtige Antwort lautete: §e{0}", + "quiz-right-answer-was-multiple": "Die richtigen Antworten lauteten: §e{0}", + + "quiz-question-often-have": "Wie oft hast du §e{0}§7{1}?", + "quiz-question-often-be": "Wie oft bist du §e{0}§7{1}?", + "quiz-question-far-be": "Wie weit bist du {0}?", + "quiz-question-most": "Was hast du von diesen {1} am meisten {0}?", + "quiz-question-damage-have": "Wie viel Schaden hast du {0}{1}?", + "quiz-question-damage-taken-have": "Wie viel Schaden hast du durch {0}{1}?", + + "quiz-verb-traveled": "gelaufen", + "quiz-verb-jumped": "gesprungen", + "quiz-verb-sneaked": "geschlichen", + "quiz-verb-killed": "getötet", + "quiz-verb-damaged": "zugefügt", + "quiz-verb-broken": "abgebaut", + "quiz-verb-placed": "platziert", + "quiz-verb-dropped": "gedropped", + "quiz-verb-suffered": "erlitten", + "bossbar-timer-paused": "§8» §7Der Timer ist §cpausiert", "bossbar-mob-transformation": "§8» §7Letzter Mob §8§l┃ §a{0}", "bossbar-biome-time-left": "§8» §7Zeit übrig in §e{0} §8§l┃ §a{1}s", diff --git a/language/files/en.json b/language/files/en.json index 57e13303d..d4a6ca9bb 100644 --- a/language/files/en.json +++ b/language/files/en.json @@ -299,6 +299,37 @@ "Are you sick??", "What's going on now?!" ], + + "quiz-how-to": "Write your answer with §e/guess ", + + "quiz-right-answer": "§e{0} §7is the §aright §7answer!", + "quiz-right-answer-other": "§e{0} §7answered the question §acorrectly§7!", + + "quiz-wrong-answer": "§e{0} §7is a §cwrong §7answer!", + "quiz-wrong-answer-other": "§e{0} §7answered the question §cincorrectly§7!", + "quiz-time-up": "The time is §cup§7!", + "quiz-cancel": "The question was §ccancelled§7!", + + "quiz-right-answer-was": "The right answer was: §e{0}", + "quiz-right-answer-was-multiple": "the right answers were: §e{0}", + + "quiz-question-often-have": "How often have you{1} §e{0}?", + "quiz-question-often-be": "How often did you{1} §e{0}?", + "quiz-question-far-be": "How far did you {0}?", + "quiz-question-most": "What do you have the most of these {1} {0}?", + "quiz-question-damage-have": "How much damage have you {0}", + "quiz-question-damage-taken-have": "How much damage have you taken from {0}", + + "quiz-verb-traveled": "walk", + "quiz-verb-jumped": "jump", + "quiz-verb-sneaked": "sneak", + "quiz-verb-killed": "killed", + "quiz-verb-damaged": "hurt", + "quiz-verb-broken": "broken", + "quiz-verb-placed": "placed", + "quiz-verb-dropped": "dropped", + "quiz-verb-suffered": "suffered", + "bossbar-timer-paused": "§8» §7The timer is §cpaused", "bossbar-mob-transformation": "§8» §7Last mob §8§l┃ §a{0}", "bossbar-biome-time-left": "§8» §7Time left in §e{0} §8§l┃ §a{1}s", diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java index 4848e8820..67569118c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java @@ -10,6 +10,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory.*; import net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous.*; import net.codingarea.challenges.plugin.challenges.implementation.challenge.movement.*; +import net.codingarea.challenges.plugin.challenges.implementation.challenge.quiz.QuizChallenge; import net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer.*; import net.codingarea.challenges.plugin.challenges.implementation.challenge.time.MaxBiomeTimeChallenge; import net.codingarea.challenges.plugin.challenges.implementation.challenge.time.MaxHeightTimeChallenge; @@ -191,6 +192,7 @@ public void enable() { register(EnderGamesChallenge.class); register(InvertHealthChallenge.class); register(NoSharedAdvancementsChallenge.class); + registerWithCommand(QuizChallenge.class, "guess"); // Goal diff --git a/plugin/src/main/resources/plugin.yml b/plugin/src/main/resources/plugin.yml index 70cb24ec3..8274c3831 100644 --- a/plugin/src/main/resources/plugin.yml +++ b/plugin/src/main/resources/plugin.yml @@ -215,6 +215,9 @@ commands: usage: "/result" description: "Shows the result of the current force battle (if enabled)" permission: "challenges.result" + guess: + usage: "/guess " + description: "Used to guess at quiz challenge" skiptimer: usage: "/skiptimer" description: "Skips all activated timers" From 73eda387e38c5920728dd4c01ae97410ac54c371 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Wed, 3 Jun 2026 02:24:11 +0200 Subject: [PATCH 091/119] feat: bukkit module extension: set yaml value --- .../commons/bukkit/core/BukkitModule.java | 85 +++++-- .../common/config/document/YamlHelper.java | 233 ++++++++++++++++++ 2 files changed, 293 insertions(+), 25 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/commons/common/config/document/YamlHelper.java diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java index fa280521a..369da1fbe 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java @@ -1,19 +1,18 @@ package net.codingarea.commons.bukkit.core; -import com.google.common.base.Charsets; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.commons.bukkit.utils.menu.MenuPositionListener; import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.commons.bukkit.utils.wrapper.ActionListener; import net.codingarea.commons.bukkit.utils.wrapper.SimpleEventExecutor; -import net.codingarea.commons.common.annotations.DeprecatedSince; import net.codingarea.commons.common.annotations.ReplaceWith; import net.codingarea.commons.common.collection.NamedThreadFactory; import net.codingarea.commons.common.collection.WrappedException; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.FileDocument; import net.codingarea.commons.common.config.document.YamlDocument; +import net.codingarea.commons.common.config.document.YamlHelper; import net.codingarea.commons.common.logging.ILogger; import net.codingarea.commons.common.logging.internal.BukkitLoggerWrapper; import net.codingarea.commons.common.logging.lib.JavaILogger; @@ -28,16 +27,21 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryView; import org.bukkit.plugin.java.JavaPlugin; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.io.File; +import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; import java.util.function.Consumer; import java.util.logging.Level; @@ -76,10 +80,12 @@ public final void onLoad() { ILogger.setConstantFactory(this.getILogger()); trySaveDefaultConfig(); if (wasShutdown) isReloaded = true; - if (firstInstall = !getDataFolder().exists()) { + firstInstall = !getDataFolder().exists(); + if (firstInstall) { getILogger().info("Detected first install!"); } - if (devMode = getConfigDocument().getBoolean("dev-mode") || getConfigDocument().getBoolean("dev-mode.enabled")) { + devMode = getConfigDocument().getBoolean("dev-mode") || getConfigDocument().getBoolean("dev-mode.enabled"); + if (devMode) { getILogger().setLevel(Level.ALL); getILogger().debug("Devmode is enabled: Showing debug messages. This can be disabled in the plugin.yml ('dev-mode')"); } else { @@ -178,6 +184,11 @@ public Document getConfigDocument() { return config != null ? config : (config = new YamlDocument(super.getConfig())); } + @NotNull + public File getConfigFile() { + return getDataFile("config.yml"); + } + @Override public void reloadConfig() { config = null; @@ -189,8 +200,10 @@ public void reloadConfig() { */ @NotNull public Document getPluginDocument() { - return pluginConfig != null ? pluginConfig : - (pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(getResource("plugin.yml"), Charsets.UTF_8)))); + if (pluginConfig != null) return pluginConfig; + InputStream resource = getResource("plugin.yml"); + if (resource == null) throw new IllegalStateException("Could not load plugin.yml as resource"); + return pluginConfig = new YamlDocument(YamlConfiguration.loadConfiguration(new InputStreamReader(resource, StandardCharsets.UTF_8))); } @NotNull @@ -203,22 +216,6 @@ public Version getVersion() { return version != null ? version : (version = Version.parse(getDescription().getVersion())); } - @NotNull - @Deprecated - @DeprecatedSince("1.3.0") - @ReplaceWith("MinecraftVersion.current()") - public MinecraftVersion getServerVersion() { - return MinecraftVersion.current(); - } - - @NotNull - @Deprecated - @DeprecatedSince("1.3.0") - @ReplaceWith("MinecraftVersion.currentExact()") - public Version getServerVersionExact() { - return MinecraftVersion.currentExact(); - } - @NotNull @Override @Deprecated @@ -311,7 +308,9 @@ public final File getDataFile(@NotNull String subfolder, @NotNull String filenam @NotNull public ExecutorService getExecutor() { - return executorService != null ? executorService : (executorService = Executors.newCachedThreadPool(new NamedThreadFactory(threadId -> String.format("%s-Task-%s", this.getName(), threadId)))); + if (executorService != null) return executorService; + ThreadFactory factory = new NamedThreadFactory(threadId -> String.format("%s-Task-%s", this.getName(), threadId)); + return executorService = Executors.newCachedThreadPool(factory); } public void runAsync(@NotNull Runnable task) { @@ -333,7 +332,7 @@ private void registerAsFirstInstance() { registerListener( new MenuPositionListener() ); - getILogger().info("Detected server version {} -> {}", getServerVersionExact(), getServerVersion()); + getILogger().info("Detected server version {} -> {}", MinecraftVersion.currentExact(), MinecraftVersion.current()); } private void trySaveDefaultConfig() { @@ -344,6 +343,42 @@ private void trySaveDefaultConfig() { } } + + /** + * Replaces the value of an already existing key inside the {@code config.yml} while leaving every + * comment (and the rest of the file's formatting) untouched. + * Bukkit's {@link #saveConfig()} re-serializes the whole document and therefore strips all comments. + * + * @param key the dot-separated path of an existing config value + * @param value the new value, or {@code null} to write a literal {@code null} + * @return whether the value could be set + */ + public boolean setValueInConfig(@NotNull String key, @Nullable Object value) { + File file = getConfigFile(); + if (!file.exists()) { + getILogger().warn("Cannot replace '{}' in config.yml: file does not exist", key); + return false; + } + + try { + String content = Files.readString(file.toPath()); + String updated = YamlHelper.replaceValue(content, key, value); + if (updated == null) { + getILogger().warn("Cannot replace '{}' in config.yml: key not found or has a multi-line value", key); + return false; + } + + Files.writeString(file.toPath(), updated); + + // keep the loaded configuration in sync with the file we just edited + if (isLoaded()) getConfigDocument().set(key, value); + return true; + } catch (IOException ex) { + getILogger().error("Could not replace '{}' in config.yml: {}", key, ex.getMessage()); + return false; + } + } + private void injectInstance() { try { Field instanceField = this.getClass().getDeclaredField("instance"); diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlHelper.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlHelper.java new file mode 100644 index 000000000..924619e53 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/YamlHelper.java @@ -0,0 +1,233 @@ +package net.codingarea.commons.common.config.document; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; + +import java.util.ArrayList; +import java.util.List; + +/** + * Utility for editing raw YAML text in place. + *

+ * Bukkit's {@link org.bukkit.configuration.file.YamlConfiguration} re-serializes the whole document when it is + * saved and thereby strips every comment. To avoid that, this helper does not rewrite the file from the parsed + * model: it locates the single line that defines a key and swaps out only its value, leaving every comment, + * blank line, indentation and line ending exactly the way it was. + * + * @see YamlDocument + */ +public final class YamlHelper { + + private YamlHelper() { + } + + /** + * Returns a copy of {@code content} in which the value of the given dot-separated {@code key} has been + * replaced by {@code value}, serialized the way YAML would write it (strings wrapped in double quotes to + * match the usual config style). Everything else - comments, indentation, blank lines, the original line + * endings and any trailing inline comment on the edited line - is preserved unchanged. + *

+ * Only single-line values are rewritten. Returns {@code null} when the key does not exist or when it opens a + * block-style structure that spans several lines (so the caller can react instead of corrupting the file). + * + * @param content the full YAML document + * @param key the dot-separated path of an existing value, e.g. {@code "timer.format.seconds"} + * @param value the new value, or {@code null} to write a literal {@code null} + * @return the updated document, or {@code null} if {@code key} could not be replaced + */ + @Nullable + public static String replaceValue(@NotNull String content, @NotNull String key, @Nullable Object value) { + String lineSeparator = content.contains("\r\n") ? "\r\n" : "\n"; + + // split on '\n' (keeping trailing empties) and drop a possible '\r' so indentation can be measured cleanly + String[] rawLines = content.split("\n", -1); + List lines = new ArrayList<>(rawLines.length); + for (String rawLine : rawLines) { + lines.add(rawLine.endsWith("\r") ? rawLine.substring(0, rawLine.length() - 1) : rawLine); + } + + int index = findKeyLine(lines, key); + if (index == -1) return null; + + String line = lines.get(index); + int colon = indexOfKeyColon(line); + String afterColon = line.substring(colon + 1); + + // recover a possible inline comment ('value # comment') so it survives the value swap + String inlineComment = extractInlineComment(afterColon); + String existingValue = afterColon.substring(0, afterColon.length() - inlineComment.length()).trim(); + + // refuse block-style parents (nothing on this line, children indented underneath) - replacing the line + // would orphan those children + if (existingValue.isEmpty() && opensBlock(lines, index)) return null; + + // keep the indentation, the key and its colon exactly as they are + String keyPart = line.substring(0, colon + 1); + lines.set(index, keyPart + " " + serializeValue(value) + inlineComment); + + return String.join(lineSeparator, lines); + } + + /** + * Serializes a single value the way YAML would write it, forced onto one line (flow style) so it can be + * dropped into an existing line. String scalars are wrapped in double quotes to match the surrounding config + * style, while numbers, booleans and {@code null} stay bare so they remain type-correct on re-read. Quoting + * of values that need it (e.g. the string {@code "2.4"}, which would otherwise be read as a number) is left + * to SnakeYAML. + */ + @NotNull + public static String serializeValue(@Nullable Object value) { + if (value instanceof Enum) value = ((Enum) value).name(); + + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.FLOW); // keep collections on a single line + options.setWidth(Integer.MAX_VALUE); // never wrap the value across multiple lines + if (isStringOnly(value)) { + // prefer double quotes ("...") over SnakeYAML's default single quotes ('...'); only safe to force on + // string-only values, otherwise numbers/booleans would be quoted and read back as strings + options.setDefaultScalarStyle(DumperOptions.ScalarStyle.DOUBLE_QUOTED); + } + + // Yaml#dump appends a trailing line break (and, for flow scalars, no document markers) + return new Yaml(options).dump(value).trim(); + } + + /** + * Finds the index of the line that defines the given dot-separated {@code key} by tracking the mapping nesting + * through indentation, or {@code -1} if no such line exists. + */ + private static int findKeyLine(@NotNull List lines, @NotNull String key) { + String[] segments = key.split("\\."); + List pathKeys = new ArrayList<>(); + List pathIndents = new ArrayList<>(); + + for (int i = 0; i < lines.size(); i++) { + String line = lines.get(i); + String trimmed = line.trim(); + // skip blank lines, full-line comments and (block) sequence items - none of them open a mapping key + if (trimmed.isEmpty() || trimmed.charAt(0) == '#' || trimmed.charAt(0) == '-') continue; + + int colon = indexOfKeyColon(line); + if (colon == -1) continue; + + int indent = countIndent(line); + String keyName = unquote(line.substring(indent, colon).trim()); + + // walk back up to the parent of the current indentation level + while (!pathIndents.isEmpty() && pathIndents.get(pathIndents.size() - 1) >= indent) { + pathIndents.remove(pathIndents.size() - 1); + pathKeys.remove(pathKeys.size() - 1); + } + pathIndents.add(indent); + pathKeys.add(keyName); + + if (pathMatches(pathKeys, segments)) return i; + } + + return -1; + } + + private static boolean pathMatches(@NotNull List pathKeys, @NotNull String[] segments) { + if (pathKeys.size() != segments.length) return false; + for (int i = 0; i < segments.length; i++) { + if (!pathKeys.get(i).equals(segments[i])) return false; + } + return true; + } + + /** + * Returns {@code true} if the key on the given line has no value of its own but is followed by a deeper + * indented (block-style) child line. + */ + private static boolean opensBlock(@NotNull List lines, int index) { + int keyIndent = countIndent(lines.get(index)); + for (int i = index + 1; i < lines.size(); i++) { + String trimmed = lines.get(i).trim(); + if (trimmed.isEmpty() || trimmed.charAt(0) == '#') continue; + return countIndent(lines.get(i)) > keyIndent; + } + return false; + } + + /** + * Returns the index of the colon that separates the key from its value, ignoring colons that appear inside a + * quoted scalar, or {@code -1} if the line carries no mapping key. + */ + private static int indexOfKeyColon(@NotNull String line) { + boolean inSingle = false, inDouble = false; + for (int i = 0; i < line.length(); i++) { + char c = line.charAt(i); + if (c == '\'' && !inDouble) inSingle = !inSingle; + else if (c == '"' && !inSingle) inDouble = !inDouble; + else if (c == ':' && !inSingle && !inDouble) { + // a key/value colon is followed by whitespace or ends the line + if (i + 1 >= line.length() || line.charAt(i + 1) == ' ' || line.charAt(i + 1) == '\t') return i; + } + } + return -1; + } + + /** + * Extracts the trailing inline comment from the part of a line that follows the key's colon, including the + * whitespace in front of the {@code #} so it can be re-appended unchanged. Returns an empty string when there + * is no inline comment. The {@code #} must be preceded by whitespace and must not sit inside a quoted scalar. + */ + @NotNull + private static String extractInlineComment(@NotNull String valuePart) { + boolean inSingle = false, inDouble = false; + for (int i = 0; i < valuePart.length(); i++) { + char c = valuePart.charAt(i); + if (c == '\'' && !inDouble) inSingle = !inSingle; + else if (c == '"' && !inSingle) inDouble = !inDouble; + else if (c == '#' && !inSingle && !inDouble && (i == 0 || isWhitespace(valuePart.charAt(i - 1)))) { + int start = i; + while (start > 0 && isWhitespace(valuePart.charAt(start - 1))) start--; + return valuePart.substring(start); + } + } + return ""; + } + + private static int countIndent(@NotNull String line) { + int i = 0; + while (i < line.length() && (line.charAt(i) == ' ' || line.charAt(i) == '\t')) i++; + return i; + } + + @NotNull + private static String unquote(@NotNull String text) { + if (text.length() >= 2) { + char first = text.charAt(0), last = text.charAt(text.length() - 1); + if ((first == '"' && last == '"') || (first == '\'' && last == '\'')) + return text.substring(1, text.length() - 1); + } + return text; + } + + private static boolean isStringOnly(@Nullable Object value) { + if (value instanceof String) return true; + if (value instanceof Iterable) { + boolean any = false; + for (Object element : (Iterable) value) { + any = true; + if (!(element instanceof String)) return false; + } + return any; + } + if (value instanceof Object[]) { + Object[] array = (Object[]) value; + if (array.length == 0) return false; + for (Object element : array) { + if (!(element instanceof String)) return false; + } + return true; + } + return false; + } + + private static boolean isWhitespace(char c) { + return c == ' ' || c == '\t'; + } +} From 2799ed33746a133e1bae24d455312a75efca7f4f Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Wed, 3 Jun 2026 02:26:21 +0200 Subject: [PATCH 092/119] refactor: bundle localization files, opt-in online pull Remove IDE module file and refactor language handling: LanguageLoader now reads languages from bundled resources, supports online updates, and allows a direct overwrite path. Migrates away from a separate properties file, adds safer migration logic that preserves customized messages and only fills missing keys, and merges online updates if enabled (skipping in dev mode). Build script now packages language JSON files into the plugin JAR. Add new config options `language-online-update` and `language-overwrite-path` with documentation in config.yml, and rename/clean up related constants and getters. --- language/Language.iml | 8 - plugin/build.gradle.kts | 10 +- .../plugin/content/loader/LanguageLoader.java | 230 +++++++++++------- plugin/src/main/resources/config.yml | 6 + 4 files changed, 161 insertions(+), 93 deletions(-) delete mode 100644 language/Language.iml diff --git a/language/Language.iml b/language/Language.iml deleted file mode 100644 index 80cc7391b..000000000 --- a/language/Language.iml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index 3d8eb8216..0233457fb 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -26,6 +26,14 @@ dependencies { } tasks { + + processResources { + from("../language") { + into("language") + include("**/*.json") + } + } + jar { archiveClassifier = "plain" } @@ -53,5 +61,5 @@ tasks { val localBuild = file("local.gradle.kts") if (localBuild.exists()) { - apply(from = localBuild) + apply(from = localBuild) } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index 2a043ed10..7ee18f501 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -1,6 +1,5 @@ package net.codingarea.challenges.plugin.content.loader; -import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -11,20 +10,29 @@ import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.collection.IOUtils; import net.codingarea.commons.common.config.Document; -import net.codingarea.commons.common.config.FileDocument; import net.codingarea.commons.common.misc.FileUtils; import net.codingarea.commons.common.misc.GsonUtils; +import org.jetbrains.annotations.CheckReturnValue; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; +import java.io.InputStream; +import java.util.Collections; +import java.util.List; import java.util.Map.Entry; +import java.util.Objects; public final class LanguageLoader extends ContentLoader { - public static final String DEFAULT_LANGUAGE = "en"; + public static final String FALLBACK_LANGUAGE = "en"; - public static final String KEY_LANGUAGE = "language", KEY_SMALL_CAPS = "smallcaps", KEY_DIRECT_LANGUAGE_FILE = "manualfile"; + public static final String + KEY_LANGUAGE = "language", + KEY_ONLINE_UPDATE = "language-online-update", + KEY_LANGUAGE_OVERWRITE = "language-overwrite-path", + KEY_SMALL_CAPS = "small-caps"; @Getter private static volatile boolean loaded = false; @@ -32,51 +40,23 @@ public final class LanguageLoader extends ContentLoader { private String language; @Getter private boolean smallCapsFont; - - public File getLanguagePropertiesFile() { - return getMessageFile("language", "properties"); - } - - public Document getLanguageProperties() { - try { - FileUtils.createFilesIfNecessary(getLanguagePropertiesFile()); - - return FileDocument.readPropertiesFile(getLanguagePropertiesFile()); - } catch (Exception e) { - Logger.error("Could not read language properties", e); - } - return Document.empty(); - } - - public void migrateLanguageConfig() { - Document configDocument = Challenges.getInstance().getConfigDocument(); - String oldLanguage = configDocument.getString("language"); - String oldDirectFilePath = configDocument.getString("direct-language-file"); - boolean oldSmallCapsFont = configDocument.getBoolean("small-caps"); - - Document languageProperties = getLanguageProperties(); - languageProperties.set(KEY_LANGUAGE, oldLanguage); - languageProperties.set(KEY_SMALL_CAPS, oldSmallCapsFont); - - if (configDocument.contains("direct-language-file")) { - languageProperties.set(KEY_DIRECT_LANGUAGE_FILE, oldDirectFilePath); - } - } + @Getter + private boolean onlineUpdate; + @Getter + private boolean languageOverwrite; @Override protected void load() { - migrateLanguageConfig(); - - Document config = getLanguageProperties(); + Document config = Challenges.getInstance().getConfigDocument(); + String languageOverwritePath = config.getString(KEY_LANGUAGE_OVERWRITE); + languageOverwrite = config.contains(KEY_LANGUAGE_OVERWRITE) && languageOverwritePath != null; smallCapsFont = config.getBoolean(KEY_SMALL_CAPS, false); + language = config.getString(KEY_LANGUAGE, FALLBACK_LANGUAGE); + onlineUpdate = config.getBoolean(KEY_ONLINE_UPDATE, false); - if (config.contains(KEY_DIRECT_LANGUAGE_FILE)) { - language = config.getString(KEY_LANGUAGE, DEFAULT_LANGUAGE); - String path = config.getString(KEY_DIRECT_LANGUAGE_FILE); - if (path == null) return; - Logger.info("Using direct language file '{}'", path); - readLanguage(new File(path)); + if (languageOverwrite) { + loadOverwrite(languageOverwritePath); return; } @@ -89,84 +69,166 @@ public void changeLanguage(@NotNull String language) { return; } - this.language = language; - Document properties = getLanguageProperties(); - properties.set(KEY_LANGUAGE, language); - try { - properties.saveToFile(getLanguagePropertiesFile()); - } catch (IOException e) { - Logger.error("Could not save language properties", e); - } - reload(language); + Challenges.getInstance().setValueInConfig(KEY_LANGUAGE, language); + reloadWithLanguage(language); Logger.info("Language changed to '{}'", language); } - public void reload(String language) { + public void reloadWithLanguage(String language) { this.language = language; read(); - download(); init(); Challenges.getInstance().getScoreboardManager().updateAll(); Challenges.getInstance().getConfigManager().getSettingsConfig().set("language", language); } + private void loadOverwrite(@NotNull String languageOverwritePath) { + Logger.info("Using direct language file '{}'", languageOverwritePath); + readLanguage(new File(languageOverwritePath)); + } + private void loadDefault() { - download(); + migrateLanguages(onlineUpdate); init(); read(); } private void init() { - - language = Challenges.getInstance().getConfigDocument().getString("language", DEFAULT_LANGUAGE); + language = Challenges.getInstance().getConfigDocument().getString("language", FALLBACK_LANGUAGE); File file = getMessageFile(language, "json"); if (!file.exists()) { - if (language.equalsIgnoreCase(DEFAULT_LANGUAGE)) return; + if (language.equalsIgnoreCase(FALLBACK_LANGUAGE)) return; ConsolePrint.unknownLanguage(language); - language = DEFAULT_LANGUAGE; + language = FALLBACK_LANGUAGE; } Logger.debug("Language '{}' is currently selected", language); } - private void download() { - try { - - JsonArray languages = JsonParser.parseString(IOUtils.toString(getGitHubUrl("language/languages.json"))).getAsJsonArray(); // TODO fix(deps) version ambiguity - Logger.debug("Fetched languages {}", languages); - for (JsonElement element : languages) { - try { - String name = element.getAsString(); - String url = getGitHubUrl("language/files/" + name + ".json"); + private void migrateLanguages(boolean onlineUpdate) { + // migrate with bundled languages + changed online translation (if enabled) + for (String language : loadBundledLanguageNames()) { + try { + Document bundledDocument = loadBundledLanguageDocument(language); + if (bundledDocument == null) continue; + + Document migratedDocument = migrateLanguageDocument(bundledDocument, language); + Document onlineDocument = onlineUpdate ? fetchOnlineLanguageDocument(language) : null; + migrateLanguageFileAndSave(migratedDocument, bundledDocument, onlineDocument, language); + } catch (IOException ex) { + Logger.error("Could not migrate language file for {}", language, ex); + } + } - Document language = Document.parseJson(IOUtils.toString(url)); - File file = getMessageFile(name, "json"); + // pull new languages + if (onlineUpdate) { + for (String language : fetchOnlineLanguages()) { + File file = getLanguageFile(language); + if (file.exists()) continue; // already exists, was migrated in previous step - Logger.debug("Writing language {} to {}", name, file); - verifyLanguage(language, file, name); - } catch (Exception exception) { - Challenges.getInstance().getILogger().error("", exception); - Logger.error("Could not download language for {}. {}: {}", element, exception.getClass().getSimpleName(), exception.getMessage()); + try { + Document onlineDocument = fetchOnlineLanguageDocument(language); + if (onlineDocument == null) continue; + onlineDocument.saveToFile(file); + Logger.info("Added new language '{}' from online update", language); + } catch (IOException ex) { + Logger.error("Could not save new language file for {}", language, ex); } } - - } catch (Exception ex) { - Logger.error("Could not download languages", ex); } } - private void verifyLanguage(@NotNull Document download, @NotNull File file, @NotNull String name) throws IOException { - Document existing = Document.readJsonFile(file); - FileUtils.createFilesIfNecessary(file); - download.forEach((key, value) -> { + @NotNull + @CheckReturnValue + private Document migrateLanguageDocument(@NotNull Document bundledLanguage, @NotNull String languageName) { + File destinationFile = getLanguageFile(languageName); + if (!destinationFile.exists()) { + return bundledLanguage; + } + + // if the language file already exists, don't overwrite customized messages, only add missing ones + Document existing = Document.readJsonFile(destinationFile); + bundledLanguage.forEach((key, value) -> { if (!existing.contains(key)) { - Logger.debug("Overwriting message {} in {} with {}", key, name, String.valueOf(value).replace("\"", "§r\"")); + Logger.debug("Overwriting message {} in {} from bundled with {}", key, languageName, String.valueOf(value).replace("\"", "§r\"")); existing.set(key, value); } }); - existing.saveToFile(file); + return existing; + } + + private void migrateLanguageFileAndSave(@NotNull Document migratedLanguage, @NotNull Document bundledLanguage, + @Nullable Document onlineLanguage, @NotNull String languageName) throws IOException { + File destinationFile = getLanguageFile(languageName); + if (onlineLanguage == null || Challenges.getInstance().isDevMode()) { // ignore online update in dev-mode! + migratedLanguage.saveToFile(destinationFile); + return; + } + + onlineLanguage.forEach((key, value) -> { + if (!migratedLanguage.contains(key)) { + Logger.debug("Overwriting message {} in {} from online-update with {}", key, languageName, String.valueOf(value).replace("\"", "§r\"")); + migratedLanguage.set(key, value); + } else if (Objects.equals(migratedLanguage.getString(key), bundledLanguage.getString(key))) { + // if the message was not customized, overwrite it with the online version (like typo fix) + Logger.debug("Overwriting message {} in {} from online-update with {}", key, languageName, String.valueOf(value).replace("\"", "§r\"")); + migratedLanguage.set(key, value); + } + }); + migratedLanguage.saveToFile(destinationFile); + } + + @NotNull + private List loadBundledLanguageNames() { + try (InputStream in = getLanguageResourceStream("languages.json")) { + return Document.parseStringArray(IOUtils.toString(in)); + } catch (Exception ex) { + Logger.error("Could not load bundled languages", ex); + return Collections.emptyList(); + } + } + + @Nullable + private Document loadBundledLanguageDocument(@NotNull String languageName) { + try (InputStream in = getLanguageResourceStream("files/" + languageName + ".json")) { + if (in == null) return null; + return Document.parseJson(in); + } catch (Exception ex) { + Logger.error("Could not load bundled language '{}' from jar", languageName, ex); + return null; + } + } + + private InputStream getLanguageResourceStream(String path) { + // no leading slash! + return Challenges.getInstance().getResource("language/" + path); + } + + private File getLanguageFile(String languageName) { + return getMessageFile(languageName, "json"); + } + + @NotNull + private List fetchOnlineLanguages() { + try { + return Document.parseStringArray(IOUtils.toString(getGitHubUrl("language/languages.json"))); + } catch (Exception ex) { + Logger.error("Could not fetch online languages", ex); + return Collections.emptyList(); + } + } + + @Nullable + private Document fetchOnlineLanguageDocument(@NotNull String languageName) { + String url = getGitHubUrl("language/files/" + languageName + ".json"); + try { + return Document.parseJson(IOUtils.toString(url)); + } catch (Exception ex) { + Logger.error("Could not fetch online language '{}'", languageName, ex); + return null; + } } private void read() { diff --git a/plugin/src/main/resources/config.yml b/plugin/src/main/resources/config.yml index b63f1ff1f..efacd5b3b 100644 --- a/plugin/src/main/resources/config.yml +++ b/plugin/src/main/resources/config.yml @@ -29,6 +29,12 @@ config-version: "2.4" # - de (German / Deutsch) language: "de" +# Whether the plugin should pull newer/missing translations from https://github.com/anweisen/Challenges +# on every load. Defaults to off so the plugin doesn't make outbound HTTP calls without consent. +language-online-update: false +# If you want to use a custom translations file, you can specify the path to the folder where the file is located. +language-overwrite-path: null + # Makes text from the plugin appear in the 'small caps' font # Example: ᴛʜɪs ɪs sᴍᴀʟʟ ᴄᴀᴘs small-caps: false From 6de013ee399016fe881fe013a8d73e15b8e9781c Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Wed, 3 Jun 2026 13:31:12 +0200 Subject: [PATCH 093/119] refactor: challenge since annotation --- .../challenge/DamageTeleportChallenge.java | 2 +- .../challenge/ZeroHeartsChallenge.java | 2 +- .../damage/BlockPlaceDamageChallenge.java | 2 +- .../damage/DeathOnFallChallenge.java | 2 +- .../damage/DelayDamageChallenge.java | 2 +- .../challenge/damage/FreezeChallenge.java | 2 +- .../challenge/damage/JumpDamageChallenge.java | 2 +- .../damage/WaterAllergyChallenge.java | 2 +- .../effect/BlockEffectChallenge.java | 2 +- .../effect/ChunkRandomEffectChallenge.java | 2 +- .../effect/EntityRandomEffectChallenge.java | 2 +- .../PermanentEffectOnDamageChallenge.java | 2 +- .../effect/RandomPotionEffectChallenge.java | 2 +- .../entities/AllMobsToDeathPoint.java | 2 +- .../entities/BlockMobsChallenge.java | 2 +- .../entities/HydraPlusChallenge.java | 2 +- .../entities/InvisibleMobsChallenge.java | 2 +- .../entities/MobSightDamageChallenge.java | 2 +- .../entities/MobTransformationChallenge.java | 2 +- .../entities/MobsRespawnInEndChallenge.java | 2 +- .../entities/NewEntityOnJumpChallenge.java | 2 +- .../entities/StoneSightChallenge.java | 2 +- .../challenge/force/ForceBiomeChallenge.java | 2 +- .../challenge/force/ForceItemChallenge.java | 2 +- .../inventory/MissingItemsChallenge.java | 2 +- .../MovementItemRemovingChallenge.java | 2 +- .../inventory/NoDupedItemsChallenge.java | 2 +- .../inventory/PermanentItemChallenge.java | 2 +- .../inventory/PickupItemLaunchChallenge.java | 2 +- .../inventory/UncraftItemsChallenge.java | 2 +- .../miscellaneous/EnderGamesChallenge.java | 2 +- .../miscellaneous/FoodLaunchChallenge.java | 2 +- .../miscellaneous/InvertHealthChallenge.java | 2 +- .../miscellaneous/LowDropRateChallenge.java | 2 +- .../NoSharedAdvancementsChallenge.java | 2 +- .../movement/AlwaysRunningChallenge.java | 2 +- .../movement/DontStopRunningChallenge.java | 2 +- .../movement/FiveHundredBlocksChallenge.java | 2 +- .../movement/HungerPerBlockChallenge.java | 2 +- .../challenge/movement/MoveMouseDamage.java | 2 +- .../challenge/movement/OnlyDownChallenge.java | 2 +- .../movement/TrafficLightChallenge.java | 2 +- .../challenge/quiz/QuizChallenge.java | 2 +- .../EntityLootRandomizerChallenge.java | 2 +- .../randomizer/HotBarRandomizerChallenge.java | 2 +- .../randomizer/MobRandomizerChallenge.java | 2 +- .../randomizer/RandomChallengeChallenge.java | 2 +- .../randomizer/RandomEventChallenge.java | 2 +- .../randomizer/RandomItemChallenge.java | 2 +- .../RandomItemDroppingChallenge.java | 2 +- .../RandomItemRemovingChallenge.java | 2 +- .../RandomItemSwappingChallenge.java | 2 +- .../RandomTeleportOnHitChallenge.java | 2 +- .../challenge/time/MaxBiomeTimeChallenge.java | 2 +- .../time/MaxHeightTimeChallenge.java | 2 +- .../world/AllBlocksDisappearChallenge.java | 2 +- .../world/BlockFlyInAirChallenge.java | 2 +- .../BlocksDisappearAfterTimeChallenge.java | 2 +- .../challenge/world/IceFloorChallenge.java | 2 +- .../challenge/world/LevelBorderChallenge.java | 2 +- .../challenge/world/LoopChallenge.java | 2 +- .../world/RepeatInChunkChallenge.java | 2 +- .../challenge/world/TsunamiChallenge.java | 2 +- .../goal/AllAdvancementGoal.java | 2 +- .../goal/CollectAllItemsGoal.java | 2 +- .../goal/CollectHorseAmorGoal.java | 2 +- .../goal/CollectIceBlocksGoal.java | 2 +- .../goal/CollectMostExpGoal.java | 2 +- .../goal/CollectSwordsGoal.java | 2 +- .../goal/CollectWorkstationsGoal.java | 2 +- .../implementation/goal/EatCakeGoal.java | 2 +- .../implementation/goal/EatMostGoal.java | 2 +- .../implementation/goal/FindElytraGoal.java | 2 +- .../implementation/goal/FinishRaidGoal.java | 2 +- .../goal/FirstOneToDieGoal.java | 2 +- .../goal/GetFullHealthGoal.java | 2 +- .../goal/KillAllBossesGoal.java | 2 +- .../goal/KillAllBossesNewGoal.java | 2 +- .../implementation/goal/KillAllMobsGoal.java | 2 +- .../goal/KillAllMonsterGoal.java | 2 +- .../goal/KillElderGuardianGoal.java | 2 +- .../goal/KillIronGolemGoal.java | 2 +- .../goal/KillSnowGolemGoal.java | 2 +- .../implementation/goal/KillWardenGoal.java | 2 +- .../goal/LastManStandingGoal.java | 2 +- .../implementation/goal/MaxHeightGoal.java | 2 +- .../implementation/goal/MinHeightGoal.java | 2 +- .../implementation/goal/MostEmeraldsGoal.java | 2 +- .../implementation/goal/MostOresGoal.java | 2 +- .../implementation/goal/RaceGoal.java | 2 +- .../ForceAdvancementBattleGoal.java | 2 +- .../forcebattle/ForceBlockBattleGoal.java | 2 +- .../goal/forcebattle/ForceItemBattleGoal.java | 2 +- .../goal/forcebattle/ForceMobBattleGoal.java | 2 +- .../setting/BastionSpawnSetting.java | 2 +- .../setting/CutCleanSetting.java | 2 +- .../setting/DeathPositionSetting.java | 2 +- .../setting/EnderChestCommandSetting.java | 2 +- .../setting/FortressSpawnSetting.java | 2 +- .../setting/HealthDisplaySetting.java | 2 +- .../setting/ImmediateRespawnSetting.java | 2 +- .../setting/NoOffhandSetting.java | 2 +- .../implementation/setting/OldPvPSetting.java | 2 +- .../setting/SlotLimitSetting.java | 2 +- .../setting/TotemSaveDeathSetting.java | 2 +- .../type/annotation/ChallengeAnnotations.java | 21 +++++++++++++++++++ .../challenges/type/annotation}/Since.java | 4 ++-- .../generator/ChallengeMenuGenerator.java | 3 ++- .../commons/common/version/Version.java | 11 +++------- .../common/version/VersionComparator.java | 2 ++ .../commons/common/version/VersionInfo.java | 5 ----- 111 files changed, 135 insertions(+), 121 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java rename plugin/src/main/java/net/codingarea/{commons/common/annotations => challenges/plugin/challenges/type/annotation}/Since.java (55%) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java index ef256edb9..b9d029db2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index dfc4fc60a..a1019dfb7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.setting.MaxHealthSetting; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -10,7 +11,6 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java index df833d52c..c6cbedfe6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.block.BlockPlaceEvent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java index 7f0a0fea8..fc33b2d74 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java index 4385ef78f..cf2a7f12b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java index ecc6ece2b..017d64da0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java index d96a2c4d9..c135e75be 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -10,7 +11,6 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.LeatherArmorBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java index 95674e6ef..8bb6383bb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java index 1e278c99a..7f92d8711 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -11,7 +12,6 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.collection.SeededRandomWrapper; import org.bukkit.Location; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java index d7ebb1bc5..bf2662c9f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java @@ -2,13 +2,13 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.collection.SeededRandomWrapper; import org.bukkit.Chunk; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java index 2251648dc..194f0946c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java @@ -2,11 +2,11 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java index a1a36e792..58d64b142 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -13,7 +14,6 @@ import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.TriConsumer; import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index 125dbfac2..70ab48687 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.collection.IRandom; import org.bukkit.Bukkit; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java index 0c3bc4351..d11f98050 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDeathByPlayerEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.*; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java index f8cf8656d..5c16a0a61 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java @@ -2,11 +2,11 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomMobAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java index 421cc89f2..07c304f4d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; import net.codingarea.challenges.plugin.challenges.type.abstraction.HydraChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java index 63d76e871..2960d7e58 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; @@ -9,7 +10,6 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.World; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java index 964b968ed..69258d5d1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java index e320aa2f4..b244e7088 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDamageByPlayerEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.EnderDragon; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java index 76ae0acce..301bafd72 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -9,7 +10,6 @@ import net.codingarea.challenges.plugin.spigot.events.EntityDeathByPlayerEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.config.Document; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java index d8053d8ab..c0d27ef17 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java @@ -2,13 +2,13 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomMobAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder.LeatherArmorBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java index 5e3ca563e..7f2078d08 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java index 8aa7e8162..193430e8f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -12,7 +13,6 @@ import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.NamespacedKey; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java index b7ad48b72..2c769955c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -16,7 +17,6 @@ import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.item.ItemUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java index cd39a3f98..0ebfd4f8d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -16,7 +17,6 @@ import net.codingarea.commons.bukkit.utils.item.ItemUtils; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.collection.pair.Tuple; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.ClickEvent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java index 3dac9faf3..0d448742f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -9,7 +10,6 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java index 48abf2483..10136606c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -11,7 +12,6 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.collection.pair.Triple; import org.bukkit.Bukkit; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java index a4c14a102..65667c3a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java index 3b66b41aa..be9b16014 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -8,7 +9,6 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java index ff7c92151..2f59704cb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index d60bb4e7e..1a538b36e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java index 9e582f278..c15bcb851 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java index f70a00886..f9e13917c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -8,7 +9,6 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java index b2d410412..e56e64d34 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java @@ -2,13 +2,13 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.DropPriority; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java index e05f5f2ad..eaff16731 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java index 9a3429152..869276f08 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.util.Vector; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java index 7c6dacd6c..c8ebde0ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -8,7 +9,6 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java index 3b4fdc3fe..c7a5a3b75 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -10,7 +11,6 @@ import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java index 93d9cc583..5fa756b80 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java index 55cc26801..a49538953 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -10,7 +11,6 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java index 325c059d2..3a4d85aba 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -8,7 +9,6 @@ import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java index 7e17c62b0..39f51b393 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -10,7 +11,6 @@ import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index 995ad121c..c89ddb538 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.challenge.quiz.QuizChallenge.IQuestion.Question; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -17,7 +18,6 @@ import net.codingarea.challenges.plugin.utils.misc.TriFunction; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.misc.StringUtils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java index 1cf2f7058..ce84d3e39 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -11,7 +12,6 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; import net.codingarea.challenges.plugin.utils.misc.Utils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 76c07e790..59a6f28bd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -11,7 +12,6 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java index d3268e059..19b7b2e1e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; @@ -11,7 +12,6 @@ import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java index e28be1f94..319b4e05f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java @@ -6,13 +6,13 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java index 83876e781..0561bde31 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -10,7 +11,6 @@ import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java index 1ecd498ba..7a0383d0a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java @@ -2,12 +2,12 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomItemAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java index 03ca11d88..383efc499 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java index 6bc569cc9..d8fc7b05e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java index 8fc8c9743..793ae3957 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java index 87e30ab43..d1f872283 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDamageByPlayerEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java index d74e42fd4..32919deac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.time; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.block.Biome; import org.bukkit.boss.BarColor; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java index d873baec3..ac6cd56ba 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.time; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.boss.BarColor; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java index 3065a48a0..3c0a8558f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeConfigHelper; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; @@ -10,7 +11,6 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.config.Document; import org.bukkit.Chunk; import org.bukkit.Location; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java index 16233d54c..024ccb36b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java index 9a28748d3..df17e3a71 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java index c350e1fbb..6428654dd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java index 326aca912..90c719565 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -15,7 +16,6 @@ import net.codingarea.challenges.plugin.utils.bukkit.nms.type.PacketBorder; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.document.GsonDocument; import org.bukkit.*; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index 435f78c6a..908fdcf75 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -15,7 +16,6 @@ import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java index 426e596fb..0b584a0bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java @@ -3,13 +3,13 @@ import com.google.common.collect.Lists; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.collection.pair.Triple; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.document.GsonDocument; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java index 2372aae4b..f4885377e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -9,7 +10,6 @@ import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Chunk; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java index 50167e3b6..008cac40e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java @@ -2,12 +2,12 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.advancement.Advancement; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index 2cbd98394..4a23df327 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -3,6 +3,7 @@ import lombok.Getter; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; @@ -14,7 +15,6 @@ import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.item.ItemUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.collection.SeededRandomWrapper; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java index 51d16ad5c..508e7bc88 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java index d1841ba32..15b177654 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java index 6e10ba9a1..983450dee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java index e607eb32a..669f6e1f2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java index 539e927a7..bf7810a16 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java index 81de60ac2..ebdbff49c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java @@ -2,11 +2,11 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java index 14b2a0bb5..2d0bd52e5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java index a304a9a1f..da84379bc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.FindItemGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java index be3648a6b..692bcaa9f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java @@ -2,13 +2,13 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.Raid.RaidStatus; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java index b237c8c54..521025775 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java @@ -2,11 +2,11 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index ea9bae95e..e944c0c4b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -9,7 +10,6 @@ import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java index e1281d49a..14a773bba 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java index a466bbb5d..4bc6af91b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java index b6fb7bb9e..097f62e42 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java index 5cedfaa6e..e88def8fb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.bukkit.entity.Monster; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java index d04c79afd..c96ae3691 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java index 0badc6037..06f349fa6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java index b070346bb..fd4c00053 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.Sound; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java index f9bdd0bfe..67f938432 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java index a7f09c5cf..7e9e5ec2c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java @@ -2,10 +2,10 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java index f87686d2d..7f4e6188d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java @@ -2,10 +2,10 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.FirstPlayerAtHeightGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.World.Environment; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java index 0af817a88..6d6a8363d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java @@ -2,11 +2,11 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.FirstPlayerAtHeightGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.World.Environment; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java index b9f755bf3..c7f9c40ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java index 976936bfa..528fe00ea 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java index 5d26a7da9..d12b96e38 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; @@ -15,7 +16,6 @@ import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.config.Document; import org.bukkit.Color; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java index cf4e3b33c..e03c0be9e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java @@ -2,10 +2,10 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.AdvancementTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java index 3a03236ea..a91c1b13b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java @@ -2,12 +2,12 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.BlockTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java index d0bbaec8c..96cabb5b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java @@ -2,12 +2,12 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ItemTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java index 4f6273580..a665c556f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java @@ -2,9 +2,9 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.MobTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java index 2aca8175b..b4ef74d61 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java @@ -1,13 +1,13 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.NetherPortalSpawnSetting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.StructureType; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java index f7a18a17b..17ee16968 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.DropPriority; @@ -13,7 +14,6 @@ import net.codingarea.challenges.plugin.utils.misc.Utils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.item.ItemUtils; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java index a85ea9e24..5936d33df 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java @@ -2,10 +2,10 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java index 9d59a29d6..a12d1d360 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java @@ -2,12 +2,12 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java index 376eb06f5..7168e54f5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.NetherPortalSpawnSetting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.StructureType; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java index 4a74c4998..af2441922 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java @@ -2,10 +2,10 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java index 1c1c6e272..12839b148 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.World; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java index c5de2e8b0..f48e41ba7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java index 94dc303db..ece0ccf85 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java index b2edf6b88..4a7dc4fba 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; @@ -9,7 +10,6 @@ import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java index d7d05e14f..520a315ee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.Since; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java new file mode 100644 index 000000000..e9f565d6e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java @@ -0,0 +1,21 @@ +package net.codingarea.challenges.plugin.challenges.type.annotation; + +import net.codingarea.commons.common.version.Version; +import org.jetbrains.annotations.NotNull; + +public final class ChallengeAnnotations { + + private ChallengeAnnotations() { + } + + @NotNull + public static Version getSince(@NotNull Object object) { + return getSince(object.getClass()); + } + + @NotNull + public static Version getSince(@NotNull Class clazz) { + if (!clazz.isAnnotationPresent(Since.class)) return Version.FALLBACK; + return Version.parse(clazz.getAnnotation(Since.class).value()); + } +} diff --git a/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/Since.java similarity index 55% rename from plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/Since.java index 88721c953..00b7ab3d7 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/annotations/Since.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/Since.java @@ -1,11 +1,11 @@ -package net.codingarea.commons.common.annotations; +package net.codingarea.challenges.plugin.challenges.type.annotation; import org.jetbrains.annotations.NotNull; import java.lang.annotation.*; @Documented -@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PACKAGE}) +@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Since { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java index 2db7b6e1a..c9130e156 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java @@ -3,6 +3,7 @@ import com.google.common.collect.ImmutableList; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.ChallengeAnnotations; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuManager; import net.codingarea.challenges.plugin.management.menu.position.GeneratorMenuPosition; @@ -166,7 +167,7 @@ protected ItemStack getSettingsItem(@NotNull IChallenge challenge) { protected boolean isNew(@NotNull IChallenge challenge) { Version version = Challenges.getInstance().getVersion(); - Version since = Version.getAnnotatedSince(challenge); + Version since = ChallengeAnnotations.getSince(challenge); return since.isNewerOrEqualThan(version); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/Version.java b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java index 2b858d9da..66946d787 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/Version.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java @@ -1,6 +1,5 @@ package net.codingarea.commons.common.version; -import net.codingarea.commons.common.annotations.Since; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -8,6 +7,8 @@ public interface Version { + Version FALLBACK = new VersionInfo(1, 0, 0); + int getMajor(); int getMinor(); @@ -69,12 +70,6 @@ static Version parseExceptionally(@Nullable String input) { return VersionInfo.parseExceptionally(input); } - @NotNull - static Version getAnnotatedSince(@NotNull Object object) { - if (!object.getClass().isAnnotationPresent(Since.class)) return new VersionInfo(1, 0, 0); - return parse(object.getClass().getAnnotation(Since.class).value()); - } - @NotNull static V findNearest(@NotNull Version target, @NotNull V[] sortedVersionsArray) { List versions = new ArrayList<>(Arrays.asList(sortedVersionsArray)); @@ -88,7 +83,7 @@ static V findNearest(@NotNull Version target, @NotNull V[] s @NotNull static Comparator comparator() { - return new VersionComparator(); + return VersionComparator.INSTANCE; } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java index 71dcd75e5..3aad5e285 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java @@ -6,6 +6,8 @@ public class VersionComparator implements Comparator { + public static final VersionComparator INSTANCE = new VersionComparator(); + @Override public int compare(@NotNull Version v1, @NotNull Version v2) { return v1.equals(v2) ? 0 : v1.isNewerThan(v2) ? 1 : -1; diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java index 16443488b..053e52c2b 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java @@ -11,10 +11,6 @@ public class VersionInfo implements Version { private final int major, minor, revision; - public VersionInfo() { - this(1, 0, 0); - } - public VersionInfo(int major, int minor, int revision) { this.major = major; this.minor = minor; @@ -75,5 +71,4 @@ public static Version parse(@Nullable String input, Version def) { return def; } } - } From 3563210b544c30db92547eff48cdb1c6d24602ac Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Wed, 3 Jun 2026 16:37:41 +0200 Subject: [PATCH 094/119] feat: challenge update annotation --- language/files/de.json | 1 + language/files/en.json | 1 + .../type/annotation/ChallengeAnnotations.java | 27 +++++++++++++++++++ .../challenges/type/annotation/Updated.java | 15 +++++++++++ .../plugin/management/menu/MenuManager.java | 2 +- .../generator/ChallengeMenuGenerator.java | 26 +++++++++--------- .../categorised/CategorisedMenuGenerator.java | 6 ++++- .../commons/common/version/Version.java | 2 +- plugin/src/main/resources/config.yml | 13 +++++---- 9 files changed, 73 insertions(+), 20 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/Updated.java diff --git a/language/files/de.json b/language/files/de.json index a489ac749..eb858fc26 100644 --- a/language/files/de.json +++ b/language/files/de.json @@ -32,6 +32,7 @@ "Die Challenge wurde §cnoch nicht §7gestartet" ], "new-challenge": "§a§lNeu!", + "updated-challenge": "§e§lUpdate!", "feature-disabled": "Diese Funktion ist derzeit §cdeaktiviert", "challenge-disabled": "Diese Challenge ist derzeit §cdeaktiviert", "stopped-message": "§8• §7Timer §c§lpaused §8•", diff --git a/language/files/en.json b/language/files/en.json index d4a6ca9bb..d43a466ca 100644 --- a/language/files/en.json +++ b/language/files/en.json @@ -32,6 +32,7 @@ "The Challenge §chasn't been §7started" ], "new-challenge": "§a§lNew!", + "updated-challenge": "§e§lUpdated!", "feature-disabled": "This function is currently §cdeactivated", "challenge-disabled": "This challenge is currently §cdeactivated", "stopped-message": "§8• §7Timer §c§lpaused §8•", diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java index e9f565d6e..b3a8cb59a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java @@ -1,5 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.annotation; +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.commons.common.version.Version; import org.jetbrains.annotations.NotNull; @@ -18,4 +20,29 @@ public static Version getSince(@NotNull Class clazz) { if (!clazz.isAnnotationPresent(Since.class)) return Version.FALLBACK; return Version.parse(clazz.getAnnotation(Since.class).value()); } + + @NotNull + public static Version getUpdated(@NotNull Object object) { + return getUpdated(object.getClass()); + } + + @NotNull + public static Version getUpdated(@NotNull Class clazz) { + if (!clazz.isAnnotationPresent(Updated.class)) return Version.FALLBACK; + return Version.parse(clazz.getAnnotation(Updated.class).value()); + } + + public static boolean isNew(@NotNull IChallenge challenge) { + return isVersionNewer(getSince(challenge)); + } + + public static boolean isUpdated(@NotNull IChallenge challenge) { + return isVersionNewer(getUpdated(challenge)); + } + + private static boolean isVersionNewer(@NotNull Version challengeVersion) { + Version pluginVersion = Challenges.getInstance().getVersion(); + return challengeVersion.isNewerOrEqualThan(pluginVersion); + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/Updated.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/Updated.java new file mode 100644 index 000000000..fec3ecbef --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/Updated.java @@ -0,0 +1,15 @@ +package net.codingarea.challenges.plugin.challenges.type.annotation; + +import org.jetbrains.annotations.NotNull; + +import java.lang.annotation.*; + +@Documented +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface Updated { + + @NotNull + String value(); + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java index c8b69d9ce..03d0dc50b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java @@ -31,7 +31,7 @@ public final class MenuManager { public MenuManager() { ChallengeAPI.subscribeLoader(LanguageLoader.class, this::generateMenus); ChallengeAPI.subscribeLoader(LanguageLoader.class, this::generateMainMenu); - displayNewInFront = Challenges.getInstance().getConfigDocument().getBoolean("display-new-in-front"); + displayNewInFront = Challenges.getInstance().getConfigDocument().getBoolean("challenge-updates.new.in-front"); permissionToManageGUI = Challenges.getInstance().getConfigDocument().getBoolean("manage-settings-permission"); generateMainMenu(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java index c9130e156..db7ea257b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java @@ -13,7 +13,7 @@ import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import net.codingarea.commons.common.version.Version; +import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; @@ -28,12 +28,15 @@ public abstract class ChallengeMenuGenerator extends MultiPageMenuGenerator { protected final List challenges = new LinkedList<>(); protected final boolean newSuffix; + protected final boolean updatedSuffix; private final int startPage; protected Consumer onLeaveClick; public ChallengeMenuGenerator(int startPage, Consumer onLeaveClick) { - newSuffix = Challenges.getInstance().getConfigDocument().getBoolean("new-suffix"); + Document config = Challenges.getInstance().getConfigDocument(); + this.newSuffix = config.getBoolean("challenge-updates.new.suffix"); + this.updatedSuffix = config.getBoolean("challenge-updates.updated.suffix"); this.startPage = startPage; this.onLeaveClick = onLeaveClick; } @@ -96,9 +99,12 @@ public void updateItem(IChallenge challenge) { Inventory inventory = getInventories().get(page + startPage); setSettingsItems(inventory, challenge, slot); - if (newSuffix && isNew(challenge)) { + if (newSuffix && ChallengeAnnotations.isNew(challenge)) { inventory.setItem(slot + 1, new ItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); inventory.setItem(slot + 28, new ItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); + } else if (updatedSuffix && ChallengeAnnotations.isUpdated(challenge)) { + inventory.setItem(slot + 1, new ItemBuilder(Material.YELLOW_STAINED_GLASS_PANE, "§0").build()); + inventory.setItem(slot + 28, new ItemBuilder(Material.YELLOW_STAINED_GLASS_PANE, "§0").build()); } } @@ -126,7 +132,7 @@ public boolean isInChallengeCache(@NotNull IChallenge challenge) { } public void addChallengeToCache(@NotNull IChallenge challenge) { - if (isNew(challenge) && Challenges.getInstance().getMenuManager().isDisplayNewInFront()) { + if (ChallengeAnnotations.isNew(challenge) && Challenges.getInstance().getMenuManager().isDisplayNewInFront()) { challenges.add(countNewChallenges(), challenge); } else { challenges.add(challenge); @@ -144,8 +150,10 @@ protected ItemStack getDisplayItem(@NotNull IChallenge challenge) { protected ItemBuilder getDisplayItemBuilder(@NotNull IChallenge challenge) { try { ItemBuilder item = new ItemBuilder(challenge.getDisplayItem()).hideAttributes(); - if (newSuffix && isNew(challenge)) { + if (newSuffix && ChallengeAnnotations.isNew(challenge)) { return item.appendName(" " + Message.forName("new-challenge")); + } else if (updatedSuffix && ChallengeAnnotations.isUpdated(challenge)) { + return item.appendName(" " + Message.forName("updated-challenge")); } else { return item; } @@ -165,14 +173,8 @@ protected ItemStack getSettingsItem(@NotNull IChallenge challenge) { } } - protected boolean isNew(@NotNull IChallenge challenge) { - Version version = Challenges.getInstance().getVersion(); - Version since = ChallengeAnnotations.getSince(challenge); - return since.isNewerOrEqualThan(version); - } - protected int countNewChallenges() { - return (int) challenges.stream().filter(this::isNew).count(); + return (int) challenges.stream().filter(ChallengeAnnotations::isNew).count(); } public abstract int[] getSlots(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java index ad02f7280..dbb23d581 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.ChallengeAnnotations; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -67,9 +68,12 @@ public void generatePage(@NotNull Inventory inventory, int page) { if (i >= 7) slot += 2; for (IChallenge challenge : generator.getChallenges()) { - if (newSuffix && isNew(challenge)) { + if (newSuffix && ChallengeAnnotations.isNew(challenge)) { builder.appendName(" " + Message.forName("new-challenge")); break; + } else if (updatedSuffix && ChallengeAnnotations.isUpdated(challenge)) { + builder.appendName(" " + Message.forName("updated-challenge")); + break; } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/Version.java b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java index 66946d787..14eef7e4e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/Version.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java @@ -58,7 +58,7 @@ default int intValue() { @NotNull static Version parse(@Nullable String input) { - return parse(input, new VersionInfo(1, 0, 0)); + return parse(input, FALLBACK); } static Version parse(@Nullable String input, Version def) { diff --git a/plugin/src/main/resources/config.yml b/plugin/src/main/resources/config.yml index efacd5b3b..04d3cfd49 100644 --- a/plugin/src/main/resources/config.yml +++ b/plugin/src/main/resources/config.yml @@ -90,11 +90,14 @@ permission-info: true # Players with the permission 'challenges.gui' will get a message if the timer is paused when they join timer-is-paused-info: true -# New challenges will be displayed first in the setting menu. -display-new-in-front: false - -# New challenges will have a suffix in their title -new-suffix: true +# Whether to display new/updated challenges at the front of the setting menu +# and whether to add a suffix to their name indicating their update. +challenge-updates: + new: + in-front: false + suffix: true + updated: + suffix: true # If activated players need the permission "challenges.manage" to manage settings in the gui # To manage the timer in the gui, players will always need the permission "challenges.timer" From 9bb9c740d0672262e228c2553ec03309f18a59dc Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Thu, 4 Jun 2026 21:25:47 +0200 Subject: [PATCH 095/119] chore: register submodules dynamically --- settings.gradle.kts | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/settings.gradle.kts b/settings.gradle.kts index 27b097582..cd5191dda 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,9 +1,16 @@ rootProject.name = "Challenges" -include( - "plugin", - "mongo-connector", - "cloud-support:api", - "cloud-support:cloudnet2", - "cloud-support:cloudnet3", -) +include("plugin", "mongo-connector") + +includeSubmodules("cloud-support") + +fun includeSubmodules(parentDirName: String) { + val parentDir = File(settingsDir, parentDirName) + if (parentDir.exists() && parentDir.isDirectory) { + parentDir.listFiles { file -> file.isDirectory }?.forEach { dir -> + if (File(dir, "build.gradle").exists() || File(dir, "build.gradle.kts").exists()) { + include("$parentDirName:${dir.name}") + } + } + } +} From 7a9458d28ee3145572d9d9fd532b78f21b9577a0 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Mon, 8 Jun 2026 22:19:27 +0200 Subject: [PATCH 096/119] refactor: minor cleanup --- build.gradle.kts | 1 - cloud-support/api/build.gradle.kts | 2 +- cloud-support/cloudnet2/build.gradle.kts | 5 +++-- cloud-support/cloudnet3/build.gradle.kts | 5 +++-- gradle/libs.versions.toml | 8 ++++++++ plugin/build.gradle.kts | 4 ++-- .../plugin/utils/misc/MinecraftNameWrapper.java | 2 +- .../plugin/utils/misc/ParticleUtils.java | 2 +- .../commons/bukkit/core/BukkitModule.java | 17 +++++++++-------- .../bukkit/core/SimpleConfigManager.java | 3 +++ .../utils/animation/AnimatedInventory.java | 14 +++++++++----- .../commons/common/config/Document.java | 2 +- .../common/config/document/GsonDocument.java | 12 +++++++++--- .../commons/common/logging/ILogger.java | 3 +-- .../commons/common/misc/GsonUtils.java | 1 - .../commons/common/misc/ReflectionUtils.java | 9 +++++++-- .../commons/common/misc/StringUtils.java | 2 +- .../database/abstraction/AbstractDatabase.java | 1 + 18 files changed, 60 insertions(+), 33 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 456ce60ca..b7f6c2343 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,6 +1,5 @@ plugins { base - id("com.gradleup.shadow") version "8.3.5" apply false } allprojects { diff --git a/cloud-support/api/build.gradle.kts b/cloud-support/api/build.gradle.kts index 4e547c495..ea667470c 100644 --- a/cloud-support/api/build.gradle.kts +++ b/cloud-support/api/build.gradle.kts @@ -1,5 +1,5 @@ plugins { - `java-library` + id("java-library") } dependencies { diff --git a/cloud-support/cloudnet2/build.gradle.kts b/cloud-support/cloudnet2/build.gradle.kts index 54b2d665c..d4aa2afdb 100644 --- a/cloud-support/cloudnet2/build.gradle.kts +++ b/cloud-support/cloudnet2/build.gradle.kts @@ -1,11 +1,12 @@ plugins { - `java-library` + id("java-library") } dependencies { compileOnly(libs.spigot.api) compileOnly(libs.cloudnet2.bridge) - compileOnly(project(":cloud-support:api")) + + api(project(":cloud-support:api")) } repositories { diff --git a/cloud-support/cloudnet3/build.gradle.kts b/cloud-support/cloudnet3/build.gradle.kts index 13f24927f..58a80ce4a 100644 --- a/cloud-support/cloudnet3/build.gradle.kts +++ b/cloud-support/cloudnet3/build.gradle.kts @@ -1,12 +1,13 @@ plugins { - `java-library` + id("java-library") } dependencies { compileOnly(libs.spigot.api) compileOnly(libs.cloudnet3.driver) compileOnly(libs.cloudnet3.bridge) - compileOnly(project(":cloud-support:api")) + + api(project(":cloud-support:api")) } repositories { diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 4b20c7106..d1dd7bec0 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -19,6 +19,9 @@ mongodb = "3.12.14" cloudnet3 = "3.4.5-RELEASE" cloudnet2 = "2.1.17" +# plugins +shadow = "8.3.11" + [libraries] @@ -41,3 +44,8 @@ mongodb-driver = { group = "org.mongodb", name = "mongodb-driver", version.ref = cloudnet3-driver = { group = "de.dytanic.cloudnet", name = "cloudnet-driver", version.ref = "cloudnet3" } cloudnet3-bridge = { group = "de.dytanic.cloudnet", name = "cloudnet-bridge", version.ref = "cloudnet3" } cloudnet2-bridge = { group = "de.dytanic.cloudnet", name = "cloudnet-api-bridge", version.ref = "cloudnet2" } + + +[plugins] + +shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index 0233457fb..9a7afc937 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -1,6 +1,6 @@ plugins { - `java-library` - id("com.gradleup.shadow") + id("java-library") + alias(libs.plugins.shadow) } dependencies { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java index dc381025a..59351e1da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java @@ -112,7 +112,7 @@ public static T getFirstConstantByNames(@NotNull Class clazz, @NotNull St @Nullable public static T getFirstConstantByNamesOrNull(@NotNull Class clazz, @NotNull String... names) { try { - return getFirstConstantByNames(clazz, names); + return getFirstConstantByNames(clazz, names); } catch (IllegalArgumentException ex) { return null; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java index 1f2c539f2..a14e8c1ea 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ParticleUtils.java @@ -54,7 +54,7 @@ private static void spawnParticleCylinder(@NotNull JavaPlugin plugin, @NotNull L } public static void spawnEffectCylinder(@NotNull JavaPlugin plugin, @NotNull Location location, - @NotNull Effect effect, int points, double radius, double height) { + @NotNull Effect effect, int points, double radius, double height) { spawnParticleCylinder(plugin, location, points, radius, height, (world, point) -> world.playEffect(point, effect, 1)); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java index 369da1fbe..9445ccb0e 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java @@ -51,8 +51,8 @@ public abstract class BukkitModule extends JavaPlugin { private static boolean setFirstInstance = true; private static boolean wasShutdown; - private final Map commands = new HashMap<>(); - private final List listeners = new ArrayList<>(); + private final Map commandsQueue = new HashMap<>(); + private final List listenersQueue = new ArrayList<>(); private final SimpleConfigManager configManager = new SimpleConfigManager(this); private JavaILogger logger; @@ -105,8 +105,11 @@ public final void onLoad() { public final void onEnable() { if (!requirementsMet) return; - commands.forEach((name, executor) -> registerCommand0(executor, name)); - listeners.forEach(this::registerListener); + commandsQueue.forEach((name, executor) -> registerCommand0(executor, name)); + commandsQueue.clear(); + + listenersQueue.forEach(this::registerListener); + listenersQueue.clear(); try { @@ -128,8 +131,6 @@ public final void onDisable() { setFirstInstance = true; wasShutdown = true; isLoaded = false; - commands.clear(); - listeners.clear(); if (executorService != null) executorService.shutdown(); @@ -244,7 +245,7 @@ public final void registerCommand(@NotNull CommandExecutor executor, @NotNull St if (isEnabled()) { registerCommand0(executor, name); } else { - commands.put(name, executor); + commandsQueue.put(name, executor); } } } @@ -264,7 +265,7 @@ public final void registerListener(@NotNull Listener... listeners) { registerListener0(listener); } } else { - this.listeners.addAll(Arrays.asList(listeners)); + this.listenersQueue.addAll(Arrays.asList(listeners)); } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java index c3f4f03a6..8065161c8 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/SimpleConfigManager.java @@ -3,6 +3,7 @@ import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.FileDocument; import net.codingarea.commons.common.config.document.GsonDocument; +import net.codingarea.commons.common.config.document.PropertiesDocument; import net.codingarea.commons.common.config.document.YamlDocument; import net.codingarea.commons.common.misc.FileUtils; import org.jetbrains.annotations.NotNull; @@ -39,6 +40,8 @@ public static Class resolveType(@NotNull String extension) { case "yml": case "yaml": return YamlDocument.class; + case "properties": + return PropertiesDocument.class; default: throw new IllegalArgumentException("Unknown document file extension '" + extension + "'"); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java index bb39085d7..876ab3d32 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java @@ -12,13 +12,13 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; public class AnimatedInventory { private final List frames = new ArrayList<>(); - private final InventoryHolder holder; + private final Function sizeToNewInventory; private final int size; - private final String title; private SoundSample frameSound = SoundSample.CLICK, endSound = SoundSample.OPEN; private int frameDelay = 1; @@ -27,9 +27,13 @@ public AnimatedInventory(@NotNull String title, int size) { } public AnimatedInventory(@NotNull String title, int size, @Nullable InventoryHolder holder) { - this.title = title; this.size = size; - this.holder = holder; + this.sizeToNewInventory = forSize -> Bukkit.createInventory(holder, forSize, title); + } + + public AnimatedInventory(int size, @NotNull Function sizeToNewInventory) { + this.sizeToNewInventory = sizeToNewInventory; + this.size = size; } public void open(@NotNull Player player) { @@ -163,7 +167,7 @@ public AnimatedInventory setFrameDelay(int delay) { @NotNull private Inventory createInventory() { - return Bukkit.createInventory(holder, size, title); + return sizeToNewInventory.apply(size); } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/Document.java b/plugin/src/main/java/net/codingarea/commons/common/config/Document.java index c37ab9570..1f2ebdfd5 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/Document.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/Document.java @@ -263,7 +263,7 @@ static List parseJsonArray(@NotNull String jsonInput) { @NotNull @CheckReturnValue - static List parseStringArray(@NotNull String jsonInput) { + static List parseJsonStringArray(@NotNull String jsonInput) { return GsonDocument.convertArrayToStrings(GsonDocument.GSON.fromJson(jsonInput, JsonArray.class)); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java b/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java index 800d3c4ad..e878168b2 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java +++ b/plugin/src/main/java/net/codingarea/commons/common/config/document/GsonDocument.java @@ -54,11 +54,11 @@ public Number read(JsonReader in) throws IOException { case STRING: return new LazilyParsedNumber(in.nextString()); case BOOLEAN: - default: - throw new JsonSyntaxException("Expecting number, got: " + jsonToken); case NULL: in.nextNull(); return null; + default: + throw new JsonSyntaxException("Expecting number, got: " + jsonToken); } } }; @@ -99,7 +99,7 @@ public static List convertArrayToDocuments(@NotNull JsonArray array) { public static List convertArrayToStrings(@NotNull JsonArray array) { List list = new ArrayList<>(array.size()); for (JsonElement element : array) { - if (!element.isJsonObject()) continue; + if (!element.isJsonPrimitive()) continue; list.add(element.getAsString()); } return list; @@ -359,6 +359,12 @@ public void forEach(@NotNull BiConsumer action) @NotNull @Override public Collection keys() { + try { + // JsonObject#keySet was added in a later version + return jsonObject.keySet(); + } catch (Throwable ignored) { + } + Collection keys = new ArrayList<>(size()); for (Entry entry : jsonObject.entrySet()) { keys.add(entry.getKey()); diff --git a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java index e54c2765a..4b34dd996 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java +++ b/plugin/src/main/java/net/codingarea/commons/common/logging/ILogger.java @@ -15,7 +15,6 @@ import org.jetbrains.annotations.CheckReturnValue; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.slf4j.LoggerFactory; import java.io.PrintStream; import java.nio.charset.StandardCharsets; @@ -55,7 +54,7 @@ private static synchronized void createData() { } catch (ClassNotFoundException eService) { // there was no service provider interface (SLF4J 1.8.x+) try { // prints warning of missing implementation - LoggerFactory.getLogger(ILogger.class); + org.slf4j.LoggerFactory.getLogger(ILogger.class); } catch (NoClassDefFoundError eApi) { slf4jApi = false; } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java index 4a0f37c34..2e5ab8161 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/GsonUtils.java @@ -59,7 +59,6 @@ public static void convertJsonObjectToMap(@NotNull JsonObject object, @NotNull M } } - @NotNull public static List convertJsonArrayToStringList(@NotNull JsonArray array) { List list = new ArrayList<>(array.size()); diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java index d27ccb443..44a10f22c 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java @@ -115,14 +115,19 @@ public static Class getCaller() { } @NotNull - public static String getCallerName() { + public static String getCallerName(int skip) { StackTraceElement[] trace = Thread.currentThread().getStackTrace(); - StackTraceElement element = trace[3]; + StackTraceElement element = trace[3 + skip]; String className = StringUtils.getAfterLastIndex(element.getClassName(), "."); return className + "." + element.getMethodName(); } + @NotNull + public static String getCallerName() { + return getCallerName(1); + } + /** * Takes a {@link Enum} and returns the corresponding {@link Field} using {@link Class#getField(String)} * diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java index 457755a5d..24e150c1e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/StringUtils.java @@ -75,7 +75,7 @@ public static String format(@NotNull String sequence, @NotNull Object... args) { } builder.append(c); } - if (argument.length() > 0) builder.append(start).append(argument); + if (!argument.isEmpty()) builder.append(start).append(argument); return builder.toString(); } diff --git a/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java b/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java index f346a9a3a..c8990a668 100644 --- a/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java +++ b/plugin/src/main/java/net/codingarea/commons/database/abstraction/AbstractDatabase.java @@ -19,6 +19,7 @@ public AbstractDatabase(@NotNull DatabaseConfig config) { @Override public boolean disconnectSafely() { + if (!isConnected()) return true; try { disconnect(); LOGGER.info("Successfully closed connection to database of type " + this.getClass().getSimpleName()); From 6c6bdc019b6410f33d427803f3a0e1ea29a22d16 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Mon, 22 Jun 2026 19:11:50 +0200 Subject: [PATCH 097/119] feat: initial pass on message refactor [BREAKING] --- .github/workflows/build.yml | 4 +- build.gradle.kts | 9 +- gradle/libs.versions.toml | 13 + gradle/wrapper/gradle-wrapper.jar | Bin 60756 -> 45457 bytes gradle/wrapper/gradle-wrapper.properties | 2 +- gradlew | 50 +- gradlew.bat | 40 +- language/files/de.json | 420 ++++++++---- language/files/en.json | 2 +- language/files/global.json | 189 ++++++ language/languages.json | 1 + mongo-connector/build.gradle.kts | 4 +- platform/api/build.gradle.kts | 13 + .../platform/message/MessageHolder.java | 13 + .../platform/message/MessagePlatform.java | 66 ++ .../message/wrapper/MessageBossBar.java | 27 + platform/common/build.gradle.kts | 24 + .../common/AbstractMiniMessagePlatform.java | 331 +++++++++ .../common/BukkitTranslationKeyExtractor.java | 24 + .../message/common/ComponentSplitter.java | 85 +++ .../common/TranslatableComponents.java | 60 ++ .../wrapper/AdventureMessageBossBar.java | 73 ++ platform/legacy/build.gradle.kts | 62 ++ .../legacy/LegacyMiniMessagePlatform.java | 129 ++++ platform/paper/build.gradle.kts | 19 + .../paper/NativePaperMessagePlatform.java | 120 ++++ .../NativePaperMessagePlatformChecker.java | 30 + plugin/build.gradle.kts | 66 +- .../challenges/plugin/Challenges.java | 13 +- .../challenges/custom/CustomChallenge.java | 22 +- .../settings/ChallengeExecutionData.java | 3 +- .../custom/settings/CustomSettingsLoader.java | 2 +- .../settings/action/ChallengeAction.java | 10 +- .../settings/action/PlayerTargetAction.java | 3 +- .../action/impl/BoostEntityInAirAction.java | 4 +- .../action/impl/ChangeWorldBorderAction.java | 4 +- .../action/impl/DamageEntityAction.java | 4 +- .../action/impl/ExecuteCommandAction.java | 10 +- .../action/impl/HealEntityAction.java | 4 +- .../action/impl/HungerPlayerAction.java | 4 +- .../action/impl/ModifyMaxHealthAction.java | 4 +- .../action/impl/PlaceStructureAction.java | 2 +- .../custom/settings/sub/ValueSetting.java | 12 +- .../builder/ChooseItemSubSettingsBuilder.java | 6 +- .../ChooseMultipleItemSubSettingBuilder.java | 6 +- .../builder/GeneratorSubSettingsBuilder.java | 2 +- .../sub/builder/ValueSubSettingsBuilder.java | 16 +- .../settings/sub/impl/BooleanSetting.java | 6 +- .../settings/sub/impl/ModifierSetting.java | 12 +- .../settings/trigger/ChallengeTrigger.java | 7 +- .../trigger/impl/ConsumeItemTrigger.java | 4 +- .../trigger/impl/EntityDamageTrigger.java | 6 +- .../trigger/impl/InLiquidTrigger.java | 6 +- .../trigger/impl/IntervallTrigger.java | 24 +- .../challenge/DamageTeleportChallenge.java | 29 +- .../challenge/ZeroHeartsChallenge.java | 21 +- .../damage/AdvancementDamageChallenge.java | 27 +- .../damage/BlockBreakDamageChallenge.java | 28 +- .../damage/BlockPlaceDamageChallenge.java | 29 +- .../damage/DamagePerBlockChallenge.java | 29 +- .../damage/DamagePerItemChallenge.java | 14 +- .../damage/DeathOnFallChallenge.java | 14 +- .../damage/DelayDamageChallenge.java | 31 +- .../challenge/damage/FreezeChallenge.java | 25 +- .../challenge/damage/JumpDamageChallenge.java | 28 +- .../damage/ReversedDamageChallenge.java | 14 +- .../damage/SneakDamageChallenge.java | 28 +- .../damage/WaterAllergyChallenge.java | 29 +- .../effect/BlockEffectChallenge.java | 15 +- .../effect/ChunkRandomEffectChallenge.java | 15 +- .../effect/EntityRandomEffectChallenge.java | 15 +- .../challenge/effect/InfectionChallenge.java | 14 +- .../PermanentEffectOnDamageChallenge.java | 37 +- .../effect/RandomPotionEffectChallenge.java | 75 +-- .../entities/AllMobsToDeathPoint.java | 15 +- .../entities/BlockMobsChallenge.java | 14 +- .../entities/DupedSpawningChallenge.java | 14 +- .../entities/HydraNormalChallenge.java | 14 +- .../entities/HydraPlusChallenge.java | 14 +- .../entities/InvisibleMobsChallenge.java | 16 +- .../entities/MobSightDamageChallenge.java | 24 +- .../entities/MobTransformationChallenge.java | 13 +- .../entities/MobsRespawnInEndChallenge.java | 13 +- .../entities/NewEntityOnJumpChallenge.java | 16 +- .../entities/StoneSightChallenge.java | 14 +- .../extraworld/JumpAndRunChallenge.java | 43 +- .../extraworld/WaterMLGChallenge.java | 23 +- .../challenge/force/ForceBiomeChallenge.java | 28 +- .../challenge/force/ForceBlockChallenge.java | 28 +- .../challenge/force/ForceHeightChallenge.java | 28 +- .../challenge/force/ForceItemChallenge.java | 27 +- .../challenge/force/ForceMobChallenge.java | 28 +- .../DamageInventoryClearChallenge.java | 32 +- .../inventory/MissingItemsChallenge.java | 31 +- .../MovementItemRemovingChallenge.java | 30 +- .../inventory/NoDupedItemsChallenge.java | 16 +- .../inventory/PermanentItemChallenge.java | 14 +- .../inventory/PickupItemLaunchChallenge.java | 24 +- .../inventory/UncraftItemsChallenge.java | 31 +- .../miscellaneous/EnderGamesChallenge.java | 26 +- .../miscellaneous/FoodLaunchChallenge.java | 21 +- .../miscellaneous/FoodOnceChallenge.java | 40 +- .../miscellaneous/InvertHealthChallenge.java | 25 +- .../miscellaneous/LowDropRateChallenge.java | 23 +- .../miscellaneous/NoExpChallenge.java | 13 +- .../NoSharedAdvancementsChallenge.java | 11 +- .../miscellaneous/NoTradingChallenge.java | 11 +- .../miscellaneous/OneDurabilityChallenge.java | 10 +- .../movement/AlwaysRunningChallenge.java | 15 +- .../movement/DontStopRunningChallenge.java | 18 +- .../movement/FiveHundredBlocksChallenge.java | 24 +- .../movement/HigherJumpsChallenge.java | 14 +- .../movement/HungerPerBlockChallenge.java | 14 +- .../challenge/movement/MoveMouseDamage.java | 26 +- .../challenge/movement/OnlyDirtChallenge.java | 25 +- .../challenge/movement/OnlyDownChallenge.java | 15 +- .../movement/TrafficLightChallenge.java | 30 +- .../challenge/quiz/QuizChallenge.java | 32 +- .../randomizer/BlockRandomizerChallenge.java | 12 +- .../CraftingRandomizerChallenge.java | 13 +- .../EntityLootRandomizerChallenge.java | 29 +- .../randomizer/HotBarRandomizerChallenge.java | 27 +- .../randomizer/MobRandomizerChallenge.java | 12 +- .../randomizer/RandomChallengeChallenge.java | 26 +- .../randomizer/RandomEventChallenge.java | 26 +- .../randomizer/RandomItemChallenge.java | 26 +- .../RandomItemDroppingChallenge.java | 26 +- .../RandomItemRemovingChallenge.java | 26 +- .../RandomItemSwappingChallenge.java | 26 +- .../RandomTeleportOnHitChallenge.java | 15 +- .../randomizer/RandomizedHPChallenge.java | 50 +- .../challenge/time/MaxBiomeTimeChallenge.java | 26 +- .../time/MaxHeightTimeChallenge.java | 26 +- .../world/AllBlocksDisappearChallenge.java | 30 +- .../challenge/world/AnvilRainChallenge.java | 86 ++- .../challenge/world/BedrockPathChallenge.java | 16 +- .../challenge/world/BedrockWallChallenge.java | 24 +- .../world/BlockFlyInAirChallenge.java | 15 +- .../BlocksDisappearAfterTimeChallenge.java | 25 +- .../world/ChunkDeconstructionChallenge.java | 24 +- .../world/ChunkDeletionChallenge.java | 21 +- .../challenge/world/FloorIsLavaChallenge.java | 25 +- .../challenge/world/IceFloorChallenge.java | 12 +- .../challenge/world/LevelBorderChallenge.java | 15 +- .../challenge/world/LoopChallenge.java | 14 +- .../world/RepeatInChunkChallenge.java | 14 +- .../challenge/world/SnakeChallenge.java | 18 +- .../challenge/world/SurfaceHoleChallenge.java | 24 +- .../challenge/world/TsunamiChallenge.java | 26 +- .../damage/DamageRuleSetting.java | 15 +- .../goal/AllAdvancementGoal.java | 12 +- .../goal/CollectAllItemsGoal.java | 17 +- .../goal/CollectHorseAmorGoal.java | 15 +- .../goal/CollectIceBlocksGoal.java | 15 +- .../goal/CollectMostDeathsGoal.java | 19 +- .../goal/CollectMostExpGoal.java | 14 +- .../goal/CollectMostItemsGoal.java | 18 +- .../goal/CollectSwordsGoal.java | 14 +- .../implementation/goal/CollectWoodGoal.java | 39 +- .../goal/CollectWorkstationsGoal.java | 16 +- .../implementation/goal/EatCakeGoal.java | 14 +- .../implementation/goal/EatMostGoal.java | 20 +- .../implementation/goal/FindElytraGoal.java | 15 +- .../implementation/goal/FinishRaidGoal.java | 16 +- .../goal/FirstOneToDieGoal.java | 14 +- .../goal/GetFullHealthGoal.java | 20 +- .../goal/KillAllBossesGoal.java | 15 +- .../goal/KillAllBossesNewGoal.java | 17 +- .../implementation/goal/KillAllMobsGoal.java | 14 +- .../goal/KillAllMonsterGoal.java | 14 +- .../goal/KillElderGuardianGoal.java | 14 +- .../goal/KillEnderDragonGoal.java | 15 +- .../goal/KillIronGolemGoal.java | 14 +- .../goal/KillSnowGolemGoal.java | 14 +- .../implementation/goal/KillWardenGoal.java | 16 +- .../implementation/goal/KillWitherGoal.java | 14 +- .../goal/LastManStandingGoal.java | 9 +- .../implementation/goal/MaxHeightGoal.java | 14 +- .../implementation/goal/MinHeightGoal.java | 14 +- .../goal/MineMostBlocksGoal.java | 14 +- .../implementation/goal/MostEmeraldsGoal.java | 13 +- .../implementation/goal/MostOresGoal.java | 21 +- .../implementation/goal/RaceGoal.java | 41 +- .../forcebattle/ExtremeForceBattleGoal.java | 32 +- .../ForceAdvancementBattleGoal.java | 12 +- .../forcebattle/ForceBiomeBattleGoal.java | 12 +- .../forcebattle/ForceBlockBattleGoal.java | 20 +- .../forcebattle/ForceDamageBattleGoal.java | 11 +- .../forcebattle/ForceHeightBattleGoal.java | 12 +- .../goal/forcebattle/ForceItemBattleGoal.java | 20 +- .../goal/forcebattle/ForceMobBattleGoal.java | 11 +- .../forcebattle/ForcePositionBattleGoal.java | 28 +- .../material/BlockMaterialSetting.java | 19 +- .../setting/BackpackSetting.java | 38 +- .../setting/BastionSpawnSetting.java | 15 +- .../setting/CutCleanSetting.java | 55 +- .../setting/DamageDisplaySetting.java | 13 +- .../setting/DamageMultiplierModifier.java | 16 +- .../setting/DeathMessageSetting.java | 32 +- .../setting/DeathPositionSetting.java | 16 +- .../setting/DifficultySetting.java | 38 +- .../setting/EnderChestCommandSetting.java | 18 +- .../setting/FortressSpawnSetting.java | 12 +- .../setting/HealthDisplaySetting.java | 11 +- .../setting/ImmediateRespawnSetting.java | 11 +- .../setting/KeepInventorySetting.java | 12 +- .../setting/LanguageSetting.java | 27 +- .../setting/MaxHealthSetting.java | 17 +- .../setting/MobGriefingSetting.java | 11 +- .../setting/NoHitDelaySetting.java | 11 +- .../setting/NoHungerSetting.java | 11 +- .../setting/NoItemDamageSetting.java | 11 +- .../setting/NoOffhandSetting.java | 11 +- .../implementation/setting/OldPvPSetting.java | 11 +- .../setting/OneTeamLifeSetting.java | 11 +- .../setting/PlayerGlowSetting.java | 12 +- .../setting/PositionSetting.java | 62 +- .../setting/PregameMovementSetting.java | 11 +- .../implementation/setting/PvPSetting.java | 11 +- .../setting/RegenerationSetting.java | 39 +- .../setting/RespawnSetting.java | 11 +- .../setting/SlotLimitSetting.java | 27 +- .../implementation/setting/SoupSetting.java | 13 +- .../setting/SplitHealthSetting.java | 14 +- .../implementation/setting/TimberSetting.java | 29 +- .../setting/TopCommandSetting.java | 20 +- .../setting/TotemSaveDeathSetting.java | 11 +- .../challenges/type/EmptyChallenge.java | 98 --- .../plugin/challenges/type/IChallenge.java | 17 +- .../type/abstraction/AbstractChallenge.java | 134 ++-- .../abstraction/AbstractForceChallenge.java | 25 +- .../type/abstraction/CollectionGoal.java | 13 +- .../CompletableForceChallenge.java | 23 +- .../abstraction/EndingForceChallenge.java | 23 +- .../type/abstraction/FindItemGoal.java | 6 +- .../abstraction/FirstPlayerAtHeightGoal.java | 9 +- .../abstraction/ForceBattleDisplayGoal.java | 5 +- .../type/abstraction/ForceBattleGoal.java | 53 +- .../type/abstraction/HydraChallenge.java | 13 +- .../type/abstraction/ItemCollectionGoal.java | 18 +- .../type/abstraction/KillEntityGoal.java | 23 +- .../type/abstraction/KillMobsGoal.java | 9 +- .../type/abstraction/MenuSetting.java | 628 ------------------ .../challenges/type/abstraction/Modifier.java | 37 +- .../abstraction/ModifierCollectionGoal.java | 23 +- .../abstraction/NetherPortalSpawnSetting.java | 27 +- .../type/abstraction/OneEnabledSetting.java | 14 +- .../type/abstraction/PointsGoal.java | 12 +- .../type/abstraction/RandomizerSetting.java | 14 +- .../challenges/type/abstraction/Setting.java | 21 +- .../type/abstraction/SettingGoal.java | 11 +- .../type/abstraction/SettingModifier.java | 35 +- .../SettingModifierCollectionGoal.java | 36 +- .../type/abstraction/SettingModifierGoal.java | 22 +- .../type/abstraction/TimedChallenge.java | 43 +- .../abstraction/WorldDependentChallenge.java | 38 +- .../type/abstraction/{ => menu}/MenuGoal.java | 11 +- .../type/abstraction/menu/MenuSetting.java | 435 ++++++++++++ .../menu/SubSettingsMenuGenerator.java | 159 +++++ .../annotation}/CanInstaKillOnEnable.java | 2 +- .../type/annotation/ChallengeAnnotations.java | 6 +- .../ExcludeFromRandomChallenges.java | 2 +- .../type/annotation}/RequireVersion.java | 2 +- .../type/helper/ChallengeHelper.java | 30 +- .../type/helper/SubSettingsHelper.java | 44 +- .../plugin/content/ItemDescription.java | 1 + .../challenges/plugin/content/Message.java | 3 + .../challenges/plugin/content/Prefix.java | 67 -- .../plugin/content/i18n/LanguageProvider.java | 25 + .../content/i18n/LocalizableMessage.java | 28 + .../plugin/content/i18n/MessageKey.java | 286 ++++++++ .../plugin/content/i18n/Prefix.java | 42 ++ .../content/i18n/TranslationManager.java | 122 ++++ .../content/i18n/impl/MessageFormatter.java | 353 ++++++++++ .../content/i18n/impl/MessageKeyImpl.java | 356 ++++++++++ .../plugin/content/impl/MessageImpl.java | 12 +- .../plugin/content/impl/MessageManager.java | 9 +- .../plugin/content/loader/LanguageLoader.java | 180 ++--- .../plugin/content/loader/LoaderRegistry.java | 13 +- .../plugin/content/loader/PrefixLoader.java | 40 -- .../management/blocks/BlockDropManager.java | 2 +- .../management/bstats/MetricsLoader.java | 10 +- .../challenges/ChallengeLoader.java | 2 +- .../challenges/ChallengeManager.java | 7 +- .../challenges/CustomChallengesLoader.java | 19 +- .../challenges/ModuleChallengeLoader.java | 16 +- .../management/files/ConfigManager.java | 20 +- .../inventory/PlayerInventoryManager.java | 5 +- .../menu/InventoryTitleManager.java | 7 +- .../plugin/management/menu/MenuManager.java | 78 +-- .../plugin/management/menu/MenuType.java | 53 +- .../management/menu/SettingCategory.java | 75 +++ .../menu/generator/AbstractMenuGenerator.java | 183 +++++ .../menu/generator/IDynamicMenuGenerator.java | 19 + .../menu/generator/IMenuGenerator.java | 31 + .../generator/MultiPageMenuGenerator.java | 127 ++-- .../SingleAnimatedMenuGenerator.java | 70 ++ .../generator/SinglePageMenuGenerator.java | 84 +++ .../categorised/CategorisedMenuGenerator.java | 13 +- .../categorised/SettingCategory.java | 49 -- .../generator/impl/MainMenuGenerator.java | 92 +++ .../generator/impl/TimerMenuGenerator.java | 230 +++++++ .../challenge/ChallengeListMenuGenerator.java | 265 ++++++++ .../challenge/ChallengesMenuGenerator.java | 26 + .../CategorisedListMenuGenerator.java | 32 + .../categorised/CategorisedMenuGenerator.java | 227 +++++++ .../implementation/SettingsMenuGenerator.java | 2 +- .../implementation/TimerMenuGenerator.java | 227 ------- .../CustomMainSettingsMenuGenerator.java | 2 +- .../custom/InfoMenuGenerator.java | 37 +- .../custom/MainCustomMenuGenerator.java | 15 +- .../custom/MaterialMenuGenerator.java | 2 +- .../custom/SubSettingChooseMenuGenerator.java | 2 +- ...SubSettingChooseMultipleMenuGenerator.java | 2 +- .../custom/SubSettingValueMenuGenerator.java | 2 +- .../{ => legacy}/ChallengeMenuGenerator.java | 34 +- .../{ => legacy}/ChooseItemGenerator.java | 8 +- .../ChooseMultipleItemGenerator.java | 12 +- .../generator/{ => legacy}/MenuGenerator.java | 17 +- .../legacy/MultiPageMenuGenerator.java | 70 ++ .../{ => legacy}/ValueMenuGenerator.java | 8 +- ....java => LegacyGeneratorMenuPosition.java} | 6 +- .../scheduler/timer/ChallengeTimer.java | 57 +- .../scheduler/timer/TimerFormat.java | 2 + .../management/server/PlatformManager.java | 49 ++ .../management/server/ServerManager.java | 19 +- .../management/server/TitleManager.java | 11 +- .../management/server/WorldManager.java | 2 +- .../server/scoreboard/CBossBar.java | 16 + .../plugin/spigot/command/BackCommand.java | 7 +- .../spigot/command/ChallengesCommand.java | 10 +- .../spigot/command/DatabaseCommand.java | 22 +- .../plugin/spigot/command/FeedCommand.java | 10 +- .../plugin/spigot/command/FlyCommand.java | 12 +- .../spigot/command/GamemodeCommand.java | 14 +- .../spigot/command/GamestateCommand.java | 12 +- .../plugin/spigot/command/GodModeCommand.java | 12 +- .../plugin/spigot/command/HealCommand.java | 10 +- .../plugin/spigot/command/InvseeCommand.java | 16 +- .../spigot/command/LanguageCommand.java | 13 +- .../spigot/command/LeaderboardCommand.java | 19 +- .../plugin/spigot/command/ResetCommand.java | 9 +- .../plugin/spigot/command/ResultCommand.java | 8 +- .../plugin/spigot/command/SearchCommand.java | 14 +- .../plugin/spigot/command/StatsCommand.java | 19 +- .../plugin/spigot/command/TimeCommand.java | 23 +- .../plugin/spigot/command/TimerCommand.java | 16 +- .../plugin/spigot/command/VillageCommand.java | 10 +- .../plugin/spigot/command/WeatherCommand.java | 14 +- .../plugin/spigot/command/WorldCommand.java | 12 +- .../plugin/spigot/listener/CheatListener.java | 2 +- .../plugin/spigot/listener/HelpListener.java | 11 +- .../listener/PlayerConnectionListener.java | 40 +- .../utils/bukkit/command/PlayerCommand.java | 6 +- .../utils/bukkit/command/SenderCommand.java | 2 +- .../utils/bukkit/misc/BukkitStringUtils.java | 12 +- .../plugin/utils/item/DefaultItem.java | 54 +- .../plugin/utils/item/DefaultItems.java | 57 ++ .../plugin/utils/item/ItemBuilder.java | 390 +++++------ .../plugin/utils/item/LegacyItemBuilder.java | 401 +++++++++++ .../plugin/utils/misc/InventoryUtils.java | 14 +- .../utils/misc/MinecraftNameWrapper.java | 14 +- .../plugin/utils/misc/StatsHelper.java | 14 +- .../commons/bukkit/core/BukkitModule.java | 3 +- .../utils/animation/AnimationFrame.java | 8 +- .../bukkit/utils/animation/SoundSample.java | 8 +- ...mBuilder.java => StandardItemBuilder.java} | 175 ++--- .../utils/menu/MenuPositionListener.java | 3 +- .../commons/common/misc/ReflectionUtils.java | 2 +- plugin/src/main/resources/config.yml | 14 +- settings.gradle.kts | 1 + 371 files changed, 8110 insertions(+), 5103 deletions(-) create mode 100644 language/files/global.json create mode 100644 platform/api/build.gradle.kts create mode 100644 platform/api/src/main/java/net/codingarea/challenges/platform/message/MessageHolder.java create mode 100644 platform/api/src/main/java/net/codingarea/challenges/platform/message/MessagePlatform.java create mode 100644 platform/api/src/main/java/net/codingarea/challenges/platform/message/wrapper/MessageBossBar.java create mode 100644 platform/common/build.gradle.kts create mode 100644 platform/common/src/main/java/net/codingarea/challenges/platform/message/common/AbstractMiniMessagePlatform.java create mode 100644 platform/common/src/main/java/net/codingarea/challenges/platform/message/common/BukkitTranslationKeyExtractor.java create mode 100644 platform/common/src/main/java/net/codingarea/challenges/platform/message/common/ComponentSplitter.java create mode 100644 platform/common/src/main/java/net/codingarea/challenges/platform/message/common/TranslatableComponents.java create mode 100644 platform/common/src/main/java/net/codingarea/challenges/platform/message/common/wrapper/AdventureMessageBossBar.java create mode 100644 platform/legacy/build.gradle.kts create mode 100644 platform/legacy/src/main/java/net/codingarea/challenges/platform/message/legacy/LegacyMiniMessagePlatform.java create mode 100644 platform/paper/build.gradle.kts create mode 100644 platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatform.java create mode 100644 platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatformChecker.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java rename plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/{ => menu}/MenuGoal.java (71%) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/SubSettingsMenuGenerator.java rename plugin/src/main/java/net/codingarea/challenges/plugin/{management/challenges/annotations => challenges/type/annotation}/CanInstaKillOnEnable.java (77%) rename plugin/src/main/java/net/codingarea/challenges/plugin/{management/challenges/annotations => challenges/type/annotation}/ExcludeFromRandomChallenges.java (78%) rename plugin/src/main/java/net/codingarea/challenges/plugin/{management/challenges/annotations => challenges/type/annotation}/RequireVersion.java (84%) delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LanguageProvider.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/Prefix.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/TranslationManager.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageFormatter.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/SettingCategory.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IDynamicMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SingleAnimatedMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/TimerMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengesMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedListMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{ => legacy}/ChallengeMenuGenerator.java (85%) rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{ => legacy}/ChooseItemGenerator.java (95%) rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{ => legacy}/ChooseMultipleItemGenerator.java (93%) rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{ => legacy}/MenuGenerator.java (79%) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/MultiPageMenuGenerator.java rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{ => legacy}/ValueMenuGenerator.java (96%) rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/{GeneratorMenuPosition.java => LegacyGeneratorMenuPosition.java} (67%) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/server/PlatformManager.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/CBossBar.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/LegacyItemBuilder.java rename plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/{ItemBuilder.java => StandardItemBuilder.java} (61%) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0551ebff7..a900b45e1 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -19,10 +19,10 @@ jobs: - name: Checkout code uses: actions/checkout@v4 - - name: Set up JDK 17 + - name: Set up JDK 25 uses: actions/setup-java@v4 with: - java-version: '17' + java-version: '25' distribution: 'corretto' - name: Setup Gradle diff --git a/build.gradle.kts b/build.gradle.kts index b7f6c2343..2e109c434 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -11,13 +11,18 @@ allprojects { } } +var javaVersion = libs.versions.java.get() + subprojects { apply(plugin = "java-library") + group = "${project.group}${project.path.replace(":", ".")}" // hacky fix.. + extensions.configure("java") { - sourceCompatibility = JavaVersion.VERSION_16 - targetCompatibility = JavaVersion.VERSION_16 withSourcesJar() + toolchain { + languageVersion.set(JavaLanguageVersion.of(javaVersion)) + } } tasks.withType().configureEach { diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index d1dd7bec0..a82874719 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,9 +1,15 @@ [versions] +java = "25" + # minecraft spigot = "26.1.2-R0.1-SNAPSHOT" +paper = "26.1.2.build.+" authlib = "1.5.21" +adventure = "4.26.1" +adventure-bukkit = "4.4.1" + # utilities slf4j = "1.7.32" gson = "2.13.2" @@ -21,14 +27,20 @@ cloudnet2 = "2.1.17" # plugins shadow = "8.3.11" +jvmdowngrader = "1.3.6" [libraries] # minecraft spigot-api = { group = "org.spigotmc", name = "spigot-api", version.ref = "spigot" } +paper-api = { group = "io.papermc.paper", name = "paper-api", version.ref = "paper" } authlib = { group = "com.mojang", name = "authlib", version.ref = "authlib" } +adventure-text-minimessage = { module = "net.kyori:adventure-text-minimessage", version.ref = "adventure" } +adventure-text-serializer-legacy = { module = "net.kyori:adventure-text-serializer-legacy", version.ref = "adventure" } +adventure-platform-bukkit = { module = "net.kyori:adventure-platform-bukkit", version.ref = "adventure-bukkit" } + # utilities slf4j-api = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" } gson = { group = "com.google.code.gson", name = "gson", version.ref = "gson" } @@ -49,3 +61,4 @@ cloudnet2-bridge = { group = "de.dytanic.cloudnet", name = "cloudnet-api-bridge" [plugins] shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } +jvmdg = { id = "xyz.wagyourtail.jvmdowngrader", version.ref = "jvmdowngrader" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 249e5832f090a2944b7473328c07c9755baa3196..8bdaf60c75ab801e22807dde59e12a8735a34077 100644 GIT binary patch literal 45457 zcma&NW0YlEwk;ePwr$(aux;D69T}N{9ky*d!_2U4+qUuIRNZ#Jck8}7U+vcB{`IjNZqX3eq5;s6ddAkU&5{L|^Ow`ym2B0m+K02+~Q)i807X3X94qi>j)C0e$=H zm31v`=T&y}ACuKx7G~yWSYncG=NFB>O2);i9EmJ(9jSamq?Crj$g~1l3m-4M7;BWn zau2S&sSA0b0Rhg>6YlVLQa;D#)1yw+eGs~36Q$}5?avIRne3TQZXb<^e}?T69w<9~ zUmx1cG0uZ?Kd;Brd$$>r>&MrY*3$t^PWF1+J+G_xmpHW=>mly$<>~wHH+Bt3mzN7W zhR)g{_veH6>*KxLJ~~s{9HZm!UeC86d_>42NRqd$ev8zSMq4kt)q*>8kJ8p|^wuKx zq2Is_HJPoQ_apSoT?zJj7vXBp!xejBc^7F|zU0rhy%Ub*Dy#jJs!>1?CmJ-gulPVX zKit>RVmjL=G?>jytf^U@mfnC*1-7EVag@%ROu*#kA+)Rxq?MGK0v-dp^kM?nyMngb z_poL>GLThB7xAO*I7&?4^Nj`<@O@>&0M-QxIi zD@n}s%CYI4Be19C$lAb9Bbm6!R{&A;=yh=#fnFyb`s7S5W3?arZf?$khCwkGN!+GY~GT8-`!6pFr zbFBVEF`kAgtecfjJ`flN2Z!$$8}6hV>Tu;+rN%$X^t8fI>tXQnRn^$UhXO8Gu zt$~QON8`doV&{h}=2!}+xJKrNPcIQid?WuHUC-i%P^F(^z#XB`&&`xTK&L+i8a3a@ zkV-Jy;AnyQ`N=&KONV_^-0WJA{b|c#_l=v!19U@hS~M-*ix16$r01GN3#naZ|DxY2 z76nbjbOnFcx4bKbEoH~^=EikiZ)_*kOb>nW6>_vjf-UCf0uUy~QBb7~WfVO6qN@ns zz=XEG0s5Yp`mlmUad)8!(QDgIzY=OK%_hhPStbyYYd|~zDIc3J4 zy9y%wZOW>}eG4&&;Z>vj&Mjg+>4gL! z(@oCTFf-I^54t=*4AhKRoE-0Ky=qg3XK2Mu!Bmw@z>y(|a#(6PcfbVTw-dUqyx4x4 z3O#+hW1ANwSv-U+9otHE#U9T>(nWx>^7RO_aI>${jvfZQ{mUwiaxHau!H z0Nc}ucJu+bKux?l!dQ2QA(r@(5KZl(Or=U!=2K*8?D=ZT-IAcAX!5OI3w@`sF@$($ zbDk0p&3X0P%B0aKdijO|s})70K&mk1DC|P##b=k@fcJ|lo@JNWRUc>KL?6dJpvtSUK zxR|w8Bo6K&y~Bd}gvuz*3z z@sPJr{(!?mi@okhudaM{t3gp9TJ!|@j4eO1C&=@h#|QLCUKLaKVL z!lls$%N&ZG7yO#jK?U>bJ+^F@K#A4d&Jz4boGmptagnK!Qu{Ob>%+60xRYK>iffd_ z>6%0K)p!VwP$^@Apm%NrS6TpKJwj_Q=k~?4=_*NIe~eh_QtRaqX4t-rJAGYdB{pGq zSXX)-dR8mQ)X|;8@_=J6Dk7MfMp;x)^aZeCtScHs12t3vL+p-6!qhPkOM1OYQ z8YXW5tWp)Th(+$m7SnV_hNGKAP`JF4URkkNc@YV9}FK$9k zR&qgi$Cj#4bC1VK%#U)f%(+oQJ+EqvV{uAq1YG0riLvGxW@)m;*ayU-BSW61COFy0 z(-l>GJqYl;*x1PnRZ(p3Lm}* zlkpWyCoYtg9pAZ5RU^%w=vN{3Y<6WImxj(*SCcJsFj?o6CZ~>cWW^foliM#qN#We{ zwsL!u1$rzC1#4~bILZm*a!T{^kCci$XOJADm)P;y^%x5)#G#_!2uNp^S;cE`*ASCn;}H7pP^RRA z6lfXK(r4dy<_}R|(7%Lyo>QFP#s31E8zsYA${gSUykUV@?lyDNF=KhTeF^*lu7C*{ zBCIjy;bIE;9inJ$IT8_jL%)Q{7itmncYlkf2`lHl(gTwD%LmEPo^gskydVxMd~Do` zO8EzF!yn!r|BEgPjhW#>g(unY#n}=#4J;3FD2ThN5LpO0tI2~pqICaFAGT%%;3Xx$ z>~Ng(64xH-RV^Rj4=A_q1Ee8kcF}8HN{5kjYX0ADh}jq{q18x(pV!23pVsK5S}{M#p8|+LvfKx|_3;9{+6cu7%5o-+R@z>TlTft#kcJ`s2-j zUe4dgpInZU!<}aTGuwgdWJZ#8TPiV9QW<-o!ibBn&)?!ZDomECehvT7GSCRyF#VN2&5GShch9*}4p;8TX~cW*<#( zv-HmU7&+YUWO__NN3UbTFJ&^#3vxW4U9q5=&ORa+2M$4rskA4xV$rFSEYBGy55b{z z!)$_fYXiY?-GWDhGZXgTw}#ilrw=BiN(DGO*W7Vw(} zjUexksYLt_Nq?pl_nVa@c1W#edQKbT>VSN1NK?DulHkFpI-LXl7{;dl@z0#v?x%U& z8k8M1X6%TwR4BQ_eEWJASvMTy?@fQubBU__A_US567I-~;_VcX^NJ-E(ZPR^NASj1 zVP!LIf8QKtcdeH#w6ak50At)e={eF_Ns6J2Iko6dn8Qwa6!NQHZMGsD zhzWeSFK<{hJV*!cIHxjgR+e#lkUHCss-j)$g zF}DyS531TUXKPPIoePo{yH%qEr-dLMOhv^sC&@9YI~uvl?rBp^A-57{aH_wLg0&a|UxKLlYZQ24fpb24Qjil`4OCyt0<1eu>5i1Acv zaZtQRF)Q;?Aw3idg;8Yg9Cb#)03?pQ@O*bCloG zC^|TnJl`GXN*8iI;Ql&_QIY0ik}rqB;cNZ-qagp=qmci9eScHsRXG$zRNdf4SleJ} z7||<#PCW~0>3u8PP=-DjNhD(^(B0AFF+(oKOiQyO5#v4nI|v_D5@c2;zE`}DK!%;H zUn|IZ6P;rl*5`E(srr6@-hpae!jW=-G zC<*R?RLwL;#+hxN4fJ!oP4fX`vC3&)o!#l4y@MrmbmL{t;VP%7tMA-&vju_L zhtHbOL4`O;h*5^e3F{b9(mDwY6JwL8w`oi28xOyj`pVo!75hngQDNg7^D$h4t&1p2 ziWD_!ap3GM(S)?@UwWk=Szym^eDxSx3NaR}+l1~(@0car6tfP#sZRTb~w!WAS{+|SgUN3Tv`J4OMf z9ta_f>-`!`I@KA=CXj_J>CE7T`yGmej0}61sE(%nZa1WC_tV6odiysHA5gzfWN-`uXF46mhJGLpvNTBmx$!i zF67bAz~E|P{L6t1B+K|Cutp&h$fDjyq9JFy$7c_tB(Q$sR)#iMQH3{Og1AyD^lyQwX6#B|*ecl{-_;*B>~WSFInaRE_q6 zpK#uCprrCb`MU^AGddA#SS{P7-OS9h%+1`~9v-s^{s8faWNpt*Pmk_ECjt(wrpr{C_xdAqR(@!ERTSs@F%^DkE@No}wqol~pS^e7>ksF_NhL0?6R4g`P- zk8lMrVir~b(KY+hk5LQngwm`ZQT5t1^7AzHB2My6o)_ejR0{VxU<*r-Gld`l6tfA` zKoj%x9=>Ce|1R|1*aC}|F0R32^KMLAHN}MA<8NNaZ^j?HKxSwxz`N2hK8lEb{jE0& zg4G_6F@#NyDN?=i@=)eidKhlg!nQoA{`PgaH{;t|M#5z}a`u?^gy{5L~I2smLR z*4RmNxHqf9>D>sXSemHK!h4uPwMRb+W`6F>Q6j@isZ>-F=)B2*sTCD9A^jjUy)hjAw71B&$u}R(^R; zY9H3k8$|ounk>)EOi_;JAKV8U8ICSD@NrqB!&=)Ah_5hzp?L9Sw@c>>#f_kUhhm=p z1jRz8X7)~|VwO(MF3PS(|CL++1n|KT3*dhGjg!t_vR|8Yg($ z+$S$K=J`K6eG#^(J54=4&X#+7Car=_aeAuC>dHE+%v9HFu>r%ry|rwkrO-XPhR_#K zS{2Unv!_CvS7}Mb6IIT$D4Gq5v$Pvi5nbYB+1Yc&RY;3;XDihlvhhIG6AhAHsBYsm zK@MgSzs~y|+f|j-lsXKT0(%E2SkEb)p+|EkV5w8=F^!r1&0#0^tGhf9yPZ)iLJ^ zIXOg)HW_Vt{|r0W(`NmMLF$?3ZQpq+^OtjR-DaVLHpz%1+GZ7QGFA?(BIqBlVQ;)k zu)oO|KG&++gD9oL7aK4Zwjwi~5jqk6+w%{T$1`2>3Znh=OFg|kZ z>1cn>CZ>P|iQO%-Pic8wE9c*e%=3qNYKJ+z1{2=QHHFe=u3rqCWNhV_N*qzneN8A5 zj`1Ir7-5`33rjDmyIGvTx4K3qsks(I(;Kgmn%p#p3K zn8r9H8kQu+n@D$<#RZtmp$*T4B&QvT{K&qx(?>t@mX%3Lh}sr?gI#vNi=vV5d(D<=Cp5-y!a{~&y|Uz*PU{qe zI7g}mt!txT)U(q<+Xg_sSY%1wVHy;Dv3uze zJ>BIdSB2a|aK+?o63lR8QZhhP)KyQvV`J3)5q^j1-G}fq=E4&){*&hiam>ssYm!ya z#PsY0F}vT#twY1mXkGYmdd%_Uh12x0*6lN-HS-&5XWbJ^%su)-vffvKZ%rvLHVA<; zJP=h13;x?$v30`T)M)htph`=if#r#O5iC^ZHeXc6J8gewn zL!49!)>3I-q6XOZRG0=zjyQc`tl|RFCR}f-sNtc)I^~?Vv2t7tZZHvgU2Mfc9$LqG z!(iz&xb=q#4otDBO4p)KtEq}8NaIVcL3&pbvm@0Kk-~C@y3I{K61VDF_=}c`VN)3P z+{nBy^;=1N`A=xH$01dPesY_na*zrcnssA}Ix60C=sWg9EY=2>-yH&iqhhm28qq9Z z;}znS4ktr40Lf~G@6D5QxW&?q^R|=1+h!1%G4LhQs54c2Wo~4% zCA||d==lv2bP=9%hd0Dw_a$cz9kk)(Vo}NpSPx!vnV*0Bh9$CYP~ia#lEoLRJ8D#5 zSJS?}ABn1LX>8(Mfg&eefX*c0I5bf4<`gCy6VC{e>$&BbwFSJ0CgVa;0-U7=F81R+ zUmzz&c;H|%G&mSQ0K16Vosh?sjJW(Gp+1Yw+Yf4qOi|BFVbMrdO6~-U8Hr|L@LHeZ z0ALmXHsVm137&xnt#yYF$H%&AU!lf{W436Wq87nC16b%)p?r z70Wua59%7Quak50G7m3lOjtvcS>5}YL_~?Pti_pfAfQ!OxkX$arHRg|VrNx>R_Xyi z`N|Y7KV`z3(ZB2wT9{Dl8mtl zg^UOBv~k>Z(E)O>Z;~Z)W&4FhzwiPjUHE9&T#nlM)@hvAZL>cha-< zQ8_RL#P1?&2Qhk#c9fK9+xM#AneqzE-g(>chLp_Q2Xh$=MAsW z2ScEKr+YOD*R~mzy{bOJjs;X2y1}DVFZi7d_df^~((5a2%p%^4cf>vM_4Sn@@ssVJ z9ChGhs zbanJ+h74)3tWOviXI|v!=HU2mE%3Th$Mpx&lEeGFEBWRy8ogJY`BCXj@7s~bjrOY! z4nIU5S>_NrpN}|waZBC)$6ST8x91U2n?FGV8lS{&LFhHbuHU?SVU{p7yFSP_f#Eyh zJhI@o9lAeEwbZYC=~<(FZ$sJx^6j@gtl{yTOAz`Gj!Ab^y})eG&`Qt2cXdog2^~oOH^K@oHcE(L;wu2QiMv zJuGdhNd+H{t#Tjd<$PknMSfbI>L1YIdZ+uFf*Z=BEM)UPG3oDFe@8roB0h(*XAqRc zoxw`wQD@^nxGFxQXN9@GpkLqd?9@(_ZRS@EFRCO8J5{iuNAQO=!Lo5cCsPtt4=1qZN8z`EA2{ge@SjTyhiJE%ttk{~`SEl%5>s=9E~dUW0uws>&~3PwXJ!f>ShhP~U9dLvE8ElNt3g(6-d zdgtD;rgd^>1URef?*=8BkE&+HmzXD-4w61(p6o~Oxm`XexcHmnR*B~5a|u-Qz$2lf zXc$p91T~E4psJxhf^rdR!b_XmNv*?}!PK9@-asDTaen;p{Rxsa=1E}4kZ*}yQPoT0 zvM}t!CpJvk<`m~^$^1C^o1yM(BzY-Wz2q7C^+wfg-?}1bF?5Hk?S{^#U%wX4&lv0j zkNb)byI+nql(&65xV?_L<0tj!KMHX8Hmh2(udEG>@OPQ}KPtdwEuEb$?acp~yT1&r z|7YU<(v!0as6Xff5^XbKQIR&MpjSE)pmub+ECMZzn7c!|hnm_Rl&H_oXWU2!h7hhf zo&-@cLkZr#eNgUN9>b=QLE1V^b`($EX3RQIyg#45A^=G!jMY`qJ z8qjZ$*-V|?y0=zIM>!2q!Gi*t4J5Otr^OT3XzQ_GjATc(*eM zqllux#QtHhc>YtnswBNiS^t(dTDn|RYSI%i%-|sv1wh&|9jfeyx|IHowW)6uZWR<%n8I}6NidBm zJ>P7#5m`gnXLu;?7jQZ!PwA80d|AS*+mtrU6z+lzms6^vc4)6Zf+$l+Lk3AsEK7`_ zQ9LsS!2o#-pK+V`g#3hC$6*Z~PD%cwtOT8;7K3O=gHdC=WLK-i_DjPO#WN__#YLX|Akw3LnqUJUw8&7pUR;K zqJ98?rKMXE(tnmT`#080w%l1bGno7wXHQbl?QFU=GoK@d!Ov=IgsdHd-iIs4ahcgSj(L@F96=LKZ zeb5cJOVlcKBudawbz~AYk@!^p+E=dT^UhPE`96Q5J~cT-8^tp`J43nLbFD*Nf!w;6 zs>V!5#;?bwYflf0HtFvX_6_jh4GEpa0_s8UUe02@%$w^ym&%wI5_APD?9S4r9O@4m zq^Z5Br8#K)y@z*fo08@XCs;wKBydn+60ks4Z>_+PFD+PVTGNPFPg-V-|``!0l|XrTyUYA@mY?#bJYvD>jX&$o9VAbo?>?#Z^c+Y4Dl zXU9k`s74Sb$OYh7^B|SAVVz*jEW&GWG^cP<_!hW+#Qp|4791Od=HJcesFo?$#0eWD z8!Ib_>H1WQE}shsQiUNk!uWOyAzX>r(-N7;+(O333_ES7*^6z4{`p&O*q8xk{0xy@ zB&9LkW_B}_Y&?pXP-OYNJfqEWUVAPBk)pTP^;f+75Wa(W>^UO_*J05f1k{ zd-}j!4m@q#CaC6mLsQHD1&7{tJ*}LtE{g9LB>sIT7)l^ucm8&+L0=g1E_6#KHfS>A_Z?;pFP96*nX=1&ejZ+XvZ=ML`@oVu>s^WIjn^SY}n zboeP%`O9|dhzvnw%?wAsCw*lvVcv%bmO5M4cas>b%FHd;A6Z%Ej%;jgPuvL$nk=VQ=$-OTwslYg zJQtDS)|qkIs%)K$+r*_NTke8%Rv&w^v;|Ajh5QXaVh}ugccP}3E^(oGC5VO*4`&Q0 z&)z$6i_aKI*CqVBglCxo#9>eOkDD!voCJRFkNolvA2N&SAp^4<8{Y;#Kr5740 za|G`dYGE!9NGU3Ge6C)YByb6Wy#}EN`Ao#R!$LQ&SM#hifEvZp>1PAX{CSLqD4IuO z4#N4AjMj5t2|!yTMrl5r)`_{V6DlqVeTwo|tq4MHLZdZc5;=v9*ibc;IGYh+G|~PB zx2}BAv6p$}?7YpvhqHu7L;~)~Oe^Y)O(G(PJQB<&2AhwMw!(2#AHhjSsBYUd8MDeM z+UXXyV@@cQ`w}mJ2PGs>=jHE{%i44QsPPh(=yorg>jHic+K+S*q3{th6Ik^j=@%xo zXfa9L_<|xTL@UZ?4H`$vt9MOF`|*z&)!mECiuenMW`Eo2VE#|2>2ET7th6+VAmU(o zq$Fz^TUB*@a<}kr6I>r;6`l%8NWtVtkE?}Q<<$BIm*6Z(1EhDtA29O%5d1$0q#C&f zFhFrrss{hOsISjYGDOP*)j&zZUf9`xvR8G)gwxE$HtmKsezo`{Ta~V5u+J&Tg+{bh zhLlNbdzJNF6m$wZNblWNbP6>dTWhngsu=J{);9D|PPJ96aqM4Lc?&6H-J1W15uIpQ ziO{&pEc2}-cqw+)w$`p(k(_yRpmbp-Xcd`*;Y$X=o(v2K+ISW)B1(ZnkV`g4rHQ=s z+J?F9&(||&86pi}snC07Lxi1ja>6kvnut;|Ql3fD)%k+ASe^S|lN69+Ek3UwsSx=2EH)t}K>~ z`Mz-SSVH29@DWyl`ChuGAkG>J;>8ZmLhm>uEmUvLqar~vK3lS;4s<{+ehMsFXM(l- zRt=HT>h9G)JS*&(dbXrM&z;)66C=o{=+^}ciyt8|@e$Y}IREAyd_!2|CqTg=eu}yG z@sI9T;Tjix*%v)c{4G84|0j@8wX^Iig_JsPU|T%(J&KtJ>V zsAR+dcmyT5k&&G{!)VXN`oRS{n;3qd`BgAE9r?%AHy_Gf8>$&X$=>YD7M911?<{qX zkJ;IOfY$nHdy@kKk_+X%g3`T(v|jS;>`pz`?>fqMZ>Fvbx1W=8nvtuve&y`JBfvU~ zr+5pF!`$`TUVsx3^<)48&+XT92U0DS|^X6FwSa-8yviRkZ*@Wu|c*lX!m?8&$0~4T!DB0@)n}ey+ew}T1U>|fH3=W5I!=nfoNs~OkzTY7^x^G&h>M7ewZqmZ=EL0}3#ikWg+(wuoA{7hm|7eJz zNz78l-K81tP16rai+fvXtspOhN-%*RY3IzMX6~8k9oFlXWgICx9dp;`)?Toz`fxV@&m8< z{lzWJG_Y(N1nOox>yG^uDr}kDX_f`lMbtxfP`VD@l$HR*B(sDeE(+T831V-3d3$+% zDKzKnK_W(gLwAK{Saa2}zaV?1QmcuhDu$)#;*4gU(l&rgNXB^WcMuuTki*rt>|M)D zoI;l$FTWIUp}euuZjDidpVw6AS-3dal2TJJaVMGj#CROWr|;^?q>PAo2k^u-27t~v zCv10IL~E)o*|QgdM!GJTaT&|A?oW)m9qk2{=y*7qb@BIAlYgDIe)k(qVH@)#xx6%7 z@)l%aJwz5Joc84Q2jRp71d;=a@NkjSdMyN%L6OevML^(L0_msbef>ewImS=+DgrTk z4ON%Y$mYgcZ^44O*;ctP>_7=}=pslsu>~<-bw=C(jeQ-X`kUo^BS&JDHy%#L32Cj_ zXRzDCfCXKXxGSW9yOGMMOYqPKnU zTF6gDj47!7PoL%z?*{1eyc2IVF*RXX?mj1RS}++hZg_%b@6&PdO)VzvmkXxJ*O7H} z6I7XmJqwX3<>z%M@W|GD%(X|VOZ7A+=@~MxMt8zhDw`yz?V>H%C0&VY+ZZ>9AoDVZeO1c~z$r~!H zA`N_9p`X?z>jm!-leBjW1R13_i2(0&aEY2$l_+-n#powuRO;n2Fr#%jp{+3@`h$c< zcFMr;18Z`UN#spXv+3Ks_V_tSZ1!FY7H(tdAk!v}SkoL9RPYSD3O5w>A3%>7J+C-R zZfDmu=9<1w1CV8rCMEm{qyErCUaA3Q zRYYw_z!W7UDEK)8DF}la9`}8z*?N32-6c-Bwx^Jf#Muwc67sVW24 zJ4nab%>_EM8wPhL=MAN)xx1tozAl zmhXN;*-X%)s>(L=Q@vm$qmuScku>PV(W_x-6E?SFRjSk)A1xVqnml_92fbj0m};UC zcV}lRW-r*wY106|sshV`n#RN{)D9=!>XVH0vMh>od=9!1(U+sWF%#B|eeaKI9RpaW z8Ol_wAJX%j0h5fkvF)WMZ1}?#R(n-OT0CtwsL)|qk;*(!a)5a5ku2nCR9=E*iOZ`9 zy4>LHKt-BgHL@R9CBSG!v4wK zvjF8DORRva)@>nshE~VM@i2c$PKw?3nz(6-iVde;-S~~7R<5r2t$0U8k2_<5C0!$j zQg#lsRYtI#Q1YRs(-%(;F-K7oY~!m&zhuU4LL}>jbLC>B`tk8onRRcmIm{{0cpkD|o@Ixu#x9Wm5J)3oFkbfi62BX8IX1}VTe#{C(d@H|#gy5#Sa#t>sH@8v1h8XFgNGs?)tyF_S^ueJX_-1%+LR`1X@C zS3Oc)o)!8Z9!u9d!35YD^!aXtH;IMNzPp`NS|EcdaQw~<;z`lmkg zE|tQRF7!S!UCsbag%XlQZXmzAOSs= zIUjgY2jcN9`xA6mzG{m|Zw=3kZC4@XY=Bj%k8%D&iadvne$pYNfZI$^2BAB|-MnZW zU4U?*qE3`ZDx-bH})>wz~)a z_SWM!E=-BS#wdrfh;EfPNOS*9!;*+wp-zDthj<>P0a2n?$xfe;YmX~5a;(mNV5nKx zYR86%WtAPsOMIg&*o9uUfD!v&4(mpS6P`bFohPP<&^fZzfA|SvVzPQgbtwwM>IO>Z z75ejU$1_SB1tn!Y-9tajZ~F=Fa~{cnj%Y|$;%z6fJV1XC0080f)Pj|87j142q6`i>#)BCIi+x&jAH9|H#iMvS~?w;&E`y zoarJ)+5HWmZ{&OqlzbdQU=SE3GKmnQq zI{h6f$C@}Mbqf#JDsJyi&7M0O2ORXtEB`#cZ;#AcB zkao0`&|iH8XKvZ_RH|VaK@tAGKMq9x{sdd%p-o`!cJzmd&hb86N!KKxp($2G?#(#BJn5%hF0(^`= z2qRg5?82({w-HyjbffI>eqUXavp&|D8(I6zMOfM}0;h%*D_Dr@+%TaWpIEQX3*$vQ z8_)wkNMDi{rW`L+`yN^J*Gt(l7PExu3_hrntgbW0s}7m~1K=(mFymoU87#{|t*fJ?w8&>Uh zcS$Ny$HNRbT!UCFldTSp2*;%EoW+yhJD8<3FUt8@XSBeJM2dSEz+5}BWmBvdYK(OA zlm`nDDsjKED{$v*jl(&)H7-+*#jWI)W|_X)!em1qpjS_CBbAiyMt;tx*+0P%*m&v< zxV9rlslu8#cS!of#^1O$(ds8aviMFiT`6W+FzMHW{YS+SieJ^?TQb%NT&pasw^kbc znd`=%(bebvrNx3#7vq@vAX-G`4|>cY0svIXopH02{v;GZ{wJM#psz4!m8(IZu<)9D zqR~U7@cz-6H{724_*}-DWwE8Sk+dYBb*O-=c z+wdchFcm6$$^Z0_qGnv0P`)h1=D$_eg8!2-|7Y;o*c)4ax!Me0*EVcioh{wI#!qcb z1&xhOotXMrlo7P6{+C8m;E#4*=8(2y!r0d<6 zKi$d2X;O*zS(&Xiz_?|`ympxITf|&M%^WHp=694g6W@k+BL_T1JtSYX0OZ}o%?Pzu zJ{%P8A$uq?4F!NWGtq>_GLK3*c6dIcGH)??L`9Av&0k$A*14ED9!e9z_SZd3OH6ER zg%5^)3^gw;4DFw(RC;~r`bPJOR}H}?2n60=g4ESUTud$bkBLPyI#4#Ye{5x3@Yw<* z;P5Up>Yn(QdP#momCf=kOzZYzg9E330=67WOPbCMm2-T1%8{=or9L8+HGL{%83lri zODB;Y|LS`@mn#Wmez7t6-x`a2{}U9hE|xY7|BVcFCqoAZQzsEi=dYHB z(bqG3J5?teVSBqTj{aiqe<9}}CEc$HdsJSMp#I;4(EXRy_k|Y8X#5hwkqAaIGKARF zX?$|UO{>3-FU;IlFi80O^t+WMNw4So2nsg}^T1`-Ox&C%Gn_AZ-49Nir=2oYX6 z`uVke@L5PVh)YsvAgFMZfKi{DuSgWnlAaag{RN6t6oLm6{4)H~4xg#Xfcq-e@ALk& z@UP4;uCe(Yjg4jaJZ4pu*+*?4#+XCi%sTrqaT*jNY7|WQ!oR;S8nt)cI27W$Sz!94 z01zoTW`C*P3E?1@6thPe(QpIue$A54gp#C7pmfwRj}GxIw$!!qQetn`nvuwIvMBQ; zfF8K-D~O4aJKmLbNRN1?AZsWY&rp?iy`LP^3KT0UcGNy=Z@7qVM(#5u#Du#w>a&Bs z@f#zU{wk&5n!YF%D11S9*CyaI8%^oX=vq$Ei9cL1&kvv9|8vZD;Mhs1&slm`$A%ED zvz6SQ8aty~`IYp2Xd~G$z%Jf4zwVPKkCtqObrnc2gHKj^jg&-NH|xdNK_;+2d4ZXw zN9j)`jcp7y65&6P@}LsD_OLSi(#GW#hC*qF5KpmeXuQDNS%ZYpuW<;JI<>P6ln!p@ z>KPAM>8^cX|2!n@tV=P)f2Euv?!}UM`^RJ~nTT@W>KC2{{}xXS{}WH{|3najkiEUj z7l;fUWDPCtzQ$?(f)6RvzW~Tqan$bXibe%dv}**BqY!d4J?`1iX`-iy8nPo$s4^mQ z5+@=3xuZAl#KoDF*%>bJ4UrEB2EE8m7sQn!r7Z-ggig`?yy`p~3;&NFukc$`_>?}a z?LMo2LV^n>m!fv^HKKRrDn|2|zk?~S6i|xOHt%K(*TGWkq3{~|9+(G3M-L=;U-YRa zp{kIXZ8P!koE;BN2A;nBx!={yg4v=-xGOMC#~MA07zfR)yZtSF_2W^pDLcXg->*WD zY7Sz5%<_k+lbS^`y)=vX|KaN!gEMQob|(`%nP6huwr$%^?%0^vwr$(CZQD*Jc5?E( zb-q9E`OfoWSJ$rUs$ILfSFg3Mb*-!Ozgaz^%7ZkX@=3km0G;?+e?FQT_l5A9vKr<> z_CoemDo@6YIyl57l*gnJ^7+8xLW5oEGzjLv2P8vj*Q%O1^KOfrsC6eHvk{+$BMLGu z%goP8UY?J7Lj=@jcI$4{m2Sw?1E%_0C7M$lj}w{E#hM4%3QX|;tH6>RJf-TI_1A0w z@KcTEFx(@uitbo?UMMqUaSgt=n`Bu*;$4@cbg9JIS})3#2T;B7S

Z?HZkSa`=MM?n)?|XcM)@e1qmzJ$_4K^?-``~Oi&38`2}sjmP?kK z$yT)K(UU3fJID@~3R;)fU%k%9*4f>oq`y>#t90$(y*sZTzWcW$H=Xv|%^u^?2*n)Csx;35O0v7Nab-REgxDZNf5`cI69k$` zx(&pP6zVxlK5Apn5hAhui}b)(IwZD}D?&)_{_yTL7QgTxL|_X!o@A`)P#!%t9al+# zLD(Rr+?HHJEOl545~m1)cwawqY>cf~9hu-L`crI^5p~-9Mgp9{U5V&dJSwolnl_CM zwAMM1Tl$D@>v?LN2PLe0IZrQL1M zcA%i@Lc)URretFJhtw7IaZXYC6#8slg|*HfUF2Z5{3R_tw)YQ94=dprT`SFAvHB+7 z)-Hd1yE8LB1S+4H7iy$5XruPxq6pc_V)+VO{seA8^`o5{T5s<8bJ`>I3&m%R4cm1S z`hoNk%_=KU2;+#$Y!x7L%|;!Nxbu~TKw?zSP(?H0_b8Qqj4EPrb@~IE`~^#~C%D9k zvJ=ERh`xLgUwvusQbo6S=I5T+?lITYsVyeCCwT9R>DwQa&$e(PxF<}RpLD9Vm2vV# zI#M%ksVNFG1U?;QR{Kx2sf>@y$7sop6SOnBC4sv8S0-`gEt0eHJ{`QSW(_06Uwg*~ zIw}1dZ9c=K$a$N?;j`s3>)AqC$`ld?bOs^^stmYmsWA$XEVhUtGlx&OyziN1~2 z)s5fD(d@gq7htIGX!GCxKT=8aAOHW&DAP=$MpZ)SpeEZhk83}K) z0(Uv)+&pE?|4)D2PX4r6gOGHDY}$8FSg$3eDb*nEVmkFQ#lFpcH~IPeatiH3nPTkP z*xDN7l}r2GM9jwSsl=*!547nRPCS0pb;uE#myTqV+=se>bU=#e)f2}wCp%f-cIrh`FHA$2`monVy?qvJ~o2B6I7IE28bCY4=c#^){*essLG zXUH50W&SWmi{RIG9G^p;PohSPtC}djjXSoC)kyA8`o+L}SjE{i?%;Vh=h;QC{s`T7 zLmmHCr8F}#^O8_~lR)^clv$mMe`e*{MW#Sxd`rDckCnFBo9sC*vw2)dA9Q3lUi*Fy zgDsLt`xt|7G=O6+ms=`_FpD4}37uvelFLc^?snyNUNxbdSj2+Mpv<67NR{(mdtSDNJ3gSD@>gX_7S5 zCD)JP5Hnv!llc-9fwG=4@?=%qu~(4j>YXtgz%gZ#+A9i^H!_R!MxWlFsH(ClP3dU} za&`m(cM0xebj&S170&KLU%39I+XVWOJ_1XpF^ip}3|y()Fn5P@$pP5rvtiEK6w&+w z7uqIxZUj$#qN|<_LFhE@@SAdBy8)xTu>>`xC>VYU@d}E)^sb9k0}YKr=B8-5M?3}d z7&LqQWQ`a&=ihhANxe3^YT>yj&72x#X4NXRTc#+sk;K z=VUp#I(YIRO`g7#;5))p=y=MQ54JWeS(A^$qt>Y#unGRT$0BG=rI(tr>YqSxNm+-x z6n;-y8B>#FnhZX#mhVOT30baJ{47E^j-I6EOp;am;FvTlYRR2_?CjCWY+ypoUD-2S zqnFH6FS+q$H$^7>>(nd^WE+?Zn#@HU3#t|&=JnEDgIU+;CgS+krs+Y8vMo6U zHVkPoReZ-Di3z!xdBu#aW1f{8sC)etjN90`2|Y@{2=Os`(XLL9+ z1$_PE$GgTQrVx`^sx=Y(_y-SvquMF5<`9C=vM52+e+-r=g?D z+E|97MyoaK5M^n1(mnWeBpgtMs8fXOu4Q$89C5q4@YY0H{N47VANA1}M2e zspor6LdndC=kEvxs3YrPGbc;`q}|zeg`f;t3-8na)dGdZ9&d(n{|%mNaHaKJOA~@8 zgP?nkzV-=ULb)L3r`p)vj4<702a5h~Y%byo4)lh?rtu1YXYOY+qyTwzs!59I zL}XLe=q$e<+Wm7tvB$n88#a9LzBkgHhfT<&i#%e*y|}@I z!N~_)vodngB7%CI2pJT*{GX|cI5y>ZBN)}mezK~fFv@$*L`84rb0)V=PvQ2KN}3lTpT@$>a=CP?kcC0S_^PZ#Vd9#CF4 zP&`6{Y!hd^qmL!zr#F~FB0yag-V;qrmW9Jnq~-l>Sg$b%%TpO}{Q+*Pd-@n2suVh_ zSYP->P@# z&gQ^f{?}m(u5B9xqo63pUvDsJDQJi5B~ak+J{tX8$oL!_{Dh zL@=XFzWb+83H3wPbTic+osVp&~UoW3SqK0#P6+BKbOzK65tz)-@AW#g}Ew+pE3@ zVbdJkJ}EM@-Ghxp_4a)|asEk* z5)mMI&EK~BI^aaTMRl)oPJRH^Ld{;1FC&#pS`gh;l3Y;DF*`pR%OSz8U@B@zJxPNX zwyP_&8GsQ7^eYyUO3FEE|9~I~X8;{WTN=DJW0$2OH=3-!KZG=X6TH?>URr(A0l@+d zj^B9G-ACel;yYGZc}G`w9sR$Mo{tzE7&%XKuW$|u7DM<6_z}L>I{o`(=!*1 z{5?1p3F^aBONr6Ws!6@G?XRxJxXt_6b}2%Bp=0Iv5ngnpU^P+?(?O0hKwAK z*|wAisG&8&Td1XY+6qI~-5&+4DE2p|Dj8@do;!40o)F)QuoeUY;*I&QZ0*4?u)$s`VTkNl1WG`}g@J_i zjjmv4L%g&>@U9_|l>8^CN}`@4<D2aMN&?XXD-HNnsVM`irjv$ z^YVNUx3r1{-o6waQfDp=OG^P+vd;qEvd{UUYc;gF0UwaeacXkw32He^qyoYHjZeFS zo(#C9#&NEdFRcFrj7Q{CJgbmDejNS!H%aF6?;|KJQn_*Ps3pkq9yE~G{0wIS*mo0XIEYH zzIiJ>rbmD;sGXt#jlx7AXSGGcjty)5z5lTGp|M#5DCl0q0|~pNQ%1dP!-1>_7^BA~ zwu+uumJmTCcd)r|Hc)uWm7S!+Dw4;E|5+bwPb4i17Ued>NklnnsG+A{T-&}0=sLM- zY;sA9v@YH>b9#c$Vg{j@+>UULBX=jtu~N^%Y#BB5)pB|$?0Mf7msMD<7eACoP1(XY zPO^h5Brvhn$%(0JSo3KFwEPV&dz8(P41o=mo7G~A*P6wLJ@-#|_A z7>k~4&lbqyP1!la!qmhFBfIfT?nIHQ0j2WlohXk^sZ`?8-vwEwV0~uu{RDE^0yfl$ znua{^`VTZ)-h#ch_6^e2{VPaE@o&55|3dx$z_b6gbqduXJ(Lz(zq&ZbJ6qA4Ac4RT zhJO4KBLN!t;h(eW(?cZJw^swf8lP@tWMZ8GD)zg)siA3!2EJYI(j>WI$=pK!mo!Ry z?q&YkTIbTTr<>=}+N8C_EAR0XQL2&O{nNAXb?33iwo8{M``rUHJgnk z8KgZzZLFf|(O6oeugsm<;5m~4N$2Jm5#dph*@TgXC2_k&d%TG0LPY=Fw)=gf(hy9QmY*D6jCAiq44 zo-k2C+?3*+Wu7xm1w*LEAl`Vsq(sYPUMw|MiXrW)92>rVOAse5Pmx^OSi{y%EwPAE zx|csvE{U3c{vA>@;>xcjdCW15pE31F3aoIBsz@OQRvi%_MMfgar2j3Ob`9e@gLQk# zlzznEHgr|Ols%f*a+B-0klD`czi@RWGPPpR1tE@GB|nwe`td1OwG#OjGlTH zfT#^r?%3Ocp^U0F8Kekck6-Vg2gWs|sD_DTJ%2TR<5H3a$}B4ZYpP=p)oAoHxr8I! z1SYJ~v-iP&mNm{ra7!KP^KVpkER>-HFvq*>eG4J#kz1|eu;=~u2|>}TE_5nv2=d!0 z3P~?@blSo^uumuEt{lBsGcx{_IXPO8s01+7DP^yt&>k;<5(NRrF|To2h7hTWBFQ_A z+;?Q$o5L|LlIB>PH(4j)j3`JIb1xA_C@HRFnPnlg{zGO|-RO7Xn}!*2U=Z2V?{5Al z9+iL+n^_T~6Uu{law`R&fFadSVi}da8G>|>D<{(#vi{OU;}1ZnfXy8=etC7)Ae<2S zAlI`&=HkNiHhT0|tQztSLNsRR6v8bmf&$6CI|7b8V4kyJ{=pG#h{1sVeC28&Ho%Fh zwo_FIS}ST-2OF6jNQ$(pjrq)P)@sie#tigN1zSclxJLb-O9V|trp^G8<1rpsj8@+$ z2y27iiM>H8kfd%AMlK|9C>Lkvfs9iSk>k2}tCFlqF~Z_>-uWVQDd$5{3sM%2$du9; z*ukNSo}~@w@DPF)_vS^VaZ)7Mk&8ijX2hNhKom$#PM%bzSA-s$ z0O!broj`!Nuk)Qcp3(>dL|5om#XMx2RUSDMDY9#1|+~fxwP}1I4iYy4j$CGx3jD&eKhf%z`Jn z7mD!y6`nVq%&Q#5yqG`|+e~1$Zkgu!O(~~pWSDTw2^va3u!DOMVRQ8ycq)sk&H%vb z;$a`3gp74~I@swI!ILOkzVK3G&SdTcVe~RzN<+z`u(BY=yuwez{#T3a_83)8>2!X?`^02zVjqx-fN+tW`zCqH^XG>#Ies$qxa!n4*FF0m zxgJlPPYl*q4ylX;DVu3G*I6T&JyWvs`A(*u0+62=+ylt2!u)6LJ=Qe1rA$OWcNCmH zLu7PwMDY#rYQA1!!ONNcz~I^uMvi6N&Lo4dD&HF?1Su5}COTZ-jwR)-zLq=6@bN}X zSP(-MY`TOJ@1O`bLPphMMSWm+YL{Ger>cA$KT~)DuTl+H)!2Lf`c+lZ0ipxd>KfKn zIv;;eEmz(_(nwW24a+>v{K}$)A?=tp+?>zAmfL{}@0r|1>iFQfJ5C*6dKdijK=j16 zQpl4gl93ttF5@d<9e2LoZ~cqkH)aFMgt(el_)#OG4R4Hnqm(@D*Uj>2ZuUCy)o-yy z_J|&S-@o5#2IMcL(}qWF3EL<4n(`cygenA)G%Ssi7k4w)LafelpV5FvS9uJES+(Ml z?rzZ={vYrB#mB-Hd#ID{KS5dKl-|Wh_~v+Lvq3|<@w^MD-RA{q!$gkUUNIvAaex5y z)jIGW{#U=#UWyku7FIAB=TES8>L%Y9*h2N`#Gghie+a?>$CRNth?ORq)!Tde24f5K zKh>cz5oLC;ry*tHIEQEL>8L=zsjG7+(~LUN5K1pT`_Z-4Z}k^m%&H%g3*^e(FDCC{ zBh~eqx%bY?qqu_2qa+9A+oS&yFw^3nLRsN#?FcZvt?*dZhRC_a%Jd{qou(p5AG_Q6 ziOJMu8D~kJ7xEkG(69$Dl3t1J592=Olom%;13uZvYDda08YwzqFlND-;YodmA!SL) z!AOSI=(uCnG#Yo&BgrH(muUemmhQW7?}IHfxI~T`44wuLGFOMdKreQO!a=Z-LkH{T z@h;`A_l2Pp>Xg#`Vo@-?WJn-0((RR4uKM6P2*^-qprHgQhMzSd32@ho>%fFMbp9Y$ zx-#!r8gEu;VZN(fDbP7he+Nu7^o3<+pT!<<>m;m z=FC$N)wx)asxb_KLs}Z^;x*hQM}wQGr((&=%+=#jW^j|Gjn$(qqXwt-o-|>kL!?=T zh0*?m<^>S*F}kPiq@)Cp+^fnKi2)%<-Tw4K3oHwmI-}h}Kc^+%1P!D8aWp!hB@-ZT zybHrRdeYlYulEj>Bk zEIi|PU0eGg&~kWQ{q)gw%~bFT0`Q%k5S|tt!JIZXVXX=>er!7R^w>zeQ%M-(C|eOQG>5i|}i3}X#?aqAg~b1t{-fqwKd(&CyA zmyy)et*E}+q_lEqgbClewiJ=u@bFX}LKe)5o26K9fS;R`!er~a?lUCKf60`4Zq7{2q$L?k?IrAdcDu+ z4A0QJBUiGx&$TBASI2ASM_Wj{?fjv=CORO3GZz;1X*AYY`anM zI`M6C%8OUFSc$tKjiFJ|V74Yj-lK&Epi7F^Gp*rLeDTokfW#o6sl33W^~4V|edbS1 zhx%1PTdnI!C96iYqSA=qu6;p&Dd%)Skjjw0fyl>3k@O?I@x5|>2_7G#_Yc2*1>=^# z|H43bJDx$SS2!vkaMG!;VRGMbY{eJhT%FR{(a+RXDbd4OT?DRoE(`NhiVI6MsUCsT z1gc^~Nv>i;cIm2~_SYOfFpkUvV)(iINXEep;i4>&8@N#|h+_;DgzLqh3I#lzhn>cN zjm;m6U{+JXR2Mi)=~WxM&t9~WShlyA$Pnu+VIW2#;0)4J*C!{1W|y1TP{Q;!tldR< zI7aoH&cMm*apW}~BabBT;`fQ1-9q|!?6nTzmhiIo6fGQlcP{pu)kJh- zUK&Ei9lArSO6ep_SN$Lt_01|Y#@Ksznl@f<+%ku1F|k#Gcwa`(^M<2%M3FAZVb99?Ez4d9O)rqM< zCbYsdZlSo{X#nKqiRA$}XG}1Tw@)D|jGKo1ITqmvE4;ovYH{NAk{h8*Ysh@=nZFiF zmDF`@4do#UDKKM*@wDbwoO@tPx4aExhPF_dvlR&dB5>)W=wG6Pil zq{eBzw%Ov!?D+%8&(uK`m7JV7pqNp-krMd>ECQypq&?p#_3wy){eW{(2q}ij{6bfmyE+-ZO z)G4OtI;ga9;EVyKF6v3kO1RdQV+!*>tV-ditH-=;`n|2T zu(vYR*BJSBsjzFl1Oy#DpL=|pfEY4NM;y5Yly__T*Eg^3Mb_()pHwn)mAsh!7Yz-Z zY`hBLDXS4F^{>x=oOphq|LMo;G!C(b2hS9A6lJqb+e$2af}7C>zW2p{m18@Bdd>iL zoEE$nFUnaz_6p${cMO|;(c1f9nm5G5R;p)m4dcC1?1YD=2Mi&20=4{nu>AV#R^d%A zsmm_RlT#`;g~an9mo#O1dYV)2{mgUWEqb*a@^Ok;ckj;uqy{%*YB^({d{^V)P9VvP zC^qbK&lq~}TWm^RF8d4zbo~bJuw zFV!!}b^4BlJ0>5S3Q>;u*BLC&G6Fa5V|~w&bRZ*-YU>df6%qAvK?%Qf+#=M-+JqLw&w*l4{v7XTstY4j z26z69U#SVzSbY9HBXyD;%P$#vVU7G*Yb-*fy)Qpx?;ed;-P24>-L6U+OAC9Jj63kg zlY`G2+5tg1szc#*9ga3%f9H9~!(^QjECetX-PlacTR+^g8L<#VRovPGvsT)ln3lr= zm5WO@!NDuw+d4MY;K4WJg3B|Sp|WdumpFJO>I2tz$72s4^uXljWseYSAd+vGfjutO z-x~Qlct+BnlI+Iun)fOklxPH?30i&j9R$6g5^f&(x7bIom|FLKq9CUE);w2G>}vye zxWvEaXhx8|~2j)({Rq>0J9}lzdE`yhQ(l$z! z;x%d%_u?^4vlES_>JaIjJBN|N8z5}@l1#PG_@{mh`oWXQOI41_kPG}R_pV+jd^PU) zEor^SHo`VMul*80-K$0mSk|FiI+tHdWt-hzt~S>6!2-!R&rdL_^gGGUzkPe zEZkUKU=EY(5Ex)zeTA4-{Bkbn!Gm?nuaI4jLE%X;zMZ7bwn4FXz(?az;9(Uv;38U6 zi)}rA3xAcD2&6BY<~Pj9Q1~4Dyjs&!$)hyHiiTI@%qXd~+>> zW}$_puSSJ^uWv$jtWakn}}@eX6_LGz|7M#$!3yjY ztS{>HmQ%-8u0@|ig{kzD&CNK~-dIK5e{;@uWOs8$r>J7^c2P~Pwx%QVX0e8~oXK0J zM4HCNK?%t6?v~#;eP#t@tM$@SXRt;(b&kU7uDzlzUuu;+LQ5g%=FqpJPGrX8HJ8CS zITK|(fjhs3@CR}H4@)EjL@J zV_HPexOQ!@k&kvsQG)n;7lZaUh>{87l4NS_=Y-O9Ul3CaKG8iy+xD=QXZSr57a-hb z7jz3Ts-NVsMI783OPEdlE|e&a2;l^h@e>oYMh5@=Lte-9A+20|?!9>Djl~{XkAo>0p9`n&nfWGdGAfT-mSYW z1cvG>GT9dRJdcm7M_AG9JX5AqTCdJ6MRqR3p?+FvMxp(oB-6MZ`lRzSAj%N(1#8@_ zDnIIo9Rtv12(Eo}k_#FILhaZQ`yRD^Vn5tm+IK@hZO>s=t5`@p1#k?Umz2y*R64CF zGM-v&*k}zZ%Xm<_?1=g~<*&3KAy;_^QfccIp~CS7NW24Tn|mSDxb%pvvi}S}(~`2# z3I|kD@||l@lAW06K2%*gHd4x9YKeXWpwU%!ozYcJ+KJeX!s6b94j!Qyy7>S!wb?{qaMa`rpbU1phn0EpF}L zsBdZc|Im#iRiQmJjZwb5#n;`_O{$Zu$I zMXqbfu0yVmt!!Y`Fzl}QV7HUSOPib#da4i@vM$0u2FEYytsvrbR#ui9lrMkZ(AVVJ zMVl^Wi_fSRsEXLA_#rdaG%r(@UCw#o7*yBN)%22b)VSNyng6Lxk|2;XK3Qb=C_<`F zN##8MLHz-s%&O6JE~@P1=iHpj8go@4sC7*AWe99tuf$f7?2~wC&RA^UjB*2`K!%$y zSDzMd7}!vvN|#wDuP%%nuGk8&>N)7eRxtqdMXHD1W%hP7tYW{W>^DJp`3WS>3}i+$ z_li?4AlEj`r=!SPiIc+NNUZ9NCrMv&G0BdQHBO&S7d48aB)LfGi@D%5CC1%)1hVcJ zB~=yNC}LBn(K?cHkPmAX$5^M7JSnNkcc!X!0kD&^F$cJmRP(SJ`9b7}b)o$rj=BZ- zC;BX3IG94%Qz&(V$)7O~v|!=jd-yU1(6wd1u;*$z4DDe6+BFLhz>+8?59?d2Ngxck zm92yR!jk@MP@>>9FtAY2L+Z|MaSp{MnL-;fm}W3~fg!9TRr3;S@ysLf@#<)keHDRO zsJI1tP`g3PNL`2(8hK3!4;r|E-ZQbU0e-9u{(@du`4wjGj|A!QB&9w~?OI1r}M? zw)6tvsknfPfmNijZ;3VZX&HM6=|&W zy6GIe3a?_(pRxdUc==do9?C&v7+6cgIoL4)Ka^bOG9`l;S|QmVzjv%)3^PDi@=-cp z=!R0bU<@_;#*D}e1m@0!%k=VPtyRAkWYW(VFl|eu0LteWH7eDB%P|uF7BQ-|D4`n; z)UpuY1)*s32UwW756>!OoAq#5GAtfrjo*^7YUv^(eiySE?!TQzKxzqXE@jM_bq3Zq zg#1orE*Zd5ZWEpDXW9$=NzuadNSO*NW)ZJ@IDuU`w}j_FRE4-QS*rD4mPVQPH(jGg z+-Ye?3%G%=DT5U1b+TnNHHv(nz-S?3!M4hXtEB@J4WK%%p zkv=Bb`1DHmgUdYo>3kwB(T>Ba#DKv%cLp2h4r8v}p=Np}wL!&PB5J-w4V4REM{kMD z${oSuAw9?*yo3?tNp~X5WF@B^P<6L0HtIW0H7^`R8~9zAXgREH`6H{ntGu$aQ;oNq zig;pB^@KMHNoJcEb0f1fz+!M6sy?hQjof-QoxJgBM`!k^T~cykcmi^s_@1B9 z)t1)Y-ZsV9iA&FDrVoF=L7U#4&inXk{3+Xm9A|R<=ErgxPW~Fq zqu-~x0dIBlR+5_}`IK^*5l3f5$&K@l?J{)_d_*459pvsF*e*#+2guls(cid4!N%DG zl3(2`az#5!^@HNRe3O4(_5nc+){q?ENQG2|uKW0U0$aJ5SQ6hg>G4OyN6os76y%u8qNNHi;}XnRNwpsfn^!6Qt(-4tE`uxaDZ`hQp#aFX373|F?vjEiSEkV>K)cTBG+UL#wDj0_ zM9$H&-86zP=9=5_Q7d3onkqKNr4PAlF<>U^^yYAAEso|Ak~p$3NNZ$~4&kE9Nj^As zQPoo!m*uZ;z1~;#g(?zFECJ$O2@EBy<;F)fnQxOKvH`MojG5T?7thbe%F@JyN^k1K zn3H*%Ymoim)ePf)xhl2%$T)vq3P=4ty%NK)@}po&7Q^~o3l))Zm4<75Y!fFihsXJc z9?vecovF^nYfJVg#W~R3T1*PK{+^YFgb*7}Up2U#)oNyzkfJ#$)PkFxrq_{Ai?0zk zWnjq_ixF~Hs7YS9Y6H&8&k0#2cAj~!Vv4{wCM zi2f1FjQf+F@=BOB)pD|T41a4AEz+8hnH<#_PT#H|Vwm7iQ0-Tw()WMN za0eI-{B2G{sZ7+L+^k@BA)G;mOFWE$O+2nS|DzPSGZ)ede(9%+8kqu4W^wTn!yZPN z7u!Qu0u}K5(0euRZ$7=kn9DZ+llruq5A_l) zOK~wof7_^8Yeh@Qd*=P!gM)lh`Z@7^M?k8Z?t$$vMAuBG>4p56Dt!R$p{)y>QG}it zGG;Ei```7ewXrbGo6Z=!AJNQ!GP8l13m7|FIQTFZTpIg#kpZkl1wj)s1eySXjAAWy zfl;;@{QQ;Qnb$@LY8_Z&7 z6+d98F?z2Zo)sS)z$YoL(zzF>Ey8u#S_%n7)XUX1Pu(>e8gEUU1S;J=EH(#`cWi1+ zoL$5TN+?#NM8=4E7HOk)bf5MXvEo%he5QcB%_5YQ$cu_j)Pd^@5hi}d%nG}x9xXtD-JMQxr;KkC=r_dS-t`lf zF&CS?Lk~>U^!)Y0LZqNVJq+*_#F7W~!UkvZfQhzvW`q;^X&iv~ zEDDGIQ&(S;#Hb(Ej4j+#D#sDS_uHehlY0kZsQpktc?;O z22W1b%wNcdfNza<1M2{*mAkM<{}@(w`VuQ<^lG|iYSuWBD#lYK9+jsdA+&#;Y@=zXLVr840Nq_t5))#7}2s9pK* zg42zd{EY|#sIVMDhg9>t6_Y#O>JoG<{GO&OzTa;iA9&&^6=5MT21f6$7o@nS=w;R) znkgu*7Y{UNPu7B9&B&~q+N@@+%&cO0N`TZ-qQ|@f@e0g2BI+9xO$}NzMOzEbSSJ@v z1uNp(S z-dioXc$5YyA6-My@gW~1GH($Q?;GCHfk{ej-{Q^{iTFs1^Sa67RNd5y{cjX1tG+$& zbGrUte{U1{^Z_qpzW$-V!pJz$dQZrL5i(1MKU`%^= z^)i;xua4w)evDBrFVm)Id5SbXMx2u7M5Df<2L4B`wy4-Y+Wec#b^QJO|J9xF{x#M8 zuLUer`%ZL^m3gy?U&dI+`kgNZ+?bl3H%8)&k84*-=aMfADh&@$xr&IS|4{3$v&K3q zZTn&f{N(#L6<-BZYNs4 zB*Kl*@_IhGXI^_8zfXT^XNmjJ@5E~H*wFf<&er?p7suz85)$-Hqz@C zGMFg1NKs;otNViu)r-u{SOLcqwqc7$poPvm(-^ag1m71}HL#cj5t4Hw(W?*fi4GSH z9962NZ>p^ECPqVc$N}phy>N8rQsWWm%%rc5B4XLATFEtffX&TM2%|8S2Lh_q; zCytXua84HBnSybW-}(j z3Zwv4CaK)jC!{oUvdsFRXK&Sx@t)yGm(h65$!WZ!-jL52no}NX6=E<=H!aZ74h_&> zZ+~c@k!@}Cs84l{u+)%kg4fq~pOeTK3S4)gX~FKJw4t9ba!Ai{_gkKQYQvafZIyKq zX|r4xgC(l%JgmW!tvR&yNt$6uME({M`uNIi7HFiPEQo_UMRkl~12&4c& z^se;dbZWKu7>dLMg`IZq%@b@ME?|@{&xEIZEU(omKNUY? z`JszxNghuO-VA;MrZKEC0|Gi0tz3c#M?aO?WGLy64LkG4T%|PBIt_?bl{C=L@9e;A zia!35TZI7<`R8hr06xF62*rNH5T3N0v^acg+;ENvrLYo|B4!c^eILcn#+lxDZR!%l zjL6!6h9zo)<5GrSPth7+R(rLAW?HF4uu$glo?w1U-y}CR@%v+wSAlsgIXn>e%bc{FE;j@R0AoNIWf#*@BSngZ)HmNqkB z)cs3yN%_PT4f*K+Y1wFl)be=1iq+bb1G-}b|72|gJ|lMt`tf~0Jk}zMbS0+M-Mq}R z>Bv}-W6J%}j#dIz`Z0}zD(DGKn`R;E8A`)$a6qDfr(c@iHKZcCVY_nJEDpcUddGH* z*ct2$&)RelhmV}@jGXY>3Y~vp;b*l9M+hO}&x`e~q*heO8GVkvvJTwyxFetJC8VnhjR`5*+qHEDUNp16g`~$TbdliLLd}AFf}U+Oda1JXwwseRFbj?DN96;VSX~z?JxJSuA^BF}262%Z0)nv<6teKK`F zfm9^HsblS~?Xrb1_~^=5=PD!QH$Y1hD_&qe1HTQnese8N#&C(|Q)CvtAu6{{0Q%ut8ESVdn&& z4y%nsCs!$(#9d{iVjXDR##3UyoMNeY@_W^%qyuZ^K3Oa4(^!tDXOUS?b2P)yRtJ8j zSX}@qGBj+gKf;|6Kb&rq`!}S*cSu-3&S>=pM$eEB{K>PP~I}N|uGE|`3U#{Q6v^kO4nIsaq zfPld}c|4tVPI4!=!ETCNW+LjcbmEoxm0RZ%ieV0`(nVlWKClZW5^>f&h79-~CF(%+ zv|KL(^xQ7$#a}&BSGr9zf{xJ(cCfq>UR*>^-Ou_pmknCt6Y--~!duL{k2D{yLMl__ z!KeMRRg&EsD2s|cmy?xgK&XcGIKeos`&UEVhBTw;mqy|8DlP1M7PYS2z{YmTJ;n!h znPe(Qu?c7+xZz!Tm1AnE8|;&tf7fW$2dArX7ck1Jd(S1+91YB8bjISRZ`UL*?vb{b zMp*!Xq7VaLc0Ogqj5qmop8NREQ{9_iC$;tviZlubGLy1jLlIFBxAymMr@SDLAcx+) z5YRkl$bW**X)W0JzWNcLx9>fTqJj00ipY6Ua?mUlsgQrVVgpmaheE;RgA5U_+WsPh z9+X|PU4zFyNxZ2?Q+V`Mo{xH~(m}OMRZa<&$nCl7o4x`^^|V4?aPz8#KwFm=8T6_} z8=P_4$_rD2a%7}}HT6VQ>ZGKW=QF7zI-2=6oBNZR$HVn|gq`>l$HZ`48lkM7%R$>MS& zghR`WZ9Xrd_6FaDedH6_aKVJhYev*2)UQ>!CRH3PQ_d9nXlO;c z9PeqiKD@aGz^|mvD-tV<{BjfA;)B+76!*+`$CZOJ=#)}>{?!9fAg(Xngbh||n=q*C zU0mGP`NxHn$uY#@)gN<0xr)%Ue80U{-`^FX1~Q@^>WbLraiB|c#4v$5HX)0z!oA#jOXPyWg! z8EC}SBmG7j3T&zCenPLYA{kN(3l62pu}91KOWZl? zg~>T4gQ%1y3AYa^J|>ba$7F5KlVx}_&*~me*q-SYLBCXZFU=U8mHQD4K!?;B61NoX z?VS41SS&jHyhmB~+bC=w0a06V``ZXCkC~}oM9pM{$hU~-s_elYPmT1L!%B`?*<+?( zFQ@TP%y+QL`_&Y0A3679pe5~iL=z)$b)k!oSbJRyw+K};SGAvvE=|<~*aiwJc?uE@2?7a1i9|3=^N%*9smt3ZIhjY>gIsr{Q2rX(NovZ7I1n^V{ z#~(1ze-%`C>fM`^hCV**9BA-04lNuu&3=reevNOMwmX(A{yh`^c8%0mjAKMj{Th05 zXrM(zILwyL-Pcdw^(=gj(ZLVMA95zlzmLa^skb8tQq%8SV&4vp?S>L3+P4^tp`$xA zr38jBw0ItR`VbO5vB1`<3d})}aorkIU1z3*ifYN&Lpp)}|}QJS60th_v-EEkAM zyOREuj!Ou|pVeZEWg;$Hf!x;xAmFu7gB^UR$=L0BuZ~thLC@#moJ(@@wejR|`t_K@ zuQ{XmpAWz%o&~2dk!SIGR$EmpZY)@+r^gvX26%)y>1u2bt~JUPTQzQu&_tB)|{19)&n$m5Fhw0A-8S1^%XpAD%`#a z_ModVxsM|x!m3N1vRt_XEL`O-+J3cMsM1l*dbjT&S0c@}Xxl3I&AeMNT97G3c6%3C zbrZS?2EAKcEq@@Pw?r%eh0YM6z0>&Qe#n+e9hEHK?fzig3v5S#O2IxVLu;a>~c~ZfHVbgLox%_tg)bsC8Rl35P=Jhl+Y=w6zb$ z;*uO%i^U z^mp_QggBILLF$AyjPD41Z0SFdbDj&z&xjq~X|OoM7bCuBfma1CEd!4RKGqPR)K)e}+7^JfFUI_fy63cMyq#&)Z*#w18{S zhC@f9U5k#2S2`d$-)cEoH-eAz{2Qh>YF1Xa)E$rWd52N-@{#lrw3lRqr)z?BGThgO z-Mn>X=RPHQ)#9h{3ciF)<>s{uf_&XdKb&kC!a373l2OCu&y8&n#P%$7YwAVJ_lD-G zX7tgMEV8}dY^mz`R6_0tQ5Eu@CdSOyaI63Vb*mR+rCzxgsjCXLSHOmzt0tA zGoA0Cp&l>rtO@^uQayrkoe#d2@}|?SlQl9W{fmcxY(0*y zHTZ6>FL;$8FEzbb;M(o%mBe-X?o<0+1dH?ZVjcf8)Kyqb07*a zLfP1blbt)=W)TN}4M#dUnt8Gdr4p$QRA<0W)JhWLK3-g82Q~2Drmx4J z;6m4re%igus136VL}MDI-V;WmSfs4guF_(7ifNl#M~Yx5HB!UF)>*-KDQl0U?u4UXV2I*qMhEfsxb%87fi+W;mW5{h?o8!52}VUs*Fpo#aSuXk(Ug z>r>xC#&2<9Uwmao@iJQ|{Vr__?eRT2NB$OcoXQ-jZ{t|?Uy{7q$nU-i|&-R6fHPWJDgHZ69iVbK#Ab@2@y zPD*Gj=hib?PWr8NGf;g$o5I!*n>94Z!IfqRm zLvM>Gx$Y*rEL3Z-+lS42=cnEfXR)h1z`h8a+I%E_ss%qXsrgIV%qv9d|KT>fV5=3e zw>P#ju>2naGc{=6!)9TeHq$S9Pk|>$UCEl}H}lE@;0(jbNT9TXUXyss>al>S4DuGi zVCy;Qt=a2`iu2;TvrIkh2NTvNV}0)qun~9y1yEQMdOf#V#3(e(C?+--8bCsJu={Q1z5qNJIk&yW>ZnVm;A=fL~29lvXQ*4j(SLau?P zi8LC7&**O!6B6=vfY%M;!p2L2tQ+w3Y!am{b?14E`h4kN$1L0XqT5=y=DW8GI_yi% zlIWsjmf0{l#|ei>)>&IM4>jXH)?>!fK?pfWIQn9gT9N(z&w3SvjlD|u*6T@oNQRF6 zU5Uo~SA}ml5f8mvxzX>BGL}c2#AT^6Lo-TM5XluWoqBRin$tiyRQK0wJ!Ro+7S!-K z=S95p-(#IDKOZsRd{l65N(Xae`wOa4Dg9?g|Jx97N-7OfHG(rN#k=yNGW0K$Tia5J zMMX1+!ulc1%8e*FNRV8jL|OSL-_9Nv6O=CH>Ty(W@sm`j=NFa1F3tT$?wM1}GZekB z6F_VLMCSd7(b9T%IqUMo$w9sM5wOA7l8xW<(1w0T=S}MB+9X5UT|+nemtm_;!|bxX z_bnOKN+F30ehJ$459k@=69yTz^_)-hNE4XMv$~_%vlH_y^`P1pLxYF6#_IZyteO`9wpuS> z#%Vyg5mMDt?}j!0}MoBX|9PS0#B zSVo6xLVjujMN57}IVc#A{VB*_yx;#mgM4~yT6wO;Qtm8MV6DX?u(JS~JFA~PvEl%9 z2XI}c>OzPoPn_IoyXa2v}BA(M+sWq=_~L0rZ_yR17I5c^m4;?2&KdCc)3lCs!M|0OzH@(PbG8T6w%N zKzR>%SLxL_C6~r3=xm9VG8<9yLHV6rJOjFHPaNdQHHflp><44l>&;)&7s)4lX%-er znWCv8eJJe1KAi_t1p%c4`bgxD2(1v)jm(gvQLp2K-=04oaIJu{F7SIu8&)gyw7x>+ zbzYF7KXg;T71w!-=C0DjcnF^JP$^o_N>*BAjtH!^HD6t1o?(O7IrmcodeQVDD<*+j zN)JdgB6v^iiJ1q`bZ(^WvN{v@sDqG$M9L`-UV!3q&sWZUnQ{&tAkpX(nZ_L#rMs}>p7l0fU5I5IzArncQi6TWjP#1B=QZ|Uqm-3{)YPn=XFqHW-~Fb z^!0CvIdelQbgcac9;By79%T`uvNhg9tS><pLzXePP=JZzcO@?5GRAdF4)sY*)YGP* zyioMa3=HRQz(v}+cqXc0%2*Q%CQi%e2~$a9r+X*u3J8w^Shg#%4I&?!$})y@ zzg8tQ6_-`|TBa_2v$D;Q(pFutj7@yos0W$&__9$|Yn3DFe*)k{g^|JIV4bqI@2%-4kpb_p? zQ4}qQcA>R6ihbxnVa{c;f7Y)VPV&mRY-*^qm~u3HB>8lf3P&&#GhQk8uIYYgwrugY zei>mp`YdC*R^Cxuv@d0V?$~d*=m-X?1Fqd9@*IM^wQ_^-nQEuc0!OqMr#TeT=8W`JbjjXc-Dh3NhnTj8e82yP;V_B<7LIejij+B{W1ViaJ_)+q?$BaLJpxt_4@&(?rWC3NC-_Z9Sg4JJWc( zX!Y34j67vCMHKB=JcJ1|#UI^D^mn(i=A5rf-iV7y4bR5HhC=I`rFPZv4F>q+h?l34 z4(?KYwZYHwkPG%kK7$A&M#=lpIn3Qo<>s6UFy|J$Zca-s(oM7??dkuKh?f5b2`m57 zJhs4BTcVVmwsswlX?#70uQb*k1Fi3q4+9`V+ikSk{L3K=-5HgN0JekQ=J~549Nd*+H%5+fi6aJuR=K zyD3xW{X$PL7&iR)=wumlTq2gY{LdrngAaPC;Qw_xLfVE0c0Z>y918TQpL!q@?`8{L!el18Qxiki3WZONF=eK$N3)p>36EW)I@Y z7QxbWW_9_7a*`VS&5~4-9!~&g8M+*U9{I2Bz`@TJ@E(YL$l+%<=?FyR#&e&v?Y@@G zqFF`J*v;l$&(A=s`na2>4ExKnxr`|OD+Xd-b4?6xl4mQ94xuk!-$l8*%+1zQU{)!= zTooUhjC0SNBh!&Ne}Q=1%`_r=Vu1c8RuE!|(g4BQGcd5AbpLbvKv_Z~Y`l!mr!sCc zDBupoc{W@U(6KWqW@xV_`;J0~+WDx|t^WeMri#=q0U5ZN7@@FAv<1!hP6!IYX z>UjbhaEv2Fk<6C0M^@J`lH#LgKJ(`?6z5=uH+ImggSQaZtvh52WTK+EBN~-op#EQKYW`$yBmq z4wgLTJPn3;mtbs0m0RO&+EG>?rb*ZECE0#eeSOFL!2YQ$w}cae>sun`<=}m!=go!v zO2jn<0tNh4E-4)ZA(ixh5nIUuXF-qYl>0I_1)K%EAw`D7~la$=gc@6g{iWF=>i_76?Mc zh#l9h7))<|EY=sK!E|54;c!b;Zp}HLd5*-w^6^whxB98v`*P>cj!Nfu1R%@bcp{cb zUZ24(fUXn3d&oc{6H%u(@4&_O?#HO(qd^YH=V`WJ=u*u6Zie8mE^r_Oz zDw`DaXeq4G#m@EK5+p40Xe!Lr!-jTQLCV3?R1|3#`%45h8#WSA!XoLDMS7=t!SluZ4H56;G z6C9D(B6>k^ur_DGfJ@Y-=3$5HkrI zO+3P>R@$6QZ#ATUI3$)xRBEL#5IKs}yhf&fK;ANA#Qj~G zdE|k|`puh$%dyE4R0$7dZd)M*#e7s%*PKPyrS;d%&S(d{_Ktq^!Hpi&bxZx`?9pEw z%sPjo&adHm95F7Z1{RdY#*a!&LcBZVRe{qhn8d{pOUJ{fOu`_kFg7ZVeRYZ(!ezNktT5{Ab z4BZI$vS0$vm3t9q`ECjDK;pmS{8ZTKs`Js~PYv2|=VkDv{Dtt)cLU@9%K6_KqtqfM zaE*e$f$Xm=;IAURNUXw8g%=?jzG2}10ZA5qXzAaJ@eh)yv5B=ETyVwC-a*CD;GgRJ z4J1~zMUey?4iVlS0zW|F-~0nenLiN3S0)l!T2}D%;<}Z9DzeVgcB+MSj;f$KY;uP%UR#f`0u*@6U@tk@jO3N?Fjq< z{cUUhjrr$rmo>qE?52zKe+>6iP5P_tcUfxsLSy{9*)shB(w`UUveNH`a`kr$VEF@} zKh&|lTD;4;m_H6C&)9#D`kRh;S(NTa=Ve^~xe_0~x$6h8Q@B_qu#ee=(lkI9@F6$0m=z@H=4&h%Q{htM>uHs(Sr@2ry`fgLA zKj8lVXdGPyy)2J%A${}Rm_a{){wHnlM?yGPQ7#KO{8*(_l0QZHuV};nO?c%h?qwSL z3wem|w*2tdxW5&PxC(Wd0QG_w|GPbw|0UFK`u$~U%!`QKcME;=Q@?*erh4_>FP~1n zAldwG9h$$u_$RFK6Uxo20GHqJzc}Rl-EwVz3h4n z;3~%DwD84i>)-8#&#y3k)3BG5cNaP3?t4q}F%yfv?*yEiC>sSo}$f>nh0QNZXH1N)-Q7kbk=2uL9OrF)nXrE@F1y%_8Yn c82=K%QXLKFx%@O{wJjEi6Y56o#$)Bpeg literal 60756 zcmb5WV{~QRw(p$^Dz@00IL3?^hro$gg*4VI_WAaTyVM5Foj~O|-84 z$;06hMwt*rV;^8iB z1~&0XWpYJmG?Ts^K9PC62H*`G}xom%S%yq|xvG~FIfP=9*f zZoDRJBm*Y0aId=qJ?7dyb)6)JGWGwe)MHeNSzhi)Ko6J<-m@v=a%NsP537lHe0R* z`If4$aaBA#S=w!2z&m>{lpTy^Lm^mg*3?M&7HFv}7K6x*cukLIGX;bQG|QWdn{%_6 zHnwBKr84#B7Z+AnBXa16a?or^R?+>$4`}{*a_>IhbjvyTtWkHw)|ay)ahWUd-qq$~ zMbh6roVsj;_qnC-R{G+Cy6bApVOinSU-;(DxUEl!i2)1EeQ9`hrfqj(nKI7?Z>Xur zoJz-a`PxkYit1HEbv|jy%~DO^13J-ut986EEG=66S}D3!L}Efp;Bez~7tNq{QsUMm zh9~(HYg1pA*=37C0}n4g&bFbQ+?-h-W}onYeE{q;cIy%eZK9wZjSwGvT+&Cgv z?~{9p(;bY_1+k|wkt_|N!@J~aoY@|U_RGoWX<;p{Nu*D*&_phw`8jYkMNpRTWx1H* z>J-Mi_!`M468#5Aix$$u1M@rJEIOc?k^QBc?T(#=n&*5eS#u*Y)?L8Ha$9wRWdH^3D4|Ps)Y?m0q~SiKiSfEkJ!=^`lJ(%W3o|CZ zSrZL-Xxc{OrmsQD&s~zPfNJOpSZUl%V8tdG%ei}lQkM+z@-4etFPR>GOH9+Y_F<3=~SXln9Kb-o~f>2a6Xz@AS3cn^;c_>lUwlK(n>z?A>NbC z`Ud8^aQy>wy=$)w;JZzA)_*Y$Z5hU=KAG&htLw1Uh00yE!|Nu{EZkch zY9O6x7Y??>!7pUNME*d!=R#s)ghr|R#41l!c?~=3CS8&zr6*aA7n9*)*PWBV2w+&I zpW1-9fr3j{VTcls1>ua}F*bbju_Xq%^v;-W~paSqlf zolj*dt`BBjHI)H9{zrkBo=B%>8}4jeBO~kWqO!~Thi!I1H(in=n^fS%nuL=X2+s!p}HfTU#NBGiwEBF^^tKU zbhhv+0dE-sbK$>J#t-J!B$TMgN@Wh5wTtK2BG}4BGfsZOoRUS#G8Cxv|6EI*n&Xxq zt{&OxCC+BNqz$9b0WM7_PyBJEVObHFh%%`~!@MNZlo*oXDCwDcFwT~Rls!aApL<)^ zbBftGKKBRhB!{?fX@l2_y~%ygNFfF(XJzHh#?`WlSL{1lKT*gJM zs>bd^H9NCxqxn(IOky5k-wALFowQr(gw%|`0991u#9jXQh?4l|l>pd6a&rx|v=fPJ z1mutj{YzpJ_gsClbWFk(G}bSlFi-6@mwoQh-XeD*j@~huW4(8ub%^I|azA)h2t#yG z7e_V_<4jlM3D(I+qX}yEtqj)cpzN*oCdYHa!nm%0t^wHm)EmFP*|FMw!tb@&`G-u~ zK)=Sf6z+BiTAI}}i{*_Ac$ffr*Wrv$F7_0gJkjx;@)XjYSh`RjAgrCck`x!zP>Ifu z&%he4P|S)H*(9oB4uvH67^0}I-_ye_!w)u3v2+EY>eD3#8QR24<;7?*hj8k~rS)~7 zSXs5ww)T(0eHSp$hEIBnW|Iun<_i`}VE0Nc$|-R}wlSIs5pV{g_Dar(Zz<4X3`W?K z6&CAIl4U(Qk-tTcK{|zYF6QG5ArrEB!;5s?tW7 zrE3hcFY&k)+)e{+YOJ0X2uDE_hd2{|m_dC}kgEKqiE9Q^A-+>2UonB+L@v3$9?AYw zVQv?X*pK;X4Ovc6Ev5Gbg{{Eu*7{N3#0@9oMI~}KnObQE#Y{&3mM4`w%wN+xrKYgD zB-ay0Q}m{QI;iY`s1Z^NqIkjrTlf`B)B#MajZ#9u41oRBC1oM1vq0i|F59> z#StM@bHt|#`2)cpl_rWB($DNJ3Lap}QM-+A$3pe}NyP(@+i1>o^fe-oxX#Bt`mcQc zb?pD4W%#ep|3%CHAYnr*^M6Czg>~L4?l16H1OozM{P*en298b+`i4$|w$|4AHbzqB zHpYUsHZET$Z0ztC;U+0*+amF!@PI%^oUIZy{`L{%O^i{Xk}X0&nl)n~tVEpcAJSJ} zverw15zP1P-O8h9nd!&hj$zuwjg?DoxYIw{jWM zW5_pj+wFy8Tsa9g<7Qa21WaV&;ejoYflRKcz?#fSH_)@*QVlN2l4(QNk| z4aPnv&mrS&0|6NHq05XQw$J^RR9T{3SOcMKCXIR1iSf+xJ0E_Wv?jEc*I#ZPzyJN2 zUG0UOXHl+PikM*&g$U@g+KbG-RY>uaIl&DEtw_Q=FYq?etc!;hEC_}UX{eyh%dw2V zTTSlap&5>PY{6I#(6`j-9`D&I#|YPP8a;(sOzgeKDWsLa!i-$frD>zr-oid!Hf&yS z!i^cr&7tN}OOGmX2)`8k?Tn!!4=tz~3hCTq_9CdiV!NIblUDxHh(FJ$zs)B2(t5@u z-`^RA1ShrLCkg0)OhfoM;4Z{&oZmAec$qV@ zGQ(7(!CBk<5;Ar%DLJ0p0!ResC#U<+3i<|vib1?{5gCebG7$F7URKZXuX-2WgF>YJ^i zMhHDBsh9PDU8dlZ$yJKtc6JA#y!y$57%sE>4Nt+wF1lfNIWyA`=hF=9Gj%sRwi@vd z%2eVV3y&dvAgyuJ=eNJR+*080dbO_t@BFJO<@&#yqTK&+xc|FRR;p;KVk@J3$S{p` zGaMj6isho#%m)?pOG^G0mzOAw0z?!AEMsv=0T>WWcE>??WS=fII$t$(^PDPMU(P>o z_*0s^W#|x)%tx8jIgZY~A2yG;US0m2ZOQt6yJqW@XNY_>_R7(Nxb8Ged6BdYW6{prd!|zuX$@Q2o6Ona8zzYC1u!+2!Y$Jc9a;wy+pXt}o6~Bu1oF1c zp7Y|SBTNi@=I(K%A60PMjM#sfH$y*c{xUgeSpi#HB`?|`!Tb&-qJ3;vxS!TIzuTZs-&%#bAkAyw9m4PJgvey zM5?up*b}eDEY+#@tKec)-c(#QF0P?MRlD1+7%Yk*jW;)`f;0a-ZJ6CQA?E%>i2Dt7T9?s|9ZF|KP4;CNWvaVKZ+Qeut;Jith_y{v*Ny6Co6!8MZx;Wgo z=qAi%&S;8J{iyD&>3CLCQdTX*$+Rx1AwA*D_J^0>suTgBMBb=*hefV+Ars#mmr+YsI3#!F@Xc1t4F-gB@6aoyT+5O(qMz*zG<9Qq*f0w^V!03rpr*-WLH}; zfM{xSPJeu6D(%8HU%0GEa%waFHE$G?FH^kMS-&I3)ycx|iv{T6Wx}9$$D&6{%1N_8 z_CLw)_9+O4&u94##vI9b-HHm_95m)fa??q07`DniVjAy`t7;)4NpeyAY(aAk(+T_O z1om+b5K2g_B&b2DCTK<>SE$Ode1DopAi)xaJjU>**AJK3hZrnhEQ9E`2=|HHe<^tv z63e(bn#fMWuz>4erc47}!J>U58%<&N<6AOAewyzNTqi7hJc|X{782&cM zHZYclNbBwU6673=!ClmxMfkC$(CykGR@10F!zN1Se83LR&a~$Ht&>~43OX22mt7tcZUpa;9@q}KDX3O&Ugp6< zLZLfIMO5;pTee1vNyVC$FGxzK2f>0Z-6hM82zKg44nWo|n}$Zk6&;5ry3`(JFEX$q zK&KivAe${e^5ZGc3a9hOt|!UOE&OocpVryE$Y4sPcs4rJ>>Kbi2_subQ9($2VN(3o zb~tEzMsHaBmBtaHAyES+d3A(qURgiskSSwUc9CfJ@99&MKp2sooSYZu+-0t0+L*!I zYagjOlPgx|lep9tiU%ts&McF6b0VE57%E0Ho%2oi?=Ks+5%aj#au^OBwNwhec zta6QAeQI^V!dF1C)>RHAmB`HnxyqWx?td@4sd15zPd*Fc9hpDXP23kbBenBxGeD$k z;%0VBQEJ-C)&dTAw_yW@k0u?IUk*NrkJ)(XEeI z9Y>6Vel>#s_v@=@0<{4A{pl=9cQ&Iah0iD0H`q)7NeCIRz8zx;! z^OO;1+IqoQNak&pV`qKW+K0^Hqp!~gSohcyS)?^P`JNZXw@gc6{A3OLZ?@1Uc^I2v z+X!^R*HCm3{7JPq{8*Tn>5;B|X7n4QQ0Bs79uTU%nbqOJh`nX(BVj!#f;#J+WZxx4 z_yM&1Y`2XzhfqkIMO7tB3raJKQS+H5F%o83bM+hxbQ zeeJm=Dvix$2j|b4?mDacb67v-1^lTp${z=jc1=j~QD>7c*@+1?py>%Kj%Ejp7Y-!? z8iYRUlGVrQPandAaxFfks53@2EC#0)%mrnmGRn&>=$H$S8q|kE_iWko4`^vCS2aWg z#!`RHUGyOt*k?bBYu3*j3u0gB#v(3tsije zgIuNNWNtrOkx@Pzs;A9un+2LX!zw+p3_NX^Sh09HZAf>m8l@O*rXy_82aWT$Q>iyy zqO7Of)D=wcSn!0+467&!Hl))eff=$aneB?R!YykdKW@k^_uR!+Q1tR)+IJb`-6=jj zymzA>Sv4>Z&g&WWu#|~GcP7qP&m*w-S$)7Xr;(duqCTe7p8H3k5>Y-n8438+%^9~K z3r^LIT_K{i7DgEJjIocw_6d0!<;wKT`X;&vv+&msmhAAnIe!OTdybPctzcEzBy88_ zWO{6i4YT%e4^WQZB)KHCvA(0tS zHu_Bg+6Ko%a9~$EjRB90`P(2~6uI@SFibxct{H#o&y40MdiXblu@VFXbhz>Nko;7R z70Ntmm-FePqhb%9gL+7U8@(ch|JfH5Fm)5${8|`Lef>LttM_iww6LW2X61ldBmG0z zax3y)njFe>j*T{i0s8D4=L>X^j0)({R5lMGVS#7(2C9@AxL&C-lZQx~czI7Iv+{%1 z2hEG>RzX4S8x3v#9sgGAnPzptM)g&LB}@%E>fy0vGSa(&q0ch|=ncKjNrK z`jA~jObJhrJ^ri|-)J^HUyeZXz~XkBp$VhcTEcTdc#a2EUOGVX?@mYx#Vy*!qO$Jv zQ4rgOJ~M*o-_Wptam=~krnmG*p^j!JAqoQ%+YsDFW7Cc9M%YPiBOrVcD^RY>m9Pd< zu}#9M?K{+;UIO!D9qOpq9yxUquQRmQNMo0pT`@$pVt=rMvyX)ph(-CCJLvUJy71DI zBk7oc7)-%ngdj~s@76Yse3L^gV0 z2==qfp&Q~L(+%RHP0n}+xH#k(hPRx(!AdBM$JCfJ5*C=K3ts>P?@@SZ_+{U2qFZb>4kZ{Go37{# zSQc+-dq*a-Vy4?taS&{Ht|MLRiS)Sn14JOONyXqPNnpq&2y~)6wEG0oNy>qvod$FF z`9o&?&6uZjhZ4_*5qWVrEfu(>_n2Xi2{@Gz9MZ8!YmjYvIMasE9yVQL10NBrTCczq zcTY1q^PF2l!Eraguf{+PtHV3=2A?Cu&NN&a8V(y;q(^_mFc6)%Yfn&X&~Pq zU1?qCj^LF(EQB1F`8NxNjyV%fde}dEa(Hx=r7$~ts2dzDwyi6ByBAIx$NllB4%K=O z$AHz1<2bTUb>(MCVPpK(E9wlLElo(aSd(Os)^Raum`d(g9Vd_+Bf&V;l=@mM=cC>) z)9b0enb)u_7V!!E_bl>u5nf&Rl|2r=2F3rHMdb7y9E}}F82^$Rf+P8%dKnOeKh1vs zhH^P*4Ydr^$)$h@4KVzxrHyy#cKmWEa9P5DJ|- zG;!Qi35Tp7XNj60=$!S6U#!(${6hyh7d4q=pF{`0t|N^|L^d8pD{O9@tF~W;#Je*P z&ah%W!KOIN;SyAEhAeTafJ4uEL`(RtnovM+cb(O#>xQnk?dzAjG^~4$dFn^<@-Na3 z395;wBnS{t*H;Jef2eE!2}u5Ns{AHj>WYZDgQJt8v%x?9{MXqJsGP|l%OiZqQ1aB! z%E=*Ig`(!tHh>}4_z5IMpg{49UvD*Pp9!pxt_gdAW%sIf3k6CTycOT1McPl=_#0?8 zVjz8Hj*Vy9c5-krd-{BQ{6Xy|P$6LJvMuX$* zA+@I_66_ET5l2&gk9n4$1M3LN8(yEViRx&mtd#LD}AqEs?RW=xKC(OCWH;~>(X6h!uDxXIPH06xh z*`F4cVlbDP`A)-fzf>MuScYsmq&1LUMGaQ3bRm6i7OsJ|%uhTDT zlvZA1M}nz*SalJWNT|`dBm1$xlaA>CCiQ zK`xD-RuEn>-`Z?M{1%@wewf#8?F|(@1e0+T4>nmlSRrNK5f)BJ2H*$q(H>zGD0>eL zQ!tl_Wk)k*e6v^m*{~A;@6+JGeWU-q9>?+L_#UNT%G?4&BnOgvm9@o7l?ov~XL+et zbGT)|G7)KAeqb=wHSPk+J1bdg7N3$vp(ekjI1D9V$G5Cj!=R2w=3*4!z*J-r-cyeb zd(i2KmX!|Lhey!snRw z?#$Gu%S^SQEKt&kep)up#j&9}e+3=JJBS(s>MH+|=R(`8xK{mmndWo_r`-w1#SeRD&YtAJ#GiVI*TkQZ}&aq<+bU2+coU3!jCI6E+Ad_xFW*ghnZ$q zAoF*i&3n1j#?B8x;kjSJD${1jdRB;)R*)Ao!9bd|C7{;iqDo|T&>KSh6*hCD!rwv= zyK#F@2+cv3=|S1Kef(E6Niv8kyLVLX&e=U;{0x{$tDfShqkjUME>f8d(5nzSkY6@! z^-0>DM)wa&%m#UF1F?zR`8Y3X#tA!*7Q$P3lZJ%*KNlrk_uaPkxw~ zxZ1qlE;Zo;nb@!SMazSjM>;34ROOoygo%SF);LL>rRonWwR>bmSd1XD^~sGSu$Gg# zFZ`|yKU0%!v07dz^v(tY%;So(e`o{ZYTX`hm;@b0%8|H>VW`*cr8R%3n|ehw2`(9B+V72`>SY}9^8oh$En80mZK9T4abVG*to;E z1_S6bgDOW?!Oy1LwYy=w3q~KKdbNtyH#d24PFjX)KYMY93{3-mPP-H>@M-_>N~DDu zENh~reh?JBAK=TFN-SfDfT^=+{w4ea2KNWXq2Y<;?(gf(FgVp8Zp-oEjKzB%2Iqj;48GmY3h=bcdYJ}~&4tS`Q1sb=^emaW$IC$|R+r-8V- zf0$gGE(CS_n4s>oicVk)MfvVg#I>iDvf~Ov8bk}sSxluG!6#^Z_zhB&U^`eIi1@j( z^CK$z^stBHtaDDHxn+R;3u+>Lil^}fj?7eaGB z&5nl^STqcaBxI@v>%zG|j))G(rVa4aY=B@^2{TFkW~YP!8!9TG#(-nOf^^X-%m9{Z zCC?iC`G-^RcBSCuk=Z`(FaUUe?hf3{0C>>$?Vs z`2Uud9M+T&KB6o4o9kvdi^Q=Bw!asPdxbe#W-Oaa#_NP(qpyF@bVxv5D5))srkU#m zj_KA+#7sqDn*Ipf!F5Byco4HOSd!Ui$l94|IbW%Ny(s1>f4|Mv^#NfB31N~kya9!k zWCGL-$0ZQztBate^fd>R!hXY_N9ZjYp3V~4_V z#eB)Kjr8yW=+oG)BuNdZG?jaZlw+l_ma8aET(s+-x+=F-t#Qoiuu1i`^x8Sj>b^U} zs^z<()YMFP7CmjUC@M=&lA5W7t&cxTlzJAts*%PBDAPuqcV5o7HEnqjif_7xGt)F% zGx2b4w{@!tE)$p=l3&?Bf#`+!-RLOleeRk3 z7#pF|w@6_sBmn1nECqdunmG^}pr5(ZJQVvAt$6p3H(16~;vO>?sTE`Y+mq5YP&PBo zvq!7#W$Gewy`;%6o^!Dtjz~x)T}Bdk*BS#=EY=ODD&B=V6TD2z^hj1m5^d6s)D*wk zu$z~D7QuZ2b?5`p)E8e2_L38v3WE{V`bVk;6fl#o2`) z99JsWhh?$oVRn@$S#)uK&8DL8>An0&S<%V8hnGD7Z^;Y(%6;^9!7kDQ5bjR_V+~wp zfx4m3z6CWmmZ<8gDGUyg3>t8wgJ5NkkiEm^(sedCicP^&3D%}6LtIUq>mXCAt{9eF zNXL$kGcoUTf_Lhm`t;hD-SE)m=iBnxRU(NyL}f6~1uH)`K!hmYZjLI%H}AmEF5RZt z06$wn63GHnApHXZZJ}s^s)j9(BM6e*7IBK6Bq(!)d~zR#rbxK9NVIlgquoMq z=eGZ9NR!SEqP6=9UQg#@!rtbbSBUM#ynF);zKX+|!Zm}*{H z+j=d?aZ2!?@EL7C~%B?6ouCKLnO$uWn;Y6Xz zX8dSwj732u(o*U3F$F=7xwxm>E-B+SVZH;O-4XPuPkLSt_?S0)lb7EEg)Mglk0#eS z9@jl(OnH4juMxY+*r03VDfPx_IM!Lmc(5hOI;`?d37f>jPP$?9jQQIQU@i4vuG6MagEoJrQ=RD7xt@8E;c zeGV*+Pt+t$@pt!|McETOE$9k=_C!70uhwRS9X#b%ZK z%q(TIUXSS^F0`4Cx?Rk07C6wI4!UVPeI~-fxY6`YH$kABdOuiRtl73MqG|~AzZ@iL&^s?24iS;RK_pdlWkhcF z@Wv-Om(Aealfg)D^adlXh9Nvf~Uf@y;g3Y)i(YP zEXDnb1V}1pJT5ZWyw=1i+0fni9yINurD=EqH^ciOwLUGi)C%Da)tyt=zq2P7pV5-G zR7!oq28-Fgn5pW|nlu^b!S1Z#r7!Wtr{5J5PQ>pd+2P7RSD?>(U7-|Y z7ZQ5lhYIl_IF<9?T9^IPK<(Hp;l5bl5tF9>X-zG14_7PfsA>6<$~A338iYRT{a@r_ zuXBaT=`T5x3=s&3=RYx6NgG>No4?5KFBVjE(swfcivcIpPQFx5l+O;fiGsOrl5teR z_Cm+;PW}O0Dwe_(4Z@XZ)O0W-v2X><&L*<~*q3dg;bQW3g7)a#3KiQP>+qj|qo*Hk z?57>f2?f@`=Fj^nkDKeRkN2d$Z@2eNKpHo}ksj-$`QKb6n?*$^*%Fb3_Kbf1(*W9K>{L$mud2WHJ=j0^=g30Xhg8$#g^?36`p1fm;;1@0Lrx+8t`?vN0ZorM zSW?rhjCE8$C|@p^sXdx z|NOHHg+fL;HIlqyLp~SSdIF`TnSHehNCU9t89yr@)FY<~hu+X`tjg(aSVae$wDG*C zq$nY(Y494R)hD!i1|IIyP*&PD_c2FPgeY)&mX1qujB1VHPG9`yFQpLFVQ0>EKS@Bp zAfP5`C(sWGLI?AC{XEjLKR4FVNw(4+9b?kba95ukgR1H?w<8F7)G+6&(zUhIE5Ef% z=fFkL3QKA~M@h{nzjRq!Y_t!%U66#L8!(2-GgFxkD1=JRRqk=n%G(yHKn%^&$dW>; zSjAcjETMz1%205se$iH_)ZCpfg_LwvnsZQAUCS#^FExp8O4CrJb6>JquNV@qPq~3A zZ<6dOU#6|8+fcgiA#~MDmcpIEaUO02L5#T$HV0$EMD94HT_eXLZ2Zi&(! z&5E>%&|FZ`)CN10tM%tLSPD*~r#--K(H-CZqIOb99_;m|D5wdgJ<1iOJz@h2Zkq?} z%8_KXb&hf=2Wza(Wgc;3v3TN*;HTU*q2?#z&tLn_U0Nt!y>Oo>+2T)He6%XuP;fgn z-G!#h$Y2`9>Jtf}hbVrm6D70|ERzLAU>3zoWhJmjWfgM^))T+2u$~5>HF9jQDkrXR z=IzX36)V75PrFjkQ%TO+iqKGCQ-DDXbaE;C#}!-CoWQx&v*vHfyI>$HNRbpvm<`O( zlx9NBWD6_e&J%Ous4yp~s6)Ghni!I6)0W;9(9$y1wWu`$gs<$9Mcf$L*piP zPR0Av*2%ul`W;?-1_-5Zy0~}?`e@Y5A&0H!^ApyVTT}BiOm4GeFo$_oPlDEyeGBbh z1h3q&Dx~GmUS|3@4V36&$2uO8!Yp&^pD7J5&TN{?xphf*-js1fP?B|`>p_K>lh{ij zP(?H%e}AIP?_i^f&Li=FDSQ`2_NWxL+BB=nQr=$ zHojMlXNGauvvwPU>ZLq!`bX-5F4jBJ&So{kE5+ms9UEYD{66!|k~3vsP+mE}x!>%P za98bAU0!h0&ka4EoiDvBM#CP#dRNdXJcb*(%=<(g+M@<)DZ!@v1V>;54En?igcHR2 zhubQMq}VSOK)onqHfczM7YA@s=9*ow;k;8)&?J3@0JiGcP! zP#00KZ1t)GyZeRJ=f0^gc+58lc4Qh*S7RqPIC6GugG1gXe$LIQMRCo8cHf^qXgAa2 z`}t>u2Cq1CbSEpLr~E=c7~=Qkc9-vLE%(v9N*&HF`(d~(0`iukl5aQ9u4rUvc8%m) zr2GwZN4!s;{SB87lJB;veebPmqE}tSpT>+`t?<457Q9iV$th%i__Z1kOMAswFldD6 ztbOvO337S5o#ZZgN2G99_AVqPv!?Gmt3pzgD+Hp3QPQ`9qJ(g=kjvD+fUSS3upJn! zqoG7acIKEFRX~S}3|{EWT$kdz#zrDlJU(rPkxjws_iyLKU8+v|*oS_W*-guAb&Pj1 z35Z`3z<&Jb@2Mwz=KXucNYdY#SNO$tcVFr9KdKm|%^e-TXzs6M`PBper%ajkrIyUe zp$vVxVs9*>Vp4_1NC~Zg)WOCPmOxI1V34QlG4!aSFOH{QqSVq1^1)- z0P!Z?tT&E-ll(pwf0?=F=yOzik=@nh1Clxr9}Vij89z)ePDSCYAqw?lVI?v?+&*zH z)p$CScFI8rrwId~`}9YWPFu0cW1Sf@vRELs&cbntRU6QfPK-SO*mqu|u~}8AJ!Q$z znzu}50O=YbjwKCuSVBs6&CZR#0FTu)3{}qJJYX(>QPr4$RqWiwX3NT~;>cLn*_&1H zaKpIW)JVJ>b{uo2oq>oQt3y=zJjb%fU@wLqM{SyaC6x2snMx-}ivfU<1- znu1Lh;i$3Tf$Kh5Uk))G!D1UhE8pvx&nO~w^fG)BC&L!_hQk%^p`Kp@F{cz>80W&T ziOK=Sq3fdRu*V0=S53rcIfWFazI}Twj63CG(jOB;$*b`*#B9uEnBM`hDk*EwSRdwP8?5T?xGUKs=5N83XsR*)a4|ijz|c{4tIU+4j^A5C<#5 z*$c_d=5ml~%pGxw#?*q9N7aRwPux5EyqHVkdJO=5J>84!X6P>DS8PTTz>7C#FO?k#edkntG+fJk8ZMn?pmJSO@`x-QHq;7^h6GEXLXo1TCNhH z8ZDH{*NLAjo3WM`xeb=X{((uv3H(8&r8fJJg_uSs_%hOH%JDD?hu*2NvWGYD+j)&` zz#_1%O1wF^o5ryt?O0n;`lHbzp0wQ?rcbW(F1+h7_EZZ9{>rePvLAPVZ_R|n@;b$;UchU=0j<6k8G9QuQf@76oiE*4 zXOLQ&n3$NR#p4<5NJMVC*S);5x2)eRbaAM%VxWu9ohlT;pGEk7;002enCbQ>2r-us z3#bpXP9g|mE`65VrN`+3mC)M(eMj~~eOf)do<@l+fMiTR)XO}422*1SL{wyY(%oMpBgJagtiDf zz>O6(m;};>Hi=t8o{DVC@YigqS(Qh+ix3Rwa9aliH}a}IlOCW1@?%h_bRbq-W{KHF z%Vo?-j@{Xi@=~Lz5uZP27==UGE15|g^0gzD|3x)SCEXrx`*MP^FDLl%pOi~~Il;dc z^hrwp9sYeT7iZ)-ajKy@{a`kr0-5*_!XfBpXwEcFGJ;%kV$0Nx;apKrur zJN2J~CAv{Zjj%FolyurtW8RaFmpn&zKJWL>(0;;+q(%(Hx!GMW4AcfP0YJ*Vz!F4g z!ZhMyj$BdXL@MlF%KeInmPCt~9&A!;cRw)W!Hi@0DY(GD_f?jeV{=s=cJ6e}JktJw zQORnxxj3mBxfrH=x{`_^Z1ddDh}L#V7i}$njUFRVwOX?qOTKjfPMBO4y(WiU<)epb zvB9L=%jW#*SL|Nd_G?E*_h1^M-$PG6Pc_&QqF0O-FIOpa4)PAEPsyvB)GKasmBoEt z?_Q2~QCYGH+hW31x-B=@5_AN870vY#KB~3a*&{I=f);3Kv7q4Q7s)0)gVYx2#Iz9g(F2;=+Iy4 z6KI^8GJ6D@%tpS^8boU}zpi=+(5GfIR)35PzrbuXeL1Y1N%JK7PG|^2k3qIqHfX;G zQ}~JZ-UWx|60P5?d1e;AHx!_;#PG%d=^X(AR%i`l0jSpYOpXoKFW~7ip7|xvN;2^? zsYC9fanpO7rO=V7+KXqVc;Q5z%Bj})xHVrgoR04sA2 zl~DAwv=!(()DvH*=lyhIlU^hBkA0$e*7&fJpB0|oB7)rqGK#5##2T`@_I^|O2x4GO z;xh6ROcV<9>?e0)MI(y++$-ksV;G;Xe`lh76T#Htuia+(UrIXrf9?

L(tZ$0BqX1>24?V$S+&kLZ`AodQ4_)P#Q3*4xg8}lMV-FLwC*cN$< zt65Rf%7z41u^i=P*qO8>JqXPrinQFapR7qHAtp~&RZ85$>ob|Js;GS^y;S{XnGiBc zGa4IGvDl?x%gY`vNhv8wgZnP#UYI-w*^4YCZnxkF85@ldepk$&$#3EAhrJY0U)lR{F6sM3SONV^+$;Zx8BD&Eku3K zKNLZyBni3)pGzU0;n(X@1fX8wYGKYMpLmCu{N5-}epPDxClPFK#A@02WM3!myN%bkF z|GJ4GZ}3sL{3{qXemy+#Uk{4>Kf8v11;f8I&c76+B&AQ8udd<8gU7+BeWC`akUU~U zgXoxie>MS@rBoyY8O8Tc&8id!w+_ooxcr!1?#rc$-|SBBtH6S?)1e#P#S?jFZ8u-Bs&k`yLqW|{j+%c#A4AQ>+tj$Y z^CZajspu$F%73E68Lw5q7IVREED9r1Ijsg#@DzH>wKseye>hjsk^{n0g?3+gs@7`i zHx+-!sjLx^fS;fY!ERBU+Q zVJ!e0hJH%P)z!y%1^ZyG0>PN@5W~SV%f>}c?$H8r;Sy-ui>aruVTY=bHe}$e zi&Q4&XK!qT7-XjCrDaufT@>ieQ&4G(SShUob0Q>Gznep9fR783jGuUynAqc6$pYX; z7*O@@JW>O6lKIk0G00xsm|=*UVTQBB`u1f=6wGAj%nHK_;Aqmfa!eAykDmi-@u%6~ z;*c!pS1@V8r@IX9j&rW&d*}wpNs96O2Ute>%yt{yv>k!6zfT6pru{F1M3P z2WN1JDYqoTB#(`kE{H676QOoX`cnqHl1Yaru)>8Ky~VU{)r#{&s86Vz5X)v15ULHA zAZDb{99+s~qI6;-dQ5DBjHJP@GYTwn;Dv&9kE<0R!d z8tf1oq$kO`_sV(NHOSbMwr=To4r^X$`sBW4$gWUov|WY?xccQJN}1DOL|GEaD_!@& z15p?Pj+>7d`@LvNIu9*^hPN)pwcv|akvYYq)ks%`G>!+!pW{-iXPZsRp8 z35LR;DhseQKWYSD`%gO&k$Dj6_6q#vjWA}rZcWtQr=Xn*)kJ9kacA=esi*I<)1>w^ zO_+E>QvjP)qiSZg9M|GNeLtO2D7xT6vsj`88sd!94j^AqxFLi}@w9!Y*?nwWARE0P znuI_7A-saQ+%?MFA$gttMV-NAR^#tjl_e{R$N8t2NbOlX373>e7Ox=l=;y#;M7asp zRCz*CLnrm$esvSb5{T<$6CjY zmZ(i{Rs_<#pWW>(HPaaYj`%YqBra=Ey3R21O7vUbzOkJJO?V`4-D*u4$Me0Bx$K(lYo`JO}gnC zx`V}a7m-hLU9Xvb@K2ymioF)vj12<*^oAqRuG_4u%(ah?+go%$kOpfb`T96P+L$4> zQ#S+sA%VbH&mD1k5Ak7^^dZoC>`1L%i>ZXmooA!%GI)b+$D&ziKrb)a=-ds9xk#~& z7)3iem6I|r5+ZrTRe_W861x8JpD`DDIYZNm{$baw+$)X^Jtjnl0xlBgdnNY}x%5za zkQ8E6T<^$sKBPtL4(1zi_Rd(tVth*3Xs!ulflX+70?gb&jRTnI8l+*Aj9{|d%qLZ+ z>~V9Z;)`8-lds*Zgs~z1?Fg?Po7|FDl(Ce<*c^2=lFQ~ahwh6rqSjtM5+$GT>3WZW zj;u~w9xwAhOc<kF}~`CJ68 z?(S5vNJa;kriPlim33{N5`C{9?NWhzsna_~^|K2k4xz1`xcui*LXL-1#Y}Hi9`Oo!zQ>x-kgAX4LrPz63uZ+?uG*84@PKq-KgQlMNRwz=6Yes) zY}>YN+qP}nwr$(CZQFjUOI=-6J$2^XGvC~EZ+vrqWaOXB$k?%Suf5k=4>AveC1aJ! ziaW4IS%F$_Babi)kA8Y&u4F7E%99OPtm=vzw$$ zEz#9rvn`Iot_z-r3MtV>k)YvErZ<^Oa${`2>MYYODSr6?QZu+be-~MBjwPGdMvGd!b!elsdi4% z`37W*8+OGulab8YM?`KjJ8e+jM(tqLKSS@=jimq3)Ea2EB%88L8CaM+aG7;27b?5` z4zuUWBr)f)k2o&xg{iZ$IQkJ+SK>lpq4GEacu~eOW4yNFLU!Kgc{w4&D$4ecm0f}~ zTTzquRW@`f0}|IILl`!1P+;69g^upiPA6F{)U8)muWHzexRenBU$E^9X-uIY2%&1w z_=#5*(nmxJ9zF%styBwivi)?#KMG96-H@hD-H_&EZiRNsfk7mjBq{L%!E;Sqn!mVX*}kXhwH6eh;b42eD!*~upVG@ z#smUqz$ICm!Y8wY53gJeS|Iuard0=;k5i5Z_hSIs6tr)R4n*r*rE`>38Pw&lkv{_r!jNN=;#?WbMj|l>cU(9trCq; z%nN~r^y7!kH^GPOf3R}?dDhO=v^3BeP5hF|%4GNQYBSwz;x({21i4OQY->1G=KFyu z&6d`f2tT9Yl_Z8YACZaJ#v#-(gcyeqXMhYGXb=t>)M@fFa8tHp2x;ODX=Ap@a5I=U z0G80^$N0G4=U(>W%mrrThl0DjyQ-_I>+1Tdd_AuB3qpYAqY54upwa3}owa|x5iQ^1 zEf|iTZxKNGRpI>34EwkIQ2zHDEZ=(J@lRaOH>F|2Z%V_t56Km$PUYu^xA5#5Uj4I4RGqHD56xT%H{+P8Ag>e_3pN$4m8n>i%OyJFPNWaEnJ4McUZPa1QmOh?t8~n& z&RulPCors8wUaqMHECG=IhB(-tU2XvHP6#NrLVyKG%Ee*mQ5Ps%wW?mcnriTVRc4J`2YVM>$ixSF2Xi+Wn(RUZnV?mJ?GRdw%lhZ+t&3s7g!~g{%m&i<6 z5{ib-<==DYG93I(yhyv4jp*y3#*WNuDUf6`vTM%c&hiayf(%=x@4$kJ!W4MtYcE#1 zHM?3xw63;L%x3drtd?jot!8u3qeqctceX3m;tWetK+>~q7Be$h>n6riK(5@ujLgRS zvOym)k+VAtyV^mF)$29Y`nw&ijdg~jYpkx%*^ z8dz`C*g=I?;clyi5|!27e2AuSa$&%UyR(J3W!A=ZgHF9OuKA34I-1U~pyD!KuRkjA zbkN!?MfQOeN>DUPBxoy5IX}@vw`EEB->q!)8fRl_mqUVuRu|C@KD-;yl=yKc=ZT0% zB$fMwcC|HE*0f8+PVlWHi>M`zfsA(NQFET?LrM^pPcw`cK+Mo0%8*x8@65=CS_^$cG{GZQ#xv($7J z??R$P)nPLodI;P!IC3eEYEHh7TV@opr#*)6A-;EU2XuogHvC;;k1aI8asq7ovoP!* z?x%UoPrZjj<&&aWpsbr>J$Er-7!E(BmOyEv!-mbGQGeJm-U2J>74>o5x`1l;)+P&~ z>}f^=Rx(ZQ2bm+YE0u=ZYrAV@apyt=v1wb?R@`i_g64YyAwcOUl=C!i>=Lzb$`tjv zOO-P#A+)t-JbbotGMT}arNhJmmGl-lyUpMn=2UacVZxmiG!s!6H39@~&uVokS zG=5qWhfW-WOI9g4!R$n7!|ViL!|v3G?GN6HR0Pt_L5*>D#FEj5wM1DScz4Jv@Sxnl zB@MPPmdI{(2D?;*wd>3#tjAirmUnQoZrVv`xM3hARuJksF(Q)wd4P$88fGYOT1p6U z`AHSN!`St}}UMBT9o7i|G`r$ zrB=s$qV3d6$W9@?L!pl0lf%)xs%1ko^=QY$ty-57=55PvP(^6E7cc zGJ*>m2=;fOj?F~yBf@K@9qwX0hA803Xw+b0m}+#a(>RyR8}*Y<4b+kpp|OS+!whP( zH`v{%s>jsQI9rd$*vm)EkwOm#W_-rLTHcZRek)>AtF+~<(did)*oR1|&~1|e36d-d zgtm5cv1O0oqgWC%Et@P4Vhm}Ndl(Y#C^MD03g#PH-TFy+7!Osv1z^UWS9@%JhswEq~6kSr2DITo59+; ze=ZC}i2Q?CJ~Iyu?vn|=9iKV>4j8KbxhE4&!@SQ^dVa-gK@YfS9xT(0kpW*EDjYUkoj! zE49{7H&E}k%5(>sM4uGY)Q*&3>{aitqdNnRJkbOmD5Mp5rv-hxzOn80QsG=HJ_atI-EaP69cacR)Uvh{G5dTpYG7d zbtmRMq@Sexey)||UpnZ?;g_KMZq4IDCy5}@u!5&B^-=6yyY{}e4Hh3ee!ZWtL*s?G zxG(A!<9o!CL+q?u_utltPMk+hn?N2@?}xU0KlYg?Jco{Yf@|mSGC<(Zj^yHCvhmyx z?OxOYoxbptDK()tsJ42VzXdINAMWL$0Gcw?G(g8TMB)Khw_|v9`_ql#pRd2i*?CZl z7k1b!jQB=9-V@h%;Cnl7EKi;Y^&NhU0mWEcj8B|3L30Ku#-9389Q+(Yet0r$F=+3p z6AKOMAIi|OHyzlHZtOm73}|ntKtFaXF2Fy|M!gOh^L4^62kGUoWS1i{9gsds_GWBc zLw|TaLP64z3z9?=R2|T6Xh2W4_F*$cq>MtXMOy&=IPIJ`;!Tw?PqvI2b*U1)25^<2 zU_ZPoxg_V0tngA0J+mm?3;OYw{i2Zb4x}NedZug!>EoN3DC{1i)Z{Z4m*(y{ov2%- zk(w>+scOO}MN!exSc`TN)!B=NUX`zThWO~M*ohqq;J2hx9h9}|s#?@eR!=F{QTrq~ zTcY|>azkCe$|Q0XFUdpFT=lTcyW##i;-e{}ORB4D?t@SfqGo_cS z->?^rh$<&n9DL!CF+h?LMZRi)qju!meugvxX*&jfD!^1XB3?E?HnwHP8$;uX{Rvp# zh|)hM>XDv$ZGg=$1{+_bA~u-vXqlw6NH=nkpyWE0u}LQjF-3NhATL@9rRxMnpO%f7 z)EhZf{PF|mKIMFxnC?*78(}{Y)}iztV12}_OXffJ;ta!fcFIVjdchyHxH=t%ci`Xd zX2AUB?%?poD6Zv*&BA!6c5S#|xn~DK01#XvjT!w!;&`lDXSJT4_j$}!qSPrb37vc{ z9^NfC%QvPu@vlxaZ;mIbn-VHA6miwi8qJ~V;pTZkKqqOii<1Cs}0i?uUIss;hM4dKq^1O35y?Yp=l4i zf{M!@QHH~rJ&X~8uATV><23zZUbs-J^3}$IvV_ANLS08>k`Td7aU_S1sLsfi*C-m1 z-e#S%UGs4E!;CeBT@9}aaI)qR-6NU@kvS#0r`g&UWg?fC7|b^_HyCE!8}nyh^~o@< zpm7PDFs9yxp+byMS(JWm$NeL?DNrMCNE!I^ko-*csB+dsf4GAq{=6sfyf4wb>?v1v zmb`F*bN1KUx-`ra1+TJ37bXNP%`-Fd`vVQFTwWpX@;s(%nDQa#oWhgk#mYlY*!d>( zE&!|ySF!mIyfING+#%RDY3IBH_fW$}6~1%!G`suHub1kP@&DoAd5~7J55;5_noPI6eLf{t;@9Kf<{aO0`1WNKd?<)C-|?C?)3s z>wEq@8=I$Wc~Mt$o;g++5qR+(6wt9GI~pyrDJ%c?gPZe)owvy^J2S=+M^ z&WhIE`g;;J^xQLVeCtf7b%Dg#Z2gq9hp_%g)-%_`y*zb; zn9`f`mUPN-Ts&fFo(aNTsXPA|J!TJ{0hZp0^;MYHLOcD=r_~~^ymS8KLCSeU3;^QzJNqS z5{5rEAv#l(X?bvwxpU;2%pQftF`YFgrD1jt2^~Mt^~G>T*}A$yZc@(k9orlCGv&|1 zWWvVgiJsCAtamuAYT~nzs?TQFt<1LSEx!@e0~@yd6$b5!Zm(FpBl;(Cn>2vF?k zOm#TTjFwd2D-CyA!mqR^?#Uwm{NBemP>(pHmM}9;;8`c&+_o3#E5m)JzfwN?(f-a4 zyd%xZc^oQx3XT?vcCqCX&Qrk~nu;fxs@JUoyVoi5fqpi&bUhQ2y!Ok2pzsFR(M(|U zw3E+kH_zmTRQ9dUMZWRE%Zakiwc+lgv7Z%|YO9YxAy`y28`Aw;WU6HXBgU7fl@dnt z-fFBV)}H-gqP!1;V@Je$WcbYre|dRdp{xt!7sL3Eoa%IA`5CAA%;Wq8PktwPdULo! z8!sB}Qt8#jH9Sh}QiUtEPZ6H0b*7qEKGJ%ITZ|vH)5Q^2m<7o3#Z>AKc%z7_u`rXA zqrCy{-{8;9>dfllLu$^M5L z-hXs))h*qz%~ActwkIA(qOVBZl2v4lwbM>9l70Y`+T*elINFqt#>OaVWoja8RMsep z6Or3f=oBnA3vDbn*+HNZP?8LsH2MY)x%c13@(XfuGR}R?Nu<|07{$+Lc3$Uv^I!MQ z>6qWgd-=aG2Y^24g4{Bw9ueOR)(9h`scImD=86dD+MnSN4$6 z^U*o_mE-6Rk~Dp!ANp#5RE9n*LG(Vg`1)g6!(XtDzsov$Dvz|Gv1WU68J$CkshQhS zCrc|cdkW~UK}5NeaWj^F4MSgFM+@fJd{|LLM)}_O<{rj z+?*Lm?owq?IzC%U%9EBga~h-cJbIu=#C}XuWN>OLrc%M@Gu~kFEYUi4EC6l#PR2JS zQUkGKrrS#6H7}2l0F@S11DP`@pih0WRkRJl#F;u{c&ZC{^$Z+_*lB)r)-bPgRFE;* zl)@hK4`tEP=P=il02x7-C7p%l=B`vkYjw?YhdJU9!P!jcmY$OtC^12w?vy3<<=tlY zUwHJ_0lgWN9vf>1%WACBD{UT)1qHQSE2%z|JHvP{#INr13jM}oYv_5#xsnv9`)UAO zuwgyV4YZ;O)eSc3(mka6=aRohi!HH@I#xq7kng?Acdg7S4vDJb6cI5fw?2z%3yR+| zU5v@Hm}vy;${cBp&@D=HQ9j7NcFaOYL zj-wV=eYF{|XTkFNM2uz&T8uH~;)^Zo!=KP)EVyH6s9l1~4m}N%XzPpduPg|h-&lL` zAXspR0YMOKd2yO)eMFFJ4?sQ&!`dF&!|niH*!^*Ml##o0M(0*uK9&yzekFi$+mP9s z>W9d%Jb)PtVi&-Ha!o~Iyh@KRuKpQ@)I~L*d`{O8!kRObjO7=n+Gp36fe!66neh+7 zW*l^0tTKjLLzr`x4`_8&on?mjW-PzheTNox8Hg7Nt@*SbE-%kP2hWYmHu#Fn@Q^J(SsPUz*|EgOoZ6byg3ew88UGdZ>9B2Tq=jF72ZaR=4u%1A6Vm{O#?@dD!(#tmR;eP(Fu z{$0O%=Vmua7=Gjr8nY%>ul?w=FJ76O2js&17W_iq2*tb!i{pt#`qZB#im9Rl>?t?0c zicIC}et_4d+CpVPx)i4~$u6N-QX3H77ez z?ZdvXifFk|*F8~L(W$OWM~r`pSk5}#F?j_5u$Obu9lDWIknO^AGu+Blk7!9Sb;NjS zncZA?qtASdNtzQ>z7N871IsPAk^CC?iIL}+{K|F@BuG2>qQ;_RUYV#>hHO(HUPpk@ z(bn~4|F_jiZi}Sad;_7`#4}EmD<1EiIxa48QjUuR?rC}^HRocq`OQPM@aHVKP9E#q zy%6bmHygCpIddPjE}q_DPC`VH_2m;Eey&ZH)E6xGeStOK7H)#+9y!%-Hm|QF6w#A( zIC0Yw%9j$s-#odxG~C*^MZ?M<+&WJ+@?B_QPUyTg9DJGtQN#NIC&-XddRsf3n^AL6 zT@P|H;PvN;ZpL0iv$bRb7|J{0o!Hq+S>_NrH4@coZtBJu#g8#CbR7|#?6uxi8d+$g z87apN>EciJZ`%Zv2**_uiET9Vk{pny&My;+WfGDw4EVL#B!Wiw&M|A8f1A@ z(yFQS6jfbH{b8Z-S7D2?Ixl`j0{+ZnpT=;KzVMLW{B$`N?Gw^Fl0H6lT61%T2AU**!sX0u?|I(yoy&Xveg7XBL&+>n6jd1##6d>TxE*Vj=8lWiG$4=u{1UbAa5QD>5_ z;Te^42v7K6Mmu4IWT6Rnm>oxrl~b<~^e3vbj-GCdHLIB_>59}Ya+~OF68NiH=?}2o zP(X7EN=quQn&)fK>M&kqF|<_*H`}c zk=+x)GU>{Af#vx&s?`UKUsz})g^Pc&?Ka@t5$n$bqf6{r1>#mWx6Ep>9|A}VmWRnowVo`OyCr^fHsf# zQjQ3Ttp7y#iQY8l`zEUW)(@gGQdt(~rkxlkefskT(t%@i8=|p1Y9Dc5bc+z#n$s13 zGJk|V0+&Ekh(F};PJzQKKo+FG@KV8a<$gmNSD;7rd_nRdc%?9)p!|B-@P~kxQG}~B zi|{0}@}zKC(rlFUYp*dO1RuvPC^DQOkX4<+EwvBAC{IZQdYxoq1Za!MW7%p7gGr=j zzWnAq%)^O2$eItftC#TTSArUyL$U54-O7e|)4_7%Q^2tZ^0-d&3J1}qCzR4dWX!)4 zzIEKjgnYgMus^>6uw4Jm8ga6>GBtMjpNRJ6CP~W=37~||gMo_p@GA@#-3)+cVYnU> zE5=Y4kzl+EbEh%dhQokB{gqNDqx%5*qBusWV%!iprn$S!;oN_6E3?0+umADVs4ako z?P+t?m?};gev9JXQ#Q&KBpzkHPde_CGu-y z<{}RRAx=xlv#mVi+Ibrgx~ujW$h{?zPfhz)Kp7kmYS&_|97b&H&1;J-mzrBWAvY} zh8-I8hl_RK2+nnf&}!W0P+>5?#?7>npshe<1~&l_xqKd0_>dl_^RMRq@-Myz&|TKZBj1=Q()) zF{dBjv5)h=&Z)Aevx}+i|7=R9rG^Di!sa)sZCl&ctX4&LScQ-kMncgO(9o6W6)yd< z@Rk!vkja*X_N3H=BavGoR0@u0<}m-7|2v!0+2h~S2Q&a=lTH91OJsvms2MT~ zY=c@LO5i`mLpBd(vh|)I&^A3TQLtr>w=zoyzTd=^f@TPu&+*2MtqE$Avf>l>}V|3-8Fp2hzo3y<)hr_|NO(&oSD z!vEjTWBxbKTiShVl-U{n*B3#)3a8$`{~Pk}J@elZ=>Pqp|MQ}jrGv7KrNcjW%TN_< zZz8kG{#}XoeWf7qY?D)L)8?Q-b@Na&>i=)(@uNo zr;cH98T3$Iau8Hn*@vXi{A@YehxDE2zX~o+RY`)6-X{8~hMpc#C`|8y> zU8Mnv5A0dNCf{Ims*|l-^ z(MRp{qoGohB34|ggDI*p!Aw|MFyJ|v+<+E3brfrI)|+l3W~CQLPbnF@G0)P~Ly!1TJLp}xh8uW`Q+RB-v`MRYZ9Gam3cM%{ zb4Cb*f)0deR~wtNb*8w-LlIF>kc7DAv>T0D(a3@l`k4TFnrO+g9XH7;nYOHxjc4lq zMmaW6qpgAgy)MckYMhl?>sq;-1E)-1llUneeA!ya9KM$)DaNGu57Z5aE>=VST$#vb zFo=uRHr$0M{-ha>h(D_boS4zId;3B|Tpqo|?B?Z@I?G(?&Iei+-{9L_A9=h=Qfn-U z1wIUnQe9!z%_j$F_{rf&`ZFSott09gY~qrf@g3O=Y>vzAnXCyL!@(BqWa)Zqt!#_k zfZHuwS52|&&)aK;CHq9V-t9qt0au{$#6c*R#e5n3rje0hic7c7m{kW$p(_`wB=Gw7 z4k`1Hi;Mc@yA7dp@r~?@rfw)TkjAW++|pkfOG}0N|2guek}j8Zen(!+@7?qt_7ndX zB=BG6WJ31#F3#Vk3=aQr8T)3`{=p9nBHlKzE0I@v`{vJ}h8pd6vby&VgFhzH|q;=aonunAXL6G2y(X^CtAhWr*jI zGjpY@raZDQkg*aMq}Ni6cRF z{oWv}5`nhSAv>usX}m^GHt`f(t8@zHc?K|y5Zi=4G*UG1Sza{$Dpj%X8 zzEXaKT5N6F5j4J|w#qlZP!zS7BT)9b+!ZSJdToqJts1c!)fwih4d31vfb{}W)EgcA zH2pZ^8_k$9+WD2n`6q5XbOy8>3pcYH9 z07eUB+p}YD@AH!}p!iKv><2QF-Y^&xx^PAc1F13A{nUeCDg&{hnix#FiO!fe(^&%Qcux!h znu*S!s$&nnkeotYsDthh1dq(iQrE|#f_=xVgfiiL&-5eAcC-> z5L0l|DVEM$#ulf{bj+Y~7iD)j<~O8CYM8GW)dQGq)!mck)FqoL^X zwNdZb3->hFrbHFm?hLvut-*uK?zXn3q1z|UX{RZ;-WiLoOjnle!xs+W0-8D)kjU#R z+S|A^HkRg$Ij%N4v~k`jyHffKaC~=wg=9)V5h=|kLQ@;^W!o2^K+xG&2n`XCd>OY5Ydi= zgHH=lgy++erK8&+YeTl7VNyVm9-GfONlSlVb3)V9NW5tT!cJ8d7X)!b-$fb!s76{t z@d=Vg-5K_sqHA@Zx-L_}wVnc@L@GL9_K~Zl(h5@AR#FAiKad8~KeWCo@mgXIQ#~u{ zgYFwNz}2b6Vu@CP0XoqJ+dm8px(5W5-Jpis97F`+KM)TuP*X8H@zwiVKDKGVp59pI zifNHZr|B+PG|7|Y<*tqap0CvG7tbR1R>jn70t1X`XJixiMVcHf%Ez*=xm1(CrTSDt z0cle!+{8*Ja&EOZ4@$qhBuKQ$U95Q%rc7tg$VRhk?3=pE&n+T3upZg^ZJc9~c2es% zh7>+|mrmA-p&v}|OtxqmHIBgUxL~^0+cpfkSK2mhh+4b=^F1Xgd2)}U*Yp+H?ls#z zrLxWg_hm}AfK2XYWr!rzW4g;+^^&bW%LmbtRai9f3PjU${r@n`JThy-cphbcwn)rq9{A$Ht`lmYKxOacy z6v2R(?gHhD5@&kB-Eg?4!hAoD7~(h>(R!s1c1Hx#s9vGPePUR|of32bS`J5U5w{F) z>0<^ktO2UHg<0{oxkdOQ;}coZDQph8p6ruj*_?uqURCMTac;>T#v+l1Tc~%^k-Vd@ zkc5y35jVNc49vZpZx;gG$h{%yslDI%Lqga1&&;mN{Ush1c7p>7e-(zp}6E7f-XmJb4nhk zb8zS+{IVbL$QVF8pf8}~kQ|dHJAEATmmnrb_wLG}-yHe>W|A&Y|;muy-d^t^<&)g5SJfaTH@P1%euONny=mxo+C z4N&w#biWY41r8k~468tvuYVh&XN&d#%QtIf9;iVXfWY)#j=l`&B~lqDT@28+Y!0E+MkfC}}H*#(WKKdJJq=O$vNYCb(ZG@p{fJgu;h z21oHQ(14?LeT>n5)s;uD@5&ohU!@wX8w*lB6i@GEH0pM>YTG+RAIWZD;4#F1&F%Jp zXZUml2sH0!lYJT?&sA!qwez6cXzJEd(1ZC~kT5kZSp7(@=H2$Azb_*W&6aA|9iwCL zdX7Q=42;@dspHDwYE?miGX#L^3xD&%BI&fN9^;`v4OjQXPBaBmOF1;#C)8XA(WFlH zycro;DS2?(G&6wkr6rqC>rqDv3nfGw3hmN_9Al>TgvmGsL8_hXx09};l9Ow@)F5@y z#VH5WigLDwZE4nh^7&@g{1FV^UZ%_LJ-s<{HN*2R$OPg@R~Z`c-ET*2}XB@9xvAjrK&hS=f|R8Gr9 zr|0TGOsI7RD+4+2{ZiwdVD@2zmg~g@^D--YL;6UYGSM8i$NbQr4!c7T9rg!8;TM0E zT#@?&S=t>GQm)*ua|?TLT2ktj#`|R<_*FAkOu2Pz$wEc%-=Y9V*$&dg+wIei3b*O8 z2|m$!jJG!J!ZGbbIa!(Af~oSyZV+~M1qGvelMzPNE_%5?c2>;MeeG2^N?JDKjFYCy z7SbPWH-$cWF9~fX%9~v99L!G(wi!PFp>rB!9xj7=Cv|F+7CsGNwY0Q_J%FID%C^CBZQfJ9K(HK%k31j~e#&?hQ zNuD6gRkVckU)v+53-fc} z7ZCzYN-5RG4H7;>>Hg?LU9&5_aua?A0)0dpew1#MMlu)LHe(M;OHjHIUl7|%%)YPo z0cBk;AOY00%Fe6heoN*$(b<)Cd#^8Iu;-2v@>cE-OB$icUF9EEoaC&q8z9}jMTT2I z8`9;jT%z0;dy4!8U;GW{i`)3!c6&oWY`J3669C!tM<5nQFFrFRglU8f)5Op$GtR-3 zn!+SPCw|04sv?%YZ(a7#L?vsdr7ss@WKAw&A*}-1S|9~cL%uA+E~>N6QklFE>8W|% zyX-qAUGTY1hQ-+um`2|&ji0cY*(qN!zp{YpDO-r>jPk*yuVSay<)cUt`t@&FPF_&$ zcHwu1(SQ`I-l8~vYyUxm@D1UEdFJ$f5Sw^HPH7b!9 zzYT3gKMF((N(v0#4f_jPfVZ=ApN^jQJe-X$`A?X+vWjLn_%31KXE*}5_}d8 zw_B1+a#6T1?>M{ronLbHIlEsMf93muJ7AH5h%;i99<~JX^;EAgEB1uHralD*!aJ@F zV2ruuFe9i2Q1C?^^kmVy921eb=tLDD43@-AgL^rQ3IO9%+vi_&R2^dpr}x{bCVPej z7G0-0o64uyWNtr*loIvslyo0%)KSDDKjfThe0hcqs)(C-MH1>bNGBDRTW~scy_{w} zp^aq8Qb!h9Lwielq%C1b8=?Z=&U)ST&PHbS)8Xzjh2DF?d{iAv)Eh)wsUnf>UtXN( zL7=$%YrZ#|^c{MYmhn!zV#t*(jdmYdCpwqpZ{v&L8KIuKn`@IIZfp!uo}c;7J57N` zAxyZ-uA4=Gzl~Ovycz%MW9ZL7N+nRo&1cfNn9(1H5eM;V_4Z_qVann7F>5f>%{rf= zPBZFaV@_Sobl?Fy&KXyzFDV*FIdhS5`Uc~S^Gjo)aiTHgn#<0C=9o-a-}@}xDor;D zZyZ|fvf;+=3MZd>SR1F^F`RJEZo+|MdyJYQAEauKu%WDol~ayrGU3zzbHKsnHKZ*z zFiwUkL@DZ>!*x05ql&EBq@_Vqv83&?@~q5?lVmffQZ+V-=qL+!u4Xs2Z2zdCQ3U7B&QR9_Iggy} z(om{Y9eU;IPe`+p1ifLx-XWh?wI)xU9ik+m#g&pGdB5Bi<`PR*?92lE0+TkRuXI)z z5LP!N2+tTc%cB6B1F-!fj#}>S!vnpgVU~3!*U1ej^)vjUH4s-bd^%B=ItQqDCGbrEzNQi(dJ`J}-U=2{7-d zK8k^Rlq2N#0G?9&1?HSle2vlkj^KWSBYTwx`2?9TU_DX#J+f+qLiZCqY1TXHFxXZqYMuD@RU$TgcnCC{_(vwZ-*uX)~go#%PK z@}2Km_5aQ~(<3cXeJN6|F8X_1@L%@xTzs}$_*E|a^_URF_qcF;Pfhoe?FTFwvjm1o z8onf@OY@jC2tVcMaZS;|T!Ks(wOgPpRzRnFS-^RZ4E!9dsnj9sFt609a|jJbb1Dt@ z<=Gal2jDEupxUSwWu6zp<<&RnAA;d&4gKVG0iu6g(DsST(4)z6R)zDpfaQ}v{5ARt zyhwvMtF%b-YazR5XLz+oh=mn;y-Mf2a8>7?2v8qX;19y?b>Z5laGHvzH;Nu9S`B8} zI)qN$GbXIQ1VL3lnof^6TS~rvPVg4V?Dl2Bb*K2z4E{5vy<(@@K_cN@U>R!>aUIRnb zL*)=787*cs#zb31zBC49x$`=fkQbMAef)L2$dR{)6BAz!t5U_B#1zZG`^neKSS22oJ#5B=gl%U=WeqL9REF2g zZnfCb0?quf?Ztj$VXvDSWoK`0L=Zxem2q}!XWLoT-kYMOx)!7fcgT35uC~0pySEme z`{wGWTkGr7>+Kb^n;W?BZH6ZP(9tQX%-7zF>vc2}LuWDI(9kh1G#7B99r4x6;_-V+k&c{nPUrR zAXJGRiMe~aup{0qzmLNjS_BC4cB#sXjckx{%_c&^xy{M61xEb>KW_AG5VFXUOjAG4 z^>Qlm9A#1N{4snY=(AmWzatb!ngqiqPbBZ7>Uhb3)dTkSGcL#&SH>iMO-IJBPua`u zo)LWZ>=NZLr758j{%(|uQuZ)pXq_4c!!>s|aDM9#`~1bzK3J1^^D#<2bNCccH7~-X}Ggi!pIIF>uFx%aPARGQsnC8ZQc8lrQ5o~smqOg>Ti^GNme94*w z)JZy{_{#$jxGQ&`M z!OMvZMHR>8*^>eS%o*6hJwn!l8VOOjZQJvh)@tnHVW&*GYPuxqXw}%M!(f-SQf`=L z5;=5w2;%82VMH6Xi&-K3W)o&K^+vJCepWZ-rW%+Dc6X3(){z$@4zjYxQ|}8UIojeC zYZpQ1dU{fy=oTr<4VX?$q)LP}IUmpiez^O&N3E_qPpchGTi5ZM6-2ScWlQq%V&R2Euz zO|Q0Hx>lY1Q1cW5xHv5!0OGU~PVEqSuy#fD72d#O`N!C;o=m+YioGu-wH2k6!t<~K zSr`E=W9)!g==~x9VV~-8{4ZN9{~-A9zJpRe%NGg$+MDuI-dH|b@BD)~>pPCGUNNzY zMDg||0@XGQgw`YCt5C&A{_+J}mvV9Wg{6V%2n#YSRN{AP#PY?1FF1#|vO_%e+#`|2*~wGAJaeRX6=IzFNeWhz6gJc8+(03Ph4y6ELAm=AkN7TOgMUEw*N{= z_)EIDQx5q22oUR+_b*tazu9+pX|n1c*IB-}{DqIj z-?E|ks{o3AGRNb;+iKcHkZvYJvFsW&83RAPs1Oh@IWy%l#5x2oUP6ZCtv+b|q>jsf zZ_9XO;V!>n`UxH1LvH8)L4?8raIvasEhkpQoJ`%!5rBs!0Tu(s_D{`4opB;57)pkX z4$A^8CsD3U5*!|bHIEqsn~{q+Ddj$ME@Gq4JXtgVz&7l{Ok!@?EA{B3P~NAqb9)4? zkQo30A^EbHfQ@87G5&EQTd`frrwL)&Yw?%-W@uy^Gn23%j?Y!Iea2xw<-f;esq zf%w5WN@E1}zyXtYv}}`U^B>W`>XPmdLj%4{P298|SisrE;7HvXX;A}Ffi8B#3Lr;1 zHt6zVb`8{#+e$*k?w8|O{Uh|&AG}|DG1PFo1i?Y*cQm$ZwtGcVgMwtBUDa{~L1KT-{jET4w60>{KZ27vXrHJ;fW{6| z=|Y4!&UX020wU1>1iRgB@Q#m~1^Z^9CG1LqDhYBrnx%IEdIty z!46iOoKlKs)c}newDG)rWUikD%j`)p z_w9Ph&e40=(2eBy;T!}*1p1f1SAUDP9iWy^u^Ubdj21Kn{46;GR+hwLO=4D11@c~V zI8x&(D({K~Df2E)Nx_yQvYfh4;MbMJ@Z}=Dt3_>iim~QZ*hZIlEs0mEb z_54+&*?wMD`2#vsQRN3KvoT>hWofI_Vf(^C1ff-Ike@h@saEf7g}<9T`W;HAne-Nd z>RR+&SP35w)xKn8^U$7))PsM!jKwYZ*RzEcG-OlTrX3}9a{q%#Un5E5W{{hp>w~;` zGky+3(vJvQyGwBo`tCpmo0mo((?nM8vf9aXrrY1Ve}~TuVkB(zeds^jEfI}xGBCM2 zL1|#tycSaWCurP+0MiActG3LCas@_@tao@(R1ANlwB$4K53egNE_;!&(%@Qo$>h`^1S_!hN6 z)vZtG$8fN!|BXBJ=SI>e(LAU(y(i*PHvgQ2llulxS8>qsimv7yL}0q_E5WiAz7)(f zC(ahFvG8&HN9+6^jGyLHM~$)7auppeWh_^zKk&C_MQ~8;N??OlyH~azgz5fe^>~7F zl3HnPN3z-kN)I$4@`CLCMQx3sG~V8hPS^}XDXZrQA>}mQPw%7&!sd(Pp^P=tgp-s^ zjl}1-KRPNWXgV_K^HkP__SR`S-|OF0bR-N5>I%ODj&1JUeAQ3$9i;B~$S6}*^tK?= z**%aCiH7y?xdY?{LgVP}S0HOh%0%LI$wRx;$T|~Y8R)Vdwa}kGWv8?SJVm^>r6+%I z#lj1aR94{@MP;t-scEYQWc#xFA30^}?|BeX*W#9OL;Q9#WqaaM546j5j29((^_8Nu z4uq}ESLr~r*O7E7$D{!k9W>`!SLoyA53i9QwRB{!pHe8um|aDE`Cg0O*{jmor)^t)3`>V>SWN-2VJcFmj^1?~tT=JrP`fVh*t zXHarp=8HEcR#vFe+1a%XXuK+)oFs`GDD}#Z+TJ}Ri`FvKO@ek2ayn}yaOi%(8p%2$ zpEu)v0Jym@f}U|-;}CbR=9{#<^z28PzkkTNvyKvJDZe+^VS2bES3N@Jq!-*}{oQlz z@8bgC_KnDnT4}d#&Cpr!%Yb?E!brx0!eVOw~;lLwUoz#Np%d$o%9scc3&zPm`%G((Le|6o1 zM(VhOw)!f84zG^)tZ1?Egv)d8cdNi+T${=5kV+j;Wf%2{3g@FHp^Gf*qO0q!u$=m9 zCaY`4mRqJ;FTH5`a$affE5dJrk~k`HTP_7nGTY@B9o9vvnbytaID;^b=Tzp7Q#DmD zC(XEN)Ktn39z5|G!wsVNnHi) z%^q94!lL|hF`IijA^9NR0F$@h7k5R^ljOW(;Td9grRN0Mb)l_l7##{2nPQ@?;VjXv zaLZG}yuf$r$<79rVPpXg?6iiieX|r#&`p#Con2i%S8*8F}(E) zI5E6c3tG*<;m~6>!&H!GJ6zEuhH7mkAzovdhLy;)q z{H2*8I^Pb}xC4s^6Y}6bJvMu=8>g&I)7!N!5QG$xseeU#CC?ZM-TbjsHwHgDGrsD= z{%f;@Sod+Ch66Ko2WF~;Ty)v>&x^aovCbCbD7>qF*!?BXmOV3(s|nxsb*Lx_2lpB7 zokUnzrk;P=T-&kUHO}td+Zdj!3n&NR?K~cRU zAXU!DCp?51{J4w^`cV#ye}(`SQhGQkkMu}O3M*BWt4UsC^jCFUy;wTINYmhD$AT;4 z?Xd{HaJjP`raZ39qAm;%beDbrLpbRf(mkKbANan7XsL>_pE2oo^$TgdidjRP!5-`% zv0d!|iKN$c0(T|L0C~XD0aS8t{*&#LnhE;1Kb<9&=c2B+9JeLvJr*AyyRh%@jHej=AetOMSlz^=!kxX>>B{2B1uIrQyfd8KjJ+DBy!h)~*(!|&L4^Q_07SQ~E zcemVP`{9CwFvPFu7pyVGCLhH?LhEVb2{7U+Z_>o25#+3<|8%1T^5dh}*4(kfJGry} zm%r#hU+__Z;;*4fMrX=Bkc@7|v^*B;HAl0((IBPPii%X9+u3DDF6%bI&6?Eu$8&aWVqHIM7mK6?Uvq$1|(-T|)IV<>e?!(rY zqkmO1MRaLeTR=)io(0GVtQT@s6rN%C6;nS3@eu;P#ry4q;^O@1ZKCJyp_Jo)Ty^QW z+vweTx_DLm{P-XSBj~Sl<%_b^$=}odJ!S2wAcxenmzFGX1t&Qp8Vxz2VT`uQsQYtdn&_0xVivIcxZ_hnrRtwq4cZSj1c-SG9 z7vHBCA=fd0O1<4*=lu$6pn~_pVKyL@ztw1swbZi0B?spLo56ZKu5;7ZeUml1Ws1?u zqMf1p{5myAzeX$lAi{jIUqo1g4!zWLMm9cfWcnw`k6*BR^?$2(&yW?>w;G$EmTA@a z6?y#K$C~ZT8+v{87n5Dm&H6Pb_EQ@V0IWmG9cG=O;(;5aMWWrIPzz4Q`mhK;qQp~a z+BbQrEQ+w{SeiuG-~Po5f=^EvlouB@_|4xQXH@A~KgpFHrwu%dwuCR)=B&C(y6J4J zvoGk9;lLs9%iA-IJGU#RgnZZR+@{5lYl8(e1h6&>Vc_mvg0d@);X zji4T|n#lB!>pfL|8tQYkw?U2bD`W{na&;*|znjmalA&f;*U++_aBYerq;&C8Kw7mI z7tsG*?7*5j&dU)Lje;^{D_h`%(dK|pB*A*1(Jj)w^mZ9HB|vGLkF1GEFhu&rH=r=8 zMxO42e{Si6$m+Zj`_mXb&w5Q(i|Yxyg?juUrY}78uo@~3v84|8dfgbPd0iQJRdMj< zncCNGdMEcsxu#o#B5+XD{tsg*;j-eF8`mp~K8O1J!Z0+>0=7O=4M}E?)H)ENE;P*F z$Ox?ril_^p0g7xhDUf(q652l|562VFlC8^r8?lQv;TMvn+*8I}&+hIQYh2 z1}uQQaag&!-+DZ@|C+C$bN6W;S-Z@)d1|en+XGvjbOxCa-qAF*LA=6s(Jg+g;82f$ z(Vb)8I)AH@cdjGFAR5Rqd0wiNCu!xtqWbcTx&5kslzTb^7A78~Xzw1($UV6S^VWiP zFd{Rimd-0CZC_Bu(WxBFW7+k{cOW7DxBBkJdJ;VsJ4Z@lERQr%3eVv&$%)b%<~ zCl^Y4NgO}js@u{|o~KTgH}>!* z_iDNqX2(As7T0xivMH|3SC1ivm8Q}6Ffcd7owUKN5lHAtzMM4<0v+ykUT!QiowO;`@%JGv+K$bBx@*S7C8GJVqQ_K>12}M`f_Ys=S zKFh}HM9#6Izb$Y{wYzItTy+l5U2oL%boCJn?R3?jP@n$zSIwlmyGq30Cw4QBO|14` zW5c);AN*J3&eMFAk$SR~2k|&+&Bc$e>s%c{`?d~85S-UWjA>DS5+;UKZ}5oVa5O(N zqqc@>)nee)+4MUjH?FGv%hm2{IlIF-QX}ym-7ok4Z9{V+ZHVZQl$A*x!(q%<2~iVv znUa+BX35&lCb#9VE-~Y^W_f;Xhl%vgjwdjzMy$FsSIj&ok}L+X`4>J=9BkN&nu^E*gbhj3(+D>C4E z@Fwq_=N)^bKFSHTzZk?-gNU$@l}r}dwGyh_fNi=9b|n}J>&;G!lzilbWF4B}BBq4f zYIOl?b)PSh#XTPp4IS5ZR_2C!E)Z`zH0OW%4;&~z7UAyA-X|sh9@~>cQW^COA9hV4 zXcA6qUo9P{bW1_2`eo6%hgbN%(G-F1xTvq!sc?4wN6Q4`e9Hku zFwvlAcRY?6h^Fj$R8zCNEDq8`=uZB8D-xn)tA<^bFFy}4$vA}Xq0jAsv1&5!h!yRA zU()KLJya5MQ`q&LKdH#fwq&(bNFS{sKlEh_{N%{XCGO+po#(+WCLmKW6&5iOHny>g z3*VFN?mx!16V5{zyuMWDVP8U*|BGT$(%IO|)?EF|OI*sq&RovH!N%=>i_c?K*A>>k zyg1+~++zY4Q)J;VWN0axhoIKx;l&G$gvj(#go^pZskEVj8^}is3Jw26LzYYVos0HX zRPvmK$dVxM8(Tc?pHFe0Z3uq){{#OK3i-ra#@+;*=ui8)y6hsRv z4Fxx1c1+fr!VI{L3DFMwXKrfl#Q8hfP@ajgEau&QMCxd{g#!T^;ATXW)nUg&$-n25 zruy3V!!;{?OTobo|0GAxe`Acn3GV@W=&n;~&9 zQM>NWW~R@OYORkJAo+eq1!4vzmf9K%plR4(tB@TR&FSbDoRgJ8qVcH#;7lQub*nq&?Z>7WM=oeEVjkaG zT#f)=o!M2DO5hLR+op>t0CixJCIeXH*+z{-XS|%jx)y(j&}Wo|3!l7{o)HU3m7LYyhv*xF&tq z%IN7N;D4raue&&hm0xM=`qv`+TK@;_xAcGKuK(2|75~ar2Yw)geNLSmVxV@x89bQu zpViVKKnlkwjS&&c|-X6`~xdnh}Ps)Hs z4VbUL^{XNLf7_|Oi>tA%?SG5zax}esF*FH3d(JH^Gvr7Rp*n=t7frH!U;!y1gJB^i zY_M$KL_}mW&XKaDEi9K-wZR|q*L32&m+2n_8lq$xRznJ7p8}V>w+d@?uB!eS3#u<} zIaqi!b!w}a2;_BfUUhGMy#4dPx>)_>yZ`ai?Rk`}d0>~ce-PfY-b?Csd(28yX22L% zI7XI>OjIHYTk_@Xk;Gu^F52^Gn6E1&+?4MxDS2G_#PQ&yXPXP^<-p|2nLTb@AAQEY zI*UQ9Pmm{Kat}wuazpjSyXCdnrD&|C1c5DIb1TnzF}f4KIV6D)CJ!?&l&{T)e4U%3HTSYqsQ zo@zWB1o}ceQSV)<4G<)jM|@@YpL+XHuWsr5AYh^Q{K=wSV99D~4RRU52FufmMBMmd z_H}L#qe(}|I9ZyPRD6kT>Ivj&2Y?qVZq<4bG_co_DP`sE*_Xw8D;+7QR$Uq(rr+u> z8bHUWbV19i#)@@G4bCco@Xb<8u~wVDz9S`#k@ciJtlu@uP1U0X?yov8v9U3VOig2t zL9?n$P3=1U_Emi$#slR>N5wH-=J&T=EdUHA}_Z zZIl3nvMP*AZS9{cDqFanrA~S5BqxtNm9tlu;^`)3X&V4tMAkJ4gEIPl= zoV!Gyx0N{3DpD@)pv^iS*dl2FwANu;1;%EDl}JQ7MbxLMAp>)UwNwe{=V}O-5C*>F zu?Ny+F64jZn<+fKjF01}8h5H_3pey|;%bI;SFg$w8;IC<8l|3#Lz2;mNNik6sVTG3 z+Su^rIE#40C4a-587$U~%KedEEw1%r6wdvoMwpmlXH$xPnNQN#f%Z7|p)nC>WsuO= z4zyqapLS<8(UJ~Qi9d|dQijb_xhA2)v>la)<1md5s^R1N&PiuA$^k|A<+2C?OiHbj z>Bn$~t)>Y(Zb`8hW7q9xQ=s>Rv81V+UiuZJc<23HplI88isqRCId89fb`Kt|CxVIg znWcwprwXnotO>3s&Oypkte^9yJjlUVVxSe%_xlzmje|mYOVPH^vjA=?6xd0vaj0Oz zwJ4OJNiFdnHJX3rw&inskjryukl`*fRQ#SMod5J|KroJRsVXa5_$q7whSQ{gOi*s0 z1LeCy|JBWRsDPn7jCb4s(p|JZiZ8+*ExC@Vj)MF|*Vp{B(ziccSn`G1Br9bV(v!C2 z6#?eqpJBc9o@lJ#^p-`-=`4i&wFe>2)nlPK1p9yPFzJCzBQbpkcR>={YtamIw)3nt z(QEF;+)4`>8^_LU)_Q3 zC5_7lgi_6y>U%m)m@}Ku4C}=l^J=<<7c;99ec3p{aR+v=diuJR7uZi%aQv$oP?dn?@6Yu_+*^>T0ptf(oobdL;6)N-I!TO`zg^Xbv3#L0I~sn@WGk-^SmPh5>W+LB<+1PU}AKa?FCWF|qMNELOgdxR{ zbqE7@jVe+FklzdcD$!(A$&}}H*HQFTJ+AOrJYnhh}Yvta(B zQ_bW4Rr;R~&6PAKwgLWXS{Bnln(vUI+~g#kl{r+_zbngT`Y3`^Qf=!PxN4IYX#iW4 zucW7@LLJA9Zh3(rj~&SyN_pjO8H&)|(v%!BnMWySBJV=eSkB3YSTCyIeJ{i;(oc%_hk{$_l;v>nWSB)oVeg+blh=HB5JSlG_r7@P z3q;aFoZjD_qS@zygYqCn=;Zxjo!?NK!%J$ z52lOP`8G3feEj+HTp@Tnn9X~nG=;tS+z}u{mQX_J0kxtr)O30YD%oo)L@wy`jpQYM z@M>Me=95k1p*FW~rHiV1CIfVc{K8r|#Kt(ApkXKsDG$_>76UGNhHExFCw#Ky9*B-z zNq2ga*xax!HMf_|Vp-86r{;~YgQKqu7%szk8$hpvi_2I`OVbG1doP(`gn}=W<8%Gn z%81#&WjkH4GV;4u43EtSW>K_Ta3Zj!XF?;SO3V#q=<=>Tc^@?A`i;&`-cYj|;^ zEo#Jl5zSr~_V-4}y8pnufXLa80vZY4z2ko7fj>DR)#z=wWuS1$$W!L?(y}YC+yQ|G z@L&`2upy3f>~*IquAjkVNU>}c10(fq#HdbK$~Q3l6|=@-eBbo>B9(6xV`*)sae58*f zym~RRVx;xoCG3`JV`xo z!lFw)=t2Hy)e!IFs?0~7osWk(d%^wxq&>_XD4+U#y&-VF%4z?XH^i4w`TxpF{`XhZ z%G}iEzf!T(l>g;W9<~K+)$g!{UvhW{E0Lis(S^%I8OF&%kr!gJ&fMOpM=&=Aj@wuL zBX?*6i51Qb$uhkwkFYkaD_UDE+)rh1c;(&Y=B$3)J&iJfQSx!1NGgPtK!$c9OtJuu zX(pV$bfuJpRR|K(dp@^j}i&HeJOh@|7lWo8^$*o~Xqo z5Sb+!EtJ&e@6F+h&+_1ETbg7LfP5GZjvIUIN3ibCOldAv z)>YdO|NH$x7AC8dr=<2ekiY1%fN*r~e5h6Yaw<{XIErujKV~tiyrvV_DV0AzEknC- zR^xKM3i<1UkvqBj3C{wDvytOd+YtDSGu!gEMg+!&|8BQrT*|p)(dwQLEy+ zMtMzij3zo40)CA!BKZF~yWg?#lWhqD3@qR)gh~D{uZaJO;{OWV8XZ_)J@r3=)T|kt zUS1pXr6-`!Z}w2QR7nP%d?ecf90;K_7C3d!UZ`N(TZoWNN^Q~RjVhQG{Y<%E1PpV^4 z-m-K+$A~-+VDABs^Q@U*)YvhY4Znn2^w>732H?NRK(5QSS$V@D7yz2BVX4)f5A04~$WbxGOam22>t&uD)JB8-~yiQW6ik;FGblY_I>SvB_z2?PS z*Qm&qbKI{H1V@YGWzpx`!v)WeLT02};JJo*#f$a*FH?IIad-^(;9XC#YTWN6;Z6+S zm4O1KH=#V@FJw7Pha0!9Vb%ZIM$)a`VRMoiN&C|$YA3~ZC*8ayZRY^fyuP6$n%2IU z$#XceYZeqLTXw(m$_z|33I$B4k~NZO>pP6)H_}R{E$i%USGy{l{-jOE;%CloYPEU+ zRFxOn4;7lIOh!7abb23YKD+_-?O z0FP9otcAh+oSj;=f#$&*ExUHpd&e#bSF%#8*&ItcL2H$Sa)?pt0Xtf+t)z$_u^wZi z44oE}r4kIZGy3!Mc8q$B&6JqtnHZ>Znn!Zh@6rgIu|yU+zG8q`q9%B18|T|oN3zMq z`l&D;U!OL~%>vo&q0>Y==~zLiCZk4v%s_7!9DxQ~id1LLE93gf*gg&2$|hB#j8;?3 z5v4S;oM6rT{Y;I+#FdmNw z){d%tNM<<#GN%n9ox7B=3#;u7unZ~tLB_vRZ52a&2=IM)2VkXm=L+Iqq~uk#Dug|x z>S84e+A7EiOY5lj*!q?6HDkNh~0g;0Jy(al!ZHHDtur9T$y-~)94HelX1NHjXWIM7UAe}$?jiz z9?P4`I0JM=G5K{3_%2jPLC^_Mlw?-kYYgb7`qGa3@dn|^1fRMwiyM@Ch z;CB&o7&&?c5e>h`IM;Wnha0QKnEp=$hA8TJgR-07N~U5(>9vJzeoFsSRBkDq=x(YgEMpb=l4TDD`2 zwVJpWGTA_u7}?ecW7s6%rUs&NXD3+n;jB86`X?8(l3MBo6)PdakI6V6a}22{)8ilT zM~T*mU}__xSy|6XSrJ^%lDAR3Lft%+yxC|ZUvSO_nqMX!_ul3;R#*{~4DA=h$bP)%8Yv9X zyp><|e8=_ttI}ZAwOd#dlnSjck#6%273{E$kJuCGu=I@O)&6ID{nWF5@gLb16sj|&Sb~+du4e4O_%_o`Ix4NRrAsyr1_}MuP94s>de8cH-OUkVPk3+K z&jW)It9QiU-ti~AuJkL`XMca8Oh4$SyJ=`-5WU<{cIh+XVH#e4d&zive_UHC!pN>W z3TB;Mn5i)9Qn)#6@lo4QpI3jFYc0~+jS)4AFz8fVC;lD^+idw^S~Qhq>Tg(!3$yLD zzktzoFrU@6s4wwCMz}edpF5i5Q1IMmEJQHzp(LAt)pgN3&O!&d?3W@6U4)I^2V{;- z6A(?zd93hS*uQmnh4T)nHnE{wVhh(=MMD(h(P4+^p83Om6t<*cUW>l(qJzr%5vp@K zN27ka(L{JX=1~e2^)F^i=TYj&;<7jyUUR2Bek^A8+3Up*&Xwc{)1nRR5CT8vG>ExV zHnF3UqXJOAno_?bnhCX-&kwI~Ti8t4`n0%Up>!U`ZvK^w2+0Cs-b9%w%4`$+To|k= zKtgc&l}P`*8IS>8DOe?EB84^kx4BQp3<7P{Pq}&p%xF_81pg!l2|u=&I{AuUgmF5n zJQCTLv}%}xbFGYtKfbba{CBo)lWW%Z>i(_NvLhoQZ*5-@2l&x>e+I~0Nld3UI9tdL zRzu8}i;X!h8LHVvN?C+|M81e>Jr38%&*9LYQec9Ax>?NN+9(_>XSRv&6hlCYB`>Qm z1&ygi{Y()OU4@D_jd_-7vDILR{>o|7-k)Sjdxkjgvi{@S>6GqiF|o`*Otr;P)kLHN zZkpts;0zw_6;?f(@4S1FN=m!4^mv~W+lJA`&7RH%2$)49z0A+8@0BCHtj|yH--AEL z0tW6G%X-+J+5a{5*WKaM0QDznf;V?L5&uQw+yegDNDP`hA;0XPYc6e0;Xv6|i|^F2WB)Z$LR|HR4 zTQsRAby9(^Z@yATyOgcfQw7cKyr^3Tz7lc7+JEwwzA7)|2x+PtEb>nD(tpxJQm)Kn zW9K_*r!L%~N*vS8<5T=iv|o!zTe9k_2jC_j*7ik^M_ zaf%k{WX{-;0*`t`G!&`eW;gChVXnJ-Rn)To8vW-?>>a%QU1v`ZC=U)f8iA@%JG0mZ zDqH;~mgBnrCP~1II<=V9;EBL)J+xzCoiRBaeH&J6rL!{4zIY8tZka?_FBeQeNO3q6 zyG_alW54Ba&wQf{&F1v-r1R6ID)PTsqjIBc+5MHkcW5Fnvi~{-FjKe)t1bl}Y;z@< z=!%zvpRua>>t_x}^}z0<7MI!H2v6|XAyR9!t50q-A)xk0nflgF4*OQlCGK==4S|wc zRMsSscNhRzHMBU8TdcHN!q^I}x0iXJ%uehac|Zs_B$p@CnF)HeXPpB_Za}F{<@6-4 zl%kml@}kHQ(ypD8FsPJ2=14xXJE|b20RUIgs!2|R3>LUMGF6X*B_I|$`Qg=;zm7C z{mEDy9dTmPbued7mlO@phdmAmJ7p@GR1bjCkMw6*G7#4+`k>fk1czdJUB!e@Q(~6# zwo%@p@V5RL0ABU2LH7Asq^quDUho@H>eTZH9f*no9fY0T zD_-9px3e}A!>>kv5wk91%C9R1J_Nh!*&Kk$J3KNxC}c_@zlgpJZ+5L)Nw|^p=2ue}CJtm;uj*Iqr)K})kA$xtNUEvX;4!Px*^&9T_`IN{D z{6~QY=Nau6EzpvufB^hflc#XIsSq0Y9(nf$d~6ZwK}fal92)fr%T3=q{0mP-EyP_G z)UR5h@IX}3Qll2b0oCAcBF>b*@Etu*aTLPU<%C>KoOrk=x?pN!#f_Og-w+;xbFgjQ zXp`et%lDBBh~OcFnMKMUoox0YwBNy`N0q~bSPh@+enQ=4RUw1) zpovN`QoV>vZ#5LvC;cl|6jPr}O5tu!Ipoyib8iXqy}TeJ;4+_7r<1kV0v5?Kv>fYp zg>9L`;XwXa&W7-jf|9~uP2iyF5`5AJ`Q~p4eBU$MCC00`rcSF>`&0fbd^_eqR+}mK z4n*PMMa&FOcc)vTUR zlDUAn-mh`ahi_`f`=39JYTNVjsTa_Y3b1GOIi)6dY)D}xeshB0T8Eov5%UhWd1)u}kjEQ|LDo{tqKKrYIfVz~@dp!! zMOnah@vp)%_-jDTUG09l+;{CkDCH|Q{NqX*uHa1YxFShy*1+;J`gywKaz|2Q{lG8x zP?KBur`}r`!WLKXY_K;C8$EWG>jY3UIh{+BLv0=2)KH%P}6xE2kg)%(-uA6lC?u8}{K(#P*c zE9C8t*u%j2r_{;Rpe1A{9nNXU;b_N0vNgyK!EZVut~}+R2rcbsHilqsOviYh-pYX= zHw@53nlmwYI5W5KP>&`dBZe0Jn?nAdC^HY1wlR6$u^PbpB#AS&5L6zqrXN&7*N2Q` z+Rae1EwS)H=aVSIkr8Ek^1jy2iS2o7mqm~Mr&g5=jjt7VxwglQ^`h#Mx+x2v|9ZAwE$i_9918MjJxTMr?n!bZ6n$}y11u8I9COTU`Z$Fi z!AeAQLMw^gp_{+0QTEJrhL424pVDp%wpku~XRlD3iv{vQ!lAf!_jyqd_h}+Tr1XG| z`*FT*NbPqvHCUsYAkFnM`@l4u_QH&bszpUK#M~XLJt{%?00GXY?u_{gj3Hvs!=N(I z(=AuWPijyoU!r?aFTsa8pLB&cx}$*%;K$e*XqF{~*rA-qn)h^!(-;e}O#B$|S~c+U zN4vyOK0vmtx$5K!?g*+J@G1NmlEI=pyZXZ69tAv=@`t%ag_Hk{LP~OH9iE)I= zaJ69b4kuCkV0V zo(M0#>phpQ_)@j;h%m{-a*LGi(72TP)ws2w*@4|C-3+;=5DmC4s7Lp95%n%@Ko zfdr3-a7m*dys9iIci$A=4NPJ`HfJ;hujLgU)ZRuJI`n;Pw|yksu!#LQnJ#dJysgNb z@@qwR^wrk(jbq4H?d!lNyy72~Dnn87KxsgQ!)|*m(DRM+eC$wh7KnS-mho3|KE)7h zK3k;qZ;K1Lj6uEXLYUYi)1FN}F@-xJ z@@3Hb84sl|j{4$3J}aTY@cbX@pzB_qM~APljrjju6P0tY{C@ zpUCOz_NFmALMv1*blCcwUD3?U6tYs+N%cmJ98D%3)%)Xu^uvzF zS5O!sc#X6?EwsYkvPo6A%O8&y8sCCQH<%f2togVwW&{M;PR!a(ZT_A+jVAbf{@5kL zB@Z(hb$3U{T_}SKA_CoQVU-;j>2J=L#lZ~aQCFg-d<9rzs$_gO&d5N6eFSc z1ml8)P*FSi+k@!^M9nDWR5e@ATD8oxtDu=36Iv2!;dZzidIS(PCtEuXAtlBb1;H%Z zwnC^Ek*D)EX4#Q>R$$WA2sxC_t(!!6Tr?C#@{3}n{<^o;9id1RA&-Pig1e-2B1XpG zliNjgmd3c&%A}s>qf{_j#!Z`fu0xIwm4L0)OF=u(OEmp;bLCIaZX$&J_^Z%4Sq4GZ zPn6sV_#+6pJmDN_lx@1;Zw6Md_p0w9h6mHtzpuIEwNn>OnuRSC2=>fP^Hqgc)xu^4 z<3!s`cORHJh#?!nKI`Et7{3C27+EuH)Gw1f)aoP|B3y?fuVfvpYYmmukx0ya-)TQX zR{ggy5cNf4X|g)nl#jC9p>7|09_S7>1D2GTRBUTW zAkQ=JMRogZqG#v;^=11O6@rPPwvJkr{bW-Qg8`q8GoD#K`&Y+S#%&B>SGRL>;ZunM@49!}Uy zN|bBCJ%sO;@3wl0>0gbl3L@1^O60ONObz8ZI7nder>(udj-jt`;yj^nTQ$L9`OU9W zX4alF#$|GiR47%x@s&LV>2Sz2R6?;2R~5k6V>)nz!o_*1Y!$p>BC5&?hJg_MiE6UBy>RkVZj`9UWbRkN-Hk!S`=BS3t3uyX6)7SF#)71*}`~Ogz z1rap5H6~dhBJ83;q-Y<5V35C2&F^JI-it(=5D#v!fAi9p#UwV~2tZQI+W(Dv?1t9? zfh*xpxxO{-(VGB>!Q&0%^YW_F!@aZS#ucP|YaD#>wd1Fv&Z*SR&mc;asi}1G) z_H>`!akh-Zxq9#io(7%;a$)w+{QH)Y$?UK1Dt^4)up!Szcxnu}kn$0afcfJL#IL+S z5gF_Y30j;{lNrG6m~$Ay?)*V9fZuU@3=kd40=LhazjFrau>(Y>SJNtOz>8x_X-BlA zIpl{i>OarVGj1v(4?^1`R}aQB&WCRQzS~;7R{tDZG=HhgrW@B`W|#cdyj%YBky)P= zpxuOZkW>S6%q7U{VsB#G(^FMsH5QuGXhb(sY+!-R8Bmv6Sx3WzSW<1MPPN1!&PurYky(@`bP9tz z52}LH9Q?+FF5jR6-;|+GVdRA!qtd;}*-h&iIw3Tq3qF9sDIb1FFxGbo&fbG5n8$3F zyY&PWL{ys^dTO}oZ#@sIX^BKW*bon=;te9j5k+T%wJ zNJtoN1~YVj4~YRrlZl)b&kJqp+Z`DqT!la$x&&IxgOQw#yZd-nBP3!7FijBXD|IsU8Zl^ zc6?MKpJQ+7ka|tZQLfchD$PD|;K(9FiLE|eUZX#EZxhG!S-63C$jWX1Yd!6-Yxi-u zjULIr|0-Q%D9jz}IF~S%>0(jOqZ(Ln<$9PxiySr&2Oic7vb<8q=46)Ln%Z|<*z5&> z3f~Zw@m;vR(bESB<=Jqkxn(=#hQw42l(7)h`vMQQTttz9XW6^|^8EK7qhju4r_c*b zJIi`)MB$w@9epwdIfnEBR+?~);yd6C(LeMC& zn&&N*?-g&BBJcV;8&UoZi4Lmxcj16ojlxR~zMrf=O_^i1wGb9X-0@6_rpjPYemIin zmJb+;lHe;Yp=8G)Q(L1bzH*}I>}uAqhj4;g)PlvD9_e_ScR{Ipq|$8NvAvLD8MYr}xl=bU~)f%B3E>r3Bu9_t|ThF3C5~BdOve zEbk^r&r#PT&?^V1cb{72yEWH}TXEE}w>t!cY~rA+hNOTK8FAtIEoszp!qqptS&;r$ zaYV-NX96-h$6aR@1xz6_E0^N49mU)-v#bwtGJm)ibygzJ8!7|WIrcb`$XH~^!a#s& z{Db-0IOTFq#9!^j!n_F}#Z_nX{YzBK8XLPVmc&X`fT7!@$U-@2KM9soGbmOSAmqV z{nr$L^MBo_u^Joyf0E^=eo{Rt0{{e$IFA(#*kP@SQd6lWT2-#>` zP1)7_@IO!9lk>Zt?#CU?cuhiLF&)+XEM9B)cS(gvQT!X3`wL*{fArTS;Ak`J<84du zALKPz4}3nlG8Fo^MH0L|oK2-4xIY!~Oux~1sw!+It)&D3p;+N8AgqKI`ld6v71wy8I!eP0o~=RVcFQR2Gr(eP_JbSytoQ$Yt}l*4r@A8Me94y z8cTDWhqlq^qoAhbOzGBXv^Wa4vUz$(7B!mX`T=x_ueKRRDfg&Uc-e1+z4x$jyW_Pm zp?U;-R#xt^Z8Ev~`m`iL4*c#65Nn)q#=Y0l1AuD&+{|8-Gsij3LUZXpM0Bx0u7WWm zH|%yE@-#XEph2}-$-thl+S;__ciBxSSzHveP%~v}5I%u!z_l_KoW{KRx2=eB33umE zIYFtu^5=wGU`Jab8#}cnYry@9p5UE#U|VVvx_4l49JQ;jQdp(uw=$^A$EA$LM%vmE zvdEOaIcp5qX8wX{mYf0;#51~imYYPn4=k&#DsKTxo{_Mg*;S495?OBY?#gv=edYC* z^O@-sd-qa+U24xvcbL0@C7_6o!$`)sVr-jSJE4XQUQ$?L7}2(}Eixqv;L8AdJAVqc zq}RPgpnDb@E_;?6K58r3h4-!4rT4Ab#rLHLX?eMOfluJk=3i1@Gt1i#iA=O`M0@x! z(HtJP9BMHXEzuD93m|B&woj0g6T?f#^)>J>|I4C5?Gam>n9!8CT%~aT;=oco5d6U8 zMXl(=W;$ND_8+DD*?|5bJ!;8ebESXMUKBAf7YBwNVJibGaJ*(2G`F%wx)grqVPjudiaq^Kl&g$8A2 zWMxMr@_$c}d+;_B`#kUX-t|4VKH&_f^^EP0&=DPLW)H)UzBG%%Tra*5 z%$kyZe3I&S#gfie^z5)!twG={3Cuh)FdeA!Kj<-9** zvT*5%Tb`|QbE!iW-XcOuy39>D3oe6x{>&<#E$o8Ac|j)wq#kQzz|ATd=Z0K!p2$QE zPu?jL8Lb^y3_CQE{*}sTDe!2!dtlFjq&YLY@2#4>XS`}v#PLrpvc4*@q^O{mmnr5D zmyJq~t?8>FWU5vZdE(%4cuZuao0GNjp3~Dt*SLaxI#g_u>hu@k&9Ho*#CZP~lFJHj z(e!SYlLigyc?&5-YxlE{uuk$9b&l6d`uIlpg_z15dPo*iU&|Khx2*A5Fp;8iK_bdP z?T6|^7@lcx2j0T@x>X7|kuuBSB7<^zeY~R~4McconTxA2flHC0_jFxmSTv-~?zVT| zG_|yDqa9lkF*B6_{j=T>=M8r<0s;@z#h)3BQ4NLl@`Xr__o7;~M&dL3J8fP&zLfDfy z);ckcTev{@OUlZ`bCo(-3? z1u1xD`PKgSg?RqeVVsF<1SLF;XYA@Bsa&cY!I48ZJn1V<3d!?s=St?TLo zC0cNr`qD*M#s6f~X>SCNVkva^9A2ZP>CoJ9bvgXe_c}WdX-)pHM5m7O zrHt#g$F0AO+nGA;7dSJ?)|Mo~cf{z2L)Rz!`fpi73Zv)H=a5K)*$5sf_IZypi($P5 zsPwUc4~P-J1@^3C6-r9{V-u0Z&Sl7vNfmuMY4yy*cL>_)BmQF!8Om9Dej%cHxbIzA zhtV0d{=%cr?;bpBPjt@4w=#<>k5ee=TiWAXM2~tUGfm z$s&!Dm0R^V$}fOR*B^kGaipi~rx~A2cS0;t&khV1a4u38*XRUP~f za!rZMtay8bsLt6yFYl@>-y^31(*P!L^^s@mslZy(SMsv9bVoX`O#yBgEcjCmGpyc* zeH$Dw6vB5P*;jor+JOX@;6K#+xc)Z9B8M=x2a@Wx-{snPGpRmOC$zpsqW*JCh@M2Y z#K+M(>=#d^>Of9C`))h<=Bsy)6zaMJ&x-t%&+UcpLjV`jo4R2025 zXaG8EA!0lQa)|dx-@{O)qP6`$rhCkoQqZ`^SW8g-kOwrwsK8 z3ms*AIcyj}-1x&A&vSq{r=QMyp3CHdWH35!sad#!Sm>^|-|afB+Q;|Iq@LFgqIp#Z zD1%H+3I?6RGnk&IFo|u+E0dCxXz4yI^1i!QTu7uvIEH>i3rR{srcST`LIRwdV1P;W z+%AN1NIf@xxvVLiSX`8ILA8MzNqE&7>%jMzGt9wm78bo9<;h*W84i29^w!>V>{N+S zd`5Zmz^G;f=icvoOZfK5#1ctx*~UwD=ab4DGQXehQ!XYnak*dee%YN$_ZPL%KZuz$ zD;$PpT;HM^$KwtQm@7uvT`i6>Hae1CoRVM2)NL<2-k2PiX=eAx+-6j#JI?M}(tuBW zkF%jjLR)O`gI2fcPBxF^HeI|DWwQWHVR!;;{BXXHskxh8F@BMDn`oEi-NHt;CLymW z=KSv5)3dyzec0T5B*`g-MQ<;gz=nIWKUi9ko<|4I(-E0k$QncH>E4l z**1w&#={&zv4Tvhgz#c29`m|;lU-jmaXFMC11 z*dlXDMEOG>VoLMc>!rApwOu2prKSi*!w%`yzGmS+k(zm*CsLK*wv{S_0WX^8A-rKy zbk^Gf_92^7iB_uUF)EE+ET4d|X|>d&mdN?x@vxKAQk`O+r4Qdu>XGy(a(19g;=jU} zFX{O*_NG>!$@jh!U369Lnc+D~qch3uT+_Amyi}*k#LAAwh}k8IPK5a-WZ81ufD>l> z$4cF}GSz>ce`3FAic}6W4Z7m9KGO?(eWqi@L|5Hq0@L|&2flN1PVl}XgQ2q*_n2s3 zt5KtowNkTYB5b;SVuoXA@i5irXO)A&%7?V`1@HGCB&)Wgk+l|^XXChq;u(nyPB}b3 zY>m5jkxpZgi)zfbgv&ec4Zqdvm+D<?Im*mXweS9H+V>)zF#Zp3)bhl$PbISY{5=_z!8&*Jv~NYtI-g!>fDs zmvL5O^U%!^VaKA9gvKw|5?-jk>~%CVGvctKmP$kpnpfN{D8@X*Aazi$txfa%vd-|E z>kYmV66W!lNekJPom29LdZ%(I+ZLZYTXzTg*to~m?7vp%{V<~>H+2}PQ?PPAq`36R z<%wR8v6UkS>Wt#hzGk#44W<%9S=nBfB);6clKwnxY}T*w21Qc3_?IJ@4gYzC7s;WP zVQNI(M=S=JT#xsZy7G`cR(BP9*je0bfeN8JN5~zY(DDs0t{LpHOIbN);?T-69Pf3R zSNe*&p2%AwXHL>__g+xd4Hlc_vu<25H?(`nafS%)3UPP7_4;gk-9ckt8SJRTv5v0M z_Hww`qPudL?ajIR&X*;$y-`<)6dxx1U~5eGS13CB!lX;3w7n&lDDiArbAhSycd}+b zya_3p@A`$kQy;|NJZ~s44Hqo7Hwt}X86NK=(ey>lgWTtGL6k@Gy;PbO!M%1~Wcn2k zUFP|*5d>t-X*RU8g%>|(wwj*~#l4z^Aatf^DWd1Wj#Q*AY0D^V@sC`M zjJc6qXu0I7Y*2;;gGu!plAFzG=J;1%eIOdn zQA>J&e05UN*7I5@yRhK|lbBSfJ+5Uq;!&HV@xfPZrgD}kE*1DSq^=%{o%|LChhl#0 zlMb<^a6ixzpd{kNZr|3jTGeEzuo}-eLT-)Q$#b{!vKx8Tg}swCni>{#%vDY$Ww$84 zew3c9BBovqb}_&BRo#^!G(1Eg((BScRZ}C)Oz?y`T5wOrv);)b^4XR8 zhJo7+<^7)qB>I;46!GySzdneZ>n_E1oWZY;kf94#)s)kWjuJN1c+wbVoNQcmnv}{> zN0pF+Sl3E}UQ$}slSZeLJrwT>Sr}#V(dVaezCQl2|4LN`7L7v&siYR|r7M(*JYfR$ zst3=YaDw$FSc{g}KHO&QiKxuhEzF{f%RJLKe3p*7=oo`WNP)M(9X1zIQPP0XHhY3c znrP{$4#Ol$A0s|4S7Gx2L23dv*Gv2o;h((XVn+9+$qvm}s%zi6nI-_s6?mG! zj{DV;qesJb&owKeEK?=J>UcAlYckA7Sl+I&IN=yasrZOkejir*kE@SN`fk<8Fgx*$ zy&fE6?}G)d_N`){P~U@1jRVA|2*69)KSe_}!~?+`Yb{Y=O~_+@!j<&oVQQMnhoIRU zA0CyF1OFfkK44n*JD~!2!SCPM;PRSk%1XL=0&rz00wxPs&-_eapJy#$h!eqY%nS0{ z!aGg58JIJPF3_ci%n)QSVpa2H`vIe$RD43;#IRfDV&Ibit z+?>HW4{2wOfC6Fw)}4x}i1maDxcE1qi@BS*qcxD2gE@h3#4cgU*D-&3z7D|tVZWt= z-Cy2+*Cm@P4GN_TPUtaVyVesbVDazF@)j8VJ4>XZv!f%}&eO1SvIgr}4`A*3#vat< z_MoByL(qW6L7SFZ#|Gc1fFN)L2PxY+{B8tJp+pxRyz*87)vXR}*=&ahXjBlQKguuf zX6x<<6fQulE^C*KH8~W%ptpaC0l?b=_{~*U4?5Vt;dgM4t_{&UZ1C2j?b>b+5}{IF_CUyvz-@QZPMlJ)r_tS$9kH%RPv#2_nMb zRLj5;chJ72*U`Z@Dqt4$@_+k$%|8m(HqLG!qT4P^DdfvGf&){gKnGCX#H0!;W=AGP zbA&Z`-__a)VTS}kKFjWGk z%|>yE?t*EJ!qeQ%dPk$;xIQ+P0;()PCBDgjJm6Buj{f^awNoVx+9<|lg3%-$G(*f) zll6oOkN|yamn1uyl2*N-lnqRI1cvs_JxLTeahEK=THV$Sz*gQhKNb*p0fNoda#-&F zB-qJgW^g}!TtM|0bS2QZekW7_tKu%GcJ!4?lObt0z_$mZ4rbQ0o=^curCs3bJK6sq z9fu-aW-l#>z~ca(B;4yv;2RZ?tGYAU)^)Kz{L|4oPj zdOf_?de|#yS)p2v8-N||+XL=O*%3+y)oI(HbM)Ds?q8~HPzIP(vs*G`iddbWq}! z(2!VjP&{Z1w+%eUq^ /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -114,7 +114,6 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -133,22 +132,29 @@ 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. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -165,7 +171,6 @@ fi # 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" ) @@ -193,18 +198,27 @@ if "$cygwin" || "$msys" ; then 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. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. diff --git a/gradlew.bat b/gradlew.bat index 107acd32c..c4bdd3ab8 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,8 +13,10 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +27,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +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. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -56,32 +59,33 @@ 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. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail :execute @rem Setup the command line -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 %* +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +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! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +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 diff --git a/language/files/de.json b/language/files/de.json index eb858fc26..d7d50fc9c 100644 --- a/language/files/de.json +++ b/language/files/de.json @@ -1,4 +1,272 @@ { + "generic": { + "disabled": "Deaktiviert", + "enabled": "Aktiviert", + "customized": "Anpassen" + }, + "menu": { + "generic": { + "click-prefix": "[Klick] {@symbol.arrow} ", + "shift-click-prefix": "[Shift-Klick] {@symbol.arrow} ", + "right-click-prefix": "[Rechts-Klick] {@symbol.arrow} ", + "left-click-prefix": "[Links-Klick] {@symbol.arrow} " + }, + "timer": { + "name": "Timer", + "name-state": "Status", + "name-time": "Zeit", + "item-name-format": "{@item-format('{0}: {1} ({2})')}", + "item-add-format": [ + "{@item-name-format('{4}', '{0}', '{1}')}", + " ", + "{@generic.click-prefix}+1 {3}", + "{@generic.shift-click-prefix}{@symbol.arrow} +{2} {4}" + ], + "item-subtract-format": [ + "{@item-name-format('{4}', '{0}', '{1}')}", + " ", + "{@generic.click-prefix}-1 {3}", + "{@generic.shift-click-prefix} -{2} {4}" + ], + "item-state-format": [ + "{@item-name-format('{2}', '{0}', '{1}')}", + " ", + "{@generic.click-prefix}Zeit zurücksetzen" + ], + "item-seconds": "{@item-state-format('{0}', '{1}', 'Sekunden')}", + "item-seconds-add": "{@item-add-format('{0}', '{1}', '{2}', 'Sekunde', 'Sekunden')}", + "item-seconds-subtract": "{@item-subtract-format('{0}', '{1}', '{2}', 'Sekunde', 'Sekunden')}", + "item-minutes": "{@item-state-format('{0}', '{1}', 'Minuten')}", + "item-minutes-add": "{@item-add-format('{0}', '{1}', '{2}', 'Minute', 'Minuten')}", + "item-minutes-subtract": "{@item-subtract-format('{0}', '{1}', '{2}', 'Minute', 'Minuten')}", + "item-hours": "{@item-state-format('{0}', '{1}', 'Stunden')}", + "item-hours-add": "{@item-add-format('{0}', '{1}', '{2}', 'Stunde', 'Stunden')}", + "item-hours-subtract": "{@item-subtract-format('{0}', '{1}', '{2}', 'Stunde', 'Stunden')}", + "item-days": "{@item-state-format('{0}', '{1}', 'Tage')}", + "item-days-add": "{@item-add-format('{0}', '{1}', '{2}', 'Tag', 'Tage')}", + "item-days-subtract": "{@item-subtract-format('{0}', '{1}', '{2}', 'Tag', 'Tage')}" + }, + "damage": { + "name": "Schaden" + }, + "goal": { + "name": "Ziele" + }, + "items-blocks": { + "name": "Items & Blöcke" + }, + "challenges": { + "name": "Challenges" + }, + "settings": { + "name": "Einstellungen" + }, + "custom": { + "name": "Individuelle Challenges" + } + }, + "category": { + "misc_challenge": { + "menu": "Sonstige", + "desc": [ + "Challenges, die *keiner Kategorie*", + "zugeordnet werden können" + ], + "info": [ + "{@info-format('Aktiviert', '{0}/{1}')}" + ] + }, + "randomizer": { + "menu": "Randomizer", + "desc": [ + "Erlebe ein komplett", + "*durcheinandergebrachtes* Spiel" + ] + }, + "limited_time": { + "menu": "Limitierte Zeit", + "desc": [ + "Du wirst bei verschiedenen", + "Faktoren *zeitlich eingeschränkt*" + ] + }, + "force": { + "menu": "Zwischenziele", + "name": "*{@menu} (Force)*", + "desc": [ + "Du musst *bestimmte Zwischenziele*", + "erfüllen, sonst stirbst du" + ] + }, + "world": { + "menu": "Welteinfluss", + "desc": [ + "Die Welt wird nicht mehr", + "*wiedererkennbar* sein" + ] + }, + "damage": { + "menu": "Schaden", + "desc": [ + "Du wirst auf *verschiedenste*", + "Arten *Schaden* nehmen" + ] + }, + "effect": { + "menu": "Effekte", + "desc": [ + "Erlebe verrückte *Effekte*" + ] + }, + "inventory": { + "menu": "Inventar", + "desc": [ + "Dein *Inventar* wird *verdreht*" + ] + }, + "movement": { + "menu": "Bewegung", + "desc": [ + "Du wirst in deinen *Bewegungen*", + "*eingeschränkt*" + ] + }, + "entities": { + "menu": "Entities", + "desc": [ + "Entities werden *verändert*" + ] + }, + "extra_world": { + "menu": "Extra Welt", + "desc": [ + "Challenges, die in einer", + "*anderen Welt* spielen" + ] + }, + "misc_goal": { + "menu": "Sonstige Ziele", + "desc": [ + "Ziele, die *keiner Kategorie*", + "zugeordnet werden können" + ], + "info": "{@info-format('Aktuell', '{2}')}" + }, + "kill_entity": { + "menu": "Entity töten", + "desc": [ + "Töte *bestimmte Entities*,", + "um zu gewinnen" + ] + }, + "score_points": { + "menu": "Punkte sammeln", + "desc": [ + "Erziele die *meisten Punkte* in", + "einem *bestimmten Bereich*", + " ", + "Der Spieler mit den *meisten Punkten*", + "gewinnt, wenn der *Timer abläuft*" + ] + }, + "fastest_time": { + "menu": "Schnellste Zeit", + "desc": [ + "Der *schnellste Spieler*, der das Ziel", + "erreicht *gewinnt* die Challenge" + ] + }, + "force_battle": { + "menu": "Force Battles", + "desc": [ + "Erfülle die *vorgegebenen Zwischenziele*,", + "um Punkte zu erhalten.", + " ", + "Der Spieler mit den *meisten Punkten*", + "*gewinnt* die Challenge wenn der Timer *abläuft*" + ] + } + }, + "challenge": { + "random-challenge": { + "name": "*Random Challenge*", + "desc": [ + "In einem *gesetzten Intervall*", + "wird eine *zufällige Challenge* aktiviert" + ] + }, + "randomized-hp": { + "name": "*Zufällige HP*", + "desc": [ + "Die *Leben* aller *Mobs*", + "sind *zufällig*" + ] + }, + "goal-ender-dragon": { + "name": "*Enderdrache*", + "desc": [ + "Töte den *Enderdrachen* um zu gewinnen" + ] + }, + "goal-wither": { + "name": "*Wither*", + "desc": [ + "Töte einen *Wither* um zu gewinnen" + ] + }, + "goal-elder-guardian": { + "name": "*Elder Guardian*", + "desc": [ + "Töte einen *Großen Wächter* um zu gewinnen" + ] + }, + "goal-warden": { + "name": "*Warden*", + "desc": [ + "Töte einen *Warden* um zu gewinnen" + ] + }, + "goal-all-bosses": { + "name": "*Alle Bosse*", + "desc": [ + "Es müssen *alle Bosse* einmal", + "*getötet* werden, um zu *gewinnen*", + " ", + "({@goal-ender-dragon.name}, {@goal-wither.name}, {@goal-elder-guardian.name})" + ] + }, + "goal-all-bosses-new": { + "name": "*Alle Bosse (+ Warden)*", + "desc": [ + "Es müssen *alle Bosse* einmal", + "*getötet* werden, um zu *gewinnen*", + " ", + "({@goal-ender-dragon.name}, {@goal-wither.name}, {@goal-elder-guardian.name}, {@goal-warden.name})" + ] + } + }, + "title": { + "timer-started": [ + " ", + "{@symbol.arrow} Timer fortgesetzt" + ], + "timer-paused": [ + " ", + "{@symbol.arrow} Timer pausiert" + ], + "challenge-enabled": [ + "{0}", + "{@symbol.check} {@symbol.vertical} Aktiviert" + ], + "challenge-disabled": [ + "{0}", + "{@symbol.x} Deaktiviert" + ], + "challenge-value-changed": [ + "{0}", + "{@symbol.arrow} {1}" + ] + }, "syntax": "Bitte nutze §e/{0}", "reload": "Challenges Plugin wird neu geladen...", "reload-failed": "Ein §cFehler §7ist während dem Reload aufgetreten", @@ -31,11 +299,11 @@ "Der Server kann §cnicht resettet §7werden", "Die Challenge wurde §cnoch nicht §7gestartet" ], - "new-challenge": "§a§lNeu!", - "updated-challenge": "§e§lUpdate!", + "new-challenge-suffix": "{@challenge.suffix-format('Neu!')}", + "updated-challenge-suffix": "{@challenge.suffix-format('Update!')}", "feature-disabled": "Diese Funktion ist derzeit §cdeaktiviert", "challenge-disabled": "Diese Challenge ist derzeit §cdeaktiviert", - "stopped-message": "§8• §7Timer §c§lpaused §8•", + "stopped-message": "§8• §7Timer §c§lpausiert §8•", "count-up-message": "§8• §7Time: §a§l{0} §8•", "count-down-message": "§8• §7Time: §c§l{0} §8•", "timer-not-started": "Der Timer wurde noch §cnicht gestartet", @@ -76,8 +344,8 @@ "not-op": [ "§7Um dieses Plugin zu nutzen, musst du die Berechtigung haben. Gib dir die Berechtigung in der Serverkonsole mit: /op [name]" ], - "join-message": "§e{0} §7hat den Server §abetreten", - "quit-message": "§e{0} §7hat den Server §cverlassen", + "join-message": "{0} hat den Server betreten", + "quit-message": "{0} hat den Server verlassen", "timer-paused-message": [ "Der Timer ist noch §cpausiert", "Nutze §e/timer resume §7um ihn zu starten" @@ -231,7 +499,7 @@ "loops-cleared": "§e{0} §7Loops abgebrochen", "stopped-moving": "§e{0} §7hat sich zu lange nicht bewegt", "all-advancements-goal": "§7Advancements §8» §e{0}", - "Chalheight-reached": "§e{0} §7hat Höhe §e{1} §7erreicht!", + "height-reached": "§e{0} §7hat Höhe §e{1} §7erreicht!", "race-goal-reached": "§e{0} §7hat das Ziel erreicht!", "points-change": "§e{0} §7Punkte", "force-item-battle-found": "Du hast §e{0} §7gefunden!", @@ -300,27 +568,21 @@ "Bist du etwa krank?", "Was geht denn jetzt ab" ], - "quiz-how-to": "Schreibe deine Antwort mit §e/guess ", - "quiz-right-answer": "§e{0} §7ist die §arichtige §7Antwort!", "quiz-right-answer-other": "§e{0} §7hat die Frage §arichtig §7beantwortet", - "quiz-wrong-answer": "§e{0} §7ist eine §cfalsche §7Antwort!", "quiz-wrong-answer-other": "§e{0} §7hat die Frage §cfalsch beantwortet", "quiz-time-up": "Die Zeit ist §cabgelaufen§7!", "quiz-cancel": "Die Frage wurde §cabgebrochen§7!", - "quiz-right-answer-was": "Die richtige Antwort lautete: §e{0}", "quiz-right-answer-was-multiple": "Die richtigen Antworten lauteten: §e{0}", - "quiz-question-often-have": "Wie oft hast du §e{0}§7{1}?", "quiz-question-often-be": "Wie oft bist du §e{0}§7{1}?", "quiz-question-far-be": "Wie weit bist du {0}?", "quiz-question-most": "Was hast du von diesen {1} am meisten {0}?", "quiz-question-damage-have": "Wie viel Schaden hast du {0}{1}?", "quiz-question-damage-taken-have": "Wie viel Schaden hast du durch {0}{1}?", - "quiz-verb-traveled": "gelaufen", "quiz-verb-jumped": "gesprungen", "quiz-verb-sneaked": "geschlichen", @@ -330,7 +592,6 @@ "quiz-verb-placed": "platziert", "quiz-verb-dropped": "gedropped", "quiz-verb-suffered": "erlitten", - "bossbar-timer-paused": "§8» §7Der Timer ist §cpausiert", "bossbar-mob-transformation": "§8» §7Letzter Mob §8§l┃ §a{0}", "bossbar-biome-time-left": "§8» §7Zeit übrig in §e{0} §8§l┃ §a{1}s", @@ -373,15 +634,25 @@ "scoreboard-title": "§7» §f§lChallenge", "scoreboard-leaderboard": "§e#{0} §8┃ §7{1} §8» §e{2}", "your-place": "§7Dein Platz §8» §e{0}", - "server-reset": [ - "§8————————————————————", + "server-reset-restart": [ + "§8§m §r", " ", "§8» §cServerreset", " ", "§7Reset durch §4§l{0}", "§7Der Server startet nun §cneu", " ", - "§8————————————————————" + "§8§m §r" + ], + "server-reset-stop": [ + "§8§m §r", + " ", + "§8» §cServerreset", + " ", + "§7Reset durch §4§l{0}", + "§7Der Server wird nun §cgestoppt", + " ", + "§8§m §r" ], "challenge-end-timer-hit-zero": [ " ", @@ -413,7 +684,7 @@ ], "challenge-end-goal-failed": [ " ", - "§cDie Challenge ist vorbei! §6#FeelsBadMan ✞", + "§cDie Challenge ist vorbei! §6#FeelsBadMan {@symbol.cross}", "§7Zeit verschwendet: §a§l{0}", "§7Seed: §e§l{2}", " " @@ -447,7 +718,7 @@ "item-menu-timer": "§8• §5Timer §8┃ §e/timer §8•", "item-menu-leaderboard": "§8• §6Leaderboard §8┃ §e/leaderboard §8•", "item-menu-stats": "§8• §2Statistiken §8┃ §e/stats §8•", - "menu-title": "Menu", + "menu-main-title": "{@menu.title-format('Menu')}", "menu-timer": "§6Timer", "menu-goal": "§5Ziel", "menu-damage": "§7Schaden", @@ -458,83 +729,6 @@ "lore-category-activated-count": "§7Aktiviert §8» §a{0}§8/§7{1}", "lore-category-activated": "§7Aktiviert §8» §aJa", "lore-category-deactivated": "§7Aktiviert §8» §cNein", - "category-misc_challenge": [ - "§9Miscellaneous", - "Challenges, die *keiner Kategorie*", - "zugeordnet werden können" - ], - "category-randomizer": [ - "§6Randomizer", - "Erlebe ein komplett", - "*durcheinandergebrachtes* Spiel" - ], - "category-limited_time": [ - "§aLimitierte Zeit", - "Du wirst bei verschiedenen", - "Faktoren *zeitlich eingeschränkt*" - ], - "category-force": [ - "§3Zwischenziele (Force)", - "Du musst *bestimmte Zwischenziele*", - "erfüllen, sonst stirbst du" - ], - "category-world": [ - "§4Weltveränderung", - "Die Welt wird nicht mehr", - "*wiedererkennbar* sein" - ], - "category-damage": [ - "§cSchaden", - "Neue *Schadens Regeln*" - ], - "category-effect": [ - "§5Effekte", - "Erlebe verrückte *Effekte*" - ], - "category-inventory": [ - "§6Inventory", - "Dein Inventar wird *verdreht*" - ], - "category-movement": [ - "§aBewegung", - "Du wirst in deinen Bewegungen *eingeschränkt*" - ], - "category-entities": [ - "§bEntities", - "Entities werden *verändert*" - ], - "category-extra_world": [ - "§aExtra Welt", - "Challenges, die in einer", - "*anderen Welt* spielen" - ], - "category-misc_goal": [ - "§9Miscellaneous", - "Ziele, die *keiner Kategorie*", - "zugeordnet werden können" - ], - "category-kill_entity": [ - "§cEntity töten", - "Töte *bestimmte Entities*,", - "um zu gewinnen" - ], - "category-score_points": [ - "§eMeiste Punkte", - "Erziele die *meisten Punkte* in", - "einem *bestimmten Bereich*." - ], - "category-fastest_time": [ - "§6Schnellste Zeit", - "Sei der *schnellste Spieler*, der", - "das Ziel erfüllt" - ], - "category-force_battle": [ - "§bForce Battles", - "Erfülle die *vorgegebenen Zwischenziele*,", - "um Punkte zu erhalten.", - " ", - "Der Spieler mit den *meisten Punkten* gewinnt." - ], "item-time-seconds-description": "§8» §7Zeit: §e{0} §7Sekunden", "item-time-seconds-range-description": "§8» §7Zeit: §e{0}-{1} §7Sekunden", "item-time-minutes-description": "§8» §7Zeit: §e{0} §7Minuten", @@ -851,11 +1045,6 @@ "Alle *paar Minuten* musst du ein random *Jump and Run* machen,", "welches jedes Mal *schwieriger* wird" ], - "item-randomized-hp-challenge": [ - "§4Randomized HP", - "Die *Leben* aller *Mobs*", - "sind *random*" - ], "item-snake-challenge": [ "§9Snake", "*Jeder Spieler* zieht eine", @@ -1054,11 +1243,6 @@ "Du bekommst immer, wenn du *Schaden*", "erleidest, einen *zufälligen Effekt*" ], - "item-random-challenge-challenge": [ - "§cRandom Challenge", - "In einem *gesetzten Intervall*", - "wird eine *Random Challenge* aktiviert" - ], "item-anvil-rain-challenge": [ "§cAmboss Regen", "Vom *Himmel* fallen *Ambosse*" @@ -1290,22 +1474,6 @@ "Der *schaden* von allen *Spielern* ist", "zusammenaddiert und wird nach einer bestimmten *Zeit* hinzugefügt." ], - "item-dragon-goal": [ - "§5Enderdrache", - "Töte den *Enderdrachen* um zu gewinnen" - ], - "item-wither-goal": [ - "§dWither", - "Töte einen *Wither* um zu gewinnen" - ], - "item-elder-guardian-goal": [ - "§bElder Guardian", - "Töte einen *Elder Guardian* um zu gewinnen" - ], - "item-warden-goal": [ - "§5Warden", - "Töte einen *Warden* um zu gewinnen" - ], "item-iron-golem-goal": [ "§bEisengolem", "Töte einen *Eisengolem* um zu gewinnen" @@ -1348,16 +1516,6 @@ "item-collect-wood-goal-overworld": "§aOverworld", "item-collect-wood-goal-nether": "§cNether", "item-collect-wood-goal-both": "§9Beide", - "item-all-bosses-goal": [ - "§bAlle Bosse", - "Es müssen *alle Bosse* einmal", - "*getötet* werden, um zu *gewinnen*" - ], - "item-all-bosses-new-goal": [ - "§5Alle Bosse (+ Warden)", - "Es müssen *alle Bosse* einmal", - "*getötet* werden, um zu *gewinnen*" - ], "item-all-mobs-goal": [ "§bAlle Mobs", "Es müssen *alle Mobs* einmal", diff --git a/language/files/en.json b/language/files/en.json index d43a466ca..bd468e1f8 100644 --- a/language/files/en.json +++ b/language/files/en.json @@ -977,7 +977,7 @@ "in every *biome* is limited" ], "item-max-height-time-challenge": [ - "§9Max Biome Time", + "§9Max Height Time", "The *time* that you may spend", "on every *height* is limited" ], diff --git a/language/files/global.json b/language/files/global.json new file mode 100644 index 000000000..7cefbd5e0 --- /dev/null +++ b/language/files/global.json @@ -0,0 +1,189 @@ +{ + "symbol": { + "p": "➟ ➡ ➛ ➜ ➸ › ► ▶ ▷ ⇒ →", + "arrow-back": "«", + "arrow": "»", + "chevron": "›", + "chevron-back": "‹", + "dart": "▷", + "vertical": "┃", + "cross": "✞", + "check": "✔", + "x": "✘", + "heart": "❤", + "dot": "•", + "circle": "●", + "altert": "⚠", + "flag": "⚐", + "lock": "\uD83D\uDD12" + }, + "prefix": { + "format": "{@symbol.vertical} {0} {@symbol.vertical} ", + "challenges": "{@format('Challenges')}", + "timer": "{@format('Timer')}", + "backpack": "{@format('Backpack')}", + "position": "{@format('Position')}", + "damage": "{@format('Damage')}", + "custom": "{@format('Custom')}" + }, + "menu": { + "title-prefix": "{@symbol.arrow} ", + "title-delimiter": " {@symbol.vertical} ", + "title-colored": "{0}", + "title-format": "{@title-prefix}{@title-colored('{0}')}", + "title-format-page": "{@title-format('{0}')}{@title-delimiter}{@title-colored('{1}')}", + "title-name-format-sub": "{@title-colored('{0}')}{@title-delimiter}{@title-colored('{1}')}", + "item-format": "{@symbol.arrow} {0}", + "goal": { + "display": "{@name}" + }, + "timer": { + "display": "{@name}" + }, + "damage": { + "display": "{@name}" + }, + "items-blocks": { + "display": "{@name}" + }, + "challenges": { + "display": "{@name}" + }, + "settings": { + "display": "{@name}" + }, + "custom": { + "display": "{@name}" + } + }, + "category": { + "info-format": [ + " ", + "{0} {@symbol.circle} {1}" + ], + "misc_challenge": { + "*colorize": "{0}", + "name": "*{@menu}*" + }, + "randomizer": { + "*colorize": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "limited_time": { + "*colorize": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "force": { + "*colorize": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "world": { + "*colorize": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "damage": { + "*colorize": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "effect": { + "*colorize": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "inventory": { + "*colorize": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "movement": { + "*colorize": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "entities": { + "*colorize": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "extra_world": { + "*colorize": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "misc_goal": { + "*colorize": "{0}", + "name": "*{@menu}*" + }, + "kill_entity": { + "*colorize": "{0}", + "name": "*{@menu}*", + "info": "{@misc_goal.info}" + }, + "score_points": { + "*colorize": "{0}", + "name": "*{@menu}*", + "info": "{@misc_goal.info}" + }, + "fastest_time": { + "*colorize": "{0}", + "name": "*{@menu}*", + "info": "{@misc_goal.info}" + }, + "force_battle": { + "*colorize": "{0}", + "name": "*{@menu}*", + "info": "{@misc_goal.info}" + } + }, + "item": { + "format": "{@symbol.dot} {0} {@symbol.dot}", + "format-with-command": "{@format('{0} {@symbol.vertical} {1}')}" + }, + "challenge": { + "display-format": [ + "{@symbol.arrow} {0}", + " ", + "{1}" + ], + "suffix-format": " {@symbol.vertical} {0}", + "settings-format": "{@symbol.dart} {0}", + "settings-format-lore": [ + " ", + "{0}" + ], + "subsettings-format": "{@settings-format}", + "subsettings-format-lore": "{@settings-format-lore}", + "settings-modifier-value": "{0}", + "settings-modifier-multiplier": "{0}x", + "settings-modifier-health": "{0} HP ({1} {@symbol.heart})", + "random-challenge": { + "*colorize": "{0}" + }, + "randomized-hp": { + "*colorize": "{0}" + }, + "goal-ender-dragon": { + "*colorize": "{0}" + }, + "goal-wither": { + "*colorize": "{0}" + }, + "goal-elder-guardian": { + "*colorize": "{0}" + }, + "goal-warden": { + "*colorize": "{0}" + }, + "goal-all-bosses": { + "*colorize": "{0}" + }, + "goal-all-bosses-new": { + "*colorize": "{0}" + } + } +} diff --git a/language/languages.json b/language/languages.json index 3d81dfd05..dbc406963 100644 --- a/language/languages.json +++ b/language/languages.json @@ -1,4 +1,5 @@ [ + "global", "en", "de" ] diff --git a/mongo-connector/build.gradle.kts b/mongo-connector/build.gradle.kts index f9d4300f3..b663ef4ee 100644 --- a/mongo-connector/build.gradle.kts +++ b/mongo-connector/build.gradle.kts @@ -1,6 +1,6 @@ plugins { - `java-library` - id("com.gradleup.shadow") + id("java-library") + alias(libs.plugins.shadow) } dependencies { diff --git a/platform/api/build.gradle.kts b/platform/api/build.gradle.kts new file mode 100644 index 000000000..ea667470c --- /dev/null +++ b/platform/api/build.gradle.kts @@ -0,0 +1,13 @@ +plugins { + id("java-library") +} + +dependencies { + compileOnly(libs.spigot.api) +} + +tasks { + jar { + archiveClassifier = "plain" + } +} diff --git a/platform/api/src/main/java/net/codingarea/challenges/platform/message/MessageHolder.java b/platform/api/src/main/java/net/codingarea/challenges/platform/message/MessageHolder.java new file mode 100644 index 000000000..df059b32b --- /dev/null +++ b/platform/api/src/main/java/net/codingarea/challenges/platform/message/MessageHolder.java @@ -0,0 +1,13 @@ +package net.codingarea.challenges.platform.message; + +import org.jetbrains.annotations.NotNull; + +public interface MessageHolder { + + @NotNull + String[] miniMessageRaw(); + + @NotNull + Object[] positionalArgs(); + +} diff --git a/platform/api/src/main/java/net/codingarea/challenges/platform/message/MessagePlatform.java b/platform/api/src/main/java/net/codingarea/challenges/platform/message/MessagePlatform.java new file mode 100644 index 000000000..29674a3b7 --- /dev/null +++ b/platform/api/src/main/java/net/codingarea/challenges/platform/message/MessagePlatform.java @@ -0,0 +1,66 @@ +package net.codingarea.challenges.platform.message; + +import com.google.errorprone.annotations.CheckReturnValue; +import net.codingarea.challenges.platform.message.wrapper.MessageBossBar; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.meta.ItemMeta; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.regex.Pattern; + +public interface MessagePlatform { + + Pattern POS_ARG_PATTERN = Pattern.compile("\\{(\\d+)\\}"); + + char ESCAPE_CHAR = '\\'; + char START_ARG_CHAR = '{'; + char END_ARG_CHAR = '}'; + char REFERENCE_CHAR = '@'; + char START_REFERENCE_ARGS_CHAR = '('; + char END_REFERENCE_ARGS_CHAR = ')'; + char REFERENCE_ARG_CHAR = '\''; + + void enable(); + + void disable(); + + void sendSenderMessage(@NotNull CommandSender sender, @Nullable String miniMessagePrefix, + @NotNull String[] miniMessageTextLines, @NotNull Object[] positionalArgs); + + void sendChatMessage(@NotNull Player player, @Nullable String miniMessagePrefix, + @NotNull String[] miniMessageTextLines, @NotNull Object[] positionalArgs); + + void sendActionBar(@NotNull Player player, @NotNull String miniMessageText, @NotNull Object[] positionalArgs); + + void sendTitle(@NotNull Player player, @NotNull String[] miniMessageTitleAndSubtitle, @NotNull Object[] positionalArgs); + + void sendTitle(@NotNull Player player, @NotNull String[] miniMessageTitleAndSubtitle, @NotNull Object[] positionalArgs, + int fadeInTicks, int stayTicks, int fadeOutTicks); + + @NotNull + @CheckReturnValue + Inventory createInventory(@NotNull InventoryHolder owner, int size, + @NotNull String miniMessageTitle, @NotNull Object[] positionalArgs); + + @NotNull + @CheckReturnValue + Inventory createInventory(@NotNull InventoryHolder owner, @NotNull InventoryType type, + @NotNull String miniMessageTitle, @NotNull Object[] positionalArgs); + + void applyItemName(@NotNull ItemMeta item, @NotNull String miniMessageDisplayName, @NotNull Object[] positionalArgs); + + void appendItemName(@NotNull ItemMeta item, @NotNull String miniMessageDisplayNameSuffix, @NotNull Object[] positionalArgs); + + void applyItemLore(@NotNull ItemMeta item, @NotNull String[] miniMessageLore, @NotNull Object[] positionalArgs); + + void appendItemLore(@NotNull ItemMeta item, @NotNull String[] miniMessageLore, @NotNull Object[] positionalArgs); + + @NotNull + MessageBossBar createBossBar(@NotNull MessageHolder initialTitle); + +} diff --git a/platform/api/src/main/java/net/codingarea/challenges/platform/message/wrapper/MessageBossBar.java b/platform/api/src/main/java/net/codingarea/challenges/platform/message/wrapper/MessageBossBar.java new file mode 100644 index 000000000..886a2da03 --- /dev/null +++ b/platform/api/src/main/java/net/codingarea/challenges/platform/message/wrapper/MessageBossBar.java @@ -0,0 +1,27 @@ +package net.codingarea.challenges.platform.message.wrapper; + +import net.codingarea.challenges.platform.message.MessageHolder; +import org.bukkit.boss.BarColor; +import org.bukkit.boss.BarStyle; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +/** + * Wrapper for underlying boss bar api (bukkit or adventure). + * We cannot expose the adventure api BossBar due to incompatibilities. + */ +public interface MessageBossBar { + + void show(@NotNull Player player); + + void hide(@NotNull Player player); + + void setText(@NotNull MessageHolder text); + + void setColor(@NotNull BarColor color); + + void setStyle(@NotNull BarStyle style); + + void setProgress(float progress); + +} diff --git a/platform/common/build.gradle.kts b/platform/common/build.gradle.kts new file mode 100644 index 000000000..88bcb035f --- /dev/null +++ b/platform/common/build.gradle.kts @@ -0,0 +1,24 @@ +plugins { + id("java-library") +} + +dependencies { + api(project(":platform:api")) + + compileOnly(libs.spigot.api) + + // safe to use here, as it will either be used as the reloaced or native variant (this module will get duplicated) + // but it would NOT be safe to access from the main "plugin" module + compileOnly(libs.adventure.text.minimessage) + compileOnly(libs.adventure.text.serializer.legacy) + + compileOnly(libs.lombok) + + annotationProcessor(libs.lombok) +} + +tasks { + jar { + archiveClassifier = "plain" + } +} diff --git a/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/AbstractMiniMessagePlatform.java b/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/AbstractMiniMessagePlatform.java new file mode 100644 index 000000000..22323602b --- /dev/null +++ b/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/AbstractMiniMessagePlatform.java @@ -0,0 +1,331 @@ +package net.codingarea.challenges.platform.message.common; + +import lombok.AllArgsConstructor; +import net.codingarea.challenges.platform.message.MessageHolder; +import net.codingarea.challenges.platform.message.MessagePlatform; +import net.codingarea.challenges.platform.message.common.wrapper.AdventureMessageBossBar; +import net.kyori.adventure.bossbar.BossBar; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentLike; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.TextReplacementConfig; +import net.kyori.adventure.text.format.TextDecoration; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import net.kyori.adventure.title.Title; +import net.kyori.adventure.translation.Translatable; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.meta.ItemMeta; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NonNull; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Common base for implementations of MiniMessage preventing duplicate code. + * This class will be duplicated at compile time and relocated inside the legacy module for compatibility with + * relocated adventure lib. The original version (not relocated) will be used by the native impl. + *

+ * Due to version/classpath incompatibility we have to abstract all calls to the adventure api. + * + * @see #convertToComponent(Object) for compatible argument types + */ +@AllArgsConstructor +public abstract class AbstractMiniMessagePlatform implements MessagePlatform { + + protected final Map prefixCache = new ConcurrentHashMap<>(); // messages may be sent concurrently + protected final MiniMessage miniMessage; + protected final LegacyComponentSerializer legacySerializer; + + public abstract void sendSenderComponent(@NotNull CommandSender sender, @NotNull Component component); + + public abstract void sendChatComponent(@NotNull Player player, @NotNull Component component); + + public abstract void sendActionBarComponent(@NotNull Player player, @NotNull Component component); + + public abstract void sendAdventureTitle(@NotNull Player player, @NotNull Title title); + + @NotNull + public abstract Inventory createInventoryTitled(@NotNull InventoryHolder owner, int size, @NotNull Component titleComponent); + + @NotNull + public abstract Inventory createInventoryTitled(@NotNull InventoryHolder owner, @NotNull InventoryType type, + @NotNull Component titleComponent); + + @NotNull + public abstract Component getPlayerNameComponent(@NotNull Player player); + + public abstract void applyItemNameComponent(@NotNull ItemMeta meta, @NotNull Component nameComponent); + + public abstract void appendItemNameComponent(@NotNull ItemMeta meta, @NotNull Component nameComponent); + + public abstract void applyItemLoreComponent(@NotNull ItemMeta meta, @NotNull List loreComponentLines); + + public abstract void appendItemLoreComponent(@NotNull ItemMeta meta, @NotNull List loreComponentLines); + + public abstract void showAdventureBossBar(@NotNull Player player, @NotNull BossBar bar); + + public abstract void hideAdventureBossBar(@NotNull Player player, @NotNull BossBar bar); + + @Override + public void sendSenderMessage(@NotNull CommandSender sender, @Nullable String miniMessagePrefix, + @NotNull String[] miniMessageTextLines, @NotNull Object[] positionalArgs) { + if (miniMessageTextLines.length == 0) return; + sendSenderComponent(sender, deserializeLinesWithArgs(miniMessagePrefix, miniMessageTextLines, positionalArgs)); + } + + @Override + public void sendChatMessage(@NotNull Player player, @Nullable String miniMessagePrefix, + @NotNull String[] miniMessageTextLines, @NotNull Object[] positionalArgs) { + if (miniMessageTextLines.length == 0) return; + sendChatComponent(player, deserializeLinesWithArgs(miniMessagePrefix, miniMessageTextLines, positionalArgs)); + } + + @Override + public void sendActionBar(@NotNull Player player, @NotNull String miniMessageText, @NotNull Object[] positionalArgs) { + sendActionBarComponent(player, deserializeLineWithArgs(miniMessageText, positionalArgs)); + } + + @Override + public void sendTitle(@NotNull Player player, @NotNull String[] miniMessageTitleAndSubtitle, @NotNull Object[] positionalArgs) { + sendAdventureTitle(player, Title.title(deserializeTitleWithArgs(miniMessageTitleAndSubtitle, positionalArgs), + deserializeSubtitle(miniMessageTitleAndSubtitle, positionalArgs))); + } + + @Override + public void sendTitle(@NotNull Player player, @NotNull String[] miniMessageTitleAndSubtitle, @NotNull Object[] positionalArgs, + int fadeInTicks, int stayTicks, int fadeOutTicks) { + sendAdventureTitle(player, Title.title(deserializeTitleWithArgs(miniMessageTitleAndSubtitle, positionalArgs), + deserializeSubtitle(miniMessageTitleAndSubtitle, positionalArgs), fadeInTicks, stayTicks, fadeOutTicks)); + } + + @NotNull + @Override + public Inventory createInventory(@NotNull InventoryHolder owner, int size, @NotNull String miniMessageTitle, @NotNull Object[] positionalArgs) { + return createInventoryTitled(owner, size, deserializeLineWithArgs(miniMessageTitle, positionalArgs)); + } + + @NotNull + @Override + public Inventory createInventory(@NotNull InventoryHolder owner, @NotNull InventoryType type, + @NotNull String miniMessageTitle, @NotNull Object[] positionalArgs) { + return createInventoryTitled(owner, type, deserializeLineWithArgs(miniMessageTitle, positionalArgs)); + } + + @Override + public void applyItemName(@NotNull ItemMeta item, @NotNull String miniMessageDisplayName, @NotNull Object[] positionalArgs) { + applyItemNameComponent(item, deserializeLineWithArgs(miniMessageDisplayName, positionalArgs)); + } + + @Override + public void appendItemName(@NotNull ItemMeta item, @NotNull String miniMessageDisplayNameSuffix, @NotNull Object[] positionalArgs) { + appendItemNameComponent(item, deserializeLineWithArgs(miniMessageDisplayNameSuffix, positionalArgs)); + } + + @Override + public void applyItemLore(@NotNull ItemMeta item, @NotNull String[] miniMessageLore, @NotNull Object[] positionalArgs) { + applyItemLoreComponent(item, deserializeLinesAsListWithArgs(miniMessageLore, positionalArgs)); + } + + @Override + public void appendItemLore(@NotNull ItemMeta item, @NotNull String[] miniMessageLore, @NotNull Object[] positionalArgs) { + appendItemLoreComponent(item, deserializeLinesAsListWithArgs(miniMessageLore, positionalArgs)); + } + + @NotNull + @Override + public AdventureMessageBossBar createBossBar(@NonNull MessageHolder initialTitle) { + Component initialTitleComponent = convertMessageHolderToComponent(initialTitle); + return new AdventureMessageBossBar(this, createDefaultAdventureBossBar(initialTitleComponent)); + } + + @NotNull + protected Component deserializeTitleWithArgs(@NotNull String[] titleAndSubtitle, @NotNull Object[] positionalArgs) { + if (titleAndSubtitle.length == 0) return Component.empty(); + return deserializeLineWithArgs(titleAndSubtitle[0], positionalArgs); + } + + @NotNull + protected Component deserializeSubtitle(@NotNull String[] titleAndSubtitle, @NotNull Object[] positionalArgs) { + if (titleAndSubtitle.length < 1) return Component.empty(); + return deserializeLineWithArgs(titleAndSubtitle[1], positionalArgs); + } + + @NotNull + protected Component deserializeLinesWithArgs(@Nullable String prefix, @NotNull String[] textLines, @NotNull Object[] positionalArgs) { + return replacePositionalArgs(deserializeLines(prefix, textLines), positionalArgs); + } + + @NotNull + protected Component deserializeLineWithArgs(@NotNull String line, @NotNull Object[] positionalArgs) { + return replacePositionalArgs(deserializeText(line), positionalArgs); + } + + @NotNull + protected Component deserializeLines(@Nullable String prefix, @NotNull String[] textLines) { + if (textLines.length == 0) return Component.empty(); + + TextComponent.Builder rootBuilder = Component.text(); + Component prefixComponent = (prefix != null && !prefix.isEmpty()) ? + prefixCache.computeIfAbsent(prefix, this::deserializeText) : null; + + // DISCUSSION: performance trade off for caching frequently used components vs. parsing on the fly + for (int i = 0; i < textLines.length; i++) { + if (textLines[i].isEmpty() || textLines[i].isBlank()) { // no prefix for empty lines + rootBuilder.append(Component.newline()); + continue; + } + + Component lineComponent = deserializeText(textLines[i]); + + if (prefixComponent != null) { + rootBuilder.append(prefixComponent).append(lineComponent); + } else { + rootBuilder.append(lineComponent); + } + + if (i < textLines.length - 1) { + rootBuilder.append(Component.newline()); + } + } + + return rootBuilder.build(); + } + + @NotNull + protected List deserializeLinesAsListWithArgs(@NotNull String[] textLines, @NotNull Object[] args) { + if (textLines.length == 0) return Collections.emptyList(); + + boolean hasArgs = args.length > 0; // don't waste time on processing otherwise + List components = new ArrayList<>(textLines.length + args.length); // might grow with args; extending is more expensive + for (String textLine : textLines) { + Component line = deserializeText(textLine); + if (hasArgs) { + List replaced = replacePositionalArgsAsList(line, args); + components.addAll(replaced); + } else { + components.add(line); + } + } + return components; + } + + @NotNull + protected Component replacePositionalArgs(@NotNull Component component, @Nullable Object[] positionalArgs) { + if (positionalArgs == null || positionalArgs.length == 0) { + return component; + } + + return component.replaceText(TextReplacementConfig.builder() + .match(POS_ARG_PATTERN) + .replacement((matchResult, builder) -> { + int index = Integer.parseInt(matchResult.group(1)); + if (index >= 0 && index < positionalArgs.length) { + return convertToComponent(positionalArgs[index]); + } + return builder; // or else leave as is, no runtime exceptions + }).build()); + } + + @NotNull + protected List replacePositionalArgsAsList(@NotNull Component component, @Nullable Object[] positionalArgs) { + if (positionalArgs == null || positionalArgs.length == 0) { + return List.of(component); + } + + Component replaced = replacePositionalArgs(component, positionalArgs); + return ComponentSplitter.split(replaced, "\\n"); + } + + protected Component convertToComponent(@Nullable Object obj) { + return switch (obj) { + case null -> Component.empty(); + case Component component -> component; + case ComponentLike like -> like.asComponent(); + case MessageHolder holder -> convertMessageHolderToComponent(holder); + case Translatable translatable -> // net.kyori.adventure.translation.Translatable + Component.translatable(translatable); + case String string -> Component.text(string); // literal escaped text; not deserializeText + case Material material -> TranslatableComponents.fromMaterial(material); + case EntityType entityType -> TranslatableComponents.fromEntityType(entityType); + case GameMode gameMode -> TranslatableComponents.fromGameMode(gameMode); + case Player player -> getPlayerNameComponent(player); + case Object _ when TranslatableComponents.isBukkitTranslatable(obj) -> // org.bukkit.Translatable + TranslatableComponents.fromBukkitTranslatable(obj); + case Enum enumObj -> Component.text(stringifyFallbackEnumName(enumObj.name())); + default -> Component.text(obj.toString()); + }; + } + + @NotNull + public Component convertMessageHolderToComponent(@NotNull MessageHolder holder) { + return deserializeLinesWithArgs(null, holder.miniMessageRaw(), holder.positionalArgs()); + } + + @NotNull + protected Component deserializeText(@NotNull String textLine) { + return deserializeText0(textLine) + .decorationIfAbsent(TextDecoration.ITALIC, TextDecoration.State.FALSE); + } + + @NotNull + protected Component deserializeText0(@NotNull String textLine) { + if (isProbablyLegacyText(textLine)) { + return legacySerializer.deserialize(textLine); + } + try { + return miniMessage.deserialize(textLine); + } catch (Exception ex) { // maybe heuristic failed, try legacy again + return legacySerializer.deserialize(textLine); + } + } + + @NotNull + protected BossBar createDefaultAdventureBossBar(@NotNull Component initialText) { + return BossBar.bossBar(initialText, 1f, BossBar.Color.WHITE, BossBar.Overlay.PROGRESS); + } + + protected boolean isProbablyLegacyText(@NotNull String text) { + // legacy texts often start/end with a '§' color; heuristic so we don't have to check the full string + if (text.length() < 2) return false; + if (text.charAt(0) == '§') return true; + return text.charAt(text.length() - 2) == '§'; + } + + protected String stringifyFallbackEnumName(@NotNull String enumName) { + // EXAMPLE_ENUM -> "Example Enum" + int len = enumName.length(); + if (len == 0) return ""; + + char[] result = new char[len]; + boolean nextUpperCase = true; + for (int i = 0; i < len; i++) { + char letter = enumName.charAt(i); + if (letter == '_') { + result[i] = ' '; + nextUpperCase = true; + } else { + if (nextUpperCase) { + result[i] = (letter >= 'a' && letter <= 'z') ? (char) (letter - 32) : letter; // to uppercase + } else { + result[i] = (letter >= 'A' && letter <= 'Z') ? (char) (letter + 32) : letter; // to lowercase + } + nextUpperCase = false; + } + } + return new String(result); + } + +} diff --git a/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/BukkitTranslationKeyExtractor.java b/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/BukkitTranslationKeyExtractor.java new file mode 100644 index 000000000..f59d582d8 --- /dev/null +++ b/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/BukkitTranslationKeyExtractor.java @@ -0,0 +1,24 @@ +package net.codingarea.challenges.platform.message.common; + +import org.bukkit.Translatable; +import org.jetbrains.annotations.NotNull; + +// org.bukitt.Translatable available since 1.19.3 +// LinkageError due to Translatable not existing -> the whole class may not be loadable +// therefore we encapsulate it which is preferred compared to expesive reflection calls to Translatable +final class BukkitTranslationKeyExtractor { + + private BukkitTranslationKeyExtractor() { + } + + static boolean isTranslationKeyAvailable(@NotNull Object obj) throws LinkageError { + return obj instanceof Translatable; + } + + static String extractTranslationKey(@NotNull Object obj) throws LinkageError { + if (obj instanceof Translatable translatable) + return translatable.getTranslationKey(); + throw new IllegalArgumentException("Object " + obj.getClass() + " is not a org.bukkit.Translatable"); + } + +} diff --git a/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/ComponentSplitter.java b/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/ComponentSplitter.java new file mode 100644 index 000000000..9511dc7d2 --- /dev/null +++ b/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/ComponentSplitter.java @@ -0,0 +1,85 @@ +package net.codingarea.challenges.platform.message.common; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import org.intellij.lang.annotations.RegExp; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public final class ComponentSplitter { + + private ComponentSplitter() { + } + + /** + * Splits a component and the underlying component tree by a regex. Styles are being preserved, so + * splitting {@code line1\nline2} by the regex "\n" will produce two components + * with {@link net.kyori.adventure.text.format.TextColor} green. It matches the regex for all + * components and their content but not for a pattern that goes beyond one component. + * {@code line1abcline2} can therefore not be split with the regex "abc", because + * only "ab" or "c" would match. + * + * @param self A component to split at a regex. + * @param separator A regex to split the TextComponent content at. + * @return A list of new components + */ + @NotNull + @Contract(pure = true) + public static List split(@NotNull Component self, @NotNull @RegExp String separator) { + // First split component content + List lines = splitComponentContent(self, separator); + + if (self.children().isEmpty()) { + return lines; + } + + // Extract last split, which will contain all children of the same line + Component parent = lines.removeLast(); + + // Process each child in order + for (Component child : self.children()) { + // Split child to List + List childSegments = split(child, separator); + + // each split will be a new row, except the first which will stick to the parent + parent = parent.append(childSegments.get(0)); + for (int i = 1; i < childSegments.size(); i++) { + lines.add(parent); + parent = Component.empty().style(parent.style()); + parent = parent.append(childSegments.get(i)); + } + } + lines.add(parent); + return lines; + } + + /** + * Splits a {@link TextComponent} by a regex. + * + * @param component A {@link TextComponent} to split. If the provided Component is no instance of + * TextComponent, a list with only the component is returned. + * @param regex A regex that splits the content of the TextComponent, similar to + * {@link String#split(String)} + * @return A list of TextComponents that contain the string segments of the original content. + */ + @NotNull + private static List splitComponentContent(@NotNull Component component, @NotNull @RegExp String regex) { + if (!(component instanceof TextComponent t)) { + return List.of(component); + } + String[] segments = t.content().split(regex); + if (segments.length == 0) { + // Special case if the split regex is equals to the content. + segments = new String[]{"", ""}; + } + return Arrays.stream(segments) + .map(s -> Component.text(s).style(t.style())) + .map(c -> (Component) c) + .collect(Collectors.toList()); + } + +} diff --git a/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/TranslatableComponents.java b/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/TranslatableComponents.java new file mode 100644 index 000000000..02287b199 --- /dev/null +++ b/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/TranslatableComponents.java @@ -0,0 +1,60 @@ +package net.codingarea.challenges.platform.message.common; + +import net.kyori.adventure.text.Component; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.jetbrains.annotations.NotNull; + +public final class TranslatableComponents { + + private TranslatableComponents() { + } + + // org.bukkit.Translatable available since 1.19.3, but we want to provide compatibility with older versions + public static boolean isBukkitTranslatable(@NotNull Object translatable) { + try { + return BukkitTranslationKeyExtractor.isTranslationKeyAvailable(translatable); + } catch (Throwable ex) { + return false; + } + } + + @NotNull + public static Component fromBukkitTranslatable(@NotNull Object translatable) { + // must check isBukkitTranslatable first + try { + return Component.translatable(BukkitTranslationKeyExtractor.extractTranslationKey(translatable)); + } catch (Throwable ex) { + // ignore and fallback to toString silently instead of runtime exception + return Component.translatable(translatable.toString()); + } + } + + @NotNull + public static Component fromMaterial(@NotNull Material material) { + try { + return Component.translatable(material.getTranslationKey()); // 1.19.3+ + } catch (NoSuchMethodError ex) { + // hopefully this is the correct key... use namespace key instead? + String prefix = material.isItem() ? "block.minecraft." : "item.minecraft."; + return Component.translatable(prefix + material.name().toLowerCase()); + } + } + + @NotNull + public static Component fromEntityType(@NotNull EntityType entityType) { + try { + return Component.translatable(entityType.getTranslationKey()); // 1.19.3+ + } catch (NoSuchMethodError ex) { + // hopefully this is the correct key... use namespace key instead? + return Component.translatable("entity.minecraft." + entityType.name().toLowerCase()); + } + } + + @NotNull + public static Component fromGameMode(@NotNull GameMode gameMode) { + return Component.translatable("selectWorld.gameMode." + gameMode.name().toLowerCase()); + } + +} diff --git a/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/wrapper/AdventureMessageBossBar.java b/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/wrapper/AdventureMessageBossBar.java new file mode 100644 index 000000000..97b0e4cb5 --- /dev/null +++ b/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/wrapper/AdventureMessageBossBar.java @@ -0,0 +1,73 @@ +package net.codingarea.challenges.platform.message.common.wrapper; + +import lombok.RequiredArgsConstructor; +import net.codingarea.challenges.platform.message.MessageHolder; +import net.codingarea.challenges.platform.message.common.AbstractMiniMessagePlatform; +import net.codingarea.challenges.platform.message.wrapper.MessageBossBar; +import net.kyori.adventure.bossbar.BossBar; +import org.bukkit.boss.BarColor; +import org.bukkit.boss.BarStyle; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NonNull; + +@RequiredArgsConstructor +public class AdventureMessageBossBar implements MessageBossBar { + + protected final AbstractMiniMessagePlatform platform; + protected final BossBar bar; + + @Override + public void setText(@NonNull MessageHolder text) { + bar.name(platform.convertMessageHolderToComponent(text)); + } + + @Override + public void setColor(@NonNull BarColor color) { + bar.color(convertColor(color)); + } + + @Override + public void setStyle(@NonNull BarStyle style) { + bar.overlay(convertStyle(style)); + } + + @Override + public void setProgress(float progress) { + bar.progress(progress); + } + + @Override + public void show(@NonNull Player player) { + platform.showAdventureBossBar(player, bar); + } + + @Override + public void hide(@NonNull Player player) { + platform.hideAdventureBossBar(player, bar); + } + + @NotNull + protected static BossBar.Overlay convertStyle(@NotNull BarStyle style) { + return switch (style) { + case SEGMENTED_6 -> BossBar.Overlay.NOTCHED_6; + case SEGMENTED_10 -> BossBar.Overlay.NOTCHED_10; + case SEGMENTED_12 -> BossBar.Overlay.NOTCHED_12; + case SEGMENTED_20 -> BossBar.Overlay.NOTCHED_20; + default -> BossBar.Overlay.PROGRESS; + }; + } + + @NotNull + protected static BossBar.Color convertColor(@NotNull BarColor color) { + return switch (color) { + case PINK -> BossBar.Color.PINK; + case BLUE -> BossBar.Color.BLUE; + case RED -> BossBar.Color.RED; + case GREEN -> BossBar.Color.GREEN; + case YELLOW -> BossBar.Color.YELLOW; + case PURPLE -> BossBar.Color.PURPLE; + default -> BossBar.Color.WHITE; + }; + } +} diff --git a/platform/legacy/build.gradle.kts b/platform/legacy/build.gradle.kts new file mode 100644 index 000000000..73f773673 --- /dev/null +++ b/platform/legacy/build.gradle.kts @@ -0,0 +1,62 @@ +plugins { + id("java-library") + alias(libs.plugins.shadow) +} + +dependencies { + compileOnly(libs.spigot.api) + + implementation(project(":platform:common")) + + // in paper + // - since 1.16.5: adventure-api is bundled (but not minimessage) + // - since 1.18.2: minimessage is bundled in paper + // - since 1.20.5: paper migrated internal systems to minimessages, mojang rewrote internals + // breaking shaded impl + implementation(libs.adventure.text.minimessage) + // has been discontinued, but avilable implementations for legacy versions are still available and functional + // we only use it for legacy support making this a practical solution + implementation(libs.adventure.platform.bukkit) + + // not available by default + implementation(libs.adventure.text.serializer.legacy) + + // NOTE: shadow(..) does somehow not work, requiring exlusion of net.kyori.* when importing to prevent Gradle + // from bundling it twice (once relocated and once default), just using implementation for now +} + +tasks { + + jar { + archiveClassifier = "plain" + } + + shadowJar { + archiveClassifier = "" + + // relocate adventure lib (inclduing legacy bukkit platform) for compatibilty with legacy platforms + // including spigot and paper pre-1.18.2 + // - if adventure lib is fully bundled natively (e.g. modern paper version) it will use the available api + // as the shadowed adventure lib version (might) be incompatible with newer minecraft versions + // like post-1.20.5 as the component system was overhauled + // (provided and used by :platform:legacy) + relocate("net.kyori", "net.codingarea.challenges.relocate") + + // force Gradle to relocate common module for compatibility with relocated adventure lib. + // hacky & ugly fix but necessary for compatibility with older versions and prevents writing/maintating the same code twice. + relocate("net.codingarea.challenges.platform.message.common", "net.codingarea.challenges.platform.message.legacy") + } + +} + +// make Gradle expose the shadowed JAR to other projects by default +configurations { + apiElements { + outgoing.artifacts.clear() + outgoing.artifact(tasks.shadowJar) + } + runtimeElements { + outgoing.artifacts.clear() + outgoing.artifact(tasks.shadowJar) + } +} diff --git a/platform/legacy/src/main/java/net/codingarea/challenges/platform/message/legacy/LegacyMiniMessagePlatform.java b/platform/legacy/src/main/java/net/codingarea/challenges/platform/message/legacy/LegacyMiniMessagePlatform.java new file mode 100644 index 000000000..285689f22 --- /dev/null +++ b/platform/legacy/src/main/java/net/codingarea/challenges/platform/message/legacy/LegacyMiniMessagePlatform.java @@ -0,0 +1,129 @@ +package net.codingarea.challenges.platform.message.legacy; + +import net.codingarea.challenges.platform.message.common.AbstractMiniMessagePlatform; +import net.codingarea.challenges.platform.message.common.wrapper.AdventureMessageBossBar; +import net.kyori.adventure.bossbar.BossBar; +import net.kyori.adventure.platform.bukkit.BukkitAudiences; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import net.kyori.adventure.title.Title; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.plugin.java.JavaPlugin; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +/** + * Adds support for MiniMessages if there is no native implementation found, like on spigot or older paper versions. + * It uses a bundled and relocated version of the adventure dependency. + */ +public class LegacyMiniMessagePlatform extends AbstractMiniMessagePlatform { + + protected final JavaPlugin plugin; + protected BukkitAudiences audiences; + + public LegacyMiniMessagePlatform(@NotNull JavaPlugin plugin) { + super(MiniMessage.miniMessage(), LegacyComponentSerializer.legacySection()); + this.plugin = plugin; + } + + @Override + public void enable() { + // lib will try to register a PlayerJoinListener which is only possible once the plugin is enabled + this.audiences = BukkitAudiences.create(plugin); + } + + @Override + public void disable() { + audiences.close(); + } + + @Override + public void sendSenderComponent(@NotNull CommandSender sender, @NotNull Component component) { + audiences.sender(sender).sendMessage(component); + } + + @Override + public void sendChatComponent(@NotNull Player player, @NotNull Component component) { + audiences.player(player).sendMessage(component); + } + + @Override + public void sendActionBarComponent(@NotNull Player player, @NotNull Component component) { + audiences.player(player).sendActionBar(component); + } + + @Override + public void sendAdventureTitle(@NotNull Player player, @NotNull Title title) { + audiences.player(player).showTitle(title); + } + + @NotNull + @Override + public Inventory createInventoryTitled(@NotNull InventoryHolder owner, int size, @NotNull Component titleComponent) { + return Bukkit.createInventory(owner, size, legacySerializer.serialize(titleComponent)); + } + + @NotNull + @Override + public Inventory createInventoryTitled(@NotNull InventoryHolder owner, @NotNull InventoryType type, @NotNull Component titleComponent) { + return Bukkit.createInventory(owner, type, legacySerializer.serialize(titleComponent)); + } + + @NotNull + @Override + public Component getPlayerNameComponent(@NotNull Player player) { + return legacySerializer.deserialize(player.getDisplayName()); + } + + @Override + public void applyItemNameComponent(@NotNull ItemMeta meta, @NotNull Component nameComponent) { + meta.setDisplayName(legacySerializer.serialize(nameComponent)); + } + + @Override + public void appendItemNameComponent(@NotNull ItemMeta meta, @NotNull Component nameComponent) { + String existingName = meta.hasDisplayName() ? meta.getDisplayName() : ""; + meta.setDisplayName(existingName + legacySerializer.serialize(nameComponent)); + } + + @Override + public void applyItemLoreComponent(@NotNull ItemMeta meta, @NotNull List loreComponentLines) { + meta.setLore(componentsToLegacyStrings(loreComponentLines)); + } + + @Override + public void appendItemLoreComponent(@NotNull ItemMeta meta, @NotNull List loreComponentLines) { + List existingLore = meta.getLore(); + if (existingLore == null) { + applyItemLoreComponent(meta, loreComponentLines); + return; + } + existingLore.addAll(componentsToLegacyStrings(loreComponentLines)); + meta.setLore(existingLore); + } + + @Override + public void showAdventureBossBar(@NotNull Player player, @NotNull BossBar bar) { + audiences.player(player).showBossBar(bar); + } + + @Override + public void hideAdventureBossBar(@NotNull Player player, @NotNull BossBar bar) { + audiences.player(player).hideBossBar(bar); + } + + @NotNull + protected List componentsToLegacyStrings(@NotNull List components) { + return components.stream() + .map(legacySerializer::serialize) + .toList(); + } +} diff --git a/platform/paper/build.gradle.kts b/platform/paper/build.gradle.kts new file mode 100644 index 000000000..30a8b43e8 --- /dev/null +++ b/platform/paper/build.gradle.kts @@ -0,0 +1,19 @@ +plugins { + id("java-library") +} + +dependencies { + compileOnly(libs.paper.api) + + implementation(project(":platform:common")) +} + +repositories { + maven("https://repo.papermc.io/repository/maven-public/") +} + +tasks { + jar { + archiveClassifier = "plain" + } +} diff --git a/platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatform.java b/platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatform.java new file mode 100644 index 000000000..ab43cacbb --- /dev/null +++ b/platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatform.java @@ -0,0 +1,120 @@ +package net.codingarea.challenges.platform.message.paper; + +import net.codingarea.challenges.platform.message.common.AbstractMiniMessagePlatform; +import net.kyori.adventure.bossbar.BossBar; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import net.kyori.adventure.title.Title; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.meta.ItemMeta; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +/** + * Allows for native calls to paper/adventure api bundled by modern paper-like servers, + * removing the need for slower reflection wrappers with just a small overhead. + */ +public class NativePaperMessagePlatform extends AbstractMiniMessagePlatform { + + public NativePaperMessagePlatform() { + super(MiniMessage.miniMessage(), LegacyComponentSerializer.legacySection()); + } + + @Override + public void enable() { + // no initialization required + } + + @Override + public void disable() { + // no cleanup required + } + + @Override + public void sendSenderComponent(@NotNull CommandSender sender, @NotNull Component component) { + sender.sendMessage(component); + } + + @Override + public void sendChatComponent(@NotNull Player player, @NotNull Component component) { + player.sendMessage(component); + } + + @Override + public void sendActionBarComponent(@NotNull Player player, @NotNull Component component) { + player.sendActionBar(component); + } + + @Override + public void sendAdventureTitle(@NotNull Player player, @NotNull Title title) { + player.showTitle(title); + } + + @NotNull + @Override + public Inventory createInventoryTitled(@NotNull InventoryHolder owner, int size, @NotNull Component titleComponent) { + return Bukkit.createInventory(owner, size, titleComponent); + } + + @NotNull + @Override + public Inventory createInventoryTitled(@NotNull InventoryHolder owner, @NotNull InventoryType type, + @NotNull Component titleComponent) { + return Bukkit.createInventory(owner, type, titleComponent); + } + + @NotNull + @Override + public Component getPlayerNameComponent(@NotNull Player player) { + return player.displayName(); + } + + @Override + public void applyItemNameComponent(@NotNull ItemMeta meta, @NotNull Component nameComponent) { + meta.displayName(nameComponent); + } + + @Override + public void appendItemNameComponent(@NotNull ItemMeta meta, @NotNull Component nameComponent) { + Component existingName = meta.displayName(); + if (existingName == null) { + meta.displayName(nameComponent); + return; + } + + meta.displayName(existingName.append(nameComponent)); + } + + @Override + public void applyItemLoreComponent(@NotNull ItemMeta meta, @NotNull List loreComponentLines) { + meta.lore(loreComponentLines); + } + + @Override + public void appendItemLoreComponent(@NotNull ItemMeta meta, @NotNull List loreComponentLines) { + List existingLore = meta.lore(); + if (existingLore == null) { + meta.lore(loreComponentLines); + return; + } + existingLore.addAll(loreComponentLines); // meta.lore() is always modifiable? + meta.lore(existingLore); + } + + @Override + public void showAdventureBossBar(@NotNull Player player, @NotNull BossBar bar) { + player.showBossBar(bar); + } + + @Override + public void hideAdventureBossBar(@NotNull Player player, @NotNull BossBar bar) { + player.hideBossBar(bar); + } +} diff --git a/platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatformChecker.java b/platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatformChecker.java new file mode 100644 index 000000000..6ac4a4c89 --- /dev/null +++ b/platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatformChecker.java @@ -0,0 +1,30 @@ +package net.codingarea.challenges.platform.message.paper; + +import org.jetbrains.annotations.NotNull; + +public final class NativePaperMessagePlatformChecker { + + private NativePaperMessagePlatformChecker() { + } + + public static boolean isAvailable() { + try { + // test if Paper's native MiniMessage is present on the classpath + Class.forName(buildClassName("net", "kyori", "adventure", "text", "minimessage", "MiniMessage")); + // impl version we use internally; fallback if it has changed as it would lead to errors + Class.forName(buildClassName("net", "kyori", "adventure", "text", "minimessage", "MiniMessageImpl")); + // required translation api + Class.forName(buildClassName("net", "kyori", "adventure", "translation", "Translatable")); + return true; + } catch (Throwable ex) { + return false; + } + } + + private static String buildClassName(@NotNull String... location) { + // use string builder to avoid constants being remapped due to relocation + // as we don't care about our shaded impl but the native one bundled by paper + return String.join(".", location); + } + +} diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index 9a7afc937..2564b66e1 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -1,10 +1,31 @@ +import groovy.json.JsonOutput +import groovy.json.JsonSlurper + plugins { id("java-library") alias(libs.plugins.shadow) + alias(libs.plugins.jvmdg) +} + + +// hacky patch; to ensure compatibilty with older minecraft versions and newer dependencies and tools which +// require latest java, we compile against latest java versions and use a hacky plugin to downgrade the bytecode to older java, +// so it can run on older versions. +// this is inherently unsafe and could produce runtime errors that would noramlly be cauth at compile time, +// but it's a practical and working solution. +// NOTE: it does NOT map any bukkit api calls / changes, ONLY java version compatibility. +// it is also not produced by default build/shadowJar. +// DO NOT use the downgraded jar for production servers running latest java/minecraft. +jvmdg { + downgradeTo = JavaVersion.VERSION_16 +} + +repositories { + maven("https://maven.wagyourtail.xyz/releases") // jvmdg } dependencies { - implementation(libs.slf4j.api) + compileOnly(libs.slf4j.api) compileOnly(libs.spigot.api) compileOnly(libs.authlib) @@ -18,13 +39,19 @@ dependencies { annotationProcessor(libs.lombok) - // bundle cloud impl modules + api(project(":cloud-support:api")) + // TODO abstract to register dynamically - implementation(project(":cloud-support:api")) implementation(project(":cloud-support:cloudnet2")) implementation(project(":cloud-support:cloudnet3")) -} + api(project(":platform:api")) + implementation(project(":platform:common")) + implementation(project(":platform:paper")) + implementation(project(":platform:legacy")) { + exclude("net.kyori") // see platform/legacy/build.gradle.kts + } +} tasks { processResources { @@ -32,6 +59,22 @@ tasks { into("language") include("**/*.json") } + + // minify bundled json resources: doLast so we only modify the files AFTER they have been copied + // to the build/resources directory, leaving original source files intact. + doLast { + fileTree(destinationDir).matching { + include("**/*.json") + }.forEach { file -> + try { + val parsedJson = JsonSlurper().parse(file) + val minifiedJson = JsonOutput.toJson(parsedJson) + file.writeText(minifiedJson) + } catch (e: Exception) { + logger.warn("Failed to minify JSON file: ${file.name}", e) + } + } + } } jar { @@ -43,20 +86,17 @@ tasks { archiveClassifier = "" archiveVersion = "" - dependencies { - // TODO adopted from maven shade configuration, check necessity - include(dependency("net.kyori:adventure-api")) - - // TODO abstract to register dynamically - include(project(":cloud-support:api")) - include(project(":cloud-support:cloudnet2")) - include(project(":cloud-support:cloudnet3")) - } + // no explicit dependencies block - bundle "implementation" deps by default + // relocated adventure-lib in :platform:legacy } build { dependsOn(shadowJar) } + + downgradeJar { + dependsOn(shadowJar) + } } val localBuild = file("local.gradle.kts") diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java index 1f2c22ed6..f7640f2b5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java @@ -2,9 +2,9 @@ import lombok.Getter; import net.codingarea.challenges.plugin.challenges.custom.settings.CustomSettingsLoader; +import net.codingarea.challenges.plugin.content.i18n.TranslationManager; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.content.loader.LoaderRegistry; -import net.codingarea.challenges.plugin.content.loader.PrefixLoader; import net.codingarea.challenges.plugin.content.loader.UpdateLoader; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager; import net.codingarea.challenges.plugin.management.bstats.MetricsLoader; @@ -54,6 +54,8 @@ public final class Challenges extends BukkitModule { private GameWorldStorage gameWorldStorage; private GeneratorWorldPortalManager generatorWorldPortalManager; private TeamProvider teamProvider; + private TranslationManager translationManager; + private PlatformManager platformManager; @NotNull public static Challenges getInstance() { @@ -90,10 +92,10 @@ private void createManagers() { loaderRegistry = new LoaderRegistry( new LanguageLoader(), - new PrefixLoader(), new UpdateLoader() ); + platformManager = new PlatformManager(); databaseManager = new DatabaseManager(); worldManager = new WorldManager(); serverManager = new ServerManager(); @@ -114,20 +116,23 @@ private void createManagers() { metricsLoader = new MetricsLoader(); gameWorldStorage = new GameWorldStorage(); generatorWorldPortalManager = new GeneratorWorldPortalManager(); + translationManager = new TranslationManager(); } private void loadManagers() { + platformManager.createPlatforms(); loaderRegistry.load(); worldManager.load(); + challengeTimer.loadSession(); } private void enableManagers() { + platformManager.enablePlatforms(); gameWorldStorage.enable(); challengeLoader.enable(); customSettingsLoader.enable(); databaseManager.enable(); worldManager.enable(); - challengeTimer.loadSession(); challengeTimer.enable(); challengeManager.enable(); statsManager.register(); @@ -216,6 +221,8 @@ protected void handleDisable() { } challengeManager.clearChallengeCache(); } + + if (platformManager != null) platformManager.disablePlatforms(); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index 2e315fb3a..42c2a63ff 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -11,6 +11,7 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.InfoMenuGenerator; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -19,6 +20,7 @@ import org.jetbrains.annotations.Nullable; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; @@ -37,7 +39,7 @@ public class CustomChallenge extends Setting { public CustomChallenge(MenuType menuType, UUID uuid, Material displayItem, String displayName, ChallengeTrigger trigger, Map subTriggers, ChallengeAction action, Map subActions) { - super(menuType); + super(menuType, null, null, "custom-challenge"); this.uuid = uuid; this.material = displayItem; this.name = displayName; @@ -49,7 +51,7 @@ public CustomChallenge(MenuType menuType, UUID uuid, Material displayItem, Strin @NotNull @Override - public ItemStack getDisplayItem() { + public ItemBuilder getDisplayItem(@NotNull Locale locale) { // TODO String name = this.name; if (name == null) { name = "NULL"; @@ -60,7 +62,7 @@ public ItemStack getDisplayItem() { material = Material.BARRIER; } - ItemBuilder builder = new ItemBuilder(material, Message.forName("item-prefix").asString() + "§7" + name); + LegacyItemBuilder builder = new LegacyItemBuilder(material, Message.forName("item-prefix").asString() + "§7" + name); // ADDING CONDITION INFO if (getTrigger() != null) { @@ -84,13 +86,7 @@ public ItemStack getDisplayItem() { builder.appendLore(actionDisplay); } - return builder.build(); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BARRIER); + return new ItemBuilder(locale, builder.build()); } @Override @@ -110,12 +106,6 @@ public void writeSettings(@NotNull Document document) { document.set("subActions", subActions); } - @Nullable - @Override - protected String[] getSettingsDescription() { - return super.getSettingsDescription(); - } - public final void onTriggerFulfilled(ChallengeExecutionData challengeExecutionData) { if (isEnabled()) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java index 0cde7dbe5..3b248ae27 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeExecutionData.java @@ -27,8 +27,7 @@ public class ChallengeExecutionData { @Getter private int timesExecuting; - public ChallengeExecutionData( - IChallengeTrigger trigger) { + public ChallengeExecutionData(IChallengeTrigger trigger) { this.trigger = trigger; this.triggerData = new HashMap<>(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java index 520cd32b8..458394d2e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java @@ -6,7 +6,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.*; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.impl.*; -import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; +import net.codingarea.challenges.plugin.challenges.type.annotation.RequireVersion; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java index 3a29e4797..e3cc0f668 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java @@ -4,20 +4,18 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.common.collection.IRandom; import org.bukkit.inventory.ItemStack; import java.util.LinkedHashMap; import java.util.function.Supplier; -public abstract class ChallengeAction extends ChallengeSetting implements - IChallengeAction { +public abstract class ChallengeAction extends ChallengeSetting implements IChallengeAction { protected static final IRandom random = IRandom.create(); - public ChallengeAction(String name, - SubSettingsBuilder subSettingsBuilder) { + public ChallengeAction(String name, SubSettingsBuilder subSettingsBuilder) { super(name, subSettingsBuilder); } @@ -33,7 +31,7 @@ public static LinkedHashMap getMenuItems() { LinkedHashMap map = new LinkedHashMap<>(); for (ChallengeAction value : Challenges.getInstance().getCustomSettingsLoader().getActions().values()) { - map.put(value.getName(), new ItemBuilder(value.getMaterial(), Message.forName(value.getMessage())).hideAttributes().build()); + map.put(value.getName(), new LegacyItemBuilder(value.getMaterial(), Message.forName(value.getMessage())).hideAttributes().build()); } return map; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java index 32fb6d6fd..197e7c04a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/PlayerTargetAction.java @@ -17,8 +17,7 @@ public PlayerTargetAction(String name) { super(name); } - public PlayerTargetAction(String name, - Supplier builderSupplier) { + public PlayerTargetAction(String name, Supplier builderSupplier) { super(name, builderSupplier); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java index 150f374be..60a8f7397 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Material; @@ -17,7 +17,7 @@ public class BoostEntityInAirAction extends EntityTargetAction { public BoostEntityInAirAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createValueChild().fill(builder -> { builder.addModifierSetting("strength", - new ItemBuilder(Material.FEATHER, Message.forName("item-custom-action-boost_in_air-strength")), + new LegacyItemBuilder(Material.FEATHER, Message.forName("item-custom-action-boost_in_air-strength")), 1, 1, 10, value -> Message.forName("amplifier").asString(), integer -> "" diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java index 4c3ada6e8..026852ffc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java @@ -5,7 +5,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Material; import org.bukkit.World; @@ -19,7 +19,7 @@ public ChangeWorldBorderAction(String name) { super(name, SubSettingsBuilder.createValueItem() .addModifierSetting( "change", - new ItemBuilder(Material.MAGENTA_GLAZED_TERRACOTTA, Message.forName("item-custom-action-modify_border-change")), + new LegacyItemBuilder(Material.MAGENTA_GLAZED_TERRACOTTA, Message.forName("item-custom-action-modify_border-change")), 1, -10, 10 )); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java index 290f11e2b..e6434aade 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; @@ -17,7 +17,7 @@ public DamageEntityAction(String name) { String prefix = DefaultItem.getItemPrefix(); for (int i = 1; i < 21; i++) { builder.addSetting( - String.valueOf(i), new ItemBuilder(Material.FERMENTED_SPIDER_EYE, prefix + "§7" + (i / 2f) + " §c❤").setAmount(i).build()); + String.valueOf(i), new LegacyItemBuilder(Material.FERMENTED_SPIDER_EYE, prefix + "§7" + (i / 2f) + " §c❤").setAmount(i).build()); } })); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java index 8a2066b96..7611300dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java @@ -3,8 +3,8 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.action.PlayerTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.command.CommandSender; @@ -21,17 +21,17 @@ public class ExecuteCommandAction extends PlayerTargetAction { public ExecuteCommandAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true, true, true).createTextInputChild("command", player -> { - Message.forName("custom-command-info").send(player, Prefix.CUSTOM, "/" + String.join(" /", commandsThatCanBeExecuted)); + MessageKey.of("custom-command-info").send(player, Prefix.CUSTOM, "/" + String.join(" /", commandsThatCanBeExecuted)); }, event -> { String cmd = event.getMessage().split(" ")[0].toLowerCase(); if (!commandsThatCanBeExecuted.contains(cmd)) { - Message.forName("custom-command-not-allowed").send(event.getPlayer(), Prefix.CUSTOM, cmd); + MessageKey.of("custom-command-not-allowed").send(event.getPlayer(), Prefix.CUSTOM, cmd); return false; } if (event.getMessage().length() > maxCommandLength) { - Message.forName("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxCommandLength); + MessageKey.of("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxCommandLength); return false; } return true; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java index 597faf167..4018053ae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; @@ -19,7 +19,7 @@ public HealEntityAction(String name) { String prefix = DefaultItem.getItemPrefix(); for (int i = 1; i < 21; i++) { builder.addSetting( - String.valueOf(i), new ItemBuilder( + String.valueOf(i), new LegacyItemBuilder( MinecraftNameWrapper.RED_DYE, prefix + "§7" + (i / 2f) + " §c❤").setAmount(i).build()); } })); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java index 3458c69f3..732eb774c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.PlayerTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -18,7 +18,7 @@ public HungerPlayerAction(String name) { for (int i = 1; i < 21; i++) { builder.addSetting( - String.valueOf(i), new ItemBuilder(Material.ROTTEN_FLESH, prefix + "§7" + i).setAmount(i).build()); + String.valueOf(i), new LegacyItemBuilder(Material.ROTTEN_FLESH, prefix + "§7" + i).setAmount(i).build()); } })); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java index 829701896..72ebe9818 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java @@ -6,7 +6,7 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -19,7 +19,7 @@ public ModifyMaxHealthAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true) .createValueChild().fill(builder -> { builder.addModifierSetting("health_offset", - new ItemBuilder(MinecraftNameWrapper.RED_DYE, + new LegacyItemBuilder(MinecraftNameWrapper.RED_DYE, Message.forName("item-custom-action-max_health-offset")), 0, -20, 20, integer -> "", integer -> "HP §8(§e" + (integer / 2f) + " §c❤§8)"); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java index 68d127520..da5e0eb08 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.FallbackNames; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; +import net.codingarea.challenges.plugin.challenges.type.annotation.RequireVersion; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.commons.common.collection.IRandom; import org.bukkit.*; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java index e6fab4a2a..505f9b92c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java @@ -1,30 +1,30 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub; import lombok.Getter; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; public abstract class ValueSetting { @Getter private final String key; - private final ItemBuilder itemBuilder; + private final LegacyItemBuilder itemBuilder; - public ValueSetting(String key, ItemBuilder itemBuilder) { + public ValueSetting(String key, LegacyItemBuilder itemBuilder) { this.key = key; this.itemBuilder = itemBuilder; } - public ItemBuilder createDisplayItem() { + public LegacyItemBuilder createDisplayItem() { return itemBuilder; } public abstract String onClick(MenuClickInfo info, String value, int slotIndex); - public ItemBuilder getDisplayItem(String value) { + public LegacyItemBuilder getDisplayItem(String value) { return createDisplayItem().hideAttributes(); } - public abstract ItemBuilder getSettingsItem(String value); + public abstract LegacyItemBuilder getSettingsItem(String value); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java index 3ddf864c1..403d1274d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java @@ -3,10 +3,10 @@ import com.google.common.collect.Lists; import lombok.Getter; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.SubSettingChooseMenuGenerator; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -58,7 +58,7 @@ public ChooseItemSubSettingsBuilder addSetting(String key, ItemStack value) { return this; } - public ChooseItemSubSettingsBuilder addSetting(String key, ItemBuilder value) { + public ChooseItemSubSettingsBuilder addSetting(String key, LegacyItemBuilder value) { settings.put(key, value.hideAttributes().build()); return this; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java index 83ef09deb..5850b96e1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java @@ -4,11 +4,11 @@ import lombok.Getter; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.SubSettingChooseMultipleMenuGenerator; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -77,7 +77,7 @@ public ChooseMultipleItemSubSettingBuilder addSetting(String key, ItemStack valu return this; } - public ChooseMultipleItemSubSettingBuilder addSetting(String key, ItemBuilder value) { + public ChooseMultipleItemSubSettingBuilder addSetting(String key, LegacyItemBuilder value) { settings.put(key, value.hideAttributes().build()); return this; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java index 27b413afc..2974e6856 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; -import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java index 34bd817de..07b5f7f4a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java @@ -8,10 +8,10 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl.ModifierSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.impl.MessageManager; -import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.SubSettingValueMenuGenerator; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.entity.Player; @@ -50,7 +50,7 @@ public List getDisplay(Map activated) { if (entry.getKey().equals(setting.getKey())) { - ItemBuilder builder = setting.getSettingsItem(entry.getValue()[0]); + LegacyItemBuilder builder = setting.getSettingsItem(entry.getValue()[0]); if (builder != null) { display.add("§7" + getKeyTranslation(entry.getKey()) + " " + builder.getName()); @@ -71,29 +71,29 @@ public String getKeyTranslation(String key) { ? Message.forName(messageName).asString() : StringUtils.getEnumName(key); } - public ValueSubSettingsBuilder addBooleanSetting(String key, ItemBuilder displayItem, + public ValueSubSettingsBuilder addBooleanSetting(String key, LegacyItemBuilder displayItem, boolean defaultValue) { defaultSettings.put(new BooleanSetting(key, displayItem), defaultValue ? "enabled" : "disabled"); return this; } - public ValueSubSettingsBuilder addModifierSetting(String key, ItemBuilder displayItem, + public ValueSubSettingsBuilder addModifierSetting(String key, LegacyItemBuilder displayItem, int defaultValue, int min, int max) { defaultSettings.put(new ModifierSetting(key, min, max, displayItem), String.valueOf(defaultValue)); return this; } - public ValueSubSettingsBuilder addModifierSetting(String key, ItemBuilder displayItem, + public ValueSubSettingsBuilder addModifierSetting(String key, LegacyItemBuilder displayItem, int defaultValue, int min, int max, Function prefixGetter, Function suffixGetter) { defaultSettings.put(new ModifierSetting(key, min, max, displayItem, prefixGetter, suffixGetter), String.valueOf(defaultValue)); return this; } - public ValueSubSettingsBuilder addModifierSetting(String key, ItemBuilder displayItem, - int defaultValue, int min, int max, Function settingsItemGetter) { + public ValueSubSettingsBuilder addModifierSetting(String key, LegacyItemBuilder displayItem, + int defaultValue, int min, int max, Function settingsItemGetter) { defaultSettings.put(new ModifierSetting(key, min, max, displayItem, settingsItemGetter), String.valueOf(defaultValue)); return this; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java index 249c1f8ef..daef04c07 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java @@ -2,13 +2,13 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; public class BooleanSetting extends ValueSetting { - public BooleanSetting(String key, ItemBuilder itemBuilder) { + public BooleanSetting(String key, LegacyItemBuilder itemBuilder) { super(key, itemBuilder); } @@ -19,7 +19,7 @@ public String onClick(MenuClickInfo info, String value, } @Override - public ItemBuilder getSettingsItem(String value) { + public LegacyItemBuilder getSettingsItem(String value) { return value.equals("enabled") ? DefaultItem.enabled() : DefaultItem.disabled(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java index 6165ac9d5..6a46e8a6a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java @@ -5,7 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import java.util.function.Function; @@ -13,15 +13,15 @@ public class ModifierSetting extends ValueSetting implements IModifier { private final int min, max; - private final Function settingsItemGetter; + private final Function settingsItemGetter; private int tempValue; - public ModifierSetting(String key, int min, int max, ItemBuilder displayItem) { + public ModifierSetting(String key, int min, int max, LegacyItemBuilder displayItem) { this(key, min, max, displayItem, integer -> "", integer -> ""); } - public ModifierSetting(String key, int min, int max, ItemBuilder itemBuilder, Function prefixGetter, Function suffixGetter) { + public ModifierSetting(String key, int min, int max, LegacyItemBuilder itemBuilder, Function prefixGetter, Function suffixGetter) { this(key, min, max, itemBuilder, value -> { String prefix = prefixGetter.apply(value); @@ -31,7 +31,7 @@ public ModifierSetting(String key, int min, int max, ItemBuilder itemBuilder, Fu }); } - public ModifierSetting(String key, int min, int max, ItemBuilder itemBuilder, Function settingsItemGetter) { + public ModifierSetting(String key, int min, int max, LegacyItemBuilder itemBuilder, Function settingsItemGetter) { super(key, itemBuilder); this.min = min; this.max = max; @@ -76,7 +76,7 @@ public void playValueChangeTitle() { } @Override - public ItemBuilder getSettingsItem(String value) { + public LegacyItemBuilder getSettingsItem(String value) { int intValue = getIntValue(value); return settingsItemGetter.apply(intValue); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java index 26888233f..bb8a8c981 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java @@ -4,14 +4,13 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.inventory.ItemStack; import java.util.LinkedHashMap; import java.util.function.Supplier; -public abstract class ChallengeTrigger extends ChallengeSetting implements - IChallengeTrigger { +public abstract class ChallengeTrigger extends ChallengeSetting implements IChallengeTrigger { public ChallengeTrigger(String name, SubSettingsBuilder subSettingsBuilder) { @@ -30,7 +29,7 @@ public static LinkedHashMap getMenuItems() { LinkedHashMap map = new LinkedHashMap<>(); for (ChallengeTrigger value : Challenges.getInstance().getCustomSettingsLoader().getTriggers().values()) { - map.put(value.getName(), new ItemBuilder(value.getMaterial(), Message.forName(value.getMessage())).hideAttributes().build()); + map.put(value.getName(), new LegacyItemBuilder(value.getMaterial(), Message.forName(value.getMessage())).hideAttributes().build()); } return map; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java index 1311f078a..0af34725a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java @@ -5,7 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; @@ -18,7 +18,7 @@ public ConsumeItemTrigger(String name) { super(name, SubSettingsBuilder.createChooseMultipleItem(SubSettingsHelper.ITEM).fill(builder -> { for (Material material : ExperimentalUtils.getMaterials()) { if (material.isEdible()) { - builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemComponent(material).toPlainText()).build()); + builder.addSetting(material.name(), new LegacyItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemComponent(material).toPlainText()).build()); } } })); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java index 0fc9a7789..818c3b4f0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java @@ -4,8 +4,8 @@ import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.bukkit.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder.PotionBuilder; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; @@ -26,7 +26,7 @@ public EntityDamageTrigger(String name) { Arrays.asList(PotionEffectType.values())); Collections.shuffle(types, new Random(1)); - builder.addSetting(SubSettingsHelper.ANY, new ItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-trigger-damage-any"))); + builder.addSetting(SubSettingsHelper.ANY, new LegacyItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-trigger-damage-any"))); DamageCause[] values = DamageCause.values(); for (int i = 0; i < values.length; i++) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java index cf6208b42..4c1c4b0a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java @@ -6,7 +6,7 @@ import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -19,8 +19,8 @@ public class InLiquidTrigger extends ChallengeTrigger { public InLiquidTrigger(String name) { super(name, SubSettingsBuilder.createChooseMultipleItem(SubSettingsHelper.LIQUID).fill(builder -> { - builder.addSetting("LAVA", new ItemBuilder(Material.LAVA_BUCKET, DefaultItem.getItemPrefix() + "§cLava")); - builder.addSetting("WATER", new ItemBuilder(Material.WATER_BUCKET, DefaultItem.getItemPrefix() + "§9Water")); + builder.addSetting("LAVA", new LegacyItemBuilder(Material.LAVA_BUCKET, DefaultItem.getItemPrefix() + "§cLava")); + builder.addSetting("WATER", new LegacyItemBuilder(Material.WATER_BUCKET, DefaultItem.getItemPrefix() + "§9Water")); })); Challenges.getInstance().getScheduler().register(this); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java index 87f91462a..222ed95c5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java @@ -6,7 +6,7 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.PlayerCountPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Material; import java.util.LinkedList; @@ -16,19 +16,19 @@ public class IntervallTrigger extends ChallengeTrigger { public IntervallTrigger(String name) { super(name, SubSettingsBuilder.createChooseItem("time").fill(builder -> { - builder.addSetting("1", new ItemBuilder(Material.MUSIC_DISC_13, Message.forName("item-custom-trigger-intervall-second"), "1").build()); + builder.addSetting("1", new LegacyItemBuilder(Material.MUSIC_DISC_13, Message.forName("item-custom-trigger-intervall-second"), "1").build()); String seconds = "item-custom-trigger-intervall-seconds"; - builder.addSetting("2", new ItemBuilder(Material.MUSIC_DISC_CAT, Message.forName(seconds), "2")); - builder.addSetting("5", new ItemBuilder(Material.MUSIC_DISC_BLOCKS, Message.forName(seconds), "5")); - builder.addSetting("10", new ItemBuilder(Material.MUSIC_DISC_CHIRP, Message.forName(seconds), "10")); - builder.addSetting("20", new ItemBuilder(Material.MUSIC_DISC_FAR, Message.forName(seconds), "20")); - builder.addSetting("30", new ItemBuilder(Material.MUSIC_DISC_MALL, Message.forName(seconds), "30")); - builder.addSetting("60", new ItemBuilder(Material.MUSIC_DISC_MELLOHI, Message.forName(seconds), "60")); + builder.addSetting("2", new LegacyItemBuilder(Material.MUSIC_DISC_CAT, Message.forName(seconds), "2")); + builder.addSetting("5", new LegacyItemBuilder(Material.MUSIC_DISC_BLOCKS, Message.forName(seconds), "5")); + builder.addSetting("10", new LegacyItemBuilder(Material.MUSIC_DISC_CHIRP, Message.forName(seconds), "10")); + builder.addSetting("20", new LegacyItemBuilder(Material.MUSIC_DISC_FAR, Message.forName(seconds), "20")); + builder.addSetting("30", new LegacyItemBuilder(Material.MUSIC_DISC_MALL, Message.forName(seconds), "30")); + builder.addSetting("60", new LegacyItemBuilder(Material.MUSIC_DISC_MELLOHI, Message.forName(seconds), "60")); String minutes = "item-custom-trigger-intervall-minutes"; - builder.addSetting("120", new ItemBuilder(Material.MUSIC_DISC_STAL, Message.forName(minutes), "2")); - builder.addSetting("180", new ItemBuilder(Material.MUSIC_DISC_STRAD, Message.forName(minutes), "3")); - builder.addSetting("240", new ItemBuilder(Material.MUSIC_DISC_WARD, Message.forName(minutes), "4")); - builder.addSetting("300", new ItemBuilder(Material.MUSIC_DISC_11, Message.forName(minutes), "5")); + builder.addSetting("120", new LegacyItemBuilder(Material.MUSIC_DISC_STAL, Message.forName(minutes), "2")); + builder.addSetting("180", new LegacyItemBuilder(Material.MUSIC_DISC_STRAD, Message.forName(minutes), "3")); + builder.addSetting("240", new LegacyItemBuilder(Material.MUSIC_DISC_WARD, Message.forName(minutes), "4")); + builder.addSetting("300", new LegacyItemBuilder(Material.MUSIC_DISC_11, Message.forName(minutes), "5")); })); Challenges.getInstance().getScheduler().register(this); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java index b9d029db2..0689d19e5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java @@ -5,8 +5,6 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; @@ -14,6 +12,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.concurrent.ThreadLocalRandom; @@ -24,24 +23,18 @@ public class DamageTeleportChallenge extends SettingModifier { private static final int PLAYER = 1, EVERYONE = 2; public DamageTeleportChallenge() { - super(MenuType.CHALLENGES, 1, 2); + super(MenuType.CHALLENGES, null, 1, 2, new ItemStack(Material.SHULKER_SHELL), "item-damage-teleport-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SHULKER_SHELL, Message.forName("item-damage-teleport-challenge")); - } - - @NotNull - @Override - public ItemBuilder createSettingsItem() { - if (getValue() == 1) { - return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone")); - } else { - return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("player")); - } - } +// @NotNull +// @Override +// public LegacyItemBuilder createSettingsItem() { +// if (getValue() == 1) { +// return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone")); +// } else { +// return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("player")); +// } +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index a1019dfb7..1a2ff3106 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -4,11 +4,12 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Bukkit; @@ -20,6 +21,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityPotionEffectEvent; import org.bukkit.event.entity.EntityPotionEffectEvent.Action; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; @@ -28,7 +30,7 @@ public class ZeroHeartsChallenge extends SettingModifier { public ZeroHeartsChallenge() { - super(MenuType.CHALLENGES, 5, 30, 10); + super(MenuType.CHALLENGES, null, 5, 30, 10, new ItemStack(Material.ENCHANTED_GOLDEN_APPLE), "zero-hearts-challenge"); } @Override @@ -54,12 +56,6 @@ protected void onDisable() { AbstractChallenge.getFirstInstance(MaxHealthSetting.class).onValueChange(); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENCHANTED_GOLDEN_APPLE, Message.forName("item-zero-hearts-challenge")); - } - @Override protected void onValueChange() { bossbar.update(); @@ -100,12 +96,11 @@ private void removeAbsorptionEffect() { @EventHandler(priority = EventPriority.HIGH) public void onEntityPotionEffect(@NotNull EntityPotionEffectEvent event) { if (event.getAction() != Action.REMOVED) return; - if (!(event.getEntity() instanceof Player)) return; if (!shouldExecuteEffect()) return; - Player player = (Player) event.getEntity(); + if (!(event.getEntity() instanceof Player player)) return; if (ignorePlayer(player)) return; - kill(player); - Message.forName("zero-hearts-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + ChallengeHelper.kill(player); + MessageKey.of("zero-hearts-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java index 0a9a3d78d..62c1cfa1a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java @@ -2,41 +2,32 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerAdvancementDoneEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; public class AdvancementDamageChallenge extends SettingModifier { public AdvancementDamageChallenge() { - super(MenuType.CHALLENGES, 1, 40); - setCategory(SettingCategory.DAMAGE); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 40, new ItemStack(Material.BOOK), "advancement-damage-challenge"); } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); +// } + @Override public void playValueChangeTitle() { ChallengeHelper.playChallengeHeartsValueChangeTitle(this); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOOK, Message.forName("item-advancement-damage-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerAdvancementDone(@NotNull PlayerAdvancementDoneEvent event) { if (!shouldExecuteEffect()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java index 17e7bad7d..f6c411c0c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java @@ -2,23 +2,25 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.block.BlockBreakEvent; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.bukkit.inventory.ItemStack; public class BlockBreakDamageChallenge extends SettingModifier { public BlockBreakDamageChallenge() { - super(MenuType.CHALLENGES, 1, 60); - setCategory(SettingCategory.DAMAGE); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 60, new ItemStack(Material.GOLDEN_PICKAXE), "item-block-break-damage-challenge"); } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); +// } + @EventHandler public void onBreak(BlockBreakEvent event) { if (!shouldExecuteEffect()) return; @@ -31,16 +33,4 @@ public void playValueChangeTitle() { ChallengeHelper.playChallengeHeartsValueChangeTitle(this); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-block-break-damage-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java index c6cbedfe6..f802de558 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java @@ -3,24 +3,27 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.block.BlockPlaceEvent; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.bukkit.inventory.ItemStack; @Since("2.0") public class BlockPlaceDamageChallenge extends SettingModifier { public BlockPlaceDamageChallenge() { - super(MenuType.CHALLENGES, 1, 60); - setCategory(SettingCategory.DAMAGE); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 60, new ItemStack(Material.GOLD_BLOCK), "block-place-damange-challenge"); } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); +// } + + @EventHandler public void onBreak(BlockPlaceEvent event) { if (!shouldExecuteEffect()) return; @@ -33,16 +36,4 @@ public void playValueChangeTitle() { ChallengeHelper.playChallengeHeartsValueChangeTitle(this); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLD_BLOCK, Message.forName("item-block-place-damage-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java index aede1febc..bcde16c2d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java @@ -2,27 +2,30 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder.LeatherArmorBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; public class DamagePerBlockChallenge extends SettingModifier { public DamagePerBlockChallenge() { - super(MenuType.CHALLENGES, 1, 40); - setCategory(SettingCategory.DAMAGE); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 40, new StandardItemBuilder.LeatherArmorBuilder(Material.LEATHER_BOOTS).setColor(Color.RED).build(), + "damage-per-block-challenge"); } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); +// } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; @@ -38,16 +41,4 @@ public void playValueChangeTitle() { ChallengeHelper.playChallengeHeartsValueChangeTitle(this); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-damage-block-challenge")).setColor(Color.RED); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java index 4a5fbf391..91020a5c2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java @@ -1,24 +1,22 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.inventory.InventoryAction; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class DamagePerItemChallenge extends Setting { public DamagePerItemChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.DAMAGE); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, new ItemStack(Material.SHEARS), "damage-item-challenge"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @@ -43,10 +41,4 @@ private void applyDamage(@NotNull Player player, int amount) { player.damage(amount); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SHEARS, Message.forName("item-damage-item-challenge")); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java index fc33b2d74..07e8cd8f9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java @@ -2,30 +2,22 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") public class DeathOnFallChallenge extends Setting { public DeathOnFallChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.DAMAGE); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FEATHER, Message.forName("item-death-on-fall-challenge")); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, new ItemStack(Material.FEATHER), "item-death-on-fall-challenge"); } @EventHandler(priority = EventPriority.HIGH) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java index cf2a7f12b..5b6f18e64 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java @@ -3,16 +3,16 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -26,10 +26,15 @@ public class DelayDamageChallenge extends TimedChallenge { private final Map damageMap = new HashMap<>(); public DelayDamageChallenge() { - super(MenuType.CHALLENGES, 1, 64, 4, false); - setCategory(SettingCategory.DAMAGE); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 64, 4, false, new ItemStack(Material.REDSTONE), "item-delay-damage"); } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue() * 30); +// } + @Override protected int getSecondsUntilNextActivation() { return getValue() * 30; @@ -57,26 +62,14 @@ protected void onTimeActivation() { restartTimer(); } - @Override - public @NotNull ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.REDSTONE, Message.forName("item-delay-damage-description")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 30); - } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerDamage(@NotNull EntityDamageEvent event) { if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - if (ignorePlayer((Player) event.getEntity())) return; + if (!(event.getEntity() instanceof Player player)) return; + if (ignorePlayer(player)) return; if (canGetDamage) return; double damage = event.getFinalDamage(); - Player player = (Player) event.getEntity(); damageMap.put(player, damageMap.getOrDefault(player, 0.0) + damage); event.setCancelled(true); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java index 017d64da0..10b07b421 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java @@ -3,10 +3,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; @@ -15,29 +13,22 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @Since("2.0.2") public class FreezeChallenge extends SettingModifier { public FreezeChallenge() { - super(MenuType.CHALLENGES, 5, 60, 20); - setCategory(SettingCategory.DAMAGE); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 5, 60, 20, new ItemStack(Material.BLUE_ICE), "item-freeze-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BLUE_ICE, Message.forName("item-freeze-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue()); +// } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onDamage(@NotNull EntityDamageEvent event) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java index c135e75be..2d5b74749 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java @@ -4,39 +4,31 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder.LeatherArmorBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @Since("2.0") public class JumpDamageChallenge extends SettingModifier { public JumpDamageChallenge() { - super(MenuType.CHALLENGES, 1, 60); - setCategory(SettingCategory.DAMAGE); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 60, new StandardItemBuilder.LeatherArmorBuilder(Material.LEATHER_BOOTS).setColor(Color.ORANGE).build(), + "jump-damage-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-jump-damage-challenge")).setColor(Color.ORANGE); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java index 8d0d6c171..af12ee6dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java @@ -1,27 +1,19 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.damage; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDamageByPlayerEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class ReversedDamageChallenge extends Setting { public ReversedDamageChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.DAMAGE); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_SWORD, Message.forName("item-reversed-damage-challenge")); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, new ItemStack(Material.GOLDEN_SWORD), "reversed-damange-challenge"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java index e7f327172..a760ee461 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java @@ -3,38 +3,30 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder.LeatherArmorBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerToggleSneakEvent; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; public class SneakDamageChallenge extends SettingModifier { public SneakDamageChallenge() { - super(MenuType.CHALLENGES, 1, 60); - setCategory(SettingCategory.DAMAGE); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 60, new StandardItemBuilder.LeatherArmorBuilder(Material.LEATHER_BOOTS).setColor(Color.YELLOW).build(), + "sneak-damage-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-sneak-damage-challenge")).setColor(Color.YELLOW); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java index 8bb6383bb..ebda0f4dd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java @@ -3,25 +3,27 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.bukkit.inventory.ItemStack; @Since("2.0") public class WaterAllergyChallenge extends SettingModifier { public WaterAllergyChallenge() { - super(MenuType.CHALLENGES, 1, 40); - setCategory(SettingCategory.DAMAGE); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 40, new ItemStack(Material.CYAN_GLAZED_TERRACOTTA), "water-allergy-challenge"); } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); +// } + @ScheduledTask(ticks = 5, async = false) public void onFifthTick() { for (Player player : Bukkit.getOnlinePlayers()) { @@ -30,19 +32,6 @@ public void onFifthTick() { player.damage(getValue()); } } - - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CYAN_GLAZED_TERRACOTTA, Message.forName("item-water-allergy-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java index 7f92d8711..5c395667f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java @@ -3,14 +3,12 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.collection.SeededRandomWrapper; @@ -24,9 +22,9 @@ import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map; @@ -41,14 +39,7 @@ public class BlockEffectChallenge extends Setting { private Map currentPotionEffects = new HashMap<>(); public BlockEffectChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.EFFECT); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CARVED_PUMPKIN, Message.forName("item-block-effect-challenge")); + super(MenuType.CHALLENGES, SettingCategory.EFFECT, new ItemStack(Material.CARVED_PUMPKIN), "block-effect-challenge"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java index bf2662c9f..408017ad6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java @@ -3,12 +3,10 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.collection.SeededRandomWrapper; import org.bukkit.Chunk; @@ -20,9 +18,9 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map; @@ -39,14 +37,7 @@ public class ChunkRandomEffectChallenge extends Setting { private long worldSeed; public ChunkRandomEffectChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.EFFECT); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CAULDRON, Message.forName("item-chunk-effect-challenge")); + super(MenuType.CHALLENGES, SettingCategory.EFFECT, new ItemStack(Material.CAULDRON), "chunk-effect-challenge"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java index 194f0946c..7e6878301 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java @@ -3,10 +3,8 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.EntityType; @@ -14,22 +12,15 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntitySpawnEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; -import org.jetbrains.annotations.NotNull; @Since("2.1.2") public class EntityRandomEffectChallenge extends Setting { public EntityRandomEffectChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.EFFECT); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PHANTOM_MEMBRANE, Message.forName("item-entity-effect-challenge")); + super(MenuType.CHALLENGES, SettingCategory.EFFECT, new ItemStack(Material.PHANTOM_MEMBRANE), "entity-effect-challenge"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java index 83cb7fefa..366337d0c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java @@ -1,11 +1,9 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Bukkit; import org.bukkit.GameMode; @@ -13,6 +11,7 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; @@ -23,14 +22,7 @@ public class InfectionChallenge extends Setting { public InfectionChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.EFFECT); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SLIME_BALL, Message.forName("item-infection-challenge")); + super(MenuType.CHALLENGES, SettingCategory.EFFECT, new ItemStack(Material.SLIME_BALL), "infection-challenge"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java index 58d64b142..b1ab2729b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java @@ -4,13 +4,12 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.TriConsumer; import net.codingarea.commons.bukkit.utils.logging.Logger; @@ -27,6 +26,7 @@ import org.bukkit.event.player.PlayerGameModeChangeEvent; import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; @@ -41,15 +41,17 @@ public class PermanentEffectOnDamageChallenge extends SettingModifier { private final Random random = new Random(); public PermanentEffectOnDamageChallenge() { - super(MenuType.CHALLENGES, 1, 2); - setCategory(SettingCategory.EFFECT); + super(MenuType.CHALLENGES, SettingCategory.EFFECT, 1, 2, new ItemStack(Material.MAGMA_CREAM), "permanent-effect-on-damage-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MAGMA_CREAM, Message.forName("item-permanent-effect-on-damage-challenge")); - } + // @NotNull +// @Override +// public LegacyItemBuilder createSettingsItem() { +// if (!isEnabled()) return DefaultItem.disabled(); +// if (getValue() == GLOBAL_EFFECT) +// return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone").asString()).appendLore("", Message.forName("item-permanent-effect-target-everyone-description").asString()); +// return DefaultItem.create(Material.CHEST, Message.forName("player").asString()).appendLore("", Message.forName("item-permanent-effect-target-player-description").asString()); +// } @Override protected void onEnable() { @@ -141,9 +143,9 @@ private void applyNewEffect(@NotNull Player player, @NotNull PotionEffectType po } if (effectsToEveryone()) { - Message.forName("new-effect").broadcast(Prefix.CHALLENGES, potionEffectType, amplifier); + MessageKey.of("new-effect").broadcast(Prefix.CHALLENGES, potionEffectType, amplifier); } else { - Message.forName("new-effect").send(player, Prefix.CHALLENGES, potionEffectType, amplifier); + MessageKey.of("new-effect").send(player, Prefix.CHALLENGES, potionEffectType, amplifier); } getGameStateData().set(path, effects); @@ -243,15 +245,6 @@ protected void onValueChange() { updateEffects(); } - @NotNull - @Override - public ItemBuilder createSettingsItem() { - if (!isEnabled()) return DefaultItem.disabled(); - if (getValue() == GLOBAL_EFFECT) - return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone").asString()).appendLore("", Message.forName("item-permanent-effect-target-everyone-description").asString()); - return DefaultItem.create(Material.CHEST, Message.forName("player").asString()).appendLore("", Message.forName("item-permanent-effect-target-player-description").asString()); - } - @Override public void playValueChangeTitle() { if (GLOBAL_EFFECT == getValue()) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index 70ab48687..d1b0bea4d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -1,18 +1,17 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.effect; -import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; +import net.codingarea.challenges.plugin.challenges.type.abstraction.menu.MenuSetting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.common.collection.IRandom; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; @@ -21,45 +20,43 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.Random; import java.util.stream.Collectors; @Since("2.0") public class RandomPotionEffectChallenge extends MenuSetting { - private final Random random = new Random(); - int currentTime = 0; + private int currentTime = 0; public RandomPotionEffectChallenge() { - super(MenuType.CHALLENGES, Message.forName("menu-random-effect-challenge-settings")); - setCategory(SettingCategory.EFFECT); - registerSetting("time", new NumberSubSetting( - () -> new ItemBuilder(Material.CLOCK, Message.forName("item-random-effect-time-challenge")), - value -> null, - value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), - 1, - 60, - 30 - ) - ); - registerSetting("length", new NumberSubSetting( - () -> new ItemBuilder(Material.ARROW, Message.forName("item-random-effect-length-challenge")), - value -> null, - value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), - 1, - 20, - 10 - ) - ); - registerSetting("amplifier", new NumberSubSetting( - () -> new ItemBuilder(Material.STONE_SWORD, Message.forName("item-random-effect-amplifier-challenge")), - value -> null, - value -> "§7" + Message.forName("amplifier") + " §e" + value, - 1, - 8, - 3 - ) - ); +// super(Message.forName("menu-random-effect-challenge-settings")); + super(MenuType.CHALLENGES, SettingCategory.EFFECT, new ItemStack(Material.BREWING_STAND), "random-effect-challenge"); +// registerSetting("time", new NumberSubSetting( +// () -> new LegacyItemBuilder(Material.CLOCK, Message.forName("item-random-effect-time-challenge")), +// value -> null, +// value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), +// 1, +// 60, +// 30 +// ) +// ); +// registerSetting("length", new NumberSubSetting( +// () -> new LegacyItemBuilder(Material.ARROW, Message.forName("item-random-effect-length-challenge")), +// value -> null, +// value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), +// 1, +// 20, +// 10 +// ) +// ); +// registerSetting("amplifier", new NumberSubSetting( +// () -> new LegacyItemBuilder(Material.STONE_SWORD, Message.forName("item-random-effect-amplifier-challenge")), +// value -> null, +// value -> "§7" + Message.forName("amplifier") + " §e" + value, +// 1, +// 8, +// 3 +// ) +// ); } @@ -74,12 +71,6 @@ public static PotionEffectType getNewRandomEffect(@NotNull LivingEntity entity) return possibleEffects.get(IRandom.threadLocal().nextInt(possibleEffects.size())); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BREWING_STAND, Message.forName("item-random-effect-challenge")); - } - @ScheduledTask(ticks = 20, async = false) public void onSecond() { currentTime++; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java index d11f98050..7dc96d1e4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java @@ -2,15 +2,14 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDeathByPlayerEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.Collection; @@ -19,8 +18,7 @@ public class AllMobsToDeathPoint extends Setting { public AllMobsToDeathPoint() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.SPAWNER), "all-mobs-to-deaht-position"); } @EventHandler @@ -41,13 +39,6 @@ private void teleportAllMobsOfType(@NotNull EntityType entityType, @NotNull Loca ((LivingEntity) entity).setNoDamageTicks(20); entity.teleport(location); } - - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SPAWNER, Message.forName("item-all-mobs-to-death-position-challenge")); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java index 5c16a0a61..92df6aa8d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java @@ -3,10 +3,8 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomMobAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.EntityType; @@ -19,7 +17,6 @@ import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.Objects; @@ -28,14 +25,7 @@ public class BlockMobsChallenge extends Setting { public BlockMobsChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BRICKS, Message.forName("item-block-mob-challenge")); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.BRICKS), "block-mobs-challenge"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java index 338e46a69..c239c796b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java @@ -1,15 +1,14 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntitySpawnEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class DupedSpawningChallenge extends Setting { @@ -17,14 +16,7 @@ public class DupedSpawningChallenge extends Setting { private boolean inCustomSpawn = false; public DupedSpawningChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ELDER_GUARDIAN_SPAWN_EGG, Message.forName("item-duped-spawning-challenge")); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.ELDER_GUARDIAN_SPAWN_EGG), "duped-spawning-challenge"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java index 8baa720ad..ad2144995 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java @@ -1,25 +1,17 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.entities; import net.codingarea.challenges.plugin.challenges.type.abstraction.HydraChallenge; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class HydraNormalChallenge extends HydraChallenge { public HydraNormalChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.WITCH_SPAWN_EGG, Message.forName("item-hydra-challenge")); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.WITCH_SPAWN_EGG), "hydra-plus"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java index 07c304f4d..d15b81a39 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraPlusChallenge.java @@ -2,12 +2,11 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.HydraChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") @@ -16,14 +15,7 @@ public class HydraPlusChallenge extends HydraChallenge { private static final int limit = 512; public HydraPlusChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BAT_SPAWN_EGG, Message.forName("item-hydra-plus-challenge")); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.BAT_SPAWN_EGG), "hydra-plus"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java index 2960d7e58..187778736 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java @@ -3,13 +3,11 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.World; @@ -26,8 +24,8 @@ public class InvisibleMobsChallenge extends Setting { public InvisibleMobsChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new StandardItemBuilder.PotionBuilder(Material.POTION).setColor(Color.WHITE).build(), + "invsible-mobs-challenge"); } @Override @@ -35,12 +33,6 @@ protected void onEnable() { addEffectForEveryEntity(); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new PotionBuilder(Material.POTION, Message.forName("item-invisible-mobs-challenge")).setColor(Color.WHITE); - } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onSpawn(@NotNull EntitySpawnEvent event) { if (!shouldExecuteEffect()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java index 69258d5d1..6f488e6d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java @@ -5,14 +5,15 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.bukkit.util.BoundingBox; import org.bukkit.util.RayTraceResult; import org.jetbrains.annotations.NotNull; @@ -22,21 +23,14 @@ public class MobSightDamageChallenge extends SettingModifier { public MobSightDamageChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.SPIDER_EYE), "no-mob-sight-damage-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SPIDER_EYE, Message.forName("item-no-mob-sight-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java index b244e7088..087bfe33e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java @@ -4,9 +4,8 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDamageByPlayerEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.EnderDragon; @@ -15,6 +14,7 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -22,8 +22,7 @@ public class MobTransformationChallenge extends Setting { public MobTransformationChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.STONE_SWORD), "mob-transformation-challenge"); } @Override @@ -42,12 +41,6 @@ protected void onDisable() { bossbar.hide(); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-mob-transformation-challenge")); - } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onEntityDamageByPlayer(@NotNull EntityDamageByPlayerEvent event) { if (!shouldExecuteEffect()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java index 301bafd72..ccbcc4a5b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java @@ -6,9 +6,8 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDeathByPlayerEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; import org.bukkit.Location; @@ -19,6 +18,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; @@ -33,14 +33,7 @@ public class MobsRespawnInEndChallenge extends Setting { private int totalMobsInEnd = 0; public MobsRespawnInEndChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENDER_EYE, Message.forName("item-respawn-end-challenge")); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.ENDER_EYE), "respawn-end-challenge"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java index c0d27ef17..3895ce9f1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java @@ -3,12 +3,10 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.impl.RandomMobAction; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder.LeatherArmorBuilder; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; @@ -21,14 +19,8 @@ public class NewEntityOnJumpChallenge extends Setting { public NewEntityOnJumpChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-jump-entity-challenge")).setColor(Color.GREEN); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new StandardItemBuilder.LeatherArmorBuilder(Material.LEATHER_BOOTS).setColor(Color.GREEN).build(), + "jump-entity-challenge"); } @EventHandler(priority = EventPriority.HIGH) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java index 7f2078d08..865f802d2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/StoneSightChallenge.java @@ -2,11 +2,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -14,6 +12,7 @@ import org.bukkit.entity.EnderDragon; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.bukkit.util.BoundingBox; import org.bukkit.util.RayTraceResult; import org.jetbrains.annotations.NotNull; @@ -26,14 +25,7 @@ public class StoneSightChallenge extends Setting { private final Random random = new Random(); public StoneSightChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.ENTITIES); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COBBLESTONE, Message.forName("item-stone-sight-challenge")); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.COBBLESTONE), "stone-sight"); } @ScheduledTask(ticks = 1, async = false) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java index 25095defa..692fc8618 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java @@ -3,17 +3,18 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.WorldDependentChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.Updated; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.policy.ExtraWorldPolicy; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.utils.bukkit.jumpgeneration.RandomJumpGenerator; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; @@ -27,6 +28,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -35,6 +37,7 @@ import java.util.Optional; import java.util.UUID; +@Updated("2.4") public class JumpAndRunChallenge extends WorldDependentChallenge { private final List lastPlayers = new ArrayList<>(); @@ -49,20 +52,12 @@ public class JumpAndRunChallenge extends WorldDependentChallenge { private UUID currentPlayer; public JumpAndRunChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, false); - setCategory(SettingCategory.EXTRA_WORLD); + super(MenuType.CHALLENGES, 1, 10, 5, new ItemStack(Material.ACACIA_STAIRS), "item-jump-and-run-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ACACIA_STAIRS, Message.forName("item-jump-and-run-challenge")); - } - - @Nullable @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 30, getValue() * 60 + 30); + public LocalizableMessage getSettingsDescription() { + return MessageKey.of("item-time-seconds-range-description").withArgs(getValue() * 60 - 30, getValue() * 60 + 30); } @Override @@ -79,14 +74,14 @@ public void onDisable() { @Override protected void handleCountdown() { switch (getSecondsLeftUntilNextActivation()) { - case 1: - Message.forName("jnr-countdown-one").broadcast(Prefix.CHALLENGES); + case 5: + case 3: + case 2: + MessageKey.of("jnr-countdown").broadcast(Prefix.CHALLENGES, getSecondsLeftUntilNextActivation()); SoundSample.BASS_OFF.broadcast(); break; - case 2: - case 3: - case 5: - Message.forName("jnr-countdown").broadcast(Prefix.CHALLENGES, getSecondsLeftUntilNextActivation()); + case 1: + MessageKey.of("jnr-countdown-one").broadcast(Prefix.CHALLENGES); SoundSample.BASS_OFF.broadcast(); break; } @@ -122,7 +117,6 @@ protected void startJumpAndRun() { } protected void buildNextJump() { - if (lastBlock != null) lastBlock.setType(Material.AIR); lastBlock = targetBlock != null ? targetBlock : getExtraWorld().getBlockAt(0, 100, 0); @@ -131,7 +125,6 @@ protected void buildNextJump() { Material type = getRandomBlockType(); targetBlock = new RandomJumpGenerator().next(globalRandom, lastBlock, type == Material.CYAN_TERRACOTTA || type == Material.EMERALD_BLOCK, type != Material.COBBLESTONE_WALL && type != Material.SPRUCE_FENCE); targetBlock.setType(type); - } @NotNull @@ -163,11 +156,11 @@ protected Player getNextPlayer() { return globalRandom.choose(players); } - protected void finishJumpAndRun() { + protected void finishJumpAndRun(@NotNull Player player) { jumps++; jumpsDone++; - Message.forName("jnr-finished").broadcast(Prefix.CHALLENGES, Optional.ofNullable(currentPlayer).map(Bukkit::getPlayer).map(NameHelper::getName).orElse("?")); + MessageKey.of("jnr-finished").broadcast(Prefix.CHALLENGES, player); exitJumpAndRun(); SoundSample.KLING.broadcast(); } @@ -217,7 +210,7 @@ public void onMove(@NotNull PlayerMoveEvent event) { if (BlockUtils.isSameBlockLocation(event.getTo(), targetBlock.getLocation().add(0, 1, 0))) { if (++currentJump >= jumps) { - finishJumpAndRun(); + finishJumpAndRun(event.getPlayer()); // is currentPlayer } else { SoundSample.PLOP.broadcast(); buildNextJump(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java index 2c871a1f1..018f1830c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java @@ -4,10 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.WorldDependentChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; @@ -18,26 +15,18 @@ import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; public class WaterMLGChallenge extends WorldDependentChallenge { public WaterMLGChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, false); - setCategory(SettingCategory.EXTRA_WORLD); + super(MenuType.CHALLENGES, 1, 10, 5, new ItemStack(Material.WATER_BUCKET), "water-mlg-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.WATER_BUCKET, Message.forName("item-water-mlg-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 10, getValue() * 60 + 10); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 10, getValue() * 60 + 10); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java index 193430e8f..18f98201d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java @@ -2,16 +2,15 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; -import net.codingarea.challenges.plugin.management.challenges.annotations.ExcludeFromRandomChallenges; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; @@ -23,8 +22,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Objects; @@ -37,21 +36,14 @@ public class ForceBiomeChallenge extends CompletableForceChallenge { private Biome biome; public ForceBiomeChallenge() { - super(MenuType.CHALLENGES, 2, 20, 5); - setCategory(SettingCategory.FORCE); + super(MenuType.CHALLENGES, SettingCategory.FORCE, 2, 20, 5, new ItemStack(Material.CHAINMAIL_BOOTS), "force-biome-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CHAINMAIL_BOOTS, Message.forName("item-force-biome-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60 * 3, 60); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return ChallengeHelper.getTimeRangeSettingsDescription(this, 60 * 3, 60); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java index 0e3e78ab4..42e733231 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java @@ -2,14 +2,13 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; -import net.codingarea.challenges.plugin.management.challenges.annotations.ExcludeFromRandomChallenges; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; @@ -18,8 +17,8 @@ import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.function.BiConsumer; @@ -30,21 +29,14 @@ public class ForceBlockChallenge extends EndingForceChallenge { private Material block; public ForceBlockChallenge() { - super(MenuType.CHALLENGES, 2, 15); - setCategory(SettingCategory.FORCE); + super(MenuType.CHALLENGES, SettingCategory.FORCE, 2, 15, new ItemStack(Material.GOLDEN_BOOTS), "force-block"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_BOOTS, Message.forName("item-force-block-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java index e8502f0ec..838251906 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java @@ -2,14 +2,13 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; -import net.codingarea.challenges.plugin.management.challenges.annotations.ExcludeFromRandomChallenges; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.commons.common.config.Document; @@ -18,8 +17,8 @@ import org.bukkit.World.Environment; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.function.BiConsumer; @@ -29,21 +28,14 @@ public class ForceHeightChallenge extends EndingForceChallenge { private int height; public ForceHeightChallenge() { - super(MenuType.CHALLENGES, 2, 15); - setCategory(SettingCategory.FORCE); + super(MenuType.CHALLENGES, SettingCategory.FORCE, 2, 15, new ItemStack(Material.IRON_BOOTS), "force-height-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.IRON_BOOTS, Message.forName("item-force-height-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java index 2c769955c..6c100416c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java @@ -5,14 +5,14 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; -import net.codingarea.challenges.plugin.management.challenges.annotations.ExcludeFromRandomChallenges; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; @@ -41,21 +41,14 @@ public class ForceItemChallenge extends CompletableForceChallenge { private Material item; public ForceItemChallenge() { - super(MenuType.CHALLENGES, 2, 15); - setCategory(SettingCategory.FORCE); + super(MenuType.CHALLENGES, SettingCategory.FORCE, 2, 15, new ItemStack(Material.LEATHER_BOOTS), "force-item"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.LEATHER_BOOTS, Message.forName("item-force-item-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java index 3f135f0ca..7a33d2cea 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java @@ -4,12 +4,12 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; -import net.codingarea.challenges.plugin.management.challenges.annotations.ExcludeFromRandomChallenges; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.Utils; import net.codingarea.commons.common.config.Document; @@ -21,6 +21,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -35,21 +36,14 @@ public class ForceMobChallenge extends CompletableForceChallenge { private EntityType entity; public ForceMobChallenge() { - super(MenuType.CHALLENGES, 2, 15); - setCategory(SettingCategory.FORCE); + super(MenuType.CHALLENGES, SettingCategory.FORCE, 2, 15, new ItemStack(Material.DIAMOND_BOOTS), "force-mob"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-mob-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java index 6185ff956..d3ca55ea8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java @@ -4,21 +4,21 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class DamageInventoryClearChallenge extends SettingModifier { public DamageInventoryClearChallenge() { - super(MenuType.CHALLENGES, 1, 2); - setCategory(SettingCategory.INVENTORY); + super(MenuType.CHALLENGES, SettingCategory.INVENTORY, 1, 2, new ItemStack(Material.CHEST), "damage-inv-clear"); } @EventHandler @@ -35,21 +35,15 @@ public void onDamage(@NotNull EntityDamageEvent event) { } } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CHEST, Message.forName("item-damage-inv-clear-challenge")); - } - - @NotNull - @Override - public ItemBuilder createSettingsItem() { - if (getValue() == 1) { - return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone")); - } else { - return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("player")); - } - } +// @NotNull +// @Override +// public LegacyItemBuilder createSettingsItem() { +// if (getValue() == 1) { +// return DefaultItem.create(Material.ENDER_CHEST, Message.forName("everyone")); +// } else { +// return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("player")); +// } +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java index 0ebfd4f8d..b18a19b55 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java @@ -5,12 +5,11 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -33,7 +32,6 @@ import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.function.Consumer; @@ -46,15 +44,14 @@ public class MissingItemsChallenge extends TimedChallenge implements PlayerComma private List materials; public MissingItemsChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, false); - setCategory(SettingCategory.INVENTORY); + super(MenuType.CHALLENGES, SettingCategory.INVENTORY, 1, 10, 5, false, new ItemStack(Material.FISHING_ROD), "missing-items-challenge"); } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 10, getValue() * 60 + 10); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 10, getValue() * 60 + 10); +// } @Override public void playValueChangeTitle() { @@ -66,12 +63,6 @@ protected int getSecondsUntilNextActivation() { return globalRandom.around(getValue() * 60, 10); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FISHING_ROD, Message.forName("item-missing-items-challenge")); - } - @Override protected void onEnable() { materials = Arrays.stream(ExperimentalUtils.getMaterials()) @@ -96,7 +87,6 @@ protected void onTimeActivation() { } private void startGuessingGame(@NotNull Player player) { - BukkitTask task = new BukkitRunnable() { int timeLeft = (int) (2.5 * 60); @@ -129,11 +119,9 @@ public void run() { } task.cancel(); }); - } private void createMissingItemsInventory(@NotNull Player player, Consumer onFinish) { - int targetSlot = InventoryUtils.getRandomFullSlot(player.getInventory()); if (targetSlot == -1) return; @@ -152,7 +140,7 @@ private void createMissingItemsInventory(@NotNull Player player, Consumer player.closeInventory(); } else { player.closeInventory(); - kill(player); + ChallengeHelper.kill(player); } }); inventories.put(player.getUniqueId(), inventoryTuple); @@ -160,7 +148,6 @@ private void createMissingItemsInventory(@NotNull Player player, Consumer player.getInventory().setItem(targetSlot, null); sendInfoText(player); - } private void sendInfoText(@NotNull Player player) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java index 0d448742f..9293c2e2a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java @@ -5,15 +5,14 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") @@ -22,24 +21,17 @@ public class MovementItemRemovingChallenge extends SettingModifier { public static final int BLOCK = 1; public MovementItemRemovingChallenge() { - super(MenuType.CHALLENGES, 1, 2, 2); - setCategory(SettingCategory.INVENTORY); + super(MenuType.CHALLENGES, SettingCategory.INVENTORY, 1, 2, 2, new ItemStack(Material.DETECTOR_RAIL), "block-chunk-item-remove-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DETECTOR_RAIL, Message.forName("item-block-chunk-item-remove-challenge")); - } - - @NotNull - @Override - public ItemBuilder createSettingsItem() { - if (!isEnabled()) return DefaultItem.disabled(); - if (getValue() == BLOCK) - return DefaultItem.create(Material.GRASS_BLOCK, Message.forName("item-block-chunk-item-remove-challenge-block")); - return DefaultItem.create(Material.BOOK, Message.forName("item-block-chunk-item-remove-challenge-chunk")); - } +// @NotNull +// @Override +// public LegacyItemBuilder createSettingsItem() { +// if (!isEnabled()) return DefaultItem.disabled(); +// if (getValue() == BLOCK) +// return DefaultItem.create(Material.GRASS_BLOCK, Message.forName("item-block-chunk-item-remove-challenge-block")); +// return DefaultItem.create(Material.BOOK, Message.forName("item-block-chunk-item-remove-challenge-chunk")); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java index 10136606c..afe6430b7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java @@ -1,16 +1,15 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.inventory; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.CanInstaKillOnEnable; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; -import net.codingarea.challenges.plugin.management.challenges.annotations.CanInstaKillOnEnable; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.common.collection.pair.Triple; import org.bukkit.Bukkit; @@ -33,14 +32,7 @@ public class NoDupedItemsChallenge extends Setting { public NoDupedItemsChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.INVENTORY); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.OBSERVER, Message.forName("item-no-duped-items-challenge")); + super(MenuType.CHALLENGES, SettingCategory.INVENTORY, new ItemStack(Material.OBSERVER), "no-duped-items-challenge"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java index 65667c3a1..6eaf9e3b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java @@ -2,11 +2,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -15,20 +13,14 @@ import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") public class PermanentItemChallenge extends Setting { public PermanentItemChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.INVENTORY); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.VINE, Message.forName("item-permanent-item-challenge")); + super(MenuType.CHALLENGES, SettingCategory.INVENTORY, new ItemStack(Material.VINE), "permanent-item-challenge"); } @EventHandler(priority = EventPriority.HIGH) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java index be9b16014..b7d07b745 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java @@ -5,36 +5,28 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; +import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @Since("2.0") public class PickupItemLaunchChallenge extends SettingModifier { public PickupItemLaunchChallenge() { - super(MenuType.CHALLENGES, 1, 10, 2); - setCategory(SettingCategory.INVENTORY); + super(MenuType.CHALLENGES, SettingCategory.INVENTORY, 1, 10, 2, new ItemStack(Material.BOW), "pickup-launch-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOW, Message.forName("item-pickup-launch-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-launcher-description").asArray(getValue()); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-launcher-description").asArray(getValue()); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java index 2f59704cb..2711a0f73 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java @@ -4,8 +4,8 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Bukkit; @@ -23,10 +23,15 @@ public class UncraftItemsChallenge extends TimedChallenge { public UncraftItemsChallenge() { - super(MenuType.CHALLENGES, 5, 60, 20); - setCategory(SettingCategory.INVENTORY); + super(MenuType.CHALLENGES, null, 5, 60, 20, new ItemStack(Material.CRAFTING_TABLE), "uncraft-items-challenge"); } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue()); +// } + public static void uncraftInventory(@NotNull Player player) { PlayerInventory inventory = player.getInventory(); @@ -82,12 +87,8 @@ private static boolean canCraft(List recipes, Material material) { if (itemStack.getType() == material) { return true; } - } - } - - } } return false; @@ -113,18 +114,6 @@ private static List getIngredientsOfRecipe(@NotNull Recipe recipe) { return ingredients; } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CRAFTING_TABLE, Message.forName("item-uncraft-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } - @Override protected int getSecondsUntilNextActivation() { return getValue(); @@ -133,9 +122,7 @@ protected int getSecondsUntilNextActivation() { @Override protected void onTimeActivation() { restartTimer(); - broadcastFiltered(UncraftItemsChallenge::uncraftInventory); - } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 1a538b36e..32ed6d162 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -4,9 +4,10 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -14,6 +15,7 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -24,20 +26,14 @@ public class EnderGamesChallenge extends TimedChallenge { public EnderGamesChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, false); + super(MenuType.CHALLENGES, null, 1, 10, 5, false, new ItemStack(Material.ENDER_PEARL), "ender-games-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENDER_PEARL, Message.forName("item-ender-games-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); +// } @Override public void playValueChangeTitle() { @@ -70,7 +66,7 @@ private void teleportRandom(@NotNull Player player) { Location playerLocation = player.getLocation().clone(); player.teleport(targetEntity.getLocation()); - Message.forName("endergames-teleport").send(player, Prefix.CHALLENGES, targetEntity.getType()); + MessageKey.of("endergames-teleport").send(player, Prefix.CHALLENGES, targetEntity.getType()); targetEntity.teleport(playerLocation); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java index c15bcb851..1a9c05368 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java @@ -5,12 +5,13 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerItemConsumeEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -19,20 +20,14 @@ public class FoodLaunchChallenge extends SettingModifier { public FoodLaunchChallenge() { - super(MenuType.CHALLENGES, 1, 10, 2); + super(MenuType.CHALLENGES, null, 1, 10, 2, new ItemStack(Material.CAKE), "food-launch-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CAKE, Message.forName("item-consume-launch-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-launcher-description").asArray(getValue()); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-launcher-description").asArray(getValue()); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java index be08e1776..d76155e31 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java @@ -3,16 +3,18 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerItemConsumeEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -20,27 +22,21 @@ public class FoodOnceChallenge extends SettingModifier { public FoodOnceChallenge() { - super(MenuType.CHALLENGES, 2); + super(MenuType.CHALLENGES, null, 2, new ItemStack(Material.COOKED_BEEF), "food-once-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COOKED_BEEF, Message.forName("item-food-once-challenge")); - } - - @NotNull - @Override - public ItemBuilder createSettingsItem() { - switch (getValue()) { - case 1: - return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("item-food-once-challenge-player")); - case 2: - return DefaultItem.create(Material.ENDER_CHEST, Message.forName("item-food-once-challenge-everyone")); - default: - return super.createSettingsItem(); - } - } +// @NotNull +// @Override +// public LegacyItemBuilder createSettingsItem() { +// switch (getValue()) { +// case 1: +// return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("item-food-once-challenge-player")); +// case 2: +// return DefaultItem.create(Material.ENDER_CHEST, Message.forName("item-food-once-challenge-everyone")); +// default: +// return super.createSettingsItem(); +// } +// } @Override public void playValueChangeTitle() { @@ -61,7 +57,7 @@ public void onPlayerItemConsume(@NotNull PlayerItemConsumeEvent event) { if (teamFoodsActivated()) { Message.forName("food-once-new-food-team").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); } else { - Message.forName("food-once-new-food").send(event.getPlayer(), Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); + MessageKey.of("food-once-new-food").send(event.getPlayer(), Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java index f9e13917c..b64ea9f4b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java @@ -4,14 +4,15 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; -import net.codingarea.challenges.plugin.management.challenges.annotations.ExcludeFromRandomChallenges; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -20,7 +21,7 @@ public class InvertHealthChallenge extends TimedChallenge { public InvertHealthChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, false); + super(MenuType.CHALLENGES, null, 1, 10, 5, false, new ItemStack(Material.POPPY), "invert-health-challenge"); } public static void invertHealth(Player player) { @@ -32,17 +33,11 @@ public static void invertHealth(Player player) { player.setHealth(health); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.POPPY, Message.forName("item-invert-health-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java index e56e64d34..552167c72 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java @@ -4,14 +4,11 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.DropPriority; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import org.bukkit.Material; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.bukkit.inventory.ItemStack; import java.util.Arrays; import java.util.Random; @@ -22,20 +19,14 @@ public class LowDropRateChallenge extends SettingModifier { private final Random random = new Random(); public LowDropRateChallenge() { - super(MenuType.CHALLENGES, 9); + super(MenuType.CHALLENGES, null, 9, new ItemStack(Material.WOODEN_AXE), "low-drop-rate-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.WOODEN_AXE, Message.forName("item-low-drop-rate-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-chance-description").asArray(getValue() * 10); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-chance-description").asArray(getValue() * 10); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java index 1615bd175..221ec64bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java @@ -3,20 +3,19 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerExpChangeEvent; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; public class NoExpChallenge extends Setting { public NoExpChallenge() { - super(MenuType.CHALLENGES); + super(MenuType.CHALLENGES, null, new ItemStack(Material.EXPERIENCE_BOTTLE), "no-exp"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @@ -28,10 +27,4 @@ public void onExp(PlayerExpChangeEvent event) { ChallengeHelper.kill(event.getPlayer()); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-no-exp-challenge")); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java index eaff16731..56cfcaa86 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoSharedAdvancementsChallenge.java @@ -3,9 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; @@ -14,6 +12,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerAdvancementDoneEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.LinkedList; @@ -26,13 +25,7 @@ public class NoSharedAdvancementsChallenge extends Setting { private final List advancementsDone = new LinkedList<>(); public NoSharedAdvancementsChallenge() { - super(MenuType.CHALLENGES); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.KNOWLEDGE_BOOK, Message.forName("item-no-shared-advancements-challenge")); + super(MenuType.CHALLENGES, null, new ItemStack(Material.KNOWLEDGE_BOOK), "no-shared-advancements"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java index 10a213dd4..2476d322c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java @@ -1,9 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Villager; @@ -11,18 +9,13 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityPickupItemEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class NoTradingChallenge extends Setting { public NoTradingChallenge() { - super(MenuType.CHALLENGES); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.EMERALD, Message.forName("item-no-trading-challenge")); + super(MenuType.CHALLENGES, null, new ItemStack(Material.EMERALD), "no-trading-challenge"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java index 70d7d50ca..f960143ea 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java @@ -1,9 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -19,13 +17,7 @@ public class OneDurabilityChallenge extends Setting { public OneDurabilityChallenge() { - super(MenuType.CHALLENGES); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.WOODEN_HOE, Message.forName("item-one-durability-challenge")); + super(MenuType.CHALLENGES, null, new ItemStack(Material.WOODEN_HOE), "one-durability-challenge"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java index 869276f08..837385c74 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java @@ -2,29 +2,20 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; @Since("2.0") public class AlwaysRunningChallenge extends Setting { public AlwaysRunningChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.MOVEMENT); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CARROT_ON_A_STICK, Message.forName("item-always-running-challenge")); + super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, new ItemStack(Material.CARROT_ON_A_STICK), "always-running-challenge"); } @ScheduledTask(ticks = 1) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java index c8ebde0ed..565558436 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java @@ -2,12 +2,12 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Material; import org.bukkit.boss.BarColor; @@ -15,6 +15,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -29,8 +30,7 @@ public class DontStopRunningChallenge extends SettingModifier { private final Map playerStandingCount = new HashMap<>(); public DontStopRunningChallenge() { - super(MenuType.CHALLENGES, 3, 30, 10); - setCategory(SettingCategory.MOVEMENT); + super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, 3, 30, 10, new ItemStack(Material.SADDLE), "dont-stop-running"); } @Override @@ -55,12 +55,6 @@ protected void onDisable() { bossbar.hide(); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SADDLE, Message.forName("item-dont-stop-running-challenge")); - } - @ScheduledTask(ticks = 20) public void onSecond() { removeOfflinePlayers(); @@ -81,7 +75,7 @@ private void countUpOrKillEveryone() { if (count >= getValue()) { Message.forName("stopped-moving").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); playerStandingCount.remove(player); - kill(player); + ChallengeHelper.kill(player); return; } playerStandingCount.put(player, count + 1); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java index c7a5a3b75..6ede84852 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java @@ -6,8 +6,7 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; @@ -25,8 +24,8 @@ import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.world.LootGenerateEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.LinkedList; @@ -39,8 +38,7 @@ public class FiveHundredBlocksChallenge extends SettingModifier { private final Map blocksWalked = new HashMap<>(); public FiveHundredBlocksChallenge() { - super(MenuType.CHALLENGES, 1, 5, 5); - setCategory(SettingCategory.MOVEMENT); + super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, 1, 5, 5, new ItemStack(MinecraftNameWrapper.SIGN), "five-hundred-blocks-challenge"); // Loot Generate Event was added in 1.15 try { @@ -76,22 +74,16 @@ protected void onDisable() { bossbar.hide(); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(MinecraftNameWrapper.SIGN, Message.forName("item-five-hundred-blocks-challenges")); - } - @Override public void playValueChangeTitle() { ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-blocks").asString(getBlocksToWalk())); } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-blocks-description").asArray(getBlocksToWalk()); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-blocks-description").asArray(getBlocksToWalk()); +// } private int getBlocksToWalk() { return getValue() * 100; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java index 637b633da..4523605a7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java @@ -1,28 +1,20 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; +import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; public class HigherJumpsChallenge extends Setting { public HigherJumpsChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.MOVEMENT); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.RABBIT_FOOT, Message.forName("item-higher-jumps-challenge")); + super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, new ItemStack(Material.RABBIT_FOOT), "higher-jumps-challenge"); } @EventHandler(priority = EventPriority.NORMAL) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java index 5fa756b80..dc578737a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HungerPerBlockChallenge.java @@ -2,29 +2,21 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") public class HungerPerBlockChallenge extends SettingModifier { public HungerPerBlockChallenge() { - super(MenuType.CHALLENGES, 1, 20, 2); - setCategory(SettingCategory.MOVEMENT); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ROTTEN_FLESH, Message.forName("item-hunger-block-challenge")); + super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, 1, 20, 2, new ItemStack(Material.ROTTEN_FLESH), "hunger-block"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java index a49538953..032157177 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java @@ -4,16 +4,17 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -29,21 +30,14 @@ public class MoveMouseDamage extends SettingModifier { private final Map> lastView = new HashMap<>(); public MoveMouseDamage() { - super(MenuType.CHALLENGES, 60); - setCategory(SettingCategory.MOVEMENT); + super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, 60, new ItemStack(Material.COMPASS), "no-mouse-move"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COMPASS, Message.forName("item-no-mouse-move-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java index e720c1f77..702b9d95c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.movement; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.CanInstaKillOnEnable; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; -import net.codingarea.challenges.plugin.management.challenges.annotations.CanInstaKillOnEnable; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; @@ -23,20 +23,7 @@ public class OnlyDirtChallenge extends Setting { public OnlyDirtChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.MOVEMENT); - } - - @NotNull - @Override - public ItemStack getSettingsItem() { - return super.getSettingsItem(); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIRT, Message.forName("item-only-dirt-challenge")); + super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, new ItemStack(Material.DIRT), "only-dirt-challenge"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @@ -49,7 +36,7 @@ public void onPlayerMove(@NotNull PlayerMoveEvent event) { if (blockBelow == null) return; if (blockBelow.getType() != Material.DIRT && !BukkitReflectionUtils.isAir(blockBelow.getType())) { Message.forName("only-dirt-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - kill(event.getPlayer()); + ChallengeHelper.kill(event.getPlayer()); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java index 3a4d85aba..f91cbdc86 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java @@ -4,28 +4,21 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") public class OnlyDownChallenge extends Setting { public OnlyDownChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.MOVEMENT); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ACACIA_SLAB, Message.forName("item-only-down-challenge")); + super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, new ItemStack(Material.ACACIA_SLAB), "only-down-challenge"); } @EventHandler diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java index 39f51b393..d9eb5c97d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java @@ -4,10 +4,10 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -17,6 +17,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -28,21 +29,14 @@ public class TrafficLightChallenge extends TimedChallenge { private int state; public TrafficLightChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5); - setCategory(SettingCategory.MOVEMENT); + super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, 1, 10, 5, new ItemStack(Material.LIME_STAINED_GLASS), "traffic-light-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.LIME_STAINED_GLASS, Message.forName("item-traffic-light-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); +// } @Override public void playValueChangeTitle() { @@ -51,7 +45,7 @@ public void playValueChangeTitle() { @Override public void onEnable() { - bossbar.setContent((bossbar, player) -> { + bossbar.setContent((bossbar, player) -> { // TODO format switch (state) { case GREEN: bossbar.setColor(BarColor.GREEN); @@ -118,7 +112,7 @@ public void onPlayerMove(@NotNull PlayerMoveEvent event) { Player player = event.getPlayer(); Message.forName("traffic-light-challenge-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); - kill(player); + ChallengeHelper.kill(player); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index c89ddb538..046c41026 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -6,12 +6,12 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; @@ -38,8 +38,8 @@ import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerToggleSneakEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.Map.Entry; @@ -50,7 +50,7 @@ public class QuizChallenge extends TimedChallenge implements PlayerCommand, TabC private static QuizChallenge instance; - private final Prefix prefix = Prefix.forName("quiz", "§6Quiz"); + private final Prefix prefix = Prefix.create("quiz", "§6Quiz"); private final IRandom random = IRandom.create(); private IQuestion currentQuestion; @@ -58,15 +58,15 @@ public class QuizChallenge extends TimedChallenge implements PlayerCommand, TabC private int timeLeft; public QuizChallenge() { - super(MenuType.CHALLENGES, 1, 20, 5); + super(MenuType.CHALLENGES, null, 1, 20, 5, new ItemStack(Material.WRITABLE_BOOK), "quiz"); instance = this; } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BARRIER); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return ChallengeHelper.getTimeRangeSettingsDescription(this, 60 * 3, 60); +// } @Override protected void onEnable() { @@ -93,12 +93,6 @@ protected void onDisable() { bossbar.hide(); } - @Nullable - @Override - protected String[] getSettingsDescription() { - return ChallengeHelper.getTimeRangeSettingsDescription(this, 60 * 3, 60); - } - @Override public void playValueChangeTitle() { ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 * 3 - 60, getValue() * 60 * 3 + 60); @@ -136,7 +130,7 @@ protected void onTimeActivation() { onTimeActivation(); return; } - Message.forName("quiz-how-to").send(currentQuestionedPlayer, Prefix.CHALLENGES); + MessageKey.of("quiz-how-to").send(currentQuestionedPlayer, Prefix.CHALLENGES); timeLeft = 60; bossbar.update(); @@ -171,7 +165,7 @@ private void cancelQuestion() { AttributeInstance attribute = currentQuestionedPlayer.getAttribute(MinecraftNameWrapper.MAX_HEALTH); if (attribute == null) return; if (attribute.getBaseValue() == 2) { - kill(currentQuestionedPlayer); + ChallengeHelper.kill(currentQuestionedPlayer); attribute.setBaseValue(20); return; } @@ -190,7 +184,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc } if (args.length == 0) { - Message.forName("syntax").send(player, prefix, "guess "); + MessageKey.of("syntax").send(player, prefix, "guess "); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java index fc63d250a..9a2657b9b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java @@ -2,16 +2,14 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.DropPriority; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.commons.bukkit.utils.item.ItemUtils; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.Material; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Arrays; @@ -20,13 +18,7 @@ public class BlockRandomizerChallenge extends RandomizerSetting { public BlockRandomizerChallenge() { - super(MenuType.CHALLENGES); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MINECART, Message.forName("item-block-randomizer-challenge")); + super(MenuType.CHALLENGES, new ItemStack(Material.MINECART), "block-randomizer-challenge"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java index c5ba7842b..441761194 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java @@ -1,9 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.randomizer; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.commons.bukkit.utils.item.ItemUtils; import org.bukkit.Material; @@ -20,13 +19,7 @@ public class CraftingRandomizerChallenge extends RandomizerSetting { protected final Map randomization = new HashMap<>(); public CraftingRandomizerChallenge() { - super(MenuType.CHALLENGES); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CHEST_MINECART, Message.forName("item-crafting-randomizer-challenge")); + super(MenuType.CHALLENGES, new ItemStack(Material.CHEST_MINECART), "crafting-randomizer-challenge"); } @Override @@ -61,7 +54,7 @@ public void onCraftItem(@NotNull CraftItemEvent event) { if (item == null) return; Material result = randomization.get(item.getType()); if (result == null) return; - event.setCurrentItem(new ItemBuilder(result).amount(item.getAmount()).build()); + event.setCurrentItem(new LegacyItemBuilder(result).setAmount(item.getAmount()).build()); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java index ce84d3e39..dc01a095d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java @@ -3,13 +3,11 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; import net.codingarea.challenges.plugin.utils.misc.Utils; import org.bukkit.Material; @@ -35,14 +33,7 @@ public class EntityLootRandomizerChallenge extends RandomizerSetting implements protected Map randomization; public EntityLootRandomizerChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.RANDOMIZER); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FURNACE_MINECART, Message.forName("item-entity-loot-randomizer-challenge")); + super(MenuType.CHALLENGES, new ItemStack(Material.FURNACE_MINECART), "entity-loot-randomizer-challenge"); } @Override @@ -128,12 +119,12 @@ public Optional getEntityForLootTable(LootTable lootTable) { public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (!isEnabled()) { - Message.forName("command-searchloot-disabled").send(sender, Prefix.CHALLENGES); + MessageKey.of("command-searchloot-disabled").send(sender, Prefix.CHALLENGES); return; } if (args.length == 0) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "searchloot "); + MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "searchloot "); return; } @@ -141,11 +132,11 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr EntityType entityType = Utils.getEntityType(input); if (entityType == null) { - Message.forName("no-such-entity").send(sender, Prefix.CHALLENGES); + MessageKey.of("no-such-entity").send(sender, Prefix.CHALLENGES); return; } if (!entityType.isAlive()) { - Message.forName("not-alive").send(sender, Prefix.CHALLENGES, entityType); + MessageKey.of("not-alive").send(sender, Prefix.CHALLENGES, entityType); return; } @@ -153,7 +144,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr try { givenLootTable = LootTables.valueOf(entityType.name()).getLootTable(); } catch (IllegalArgumentException exception) { - Message.forName("no-loot").send(sender, Prefix.CHALLENGES, entityType); + MessageKey.of("no-loot").send(sender, Prefix.CHALLENGES, entityType); return; } @@ -161,9 +152,9 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr LootTable droppedLootTable = getLootTableForEntity(entityType); if (optionalEntity.isPresent()) { - Message.forName("command-searchloot-result").send(sender, Prefix.CHALLENGES, entityType, droppedLootTable, optionalEntity.get()); + MessageKey.of("command-searchloot-result").send(sender, Prefix.CHALLENGES, entityType, droppedLootTable, optionalEntity.get()); } else { - Message.forName("command-searchloot-nothing").send(sender, Prefix.CHALLENGES, entityType); + MessageKey.of("command-searchloot-nothing").send(sender, Prefix.CHALLENGES, entityType); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 59a6f28bd..0c7bf36eb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -3,13 +3,11 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; import org.bukkit.Bukkit; @@ -25,17 +23,23 @@ import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @Since("2.1.2") public class HotBarRandomizerChallenge extends TimedChallenge { public HotBarRandomizerChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5); - setCategory(SettingCategory.RANDOMIZER); + super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 10, 5, new ItemStack(Material.HOPPER_MINECART), "hotbar-randomizer-challenge"); } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-minutes-description").asArray(getValue()); +// } + + /** * @param force if true only sets items if inventory is empty */ @@ -51,23 +55,12 @@ public static void addItems(Player player, boolean force) { } } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.HOPPER_MINECART, Message.forName("item-hotbar-randomizer-challenge")); - } @Override protected int getSecondsUntilNextActivation() { return getValue() * 60; } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-minutes-description").asArray(getValue()); - } - @Override public void playValueChangeTitle() { ChallengeHelper.playChallengeMinutesValueChangeTitle(this, getValue()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java index 19b7b2e1e..6d37311cd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/MobRandomizerChallenge.java @@ -4,11 +4,9 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.RandomizerSetting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; @@ -20,6 +18,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntitySpawnEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -37,7 +36,7 @@ public class MobRandomizerChallenge extends RandomizerSetting { private boolean initialSpawn = false; public MobRandomizerChallenge() { - super(MenuType.CHALLENGES); + super(MenuType.CHALLENGES, new ItemStack(Material.COMMAND_BLOCK_MINECART), "mob-randomizer"); } @Override @@ -90,13 +89,6 @@ private void unLoadAllEntities() { inSpawn = false; } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COMMAND_BLOCK_MINECART, Message.forName("item-mob-randomizer-challenge")); - } - @Override protected void reloadRandomization() { List entityTypes = getSpawnAbleEntities(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java index 319b4e05f..333429606 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java @@ -9,13 +9,12 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; @@ -26,21 +25,14 @@ public class RandomChallengeChallenge extends TimedChallenge { private AbstractChallenge lastUsed; public RandomChallengeChallenge() { - super(MenuType.CHALLENGES, 3, 60, 6, false); - setCategory(SettingCategory.RANDOMIZER); + super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 3, 60, 6, false, new ItemStack(Material.REDSTONE), "random-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.REDSTONE, Message.forName("item-random-challenge-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 10); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue() * 10); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java index 0561bde31..da9bde90c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java @@ -4,10 +4,10 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; @@ -18,6 +18,7 @@ import org.bukkit.block.Block; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; @@ -29,8 +30,7 @@ public class RandomEventChallenge extends TimedChallenge { private final Event[] events; public RandomEventChallenge() { - super(MenuType.CHALLENGES, 1, 10, 3, false); - setCategory(SettingCategory.RANDOMIZER); + super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 10, 3, false, new ItemStack(Material.CLOCK), "random-event"); events = new Event[]{ new SpeedEvent(), new SpawnEntitiesEvent(), @@ -42,17 +42,11 @@ public RandomEventChallenge() { }; } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CLOCK, Message.forName("item-random-event-challenge").asItemDescription(events.length)); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 30, getValue() * 60 + 30); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 30, getValue() * 60 + 30); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java index 7a0383d0a..4ea3287b9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java @@ -4,33 +4,23 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.bukkit.inventory.ItemStack; @Since("2.0") public class RandomItemChallenge extends TimedChallenge { public RandomItemChallenge() { - super(MenuType.CHALLENGES, 1, 60, 30, false); - setCategory(SettingCategory.RANDOMIZER); + super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 60, 30, false, new ItemStack(Material.BEACON), "random-item-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BEACON, Message.forName("item-random-item-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue()); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java index 383efc499..1b03e6a90 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java @@ -3,10 +3,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -15,16 +13,20 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @Since("2.0") public class RandomItemDroppingChallenge extends TimedChallenge { public RandomItemDroppingChallenge() { - super(MenuType.CHALLENGES, 1, 60, 5); - setCategory(SettingCategory.RANDOMIZER); + super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 60, 5, new ItemStack(Material.DISPENSER), "random-dropping-challenge"); } + // @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue()); +// } + public static void dropRandomItem(Player player) { if (player.getInventory().getContents().length == 0) return; dropRandomItem(player.getLocation(), player.getInventory()); @@ -40,18 +42,6 @@ public static void dropRandomItem(@NotNull Location location, @NotNull Inventory InventoryUtils.dropItemByPlayer(location, item); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DISPENSER, Message.forName("item-random-dropping-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } - @Override public void playValueChangeTitle() { ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java index d8fc7b05e..92d9c54e8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java @@ -3,36 +3,26 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.bukkit.inventory.ItemStack; @Since("2.0") public class RandomItemRemovingChallenge extends TimedChallenge { public RandomItemRemovingChallenge() { - super(MenuType.CHALLENGES, 1, 30, 30); - setCategory(SettingCategory.RANDOMIZER); + super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 30, 30, new ItemStack(Material.DROPPER), "random-item-removing-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DROPPER, Message.forName("item-random-removing-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 10); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue() * 10); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java index 793ae3957..071d8a7e0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java @@ -3,10 +3,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -14,16 +12,20 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @Since("2.0") public class RandomItemSwappingChallenge extends TimedChallenge { public RandomItemSwappingChallenge() { - super(MenuType.CHALLENGES, 1, 60, 5); - setCategory(SettingCategory.RANDOMIZER); + super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 60, 5, new ItemStack(Material.HOPPER), "random-swapping"); } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue()); +// } + public static void swapRandomItems(Player player) { if (player.getInventory().getContents().length == 0) return; int slot = InventoryUtils.getRandomFullSlot(player.getInventory()); @@ -43,18 +45,6 @@ private static void swapItemToRandomSlot(@NotNull Inventory inventory, int slot1 inventory.setItem(slot2, item1); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.HOPPER, Message.forName("item-random-swapping-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } - @Override public void playValueChangeTitle() { ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java index d1f872283..02877ca45 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomTeleportOnHitChallenge.java @@ -2,11 +2,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDamageByPlayerEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; @@ -14,7 +12,7 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List; @@ -23,8 +21,7 @@ public class RandomTeleportOnHitChallenge extends Setting { public RandomTeleportOnHitChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.RANDOMIZER); + super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, new ItemStack(Material.ENDER_CHEST), "mob-damage-teleport"); } public static void switchEntityLocations(LivingEntity entity1, LivingEntity entity2) { @@ -37,12 +34,6 @@ public static void switchEntityLocations(LivingEntity entity1, LivingEntity enti entity1.setInvisible(false); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENDER_CHEST, Message.forName("item-mob-damage-teleport-challenge")); - } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onEntityDamageByPlayer(EntityDamageByPlayerEvent event) { if (!shouldExecuteEffect()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java index 12d08f908..b10b76e8f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java @@ -3,12 +3,11 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; @@ -22,8 +21,8 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntitySpawnEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; @@ -34,11 +33,17 @@ public class RandomizedHPChallenge extends SettingModifier { private final Random random = new Random(); public RandomizedHPChallenge() { - super(MenuType.CHALLENGES, 5); - setCategory(SettingCategory.RANDOMIZER); + super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 5, new StandardItemBuilder.PotionBuilder(Material.POTION).setColor(Color.RED).build(), + "randomized-hp"); randomizeExistingEntityHealth(); } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-max-health-description").asArray(getValue() * 50); +// } + @Override protected void onDisable() { resetExistingEntityHealth(); @@ -64,16 +69,21 @@ public void onSpawn(@NotNull EntitySpawnEvent event) { private void randomizeEntityHealth(@NotNull LivingEntity entity) { if (entity instanceof Player) return; + + AttributeInstance attribute = entity.getAttribute(MinecraftNameWrapper.MAX_HEALTH); + if (attribute == null) return; + if (!isEnabled()) { - entity.resetMaxHealth(); - entity.setHealth(entity.getMaxHealth()); + attribute.setBaseValue(attribute.getDefaultValue()); + entity.setHealth(attribute.getDefaultValue()); +// entity.resetMaxHealth(); +// entity.setHealth(entity.getMaxHealth()); return; } + int health = random.nextInt(getValue() * 100) + 1; - entity.setHealth(health); - AttributeInstance attribute = entity.getAttribute(MinecraftNameWrapper.MAX_HEALTH); - if (attribute == null) return; attribute.setBaseValue(health); + entity.setHealth(health); } private void randomizeExistingEntityHealth() { @@ -113,14 +123,8 @@ private double getDefaultHealth(@NotNull EntityType entityType) { @NotNull @Override - public ItemBuilder createDisplayItem() { - return new PotionBuilder(Material.POTION, Message.forName("item-randomized-hp-challenge")).setColor(Color.RED); - } - - @NotNull - @Override - public ItemBuilder createSettingsItem() { - return super.createSettingsItem().amount(isEnabled() ? getValue() * 5 : 1); + public ItemStack getSettingsItemPreset() { + return DefaultItems.createEnabledValuePreset(getValue() * 5); } @Override @@ -128,10 +132,4 @@ public void playValueChangeTitle() { ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() * 100); } - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-max-health-description").asArray(getValue() * 50); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java index 32919deac..e170b2336 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java @@ -5,24 +5,22 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.block.Biome; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @Since("2.0") public class MaxBiomeTimeChallenge extends SettingModifier { public MaxBiomeTimeChallenge() { - super(MenuType.CHALLENGES, 3, 20); - setCategory(SettingCategory.LIMITED_TIME); + super(MenuType.CHALLENGES, SettingCategory.LIMITED_TIME, 3, 20, new ItemStack(Material.SPRUCE_SAPLING), "max-biome-time"); } @Override @@ -47,17 +45,11 @@ protected void onValueChange() { bossbar.update(); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SPRUCE_SAPLING, Message.forName("item-max-biome-time-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 60); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue() * 60); +// } @Override public void playValueChangeTitle() { @@ -87,7 +79,7 @@ private void updateBiomeTime(@NotNull Player player) { Biome biome = player.getLocation().getBlock().getBiome(); int time = getCurrentTime(player) + 1; if (time > getValue() * 60) { - kill(player); + ChallengeHelper.kill(player); } if (time < getValue() * 60) { getPlayerData(player).set(biome.name(), time); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java index ac6cd56ba..c4484b187 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java @@ -5,24 +5,22 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @Since("2.0") public class MaxHeightTimeChallenge extends SettingModifier { public MaxHeightTimeChallenge() { - super(MenuType.CHALLENGES, 3, 20); - setCategory(SettingCategory.LIMITED_TIME); + super(MenuType.CHALLENGES, SettingCategory.LIMITED_TIME, 3, 20, new ItemStack(Material.PARROT_SPAWN_EGG), "max-height-time-challenge"); } @Override @@ -47,17 +45,11 @@ protected void onValueChange() { bossbar.update(); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PARROT_SPAWN_EGG, Message.forName("item-max-height-time-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 60); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue() * 60); +// } @Override public void playValueChangeTitle() { @@ -86,7 +78,7 @@ private void updateHeightTime(@NotNull Player player) { int time = getCurrentTime(player) + 1; if (time > getValue() * 60) { - kill(player); + ChallengeHelper.kill(player); } if (time < getValue() * 60) { getPlayerData(player).set(String.valueOf(player.getLocation().getBlockY()), time); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java index 3c0a8558f..e926af2f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java @@ -1,14 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; +import net.codingarea.challenges.plugin.challenges.type.abstraction.menu.MenuSetting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeConfigHelper; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.commons.common.config.Document; @@ -34,26 +32,20 @@ public class AllBlocksDisappearChallenge extends MenuSetting { private final int stackDropLimit; public AllBlocksDisappearChallenge() { - super(MenuType.CHALLENGES, Message.forName("menu-all-blocks-disappear-challenge-settings")); - setCategory(SettingCategory.WORLD); - registerSetting("break", new BooleanSubSetting( - () -> new ItemBuilder(Material.DIAMOND_PICKAXE, Message.forName("item-all-blocks-disappear-break-challenge")), - true - )); - registerSetting("place", new BooleanSubSetting( - () -> new ItemBuilder(Material.DIAMOND_BLOCK, Message.forName("item-all-blocks-disappear-place-challenge")) - )); +// super(Message.forName("menu-all-blocks-disappear-challenge-settings")); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.TNT), "all-blocks-disappear"); +// registerSetting("break", new BooleanSubSetting( +// () -> new LegacyItemBuilder(Material.DIAMOND_PICKAXE, Message.forName("item-all-blocks-disappear-break-challenge")), +// true +// )); +// registerSetting("place", new BooleanSubSetting( +// () -> new LegacyItemBuilder(Material.DIAMOND_BLOCK, Message.forName("item-all-blocks-disappear-place-challenge")) +// )); Document document = ChallengeConfigHelper.getSettingsDocument(); stackDropLimit = document.contains("all-block-disappear-stack-drop-limit") ? document.getInt("all-block-disappear-stack-drop-limit") : 50; } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.TNT, Message.forName("item-all-blocks-disappear-challenge")); - } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockBreak(@NotNull BlockBreakEvent event) { if (!shouldExecuteEffect()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java index 01bdb8ac2..663a6af4e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java @@ -1,14 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; -import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.challenges.type.abstraction.menu.MenuSetting; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; -import net.codingarea.challenges.plugin.management.stats.Statistic.Display; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.*; import org.bukkit.block.Block; @@ -17,6 +14,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityDropItemEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -29,42 +27,42 @@ public class AnvilRainChallenge extends MenuSetting { int currentTime = 0; public AnvilRainChallenge() { - super(MenuType.CHALLENGES, Message.forName("menu-anvil-rain-challenge-settings")); - setCategory(SettingCategory.WORLD); - registerSetting("time", new NumberSubSetting( - () -> new ItemBuilder(Material.CLOCK, Message.forName("item-anvil-rain-time-challenge")), - value -> null, - value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), - 1, - 30, - 7 - ) - ); - registerSetting("count", new NumberSubSetting( - () -> new ItemBuilder(Material.FLINT, Message.forName("item-anvil-rain-count-challenge")), - 1, - 30, - 8 - ) - ); - registerSetting("range", new NumberSubSetting( - () -> new ItemBuilder(Material.COMPASS, Message.forName("item-anvil-rain-range-challenge")), - value -> null, - value -> "§e" + value + " §7" + (value == 1 ? "chunk" : "chunks"), - 1, - 3, - 2 - ) - ); - registerSetting("damage", new NumberSubSetting( - () -> new ItemBuilder(Material.IRON_SWORD, Message.forName("item-anvil-rain-damage-challenge")), - value -> null, - value -> "§e" + Display.HEARTS.formatChat(value), - 1, - 60, - 30 - ) - ); +// super(Message.forName("menu-anvil-rain-challenge-settings")); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.ANVIL), "anvil-rain-challenge"); +// registerSetting("time", new NumberSubSetting( +// () -> new LegacyItemBuilder(Material.CLOCK, Message.forName("item-anvil-rain-time-challenge")), +// value -> null, +// value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), +// 1, +// 30, +// 7 +// ) +// ); +// registerSetting("count", new NumberSubSetting( +// () -> new LegacyItemBuilder(Material.FLINT, Message.forName("item-anvil-rain-count-challenge")), +// 1, +// 30, +// 8 +// ) +// ); +// registerSetting("range", new NumberSubSetting( +// () -> new LegacyItemBuilder(Material.COMPASS, Message.forName("item-anvil-rain-range-challenge")), +// value -> null, +// value -> "§e" + value + " §7" + (value == 1 ? "chunk" : "chunks"), +// 1, +// 3, +// 2 +// ) +// ); +// registerSetting("damage", new NumberSubSetting( +// () -> new LegacyItemBuilder(Material.IRON_SWORD, Message.forName("item-anvil-rain-damage-challenge")), +// value -> null, +// value -> "§e" + Display.HEARTS.formatChat(value), +// 1, +// 60, +// 30 +// ) +// ); } @Override @@ -88,12 +86,6 @@ private void removeAnvils() { } } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ANVIL, Message.forName("item-anvil-rain-challenge")); - } - @ScheduledTask(ticks = 20, async = false) public void onSecond() { currentTime++; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java index 2aa84e8b1..56628e1b0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java @@ -1,12 +1,10 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder.LeatherArmorBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import org.bukkit.Color; import org.bukkit.GameMode; import org.bukkit.Material; @@ -17,14 +15,8 @@ public class BedrockPathChallenge extends Setting { public BedrockPathChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new LeatherArmorBuilder(Material.LEATHER_BOOTS, Message.forName("item-bedrock-path-challenge")).setColor(Color.GRAY); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new StandardItemBuilder.LeatherArmorBuilder(Material.LEATHER_BOOTS).setColor(Color.GRAY).build(), + "bedrock-path-challenge"); } @EventHandler diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java index 4b22248c0..1749a7028 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java @@ -3,14 +3,15 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -20,8 +21,7 @@ public class BedrockWallChallenge extends SettingModifier { public BedrockWallChallenge() { - super(MenuType.CHALLENGES, 1, 60, 30); - setCategory(SettingCategory.WORLD); + super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 60, 30, new ItemStack(Material.BEDROCK), "bedrock-walls"); } @EventHandler @@ -54,16 +54,10 @@ public void onMove(@NotNull PlayerMoveEvent event) { } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BEDROCK, Message.forName("item-bedrock-walls-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue()); +// } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java index 024ccb36b..ca30f50dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java @@ -2,10 +2,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -14,21 +12,14 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; -import org.jetbrains.annotations.NotNull; @Since("2.1.1") public class BlockFlyInAirChallenge extends Setting { public BlockFlyInAirChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FERN, Message.forName("item-blocks-fly-challenge")); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.FERN), "blocks-fly-challenge"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java index df17e3a71..b8be62b6a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java @@ -2,10 +2,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; @@ -13,9 +11,9 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; @@ -26,21 +24,14 @@ public class BlocksDisappearAfterTimeChallenge extends SettingModifier { private final Map tasks = new HashMap<>(); public BlocksDisappearAfterTimeChallenge() { - super(MenuType.CHALLENGES, 60, 300); - setCategory(SettingCategory.WORLD); + super(MenuType.CHALLENGES, SettingCategory.WORLD, 60, 300, new ItemStack(Material.STRING), "blocks-disappear-time-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STRING, Message.forName("item-blocks-disappear-time-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue()); +// } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPlace(@NotNull BlockPlaceEvent event) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java index dd078d165..1133d99f0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java @@ -3,14 +3,13 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.*; import org.bukkit.block.Block; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -19,21 +18,14 @@ public class ChunkDeconstructionChallenge extends TimedChallenge { public ChunkDeconstructionChallenge() { - super(MenuType.CHALLENGES, 1, 60, 20); - setCategory(SettingCategory.WORLD); + super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 60, 20, new ItemStack(Material.DIAMOND_PICKAXE), "chunk-deconstruction-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_PICKAXE, Message.forName("item-chunk-deconstruction-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue()); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java index 089e818d1..fa492eea1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java @@ -3,9 +3,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.common.collection.pair.Tuple; import org.bukkit.*; import org.bukkit.World.Environment; @@ -15,9 +14,9 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.HashMap; @@ -26,19 +25,13 @@ public class ChunkDeletionChallenge extends SettingModifier { private final HashMap> chunks = new HashMap<>(); public ChunkDeletionChallenge() { - super(MenuType.CHALLENGES, 1, 120, 60); - setCategory(SettingCategory.WORLD); + super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 120, 60, new ItemStack(Material.GOLDEN_PICKAXE), "setting-chunk-deletion-challenge"); } - @Override - public @NotNull ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-chunk-deletion-challenge")); - } - - @Override - protected @Nullable String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } +// @Override +// protected @Nullable String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue()); +// } @Override protected void onEnable() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java index b1cd4abb8..fd5ad4654 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java @@ -1,10 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import org.bukkit.Bukkit; import org.bukkit.GameMode; @@ -12,14 +10,13 @@ import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; public class FloorIsLavaChallenge extends SettingModifier { public FloorIsLavaChallenge() { - super(MenuType.CHALLENGES, 1, 60, 30); - setCategory(SettingCategory.WORLD); + super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 60, 30, new ItemStack(Material.MAGMA_BLOCK), "floor-is-lava-challenge"); } @EventHandler @@ -46,16 +43,10 @@ private void createLavaFloor(@NotNull Location to) { BlockUtils.setBlockNatural(BlockUtils.getBlockBelow(to), Material.LAVA, true); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MAGMA_BLOCK, Message.forName("item-floor-lava-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue()); +// } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java index 6428654dd..2de35e5ac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java @@ -5,8 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.Location; import org.bukkit.Material; @@ -30,14 +29,7 @@ public class IceFloorChallenge extends Setting { private final List ignoredPlayers = new ArrayList<>(); public IceFloorChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PACKED_ICE, Message.forName("item-ice-floor-challenge")); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.PACKED_ICE), "ice-floor-challenge"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java index 90c719565..0b1299752 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java @@ -3,18 +3,17 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.challenges.annotations.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; import net.codingarea.challenges.plugin.utils.bukkit.nms.NMSProvider; import net.codingarea.challenges.plugin.utils.bukkit.nms.type.PacketBorder; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.document.GsonDocument; @@ -26,6 +25,7 @@ import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.*; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.HashMap; @@ -46,8 +46,7 @@ public class LevelBorderChallenge extends Setting { private int bestPlayerLevel = 0; public LevelBorderChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.ENCHANTING_TABLE), "level-border-challenge"); } @Override @@ -74,12 +73,6 @@ protected void onDisable() { bossbar.hide(); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENCHANTING_TABLE, Message.forName("item-level-border-challenges")); - } - public void checkBorderSize(boolean animate) { Player currentBestPlayer = bestPlayerUUID != null ? Bukkit.getPlayer(bestPlayerUUID) : null; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index 908fdcf75..55260e723 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -4,14 +4,13 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.policy.PlayerCountPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -50,14 +49,7 @@ public class LoopChallenge extends Setting { private static final Map loops = new HashMap<>(); public LoopChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.LEAD, Message.forName("item-loop-challenge")); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.LEAD), "loop-challenge"); } @ScheduledTask(ticks = 1, async = false) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java index 0b584a0bf..da1861adf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java @@ -4,11 +4,9 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.collection.pair.Triple; import net.codingarea.commons.common.config.Document; @@ -29,6 +27,7 @@ import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.vehicle.VehicleMoveEvent; import org.bukkit.event.world.ChunkUnloadEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.*; @@ -41,14 +40,7 @@ public class RepeatInChunkChallenge extends Setting { private final Set updatedChunks = new HashSet<>(); public RepeatInChunkChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-repeat-chunk-challenge")); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.GRASS_BLOCK), "repeat-in-chunk-challenge"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index e67924724..49041194e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.common.config.Document; @@ -18,6 +18,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -29,14 +30,7 @@ public class SnakeChallenge extends Setting { private final ArrayList blocks = new ArrayList<>(); public SnakeChallenge() { - super(MenuType.CHALLENGES); - setCategory(SettingCategory.WORLD); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BLUE_TERRACOTTA, Message.forName("item-snake-challenge")); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.BLUE_TERRACOTTA), "snake-challenge"); } @Override @@ -77,7 +71,7 @@ public void onMove(@NotNull PlayerMoveEvent event) { if (blocks.contains(to)) { Message.forName("snake-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); - kill(event.getPlayer()); + ChallengeHelper.kill(event.getPlayer()); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java index 189c355e4..1fca0c5f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java @@ -3,14 +3,15 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -20,8 +21,7 @@ public class SurfaceHoleChallenge extends SettingModifier { public SurfaceHoleChallenge() { - super(MenuType.CHALLENGES, 1, 60, 30); - setCategory(SettingCategory.WORLD); + super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 60, 30, new ItemStack(Material.BARRIER), "item-surface-hole-challenge"); } @EventHandler @@ -56,16 +56,10 @@ public void onMove(@NotNull PlayerMoveEvent event) { } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BARRIER, Message.forName("item-surface-hole-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue()); - } +// @Nullable // TODO! +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue()); +// } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java index f4885377e..2202e4439 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java @@ -6,8 +6,7 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.commons.common.config.Document; @@ -23,6 +22,7 @@ import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.world.ChunkUnloadEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -39,25 +39,17 @@ public class TsunamiChallenge extends TimedChallenge { private final List floodedChunks = new ArrayList<>(); - private int waterHeight = Integer.MAX_VALUE, - lavaHeight = 0; + private int waterHeight = Integer.MAX_VALUE, lavaHeight = 0; public TsunamiChallenge() { - super(MenuType.CHALLENGES, 1, 40, 4); - setCategory(SettingCategory.WORLD); + super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 40, 4, new ItemStack(Material.ICE), "tsunami-challenge"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ICE, Message.forName("item-tsunami-challenge")); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-time-seconds-description").asArray(getValue() * 15); - } +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-time-seconds-description").asArray(getValue() * 15); +// } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java index a3bc15578..249c0e1d2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java @@ -2,9 +2,8 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -20,13 +19,11 @@ public class DamageRuleSetting extends Setting { private final List causes; private final String name; - private final ItemBuilder preset; - public DamageRuleSetting(@NotNull ItemBuilder preset, @NotNull String name, @NotNull DamageCause... causes) { - super(MenuType.DAMAGE, true); + public DamageRuleSetting(@NotNull LegacyItemBuilder preset, @NotNull String name, @NotNull DamageCause... causes) { + super(MenuType.DAMAGE, null, true, preset.build(), "TITLE!"); this.causes = Arrays.asList(causes); this.name = name; - this.preset = preset; } @NotNull @@ -35,12 +32,6 @@ public String getUniqueName() { return super.getUniqueName() + name; } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return preset.clone().applyFormat(Message.forName("item-damage-rule-" + name).asItemDescription()); - } - @EventHandler(priority = EventPriority.NORMAL) public void onDamage(@NotNull EntityDamageEvent event) { if (ChallengeAPI.isWorldInUse()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java index 008cac40e..502c80daa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java @@ -5,9 +5,8 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.advancement.Advancement; @@ -18,6 +17,7 @@ import org.bukkit.event.player.PlayerAdvancementDoneEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent; import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.Collections; @@ -32,7 +32,7 @@ public class AllAdvancementGoal extends PointsGoal { private final int advancementCount; public AllAdvancementGoal() { - setCategory(SettingCategory.FASTEST_TIME); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.BOOK), "all-advancements-goal"); allAdvancements = new LinkedList<>(); Bukkit.getServer().advancementIterator().forEachRemaining(advancement -> { if (!advancement.getKey().toString().contains(":recipes/")) { @@ -66,12 +66,6 @@ public void getWinnersOnEnd(@NotNull List winners) { }); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOOK, Message.forName("item-all-advancements-goal")); - } - @EventHandler(priority = EventPriority.HIGH) public void onAdvancement(PlayerAdvancementDoneEvent event) { if (event.getAdvancement().getKey().toString().contains(":recipes/")) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index 4a23df327..c6e9fb467 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -5,12 +5,12 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -48,17 +48,12 @@ public class CollectAllItemsGoal extends SettingGoal implements SenderCommand { private Material currentItem; public CollectAllItemsGoal() { + super(null, new ItemStack(Material.GRASS_BLOCK), "collect-all-items-goal"); random = new SeededRandomWrapper(); reloadItemsToFind(); totalItemsCount = itemsToFind.size(); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-all-items-goal")); - } - private void reloadItemsToFind() { allItemsToFind = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); allItemsToFind.removeIf(material -> !material.isItem()); @@ -102,17 +97,17 @@ protected void onDisable() { @Override public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (!isEnabled()) { - Message.forName("challenge-disabled").send(sender, Prefix.CHALLENGES); + MessageKey.of("challenge-disabled").send(sender, Prefix.CHALLENGES); SoundSample.BASS_OFF.playIfPlayer(sender); return; } if (currentItem == null) { - Message.forName("all-items-already-finished").send(sender, Prefix.CHALLENGES); + MessageKey.of("all-items-already-finished").send(sender, Prefix.CHALLENGES); SoundSample.BASS_OFF.playIfPlayer(sender); return; } - Message.forName("all-items-skipped").broadcast(Prefix.CHALLENGES, getItemDisplayName(currentItem)); + MessageKey.of("all-items-skipped").broadcast(Prefix.CHALLENGES, getItemDisplayName(currentItem)); SoundSample.PLING.broadcast(); nextItem(); bossbar.update(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java index 508e7bc88..03531ab8d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java @@ -2,12 +2,10 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Material; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Arrays; @@ -17,8 +15,7 @@ public class CollectHorseAmorGoal extends ItemCollectionGoal { public CollectHorseAmorGoal() { - super(); - setCategory(SettingCategory.FASTEST_TIME); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.DIAMOND_HORSE_ARMOR), "collect-horse-armor-goal"); List targets = new ArrayList<>(Arrays.asList( Material.DIAMOND_HORSE_ARMOR, Material.GOLDEN_HORSE_ARMOR, @@ -32,10 +29,4 @@ public CollectHorseAmorGoal() { setTarget(targets.toArray(new Object[0])); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_HORSE_ARMOR, Message.forName("item-collect-horse-armor-goal")); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java index 15b177654..70c50bd0a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java @@ -2,24 +2,15 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; @Since("2.1.2") public class CollectIceBlocksGoal extends ItemCollectionGoal { public CollectIceBlocksGoal() { - super(Material.ICE, Material.BLUE_ICE, Material.PACKED_ICE, Material.SNOW_BLOCK); - setCategory(SettingCategory.FASTEST_TIME); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PACKED_ICE, Message.forName("item-collect-ice-goal")); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.PACKED_ICE), "collect-ice-goal", Material.ICE, Material.BLUE_ICE, Material.PACKED_ICE, Material.SNOW_BLOCK); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java index ab587345c..afdd82d43 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java @@ -1,10 +1,9 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.CollectionGoal; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Material; @@ -12,19 +11,13 @@ import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class CollectMostDeathsGoal extends CollectionGoal { public CollectMostDeathsGoal() { - super(DamageCause.values()); - setCategory(SettingCategory.SCORE_POINTS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.LAVA_BUCKET, Message.forName("item-most-deaths-goal")); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.LAVA_BUCKET), "most-deaths-goal", DamageCause.values()); } @EventHandler @@ -38,7 +31,7 @@ public void onDeath(@NotNull PlayerDeathEvent event) { if (cause == DamageCause.CUSTOM) return; collect(event.getEntity(), cause, () -> { - Message.forName("death-collected").send(event.getEntity(), Prefix.CHALLENGES, StringUtils.getEnumName(cause)); + MessageKey.of("death-collected").send(event.getEntity(), Prefix.CHALLENGES, StringUtils.getEnumName(cause)); SoundSample.PLING.play(event.getEntity()); }); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java index 983450dee..3d00c9c3c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java @@ -2,28 +2,20 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerExpChangeEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") public class CollectMostExpGoal extends PointsGoal { public CollectMostExpGoal() { - super(); - setCategory(SettingCategory.SCORE_POINTS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-most-xp-goal")); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.EXPERIENCE_BOTTLE), "most-xp-goal"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java index d45111b83..9176ae11a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java @@ -1,10 +1,9 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.CollectionGoal; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.item.ItemUtils; @@ -20,14 +19,7 @@ public class CollectMostItemsGoal extends CollectionGoal { public CollectMostItemsGoal() { - super(ExperimentalUtils.getMaterials()); - setCategory(SettingCategory.SCORE_POINTS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STICK, Message.forName("item-most-items-goal")); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.STICK), "most-items-goal", ExperimentalUtils.getMaterials()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @@ -55,7 +47,7 @@ public void onClick(@NotNull InventoryClickEvent event) { protected void handleNewItem(@NotNull Material material, @NotNull Player player) { collect(player, material, () -> { - Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); + MessageKey.of("item-collected").send(player, Prefix.CHALLENGES, material); SoundSample.PLING.play(player); }); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java index 669f6e1f2..d9d20fed6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java @@ -2,12 +2,10 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Material; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Arrays; @@ -17,7 +15,7 @@ public class CollectSwordsGoal extends ItemCollectionGoal { public CollectSwordsGoal() { - setCategory(SettingCategory.FASTEST_TIME); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.DIAMOND_SWORD), "collect-swords-goal"); List targets = new ArrayList<>(Arrays.asList( Material.WOODEN_SWORD, Material.STONE_SWORD, Material.IRON_SWORD, Material.GOLDEN_SWORD, @@ -31,10 +29,4 @@ public CollectSwordsGoal() { setTarget(targets.toArray(new Object[0])); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_SWORD, Message.forName("item-collect-swords-goal")); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java index 489592629..363703726 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java @@ -2,13 +2,14 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierCollectionGoal; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -17,6 +18,7 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class CollectWoodGoal extends SettingModifierCollectionGoal { @@ -28,26 +30,19 @@ public class CollectWoodGoal extends SettingModifierCollectionGoal { BOTH = 3; public CollectWoodGoal() { - super(1, newNether ? 3 : 1); - setCategory(SettingCategory.FASTEST_TIME); + super(SettingCategory.FASTEST_TIME, 1, newNether ? 3 : 1, new ItemStack(Material.GOLDEN_AXE), "collect-wood-goal"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_AXE, Message.forName("item-collect-wood-goal")); - } - - @NotNull - @Override - public ItemBuilder createSettingsItem() { - if (!newNether) return DefaultItem.enabled(); - if (getValue() == OVERWORLD) - return DefaultItem.create(Material.OAK_LOG, Message.forName("item-collect-wood-goal-overworld")); - if (getValue() == NETHER) - return DefaultItem.create(Material.WARPED_STEM, Message.forName("item-collect-wood-goal-nether")); - return DefaultItem.create(Material.CRYING_OBSIDIAN, Message.forName("item-collect-wood-goal-both")); - } +// @NotNull +// @Override +// public LegacyItemBuilder createSettingsItem() { +// if (!newNether) return DefaultItem.enabled(); +// if (getValue() == OVERWORLD) +// return DefaultItem.create(Material.OAK_LOG, Message.forName("item-collect-wood-goal-overworld")); +// if (getValue() == NETHER) +// return DefaultItem.create(Material.WARPED_STEM, Message.forName("item-collect-wood-goal-nether")); +// return DefaultItem.create(Material.CRYING_OBSIDIAN, Message.forName("item-collect-wood-goal-both")); +// } @Override public void handleClick(@NotNull ChallengeMenuClickInfo info) { @@ -119,7 +114,7 @@ public void onPlayerInventoryClick(@NotNull PlayerInventoryClickEvent event) { private void handleCollect(@NotNull Player player, @NotNull Material material) { collect(player, material, () -> { - Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); + MessageKey.of("item-collected").send(player, Prefix.CHALLENGES, material); SoundSample.PLING.play(player); }); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java index bf7810a16..944f52475 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java @@ -1,14 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.ItemCollectionGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.RequireVersion; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Material; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; @Since("2.1.2") @RequireVersion(MinecraftVersion.V1_14) @@ -16,18 +14,12 @@ public class CollectWorkstationsGoal extends ItemCollectionGoal { public CollectWorkstationsGoal() { super( + SettingCategory.FASTEST_TIME, new ItemStack(Material.FLETCHING_TABLE), "collect-workstations-goal", Material.LECTERN, Material.COMPOSTER, Material.GRINDSTONE, Material.BLAST_FURNACE, Material.SMOKER, Material.FLETCHING_TABLE, Material.CARTOGRAPHY_TABLE, Material.BREWING_STAND, Material.SMITHING_TABLE, Material.CAULDRON, Material.LOOM, Material.STONECUTTER, Material.BARREL ); - setCategory(SettingCategory.FASTEST_TIME); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FLETCHING_TABLE, Message.forName("item-collect-workstations-item")); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java index ebdbff49c..18b3e9758 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java @@ -3,16 +3,15 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.Collections; @@ -22,8 +21,7 @@ public class EatCakeGoal extends SettingGoal { public EatCakeGoal() { - super(); - setCategory(SettingCategory.FASTEST_TIME); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.CAKE), "eat-cake-goal"); } @Override @@ -31,12 +29,6 @@ public void getWinnersOnEnd(@NotNull List winners) { } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CAKE, Message.forName("item-eat-cake-goal")); - } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInteract(PlayerInteractEvent event) { if (!shouldExecuteEffect()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java index 2d0bd52e5..d0887cc03 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java @@ -2,29 +2,21 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.FoodLevelChangeEvent; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; @Since("2.1.2") public class EatMostGoal extends PointsGoal { public EatMostGoal() { - super(); - setCategory(SettingCategory.SCORE_POINTS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COOKIE, Message.forName("item-eat-most-goal")); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.COOKIE), "eat-most-goal"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @@ -35,7 +27,7 @@ public void onItemConsume(FoodLevelChangeEvent event) { int changedFoodLevel = event.getFoodLevel() - event.getEntity().getFoodLevel(); if (changedFoodLevel > 0) { addPoints(event.getEntity().getUniqueId(), changedFoodLevel); - Message.forName("points-change").send(event.getEntity(), Prefix.CHALLENGES, "+" + changedFoodLevel); + MessageKey.of("points-change").send(event.getEntity(), Prefix.CHALLENGES, "+" + changedFoodLevel); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java index da84379bc..1bcc48768 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java @@ -2,24 +2,15 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.FindItemGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; @Since("2.1.1") public class FindElytraGoal extends FindItemGoal { public FindElytraGoal() { - super(Material.ELYTRA); - setCategory(SettingCategory.FASTEST_TIME); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ELYTRA, Message.forName("item-find-elytra-goal")); + super(SettingCategory.FASTEST_TIME, Material.ELYTRA, new ItemStack(Material.ELYTRA), "find-elytra-goal"); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java index 692bcaa9f..994e19de7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java @@ -2,12 +2,10 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.RequireVersion; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Material; import org.bukkit.Raid.RaidStatus; @@ -15,6 +13,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.raid.RaidFinishEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -24,17 +23,10 @@ public class FinishRaidGoal extends SettingGoal { public FinishRaidGoal() { - super(); - setCategory(SettingCategory.FASTEST_TIME); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.CROSSBOW), "finish-raid-goal"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CROSSBOW, Message.forName("item-finish-raid-goal")); - } - @Override public void getWinnersOnEnd(@NotNull List winners) { } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java index 521025775..bd5a3e37d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java @@ -3,15 +3,14 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -22,14 +21,7 @@ public class FirstOneToDieGoal extends SettingGoal { private Player winner; public FirstOneToDieGoal() { - super(); - setCategory(SettingCategory.FASTEST_TIME); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-first-one-to-die-goal")); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.STONE_SWORD), "first-one-to-die-goal"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index e944c0c4b..a8f6bae9c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -4,11 +4,11 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -17,6 +17,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityRegainHealthEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -26,8 +27,7 @@ public class GetFullHealthGoal extends SettingModifierGoal { public GetFullHealthGoal() { - super(MenuType.GOAL, 1, 20, 20); - setCategory(SettingCategory.FASTEST_TIME); + super(MenuType.GOAL, SettingCategory.FASTEST_TIME, 1, 20, 20, new ItemStack(Material.AZURE_BLUET), "get-full-health-goal"); } @Override @@ -57,16 +57,10 @@ public void getWinnersOnEnd(@NotNull List winners) { } } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.AZURE_BLUET, Message.forName("item-get-full-health-goal")); - } - @Nullable @Override - protected String[] getSettingsDescription() { - return Message.forName("item-heart-start-description").asArray(getValue() / 2f); + public LocalizableMessage getSettingsDescription() { + return MessageKey.of("item-heart-start-description").withArgs(getValue() / 2f); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java index 14a773bba..219d72768 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java @@ -3,11 +3,10 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.entity.EntityType; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import java.util.Arrays; @@ -15,8 +14,8 @@ public class KillAllBossesGoal extends KillMobsGoal { public KillAllBossesGoal() { - super(Arrays.asList(EntityType.ENDER_DRAGON, EntityType.WITHER, EntityType.ELDER_GUARDIAN)); - setCategory(SettingCategory.KILL_ENTITY); + super(SettingCategory.KILL_ENTITY, Arrays.asList(EntityType.ENDER_DRAGON, EntityType.WITHER, EntityType.ELDER_GUARDIAN), + new ItemStack(Material.DIAMOND_SWORD), "goal-all-bosses"); } @Override @@ -24,10 +23,4 @@ public Message getBossbarMessage() { return Message.forName("bossbar-kill-all-bosses"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_SWORD, Message.forName("item-all-bosses-goal")); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java index 4bc6af91b..bd77fbf0a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java @@ -1,15 +1,14 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.RequireVersion; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Material; import org.bukkit.entity.EntityType; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import java.util.Arrays; @@ -18,8 +17,8 @@ public class KillAllBossesNewGoal extends KillMobsGoal { public KillAllBossesNewGoal() { - super(Arrays.asList(EntityType.ENDER_DRAGON, EntityType.WITHER, EntityType.ELDER_GUARDIAN, EntityType.WARDEN)); - setCategory(SettingCategory.KILL_ENTITY); + super(SettingCategory.KILL_ENTITY, Arrays.asList(EntityType.ENDER_DRAGON, EntityType.WITHER, EntityType.ELDER_GUARDIAN, EntityType.WARDEN), + new ItemStack(Material.NETHERITE_SWORD), "goal-all-bosses-new"); } @Override @@ -27,10 +26,4 @@ public Message getBossbarMessage() { return Message.forName("bossbar-kill-all-bosses"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.NETHERITE_SWORD, Message.forName("item-all-bosses-new-goal")); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java index 097f62e42..d337fe4e1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java @@ -3,11 +3,10 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.entity.EntityType; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import java.util.Arrays; import java.util.LinkedList; @@ -17,8 +16,7 @@ public class KillAllMobsGoal extends KillMobsGoal { public KillAllMobsGoal() { - super(getAllMobsToKill()); - setCategory(SettingCategory.KILL_ENTITY); + super(SettingCategory.KILL_ENTITY, getAllMobsToKill(), new ItemStack(Material.BOW), "all-mobs-goal"); } static List getAllMobsToKill() { @@ -31,12 +29,6 @@ static List getAllMobsToKill() { return list; } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOW, Message.forName("item-all-mobs-goal")); - } - @Override public Message getBossbarMessage() { return Message.forName("bossbar-kill-all-mobs"); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java index e88def8fb..0c044d35d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java @@ -3,13 +3,12 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.bukkit.entity.Monster; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import java.util.Arrays; import java.util.LinkedList; @@ -19,8 +18,7 @@ public class KillAllMonsterGoal extends KillMobsGoal { public KillAllMonsterGoal() { - super(getAllMobsToKill()); - setCategory(SettingCategory.KILL_ENTITY); + super(SettingCategory.KILL_ENTITY, getAllMobsToKill(), new ItemStack(Material.ARROW), "all-monster-goal"); } static List getAllMobsToKill() { @@ -44,12 +42,6 @@ static List getAllMobsToKill() { return list; } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ARROW, Message.forName("item-all-monster-goal")); - } - @Override public Message getBossbarMessage() { return Message.forName("bossbar-kill-all-monster"); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java index c96ae3691..1166d0e3d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillElderGuardianGoal.java @@ -2,27 +2,19 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") public class KillElderGuardianGoal extends KillEntityGoal { public KillElderGuardianGoal() { - super(EntityType.ELDER_GUARDIAN); - setCategory(SettingCategory.KILL_ENTITY); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PRISMARINE_SHARD, Message.forName("item-elder-guardian-goal")); + super(SettingCategory.KILL_ENTITY, EntityType.ELDER_GUARDIAN, new ItemStack(Material.PRISMARINE_SHARD), "goal-elder-guardian"); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java index 36af39651..2d2dc0ad3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillEnderDragonGoal.java @@ -1,21 +1,18 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Material; import org.bukkit.World.Environment; import org.bukkit.entity.EntityType; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.Nullable; public class KillEnderDragonGoal extends KillEntityGoal { public KillEnderDragonGoal() { - super(EntityType.ENDER_DRAGON, Environment.THE_END, true); - setCategory(SettingCategory.KILL_ENTITY); + super(SettingCategory.KILL_ENTITY, EntityType.ENDER_DRAGON, Environment.THE_END, true, new ItemStack(Material.DRAGON_EGG), "goal-ender-dragon"); setOneWinner(false); } @@ -25,10 +22,4 @@ public SoundSample getWinSound() { return null; } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DRAGON_EGG, Message.forName("item-dragon-goal")); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java index 06f349fa6..cc4acbcff 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java @@ -2,30 +2,22 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") public class KillIronGolemGoal extends KillEntityGoal { public KillIronGolemGoal() { - super(EntityType.IRON_GOLEM); - setCategory(SettingCategory.KILL_ENTITY); + super(SettingCategory.KILL_ENTITY, EntityType.IRON_GOLEM, new ItemStack(Material.IRON_INGOT), "iron-golem-goal"); this.killerNeeded = true; } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.IRON_INGOT, Message.forName("item-iron-golem-goal")); - } - @NotNull @Override public SoundSample getStartSound() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java index fd4c00053..95cc99f9b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java @@ -2,30 +2,22 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Material; import org.bukkit.Sound; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") public class KillSnowGolemGoal extends KillEntityGoal { public KillSnowGolemGoal() { - super(MinecraftNameWrapper.SNOW_GOLEM); - setCategory(SettingCategory.KILL_ENTITY); + super(SettingCategory.KILL_ENTITY, MinecraftNameWrapper.SNOW_GOLEM, new ItemStack(Material.SNOWBALL), "snow-golem-goal"); this.killerNeeded = true; } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SNOWBALL, Message.forName("item-snow-golem-goal")); - } - @NotNull @Override public SoundSample getStartSound() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java index 67f938432..09bc38dce 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWardenGoal.java @@ -1,16 +1,15 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; +import net.codingarea.challenges.plugin.challenges.type.annotation.RequireVersion; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.2.0") @@ -18,14 +17,7 @@ public class KillWardenGoal extends KillEntityGoal { public KillWardenGoal() { - super(EntityType.WARDEN); - setCategory(SettingCategory.KILL_ENTITY); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ECHO_SHARD, Message.forName("item-warden-goal")); + super(SettingCategory.KILL_ENTITY, EntityType.WARDEN, new ItemStack(Material.ECHO_SHARD), "goal-warden"); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java index 44aec66b7..175ff2ec6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillWitherGoal.java @@ -1,26 +1,18 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.KillEntityGoal; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class KillWitherGoal extends KillEntityGoal { public KillWitherGoal() { - super(EntityType.WITHER); - setCategory(SettingCategory.KILL_ENTITY); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.NETHER_STAR, Message.forName("item-wither-goal")); + super(SettingCategory.KILL_ENTITY, EntityType.WITHER, new ItemStack(Material.NETHER_STAR), "goal-wither"); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java index 7e9e5ec2c..fddcbbb2d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java @@ -3,9 +3,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Material; @@ -14,6 +12,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -23,10 +22,8 @@ public class LastManStandingGoal extends SettingGoal { private Player winner; - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.IRON_HELMET, Message.forName("item-last-man-standing-goal")); + public LastManStandingGoal() { + super(null, new ItemStack(Material.IRON_HELMET), "last-man-standing-goal"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java index 7f4e6188d..2abfd0a72 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java @@ -3,25 +3,17 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.FirstPlayerAtHeightGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.World.Environment; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; @Since("2.1.0") public class MaxHeightGoal extends FirstPlayerAtHeightGoal { public MaxHeightGoal() { - setCategory(SettingCategory.FASTEST_TIME); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.FEATHER), "max-height-goal"); setHeightToGetTo(ChallengeAPI.getGameWorld(Environment.NORMAL).getMaxHeight()); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FEATHER, Message.forName("item-max-height-goal").asItemDescription(getHeightToGetTo())); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java index 6d6a8363d..d4f363a70 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java @@ -3,26 +3,18 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.FirstPlayerAtHeightGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.Material; import org.bukkit.World.Environment; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; @Since("2.1.0") public class MinHeightGoal extends FirstPlayerAtHeightGoal { public MinHeightGoal() { - setCategory(SettingCategory.FASTEST_TIME); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.BEDROCK), "min-height-goal"); setHeightToGetTo(BukkitReflectionUtils.getMinHeight(ChallengeAPI.getGameWorld(Environment.NORMAL)) + 1); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BEDROCK, Message.forName("item-min-height-goal").asItemDescription(getHeightToGetTo())); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java index 5cfcb11f9..aa186835d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java @@ -1,26 +1,18 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class MineMostBlocksGoal extends PointsGoal { public MineMostBlocksGoal() { - super(); - setCategory(SettingCategory.SCORE_POINTS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-mine-most-blocks-goal")); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.GOLDEN_PICKAXE), "mine-most-blocks-goal"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java index c7f9c40ed..9c6e8e6bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java @@ -2,10 +2,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -21,14 +19,7 @@ public class MostEmeraldsGoal extends PointsGoal { public MostEmeraldsGoal() { - super(); - setCategory(SettingCategory.SCORE_POINTS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.EMERALD, Message.forName("item-most-emeralds-goal")); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.EMERALD), "most-emeralds-goal"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java index 528fe00ea..4e5a8371e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java @@ -3,29 +3,24 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.1.1") public class MostOresGoal extends PointsGoal { public MostOresGoal() { - super(); - setCategory(SettingCategory.SCORE_POINTS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COAL_ORE, Message.forName("item-most-ores-goal")); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.COAL_ORE), "most-ores-goal"); } private int getPointsForOre(Material material) { @@ -61,7 +56,7 @@ public void onUpdate(@NotNull BlockBreakEvent event) { if (ignorePlayer(event.getPlayer())) return; int points = getPointsForOre(event.getBlock().getType()); if (points > 0) { - Message.forName("points-change").send(event.getPlayer(), Prefix.CHALLENGES, "+" + points); + MessageKey.of("points-change").send(event.getPlayer(), Prefix.CHALLENGES, "+" + points); SoundSample.PLING.play(event.getPlayer()); addPoints(event.getPlayer().getUniqueId(), points); } @@ -74,7 +69,7 @@ public void onUpdate(@NotNull BlockPlaceEvent event) { int points = getPointsForOre(event.getBlock().getType()); if (points > 0) { SoundSample.BASS_OFF.play(event.getPlayer()); - Message.forName("points-change").send(event.getPlayer(), Prefix.CHALLENGES, "-" + points); + MessageKey.of("points-change").send(event.getPlayer(), Prefix.CHALLENGES, "-" + points); removePoints(event.getPlayer().getUniqueId(), points); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java index d12b96e38..1af043688 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java @@ -6,12 +6,11 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; @@ -29,13 +28,13 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; -@Since("2.1.0") +@Since("2.1") public class RaceGoal extends SettingModifierGoal { protected long seed = IRandom.create().getSeed(); @@ -43,10 +42,20 @@ public class RaceGoal extends SettingModifierGoal { private Location goal; public RaceGoal() { - super(MenuType.GOAL, 1, 30, 5); - setCategory(SettingCategory.FASTEST_TIME); + super(MenuType.GOAL, SettingCategory.FASTEST_TIME, 1, 30, 5, new ItemStack(Material.STRUCTURE_VOID), "race-goal"); } + @Override + public void playValueChangeTitle() { + ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-range-blocks").asString(getValue() * 100)); + } + +// @Nullable +// @Override +// protected String[] getSettingsDescription() { +// return Message.forName("item-range-blocks-description").asArray(getValue() * 100); +// } + @Override public void getWinnersOnEnd(@NotNull List winners) { } @@ -80,30 +89,12 @@ protected void onDisable() { goal = null; } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-range-blocks").asString(getValue() * 100)); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return Message.forName("item-range-blocks-description").asArray(getValue() * 100); - } - - @Override protected void onValueChange() { reloadGoalLocation(); bossbar.update(); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STRUCTURE_VOID, Message.forName("item-race-goal")); - } - @ScheduledTask(ticks = 20) public void onSecond() { if (goal == null) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java index a2078bb93..eaa0c73ce 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java @@ -5,10 +5,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -27,6 +26,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.*; @@ -34,24 +34,18 @@ public class ExtremeForceBattleGoal extends ForceBattleDisplayGoal> { - public ExtremeForceBattleGoal() { - super(Message.forName("menu-extreme-force-battle-goal-settings")); - - registerSetting("give-item", new BooleanSubSetting( - () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), - false - )); - registerSetting("give-block", new BooleanSubSetting( - () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-block-battle-goal-give-block")), - false - )); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOOK, Message.forName("item-extreme-force-battle-goal")); +// super(Message.forName("menu-extreme-force-battle-goal-settings")); + super(new ItemStack(Material.BOOK), "extreme-force-battle-goal"); + +// registerSetting("give-item", new BooleanSubSetting( +// () -> new LegacyItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), +// false +// )); +// registerSetting("give-block", new BooleanSubSetting( +// () -> new LegacyItemBuilder(Material.CHEST, Message.forName("item-force-block-battle-goal-give-block")), +// false +// )); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java index e03c0be9e..b63db7b42 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java @@ -4,7 +4,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; @@ -16,7 +15,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerAdvancementDoneEvent; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List; @@ -26,7 +25,8 @@ public class ForceAdvancementBattleGoal extends ForceBattleGoal { public ForceAdvancementBattleGoal() { - super(Message.forName("menu-force-advancement-battle-goal-settings")); +// super(Message.forName("menu-force-advancement-battle-goal-settings")); + super(new ItemStack(Material.EXPERIENCE_BOTTLE), "force-advancement-battle-goal"); } private void resetAdvancementProgress(Player player, Advancement advancement) { @@ -35,12 +35,6 @@ private void resetAdvancementProgress(Player player, Advancement advancement) { progress.getAwardedCriteria().forEach(progress::revokeCriteria); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.EXPERIENCE_BOTTLE, Message.forName("item-force-advancement-battle-goal")); - } - @Override protected AdvancementTarget[] getTargetsPossibleToFind() { List advancements = AdvancementTarget.getPossibleAdvancements(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java index 6ad34836d..f02e6cbeb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java @@ -5,13 +5,12 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.Registry; import org.bukkit.block.Biome; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import java.util.List; import java.util.Objects; @@ -20,13 +19,8 @@ public class ForceBiomeBattleGoal extends ForceBattleGoal { public ForceBiomeBattleGoal() { - super(Message.forName("menu-force-biome-battle-goal-settings")); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FILLED_MAP, Message.forName("item-force-biome-battle-goal")); +// super(Message.forName("menu-force-biome-battle-goal-settings")); + super(new ItemStack(Material.FILLED_MAP), "forice-biome-battle-goal"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java index a91c1b13b..bfda815a8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java @@ -6,12 +6,11 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import java.util.List; import java.util.stream.Collectors; @@ -20,12 +19,13 @@ public class ForceBlockBattleGoal extends ForceBattleDisplayGoal { public ForceBlockBattleGoal() { - super(Message.forName("menu-force-block-battle-goal-settings")); +// super(Message.forName("menu-force-block-battle-goal-settings")); + super(new ItemStack(Material.CHEST), "force-block-battle-goal"); - registerSetting("give-block", new BooleanSubSetting( - () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-block-battle-goal-give-block")), - false - )); +// registerSetting("give-block", new BooleanSubSetting( +// () -> new LegacyItemBuilder(Material.CHEST, Message.forName("item-force-block-battle-goal-give-block")), +// false +// )); } @Override @@ -49,12 +49,6 @@ public Message getLeaderboardTitleMessage() { return Message.forName("force-block-battle-leaderboard"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GRASS_BLOCK, Message.forName("item-force-block-battle-goal")); - } - @Override public void handleJokerUse(Player player) { super.handleJokerUse(player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java index 93ee186b3..bb95de040 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java @@ -4,13 +4,13 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -19,13 +19,8 @@ public class ForceDamageBattleGoal extends ForceBattleGoal { public ForceDamageBattleGoal() { - super(Message.forName("menu-force-damage-battle-goal-settings")); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.TOTEM_OF_UNDYING, Message.forName("item-force-damage-battle-goal")); +// super(Message.forName("menu-force-damage-battle-goal-settings")); + super(new ItemStack(Material.TOTEM_OF_UNDYING), "force-damange-battle-goal"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java index a20a8c3a4..41517f417 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java @@ -5,13 +5,12 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import java.util.List; import java.util.stream.Collectors; @@ -19,7 +18,8 @@ public class ForceHeightBattleGoal extends ForceBattleGoal { public ForceHeightBattleGoal() { - super(Message.forName("menu-force-height-battle-goal-settings")); +// super(Message.forName("menu-force-height-battle-goal-settings")); + super(new ItemStack(Material.RABBIT_FOOT), "force-height-battle-goal"); } @Override @@ -48,12 +48,6 @@ protected Message getLeaderboardTitleMessage() { return Message.forName("force-height-battle-leaderboard"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.RABBIT_FOOT, Message.forName("item-force-height-battle-goal")); - } - @Override protected boolean shouldRegisterDupedTargetsSetting() { return false; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java index 96cabb5b8..f0fd80075 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java @@ -6,14 +6,13 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import java.util.List; import java.util.stream.Collectors; @@ -22,12 +21,13 @@ public class ForceItemBattleGoal extends ForceBattleDisplayGoal { public ForceItemBattleGoal() { - super(Message.forName("menu-force-item-battle-goal-settings")); +// super(Message.forName("menu-force-item-battle-goal-settings")); + super(new ItemStack(Material.ITEM_FRAME), "force-item-battle-goal"); - registerSetting("give-item", new BooleanSubSetting( - () -> new ItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), - false - )); +// registerSetting("give-item", new BooleanSubSetting( +// () -> new LegacyItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), +// false +// )); } @Override @@ -51,12 +51,6 @@ public Message getLeaderboardTitleMessage() { return Message.forName("force-item-battle-leaderboard"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ITEM_FRAME, Message.forName("item-force-item-battle-goal")); - } - @Override public void handleJokerUse(Player player) { if (giveItemOnSkip()) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java index a665c556f..582c8d3bc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java @@ -4,7 +4,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.EntityType; @@ -13,6 +12,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -22,7 +22,8 @@ public class ForceMobBattleGoal extends ForceBattleDisplayGoal { public ForceMobBattleGoal() { - super(Message.forName("menu-force-mob-battle-goal-settings")); +// super(Message.forName("menu-force-mob-battle-goal-settings")); + super(new ItemStack(Material.BOW), "force-mob-battle-goal"); } @Override @@ -36,12 +37,6 @@ protected Message getLeaderboardTitleMessage() { return Message.forName("force-mob-battle-leaderboard"); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOW, Message.forName("item-force-mob-battle-goal")); - } - @Override public MobTarget getTargetFromDocument(Document document, String path) { return new MobTarget(document.getEnum(path, EntityType.class)); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java index 96ec11574..02b666faa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java @@ -5,32 +5,26 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import java.util.List; import java.util.stream.Collectors; public class ForcePositionBattleGoal extends ForceBattleGoal { public ForcePositionBattleGoal() { - super(Message.forName("menu-force-position-battle-goal-settings")); - registerSetting("radius", new NumberSubSetting( - () -> new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-position-battle-radius")), - value -> null, - value -> "§e" + (value * 100), - 1, - 100, - 15 - )); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-position-battle-goal")); +// super(Message.forName("menu-force-position-battle-goal-settings")); + super(new ItemStack(Material.DIAMOND_BOOTS), "force-position-battle-goal"); +// registerSetting("radius", new NumberSubSetting( +// () -> new LegacyItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-position-battle-radius")), +// value -> null, +// value -> "§e" + (value * 100), +// 1, +// 100, +// 15 +// )); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java index c4528c95e..e4f08eeba 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java @@ -2,11 +2,10 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import org.bukkit.Location; import org.bukkit.Material; @@ -22,23 +21,21 @@ public class BlockMaterialSetting extends Setting { private final String name; - private final ItemBuilder preset; private final Object[] replacements; private final Material[] materials; - public BlockMaterialSetting(@NotNull String name, @NotNull ItemBuilder preset, @NotNull Object[] replacements, @NotNull Material... materials) { - super(MenuType.ITEMS, true); + public BlockMaterialSetting(@NotNull String name, @NotNull LegacyItemBuilder preset, @NotNull Object[] replacements, @NotNull Material... materials) { + super(MenuType.ITEMS, null, true, preset.build(), "lol"); this.name = name; - this.preset = preset; this.replacements = replacements; this.materials = materials; } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return preset.clone().applyFormat(Message.forName(name).asItemDescription(replacements)); - } +// @NotNull +// @Override +// public LegacyItemBuilder createDisplayItem() { +// return preset.clone().applyFormat(Message.forName(name).asItemDescription(replacements)); +// } private boolean blockMaterial(Material material) { return Arrays.asList(materials).contains(material); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java index bb39d96f5..dd75e4816 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java @@ -6,13 +6,14 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeConfigHelper; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.bukkit.container.BukkitSerialization; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; @@ -29,32 +30,31 @@ public class BackpackSetting extends SettingModifier implements PlayerCommand { - public static final int SHARED = 1, - PLAYER = 2; + public static final int SHARED = 1, PLAYER = 2; private final int size; private final Map backpacks = new HashMap<>(); private final Inventory sharedBackpack; public BackpackSetting() { - super(MenuType.SETTINGS, 1, 2, SHARED); - size = Math.max(Math.min(ChallengeConfigHelper.getSettingsDocument().getInt("backpack-size") * 9, 6 * 9), 9); + super(MenuType.SETTINGS, null, 1, 2, SHARED, new ItemStack(Material.CHEST), "backpack-setting"); + size = Math.clamp(ChallengeConfigHelper.getSettingsDocument().getInt("backpack-size") * 9L, 9, 6 * 9); sharedBackpack = createInventory("§5Team Backpack"); } @NotNull @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CHEST, Message.forName("item-backpack-setting")); + public ItemStack getSettingsItemPreset() { + return super.getSettingsItemPreset(); } - @NotNull - @Override - public ItemBuilder createSettingsItem() { - if (getValue() == SHARED) - return DefaultItem.create(Material.ENDER_CHEST, Message.forName("item-backpack-setting-team")); - return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("item-backpack-setting-player")); - } +// @NotNull +// @Override +// public LegacyItemBuilder createSettingsItem() { +// if (getValue() == SHARED) +// return DefaultItem.create(Material.ENDER_CHEST, Message.forName("item-backpack-setting-team")); +// return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("item-backpack-setting-player")); +// } @Override @@ -74,23 +74,23 @@ public void playValueChangeTitle() { @Override public void onCommand(@NotNull Player player, @NotNull String[] args) { if (ChallengeAPI.isPaused()) { - Message.forName("timer-not-started").send(player, Prefix.BACKPACK); + MessageKey.of("timer-not-started").send(player, Prefix.BACKPACK); SoundSample.BASS_OFF.play(player); return; } if (!isEnabled()) { - Message.forName("backpacks-disabled").send(player, Prefix.BACKPACK); + MessageKey.of("backpacks-disabled").send(player, Prefix.BACKPACK); SoundSample.BASS_OFF.play(player); return; } if (getValue() == SHARED || getValue() == PLAYER) { - Message.forName("backpack-opened").send(player, Prefix.BACKPACK, getValue() == SHARED ? "§5Team Backpack" : "§6Player Backpack"); + MessageKey.of("backpack-opened").send(player, Prefix.BACKPACK, getValue() == SHARED ? "§5Team Backpack" : "§6Player Backpack"); player.openInventory(getCurrentBackpack(player)); SoundSample.OPEN.play(player); } else { - Message.forName("backpacks-disabled").send(player, Prefix.BACKPACK); + MessageKey.of("backpacks-disabled").send(player, Prefix.BACKPACK); SoundSample.BASS_OFF.play(player); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java index b4ef74d61..212e885ee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java @@ -1,16 +1,14 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.NetherPortalSpawnSetting; +import net.codingarea.challenges.plugin.challenges.type.annotation.RequireVersion; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Material; import org.bukkit.StructureType; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; import java.util.Arrays; import java.util.stream.Collectors; @@ -20,14 +18,9 @@ public class BastionSpawnSetting extends NetherPortalSpawnSetting { public BastionSpawnSetting() { - super(MenuType.SETTINGS, StructureType.BASTION_REMNANT, "unable-to-find-bastion", + super(MenuType.SETTINGS, null, StructureType.BASTION_REMNANT, new ItemStack(Material.NETHER_BRICK_STAIRS), + "bastion-spawn", "unable-to-find-bastion", Arrays.stream(ExperimentalUtils.getMaterials()).filter(material -> material.name().contains("BASALT")).collect(Collectors.toList())); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.POLISHED_BLACKSTONE_BRICKS, Message.forName("item-bastion-spawn-setting")); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java index 17ee16968..2898f3f8b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java @@ -1,14 +1,14 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting; +import net.codingarea.challenges.plugin.challenges.type.abstraction.menu.MenuSetting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.DropPriority; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.Utils; @@ -34,31 +34,25 @@ public class CutCleanSetting extends MenuSetting { public CutCleanSetting() { - super(MenuType.SETTINGS, Message.forName("menu-cut-clean-setting-settings")); + super(MenuType.SETTINGS, null, new ItemStack(Material.IRON_AXE), "menu-cut-clean-setting-settings"); registerSetting("iron->iron_ingot", - new ConvertDropSubSetting(() -> new ItemBuilder(Material.IRON_INGOT, Message.forName("item-cut-clean-iron-setting")), true, + new ConvertDropSubSetting(() -> new LegacyItemBuilder(Material.IRON_INGOT, Message.forName("item-cut-clean-iron-setting")), true, Material.IRON_INGOT, "IRON_ORE", "DEEPSLATE_IRON_ORE")); registerSetting("gold->gold_ingot", - new ConvertDropSubSetting(() -> new ItemBuilder(Material.GOLD_INGOT, Message.forName("item-cut-clean-gold-setting")), true, + new ConvertDropSubSetting(() -> new LegacyItemBuilder(Material.GOLD_INGOT, Message.forName("item-cut-clean-gold-setting")), true, Material.GOLD_INGOT, "GOLD_ORE", "DEEPSLATE_GOLD_ORE")); registerSetting("coal->torch", - new ConvertDropSubSetting(() -> new ItemBuilder(Material.COAL, Message.forName("item-cut-clean-coal-setting")), false, + new ConvertDropSubSetting(() -> new LegacyItemBuilder(Material.COAL, Message.forName("item-cut-clean-coal-setting")), false, Material.TORCH, "COAL_ORE", "DEEPSLATE_COAL_ORE")); registerSetting("gravel->flint", - new ConvertDropSubSetting(() -> new ItemBuilder(Material.FLINT, Message.forName("item-cut-clean-flint-setting")), false, + new ConvertDropSubSetting(() -> new LegacyItemBuilder(Material.FLINT, Message.forName("item-cut-clean-flint-setting")), false, Material.FLINT, "GRAVEL")); registerSetting("ore->veins", - new BreakOreVeinsSubSetting(() -> new ItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-cut-clean-vein-setting")), 1, 10)); + new BreakOreVeinsSubSetting(() -> new LegacyItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-cut-clean-vein-setting")), 1, 10)); registerSetting("items->inventory", - new DirectIntoInventorySubSetting(() -> new ItemBuilder(Material.CHEST, Message.forName("item-cut-clean-inventory-setting")))); + new DirectIntoInventorySubSetting(() -> new LegacyItemBuilder(Material.CHEST, Message.forName("item-cut-clean-inventory-setting")))); registerSetting("row->cooked", - new CookFoodSubSetting(() -> new ItemBuilder(Material.COOKED_BEEF, Message.forName("item-cut-clean-food-setting")), true)); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.IRON_AXE, Message.forName("item-cut-clean-setting")); + new CookFoodSubSetting(() -> new LegacyItemBuilder(Material.COOKED_BEEF, Message.forName("item-cut-clean-food-setting")), true)); } protected boolean directIntoInventory() { @@ -67,8 +61,8 @@ protected boolean directIntoInventory() { private class DirectIntoInventorySubSetting extends BooleanSubSetting { - public DirectIntoInventorySubSetting(@NotNull Supplier item) { - super(item); + public DirectIntoInventorySubSetting(@NotNull Supplier item) { + super(item.get().build()); } @NotNull @@ -84,9 +78,9 @@ private class ConvertDropSubSetting extends BooleanSubSetting { protected final Material[] from; protected final Material to; - public ConvertDropSubSetting(@NotNull Supplier item, boolean enabledByDefault, + public ConvertDropSubSetting(@NotNull Supplier item, boolean enabledByDefault, @NotNull Material to, @NotNull String... from) { - super(item, enabledByDefault); + super(item.get().build(), enabledByDefault); List materials = new ArrayList<>(); for (String s : from) { @@ -137,8 +131,8 @@ public void onBlockBreak(@NotNull BlockBreakEvent event) { private class BreakOreVeinsSubSetting extends NumberAndBooleanSubSetting { - public BreakOreVeinsSubSetting(@NotNull Supplier item, int min, int max) { - super(item, min, max); + public BreakOreVeinsSubSetting(@NotNull Supplier item, int min, int max) { + super(item.get().build(), min, max); // TODO } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @@ -201,24 +195,25 @@ private boolean canBeBroken(@NotNull Block block, @NotNull ItemStack tool) { return !block.getDrops(tool).isEmpty(); } - @NotNull - @Override - public ItemBuilder getSettingsItem() { - return getAsBoolean() ? DefaultItem.value(getValue(), "§7Max Vein Size: §e") : DefaultItem.disabled(); - } + // TODO settings name +// @NotNull +// @Override +// public LegacyItemBuilder getSettingsItem() { +// return getAsBoolean() ? DefaultItem.value(getValue(), "§7Max Vein Size: §e") : DefaultItem.disabled(); +// } } private class CookFoodSubSetting extends BooleanSubSetting { - public CookFoodSubSetting(@NotNull Supplier item, boolean enabledByDefault) { - super(item, enabledByDefault); + public CookFoodSubSetting(@NotNull Supplier item, boolean enabledByDefault) { + super(item.get().toItem(), enabledByDefault); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onEntityKill(@NotNull EntityDeathEvent event) { if (!isEnabled()) return; - event.getDrops().replaceAll(item -> new ItemBuilder(ItemUtils.convertFoodToCookedFood(item.getType())).amount(item.getAmount()).build()); + event.getDrops().replaceAll(item -> new LegacyItemBuilder(ItemUtils.convertFoodToCookedFood(item.getType())).setAmount(item.getAmount()).build()); Player killer = event.getEntity().getKiller(); if (killer != null && directIntoInventory()) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java index 3332fbfa4..faae3fc69 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java @@ -4,10 +4,10 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.stats.Statistic.Display; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Material; @@ -19,13 +19,14 @@ import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.inventory.ItemStack; import org.bukkit.projectiles.ProjectileSource; import org.jetbrains.annotations.NotNull; public class DamageDisplaySetting extends Setting { public DamageDisplaySetting() { - super(MenuType.SETTINGS, true); + super(MenuType.SETTINGS, null, true, new ItemStack(Material.COMMAND_BLOCK), "damage-display"); } public static String getCause(@NotNull EntityDamageEvent event) { @@ -76,10 +77,4 @@ public void onDamage(@NotNull EntityDamageEvent event) { String damageDisplay = damage >= 1000 ? "∞" : Display.HEARTS.formatChat(damage); Message.forName("player-damage-display").broadcast(Prefix.DAMAGE, NameHelper.getName((Player) event.getEntity()), damageDisplay, getCause(event)); } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.COMMAND_BLOCK, Message.forName("item-damage-display-setting")); - } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java index f78a94486..c9fd8a10e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java @@ -3,32 +3,28 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class DamageMultiplierModifier extends Modifier { public DamageMultiplierModifier() { - super(MenuType.SETTINGS, 10); + super(MenuType.SETTINGS, null, 10, new ItemStack(Material.STONE_SWORD), "damage-multiplier-setting"); } @NotNull @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-damage-setting")); - } - - @NotNull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.value(getValue()).appendName("x"); + public LocalizableMessage getSettingsName() { + return super.getSettingsName(); // TODO format } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java index 783124b1b..854143a0b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java @@ -3,10 +3,11 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Bukkit; @@ -17,36 +18,29 @@ import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class DeathMessageSetting extends Modifier { - public static final int ENABLED = 2, + public static final int + ENABLED = 2, VANILLA = 3; private boolean hide; public DeathMessageSetting() { - super(MenuType.SETTINGS, 1, 3, 2); + super(MenuType.SETTINGS, null, 1, 3, ENABLED, new ItemStack(Material.BOW), "death-message"); } @NotNull @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BOW, Message.forName("item-death-message-setting")); - } - - @NotNull - @Override - public ItemBuilder createSettingsItem() { - switch (getValue()) { - default: - return DefaultItem.disabled(); - case ENABLED: - return DefaultItem.enabled(); - case VANILLA: - return DefaultItem.create(MinecraftNameWrapper.SIGN, Message.forName("item-death-message-setting-vanilla")); - } + public ItemStack getSettingsItemPreset() { + return switch (getValue()) { + case VANILLA -> new ItemStack(MinecraftNameWrapper.SIGN); + case ENABLED -> DefaultItems.createEnabledPreset(); + default -> DefaultItems.createDisabledPreset(); + }; } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java index 5936d33df..9a2ff981e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java @@ -3,14 +3,13 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") @@ -19,26 +18,21 @@ public class DeathPositionSetting extends Setting { private static final String POSITION_PREFIX = "death-"; public DeathPositionSetting() { - super(MenuType.SETTINGS); + super(MenuType.SETTINGS, null, new ItemStack(Material.MUSIC_DISC_11), "death-position"); } @EventHandler(priority = EventPriority.LOWEST) public void onDeath(@NotNull PlayerDeathEvent event) { if (!shouldExecuteEffect()) return; + PositionSetting setting = AbstractChallenge.getFirstInstance(PositionSetting.class); int index = 1; - while (AbstractChallenge.getFirstInstance(PositionSetting.class).containsPosition(POSITION_PREFIX + index)) + while (setting.containsPosition(POSITION_PREFIX + index)) { index++; + } Player player = event.getEntity(); player.performCommand("pos " + POSITION_PREFIX + index); - - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MUSIC_DISC_11, Message.forName("item-death-position-setting")); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java index 38366644c..70901043f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java @@ -4,12 +4,13 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.common.config.Document; import net.md_5.bungee.api.ChatColor; @@ -23,6 +24,7 @@ import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -33,35 +35,29 @@ public class DifficultySetting extends Modifier implements SenderCommand, TabCompleter { public DifficultySetting() { - super(MenuType.SETTINGS, 0, 3, 2); - } - - @Override - protected void onValueChange() { - setDifficulty(getDifficultyByValue(getValue())); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GLISTERING_MELON_SLICE, Message.forName("item-difficulty-setting")); + super(MenuType.SETTINGS, null, 0, 3, 2, new ItemStack(Material.GLISTERING_MELON_SLICE), "difficulty"); } @NotNull @Override - public ItemBuilder createSettingsItem() { + public ItemStack getSettingsItemPreset() { switch (getValue()) { case 0: - return DefaultItem.create(Material.LIME_DYE, getDifficultyName()); + return DefaultItem.create(Material.LIME_DYE, getDifficultyName()).build(); case 1: - return DefaultItem.create(MinecraftNameWrapper.GREEN_DYE, getDifficultyName()); + return DefaultItem.create(MinecraftNameWrapper.GREEN_DYE, getDifficultyName()).build(); case 2: - return DefaultItem.create(Material.ORANGE_DYE, getDifficultyName()); + return DefaultItem.create(Material.ORANGE_DYE, getDifficultyName()).build(); default: - return DefaultItem.create(MinecraftNameWrapper.RED_DYE, getDifficultyName()); + return DefaultItem.create(MinecraftNameWrapper.RED_DYE, getDifficultyName()).build(); } } + @Override + protected void onValueChange() { + setDifficulty(getDifficultyByValue(getValue())); + } + private String getDifficultyName() { return getDifficultyComponent().toLegacyText(); } @@ -102,13 +98,13 @@ public void loadSettings(@NotNull Document document) { public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (args.length == 0) { - Message.forName("command-difficulty-current").send(sender, Prefix.CHALLENGES, getDifficultyComponent()); + MessageKey.of("command-difficulty-current").send(sender, Prefix.CHALLENGES, getDifficultyComponent()); return; } int difficulty = getDifficultyValue(args[0]); if (difficulty == -1) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "difficulty "); + MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "difficulty "); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java index a12d1d360..e888b99d1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java @@ -3,37 +3,31 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") public class EnderChestCommandSetting extends Setting implements PlayerCommand { public EnderChestCommandSetting() { - super(MenuType.SETTINGS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENDER_CHEST, Message.forName("item-enderchest-command-setting")); + super(MenuType.SETTINGS, null, new ItemStack(Material.ENDER_CHEST), "item-enderchest-command-setting"); } @Override public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (!isEnabled() || ChallengeAPI.isWorldInUse()) { - Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); + MessageKey.of("feature-disabled").send(player, Prefix.CHALLENGES); return; } player.openInventory(player.getEnderChest()); - Message.forName("command-enderchest-open").send(player, Prefix.CHALLENGES); + MessageKey.of("command-enderchest-open").send(player, Prefix.CHALLENGES); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java index 7168e54f5..2a893a977 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java @@ -4,22 +4,18 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Material; import org.bukkit.StructureType; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") public class FortressSpawnSetting extends NetherPortalSpawnSetting { public FortressSpawnSetting() { - super(MenuType.SETTINGS, StructureType.NETHER_FORTRESS, "unable-to-find-fortress", Material.NETHER_BRICKS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.NETHER_BRICK_STAIRS, Message.forName("item-fortress-spawn-setting")); + super(MenuType.SETTINGS, null, StructureType.NETHER_FORTRESS, new ItemStack(Material.NETHER_BRICK_STAIRS), + "fortress-spawn", "unable-to-find-fortress", Material.NETHER_BRICKS); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java index af2441922..da0b4fbc4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HealthDisplaySetting.java @@ -3,15 +3,14 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.scoreboard.*; import org.jetbrains.annotations.NotNull; @@ -21,13 +20,7 @@ public class HealthDisplaySetting extends Setting { public static final String OBJECTIVE_NAME = "health_display"; public HealthDisplaySetting() { - super(MenuType.SETTINGS, true); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.RED_STAINED_GLASS, Message.forName("item-health-display-setting")); + super(MenuType.SETTINGS, null, true, new ItemStack(Material.RED_STAINED_GLASS), "health-display"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java index 12839b148..45c32a9c8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -12,6 +12,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") @@ -20,13 +21,7 @@ public class ImmediateRespawnSetting extends Setting { private boolean respawnWithEvent; public ImmediateRespawnSetting() { - super(MenuType.SETTINGS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GOLDEN_APPLE, Message.forName("item-immediate-respawn-setting")); + super(MenuType.SETTINGS, null, new ItemStack(Material.GOLDEN_APPLE), "item-immediate-respawn-setting"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java index 70ad1c808..cb22597da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java @@ -1,25 +1,17 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.GameRule; import org.bukkit.Material; import org.bukkit.World; -import org.jetbrains.annotations.NotNull; +import org.bukkit.inventory.ItemStack; public class KeepInventorySetting extends Setting { public KeepInventorySetting() { - super(MenuType.SETTINGS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ENDER_EYE, Message.forName("item-keep-inventory-setting")); + super(MenuType.SETTINGS, null, new ItemStack(Material.ENDER_EYE), "keep-inventory"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java index c3b20a56d..995157a0b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java @@ -7,12 +7,11 @@ import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.Objects; - public class LanguageSetting extends Modifier { public static final int ENGLISH = 1; @@ -22,31 +21,31 @@ public class LanguageSetting extends Modifier { ENGLISH_SKULL = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvODgzMWM3M2Y1NDY4ZTg4OGMzMDE5ZTI4NDdlNDQyZGZhYTg4ODk4ZDUwY2NmMDFmZDJmOTE0YWY1NDRkNTM2OCJ9fX0"; public LanguageSetting() { - super(MenuType.SETTINGS, 1, 2, ENGLISH); + super(MenuType.SETTINGS, null, 1, 2, ENGLISH, new ItemStack(Material.KNOWLEDGE_BOOK), "language-setting"); } @NotNull @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.KNOWLEDGE_BOOK, Message.forName("item-language-setting")); + public ItemStack getSettingsItemPreset() { + return super.getSettingsItemPreset(); } - @NotNull - @Override - public ItemBuilder createSettingsItem() { - String texture = getValue() == GERMAN ? GERMAN_SKULL : ENGLISH_SKULL; - return new ItemBuilder.SkullBuilder(DefaultItem.getItemPrefix() + Message.forName(getSettingName())).setBase64Texture(texture).hideAttributes(); - } +// @NotNull +// @Override +// public LegacyItemBuilder createSettingsItem() { +// String texture = getValue() == GERMAN ? GERMAN_SKULL : ENGLISH_SKULL; +// return new LegacyItemBuilder.SkullBuilder(DefaultItem.getItemPrefix() + Message.forName(getSettingName())).setBase64Texture(texture).hideAttributes(); +// } @Override public void playValueChangeTitle() { switch (getValue()) { case GERMAN: - Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("de"); + Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class).changeLanguage("de"); ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName(getSettingName())); break; case ENGLISH: - Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("en"); + Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class).changeLanguage("en"); ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName(getSettingName())); break; default: diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index c467a56a9..23847f498 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -3,9 +3,11 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.commons.common.config.Document; @@ -14,6 +16,7 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class MaxHealthSetting extends Modifier { @@ -27,19 +30,13 @@ public class MaxHealthSetting extends Modifier { private Document valueOffset = new GsonDocument(); public MaxHealthSetting() { - super(MenuType.SETTINGS, 1, 200 * 2, 20); + super(MenuType.SETTINGS, null, 1, 200 * 2, 20, new ItemStack(MinecraftNameWrapper.RED_DYE), "max-health"); } @NotNull @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(MinecraftNameWrapper.RED_DYE, Message.forName("item-max-health-setting")); - } - - @NotNull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.value(getValue(), "§e").appendName(" §7HP §8(§e" + (getValue() / 2f) + " §c❤§8)"); + public LocalizableMessage getSettingsName() { + return MessageKey.of("").withArgs(getValue(), getValue() / 2); // TODO } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java index 2f3836178..ded42a6df 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java @@ -3,23 +3,18 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Bukkit; import org.bukkit.GameRule; import org.bukkit.Material; import org.bukkit.World; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class MobGriefingSetting extends Setting { public MobGriefingSetting() { - super(MenuType.SETTINGS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.CREEPER_HEAD, Message.forName("item-mob-griefing-setting")); + super(MenuType.SETTINGS, null, new ItemStack(Material.CREEPER_HEAD), "mob-griefing"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java index 929fc27f6..43f4d76d5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java @@ -4,19 +4,20 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class NoHitDelaySetting extends Setting { public NoHitDelaySetting() { - super(MenuType.SETTINGS); + super(MenuType.SETTINGS, null, new ItemStack(Material.FEATHER), "no-hit-delay"); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @@ -28,10 +29,4 @@ public void onDamageByEntity(@NotNull EntityDamageEvent event) { }, 1); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FEATHER, Message.forName("item-no-hit-delay-setting")); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java index c4e4f68b1..0c3c150f9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHungerSetting.java @@ -1,19 +1,18 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.entity.FoodLevelChangeEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class NoHungerSetting extends Setting { public NoHungerSetting() { - super(MenuType.SETTINGS); + super(MenuType.SETTINGS, null, new ItemStack(Material.BREAD), "no-hunger"); } @Override @@ -21,12 +20,6 @@ protected void onEnable() { broadcastFiltered(this::feedPlayer); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BREAD, Message.forName("no-hunger-setting")); - } - @EventHandler(ignoreCancelled = true) public void onHunger(@NotNull FoodLevelChangeEvent event) { if (!(event.getEntity() instanceof Player)) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java index cd20e492d..ae8fdc1c3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java @@ -3,16 +3,17 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerItemDamageEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class NoItemDamageSetting extends Setting { public NoItemDamageSetting() { - super(MenuType.SETTINGS); + super(MenuType.SETTINGS, null, new ItemStack(Material.ANVIL), "no-item-damage"); } @EventHandler @@ -24,10 +25,4 @@ public void onItemDamage(PlayerItemDamageEvent event) { event.getPlayer().updateInventory(); } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.ANVIL, Message.forName("item-no-item-damage-setting")); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java index f48e41ba7..572e1509f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java @@ -2,9 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -14,13 +12,12 @@ import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerSwapHandItemsEvent; import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; @Since("2.0") public class NoOffhandSetting extends Setting { public NoOffhandSetting() { - super(MenuType.SETTINGS); + super(MenuType.SETTINGS, null, new ItemStack(Material.SHIELD), "no-offhand-setting"); } @Override @@ -34,12 +31,6 @@ protected void onEnable() { } } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.SHIELD, Message.forName("item-no-offhand-setting")); - } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerSwapHandItems(PlayerSwapHandItemsEvent event) { if (!shouldExecuteEffect()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java index ece0ccf85..a8df39eb4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; @@ -15,6 +15,7 @@ import org.bukkit.event.player.PlayerChangedWorldEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") @@ -23,13 +24,7 @@ public class OldPvPSetting extends Setting { public static final double DISABLED = 32, NORMAL = 4; // Values copied from BackToTheRoots public OldPvPSetting() { - super(MenuType.SETTINGS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.IRON_SWORD, Message.forName("item-old-pvp-setting")); + super(MenuType.SETTINGS, null, new ItemStack(Material.IRON_SWORD), "old-pvp"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java index 3d5f02235..07203d2c3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java @@ -5,13 +5,14 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class OneTeamLifeSetting extends Setting { @@ -19,13 +20,7 @@ public class OneTeamLifeSetting extends Setting { private boolean isKilling = false; public OneTeamLifeSetting() { - super(MenuType.SETTINGS, true); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.FIRE_CHARGE, Message.forName("item-one-life-setting")); + super(MenuType.SETTINGS, null, true, new ItemStack(Material.FIRE_CHARGE), "one-life"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java index d2929f1e2..6bad8e255 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java @@ -1,16 +1,15 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; @@ -18,14 +17,7 @@ public class PlayerGlowSetting extends Setting { public PlayerGlowSetting() { - super(MenuType.SETTINGS); - } - - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.GLASS_BOTTLE, Message.forName("item-glow-setting")); + super(MenuType.SETTINGS, null, new ItemStack(Material.GLASS_BOTTLE), "glow"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java index da4fef55a..2aab9801b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java @@ -5,10 +5,11 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeConfigHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; @@ -22,6 +23,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -34,7 +36,7 @@ public class PositionSetting extends Setting implements PlayerCommand, TabComple private final boolean particleLines; public PositionSetting() { - super(MenuType.SETTINGS, true); + super(MenuType.SETTINGS, null, true, new ItemStack(Material.BLUE_BANNER), "position-setting"); particleLines = ChallengeConfigHelper.getSettingsDocument().getBoolean("position-particle-lines"); Challenges.getInstance().registerCommand(new DelPosCommand(), "delposition"); Challenges.getInstance().registerCommand(new SetPosCommand(), "setposition"); @@ -42,34 +44,28 @@ public PositionSetting() { public static Environment getWorldEnvironment(@NotNull String name) { switch (name.toLowerCase()) { - default: - return null; case "overworld": return Environment.NORMAL; case "nether": return Environment.NETHER; case "end": return Environment.THE_END; + default: + return null; } } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BLUE_BANNER, Message.forName("item-position-setting")); - } - @Override public void onCommand(@NotNull Player player, @NotNull String[] args) { if (!isEnabled()) { - Message.forName("positions-disabled").send(player, Prefix.POSITION); + MessageKey.of("positions-disabled").send(player, Prefix.POSITION); SoundSample.BASS_OFF.play(player); return; } if (args.length == 0) { if (positions.entrySet().stream().noneMatch(entry -> player.getWorld() == entry.getValue().getWorld())) { - Message.forName("no-positions").send(player, Prefix.POSITION, "position "); + MessageKey.of("no-positions").send(player, Prefix.POSITION, "position "); return; } @@ -79,21 +75,21 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) { .forEach(entry -> { Location location = entry.getValue(); - Message.forName("position").send(player, Prefix.POSITION, location.getBlockX(), location.getBlockY(), location.getBlockZ(), getWorldName(location), entry.getKey(), (int) location.distance(player.getLocation())); + MessageKey.of("position").send(player, Prefix.POSITION, location.getBlockX(), location.getBlockY(), location.getBlockZ(), getWorldName(location), entry.getKey(), (int) location.distance(player.getLocation())); }); } else if (args.length == 1) { String name = args[0].toLowerCase(); Location position = positions.get(name); if (position != null) { if (position.getWorld() != player.getLocation().getWorld()) { - Message.forName("position-other-world").send(player, Prefix.POSITION, getWorldName(position)); + MessageKey.of("position-other-world").send(player, Prefix.POSITION, getWorldName(position)); SoundSample.BASS_OFF.play(player); return; } - Message.forName("position").send(player, Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, (int) position.distance(player.getLocation())); + MessageKey.of("position").send(player, Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, (int) position.distance(player.getLocation())); playParticleLine(player, position); } else if (ChallengeAPI.isPaused()) { - Message.forName("timer-not-started").send(player, Prefix.POSITION); + MessageKey.of("timer-not-started").send(player, Prefix.POSITION); SoundSample.BASS_OFF.play(player); } else { positions.put(name, position = player.getLocation()); @@ -103,7 +99,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) { } } else { - Message.forName("syntax").send(player, Prefix.POSITION, "position [name]"); + MessageKey.of("syntax").send(player, Prefix.POSITION, "position [name]"); } } @@ -117,12 +113,12 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull Comman public String getWorldName(@NotNull Location location) { if (location.getWorld() == null) return "?"; switch (location.getWorld().getEnvironment()) { - default: - return "Overworld"; case NETHER: return "Nether"; case THE_END: return "End"; + default: + return "Overworld"; } } @@ -171,19 +167,19 @@ public class DelPosCommand implements PlayerCommand, TabCompleter { @Override public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (!isEnabled()) { - Message.forName("positions-disabled").send(player, Prefix.POSITION); + MessageKey.of("positions-disabled").send(player, Prefix.POSITION); SoundSample.BASS_OFF.play(player); return; } if (!ChallengeAPI.isStarted()) { - Message.forName("timer-not-started").send(player, Prefix.POSITION); + MessageKey.of("timer-not-started").send(player, Prefix.POSITION); SoundSample.BASS_OFF.play(player); return; } if (args.length == 0) { if (positions.isEmpty()) { - Message.forName("no-positions-global").send(player, Prefix.POSITION, "position "); + MessageKey.of("no-positions-global").send(player, Prefix.POSITION, "position "); return; } @@ -191,22 +187,22 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc .sorted(Comparator.>comparingDouble(entry -> entry.getValue().distance(player.getLocation())).reversed()) .forEach(entry -> { Location location = entry.getValue(); - Message.forName("position").send(player, Prefix.POSITION, location.getBlockX(), location.getBlockY(), location.getBlockZ(), getWorldName(location), entry.getKey(), (int) location.distance(player.getLocation())); + MessageKey.of("position").send(player, Prefix.POSITION, location.getBlockX(), location.getBlockY(), location.getBlockZ(), getWorldName(location), entry.getKey(), (int) location.distance(player.getLocation())); }); } else if (args.length == 1) { String name = args[0].toLowerCase(); Location position = positions.get(name); if (position != null) { positions.remove(name); - Message.forName("position-deleted").broadcast(Prefix.POSITION, + MessageKey.of("position-deleted").broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, NameHelper.getName(player)); } else { - Message.forName("position-not-exists").send(player, Prefix.POSITION); + MessageKey.of("position-not-exists").send(player, Prefix.POSITION); } } else { - Message.forName("syntax").send(player, Prefix.POSITION, "delposition "); + MessageKey.of("syntax").send(player, Prefix.POSITION, "delposition "); } } @@ -225,25 +221,25 @@ public class SetPosCommand implements PlayerCommand, TabCompleter { @Override public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (!isEnabled()) { - Message.forName("positions-disabled").send(player, Prefix.POSITION); + MessageKey.of("positions-disabled").send(player, Prefix.POSITION); SoundSample.BASS_OFF.play(player); return; } if (!ChallengeAPI.isStarted()) { - Message.forName("timer-not-started").send(player, Prefix.POSITION); + MessageKey.of("timer-not-started").send(player, Prefix.POSITION); SoundSample.BASS_OFF.play(player); return; } if (args.length < 5) { - Message.forName("syntax").send(player, Prefix.POSITION, "setposition "); + MessageKey.of("syntax").send(player, Prefix.POSITION, "setposition "); return; } String name = args[0].toLowerCase(); if (positions.containsKey(name)) { - Message.forName("position-already-exists").send(player, Prefix.POSITION, name); + MessageKey.of("position-already-exists").send(player, Prefix.POSITION, name); return; } @@ -262,14 +258,14 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc Location position = new Location(world, doubleX, doubleY, doubleZ); positions.put(name, position); - Message.forName("position-set") + MessageKey.of("position-set") .broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, NameHelper.getName(player)); SoundSample.BASS_ON.play(player); broadcastParticleLine(position); } catch (Exception exception) { - Message.forName("syntax").send(player, Prefix.POSITION, "setposition "); + MessageKey.of("syntax").send(player, Prefix.POSITION, "setposition "); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java index a2d56e67c..8b51b3c42 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java @@ -4,19 +4,20 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class PregameMovementSetting extends Setting { public PregameMovementSetting() { - super(MenuType.SETTINGS, true); + super(MenuType.SETTINGS, null, true, new ItemStack(Material.PISTON), "pregame-movement"); } @EventHandler @@ -47,10 +48,4 @@ private void findNearestBlock(@NotNull Location location) { ; } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.PISTON, Message.forName("pregame-movement-setting")); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java index b43339481..8f2532f07 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java @@ -4,22 +4,17 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.spigot.events.EntityDamageByPlayerEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class PvPSetting extends Setting { public PvPSetting() { - super(MenuType.SETTINGS, true); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.STONE_SWORD, Message.forName("item-pvp-setting")); + super(MenuType.SETTINGS, null, true, new ItemStack(Material.STONE_SWORD), "pvp-setting"); } @EventHandler diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java index 538be7125..bfd7ef534 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java @@ -3,10 +3,11 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -14,29 +15,34 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class RegenerationSetting extends Modifier { + public static final int DISABLED = 1, ENABLED = 2, NOT_NATURAL = 3; + public RegenerationSetting() { - super(MenuType.SETTINGS, 1, 3, 2); + super(MenuType.SETTINGS, null, 1, 3, ENABLED, + new StandardItemBuilder.PotionBuilder(Material.POTION).setColor(Color.RED).build(), "item-regeneration-setting"); } @NotNull @Override - public ItemBuilder createDisplayItem() { - return new PotionBuilder(Material.POTION, Message.forName("item-regeneration-setting")).color(Color.RED); + public ItemStack getSettingsItemPreset() { + if (getValue() == ENABLED) { + return DefaultItems.createEnabledPreset(); + } + return new ItemStack(Material.ORANGE_DYE); } @NotNull @Override - public ItemBuilder createSettingsItem() { - if (getValue() == 1) { - return DefaultItem.disabled(); - } else if (getValue() == 2) { - return DefaultItem.enabled(); + public LocalizableMessage getSettingsName() { + if (getValue() == NOT_NATURAL) { + return MessageKey.of("item-regeneration-setting-not_natural"); } - return DefaultItem.create(Material.ORANGE_DYE, Message.forName("item-regeneration-setting-not_natural")); + return MessageKey.of("enabled"); } @Override @@ -48,17 +54,22 @@ public void playValueChangeTitle() { ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 2 ? Message.forName("enabled") : Message.forName("item-regeneration-setting-not_natural")); } + @Override + public boolean isEnabled() { + return getValue() != DISABLED; + } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onEntityRegainHealth(EntityRegainHealthEvent event) { if (!(event.getEntity() instanceof Player)) return; - if (getValue() == 1) { + if (getValue() == DISABLED) { event.setAmount(0); event.setCancelled(true); return; } - if (getValue() == 3) { + if (getValue() == NOT_NATURAL) { if (event.getRegainReason() == RegainReason.SATIATED || event.getRegainReason() == RegainReason.REGEN) { event.setAmount(0); event.setCancelled(true); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java index 0331fbb61..1608e0751 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RespawnSetting.java @@ -3,10 +3,8 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -18,6 +16,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -28,13 +27,7 @@ public class RespawnSetting extends Setting { private final Map locationsBeforeRespawn = new ConcurrentHashMap<>(); public RespawnSetting() { - super(MenuType.SETTINGS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.RED_BED, Message.forName("item-respawn-setting")); + super(MenuType.SETTINGS, null, new ItemStack(Material.RED_BED), "respawn"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java index 4a7dc4fba..cd7e4187d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java @@ -3,13 +3,12 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -28,13 +27,7 @@ public class SlotLimitSetting extends Modifier { public SlotLimitSetting() { - super(MenuType.SETTINGS, 1, 36, 36); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.BARRIER, Message.forName("item-slot-limit-setting")); + super(MenuType.SETTINGS, null, 1, 36, 36, new ItemStack(Material.BARRIER), "slot-limit"); } @Override @@ -84,7 +77,7 @@ private void blockSlot(@NotNull Player player, int slot) { if (ignorePlayer(player)) return; ItemStack item = player.getInventory().getItem(slot); - if (item != null && !item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { + if (item != null && !item.isSimilar(LegacyItemBuilder.BLOCKED_ITEM)) { if (!Bukkit.isPrimaryThread()) { Bukkit.getScheduler().runTask(plugin, () -> { player.getWorld().dropItemNaturally(player.getLocation(), item); @@ -93,12 +86,12 @@ private void blockSlot(@NotNull Player player, int slot) { player.getWorld().dropItemNaturally(player.getLocation(), item); } } - player.getInventory().setItem(slot, ItemBuilder.BLOCKED_ITEM); + player.getInventory().setItem(slot, LegacyItemBuilder.BLOCKED_ITEM); } private void unBlockSlot(@NotNull Player player, int slot) { ItemStack item = player.getInventory().getItem(slot); - if (item != null && item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { + if (item != null && item.isSimilar(LegacyItemBuilder.BLOCKED_ITEM)) { player.getInventory().setItem(slot, null); } } @@ -117,7 +110,7 @@ public void onPlayerInventoryClick(@NotNull PlayerInventoryClickEvent event) { public void onPlayerDropItem(@NotNull PlayerDropItemEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; - if (!event.getItemDrop().getItemStack().isSimilar(ItemBuilder.BLOCKED_ITEM)) return; + if (!event.getItemDrop().getItemStack().isSimilar(LegacyItemBuilder.BLOCKED_ITEM)) return; event.setCancelled(true); } @@ -125,7 +118,7 @@ public void onPlayerDropItem(@NotNull PlayerDropItemEvent event) { public void onClick(@NotNull BlockPlaceEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; - if (!event.getItemInHand().isSimilar(ItemBuilder.BLOCKED_ITEM)) return; + if (!event.getItemInHand().isSimilar(LegacyItemBuilder.BLOCKED_ITEM)) return; event.setCancelled(true); } @@ -134,16 +127,16 @@ public void onSwapItem(@NotNull PlayerSwapHandItemsEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; - if (event.getMainHandItem() != null && event.getMainHandItem().isSimilar(ItemBuilder.BLOCKED_ITEM)) { + if (event.getMainHandItem() != null && event.getMainHandItem().isSimilar(LegacyItemBuilder.BLOCKED_ITEM)) { event.setCancelled(true); - } else if (event.getOffHandItem() != null && event.getOffHandItem().isSimilar(ItemBuilder.BLOCKED_ITEM)) { + } else if (event.getOffHandItem() != null && event.getOffHandItem().isSimilar(LegacyItemBuilder.BLOCKED_ITEM)) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGH) public void onPlayerDeath(@NotNull PlayerDeathEvent event) { - event.getDrops().removeIf(itemStack -> itemStack.isSimilar(ItemBuilder.BLOCKED_ITEM)); + event.getDrops().removeIf(itemStack -> itemStack.isSimilar(LegacyItemBuilder.BLOCKED_ITEM)); } @EventHandler(priority = EventPriority.HIGH) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java index 4bc199d27..3fe66bb7c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.GameMode; @@ -12,19 +12,14 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.jetbrains.annotations.NotNull; public class SoupSetting extends Setting { public SoupSetting() { - super(MenuType.SETTINGS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MUSHROOM_STEW, Message.forName("item-soup-setting")); + super(MenuType.SETTINGS, null, new ItemStack(Material.MUSHROOM_STEW), "setting-soup"); } @EventHandler @@ -40,7 +35,7 @@ public void onInteract(PlayerInteractEvent event) { if (player.getHealth() == player.getMaxHealth()) return; player.addPotionEffect(new PotionEffect(MinecraftNameWrapper.INSTANT_HEALTH, 1, 1)); - player.getInventory().setItemInMainHand(new ItemBuilder(Material.BOWL).build()); + player.getInventory().setItemInMainHand(new ItemStack(Material.BOWL)); player.updateInventory(); SoundSample.EAT.play(player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index 38b2ad2bb..cabf73b6b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -2,11 +2,9 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Color; import org.bukkit.Material; @@ -23,13 +21,7 @@ public class SplitHealthSetting extends Setting { public SplitHealthSetting() { - super(MenuType.SETTINGS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new PotionBuilder(Material.TIPPED_ARROW, Message.forName("item-split-health-setting")).color(Color.RED); + super(MenuType.SETTINGS, null, new StandardItemBuilder.PotionBuilder(Material.TIPPED_ARROW).setColor(Color.RED).build(), "item-split-health-setting"); } @Override @@ -102,7 +94,7 @@ public void setHealth(@NotNull Player player, @Nullable EntityDamageEvent damage } - @SuppressWarnings({"deprecation", "removal"}) + @SuppressWarnings({"removal"}) private void tryApplyLastDamageCause(Player player, EntityDamageEvent damageEvent) { // marked for removal in api version 1.20.4 with no apparent replacement? try { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java index 0c0f63541..80dde9378 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java @@ -4,9 +4,11 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.commons.bukkit.utils.item.ItemUtils; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; @@ -27,23 +29,22 @@ public class TimberSetting extends SettingModifier { public static final int LOGS_LEAVES = 2; - public TimberSetting() { - super(MenuType.SETTINGS, 2); + super(MenuType.SETTINGS, null, 2, new ItemStack(Material.DIAMOND_AXE), "item-timber-setting"); } @NotNull @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.DIAMOND_AXE, Message.forName("item-timber-setting")); + public ItemStack getSettingsItemPreset() { + if (getValue() == LOGS_LEAVES) + return new ItemStack(Material.OAK_LEAVES); + return new ItemStack(Material.OAK_LOG); } @NotNull @Override - public ItemBuilder createSettingsItem() { - if (getValue() == LOGS_LEAVES) - return DefaultItem.create(Material.OAK_LEAVES, Message.forName("item-timber-setting-logs-and-leaves")); - return DefaultItem.create(Material.OAK_LOG, Message.forName("item-timber-setting-logs")); + public LocalizableMessage getSettingsName() { + return getValue() == LOGS_LEAVES ? MessageKey.of("item-timber-setting-logs-and-leaves") : MessageKey.of("item-timber-setting-logs"); } @Override @@ -105,7 +106,7 @@ private List getAllTreeBlocks(@NotNull Block block, boolean leaves) { if (BukkitReflectionUtils.isAir(blockAround.getType())) continue; if (allBlocks.contains(blockAround)) continue; - if (currentBlock.getType() == blockAround.getType() || (leaves && isLeaveMaterial(currentBlock.getType(), blockAround.getType()))) { + if (currentBlock.getType() == blockAround.getType() || (leaves && isLeafMaterial(currentBlock.getType(), blockAround.getType()))) { allBlocks.add(blockAround); currentBlocks.add(blockAround); } @@ -129,17 +130,17 @@ private boolean isLeaves(Material material) { return material.name().endsWith("LEAVES") || material.name().endsWith("WART_BLOCK"); } - public boolean isLeaveMaterial(@NotNull Material logMaterial, @NotNull Material leaveMaterial) { + public boolean isLeafMaterial(@NotNull Material logMaterial, @NotNull Material leafMaterial) { // Exceptions like nether wood if (logMaterial.name().equals("CRIMSON_STEM")) - return leaveMaterial.name().equals("NETHER_WART_BLOCK") || leaveMaterial.name().equals("SHROOMLIGHT"); + return leafMaterial.name().equals("NETHER_WART_BLOCK") || leafMaterial.name().equals("SHROOMLIGHT"); if (logMaterial.name().equals("WARPED_STEM")) - return leaveMaterial.name().equals("WARPED_WART_BLOCK") || leaveMaterial.name().equals("SHROOMLIGHT"); + return leafMaterial.name().equals("WARPED_WART_BLOCK") || leafMaterial.name().equals("SHROOMLIGHT"); int firstUnderscore = logMaterial.name().indexOf("_"); if (firstUnderscore == -1) return false; String logPrefix = logMaterial.name().substring(0, firstUnderscore); - return leaveMaterial.name().startsWith(logPrefix) && leaveMaterial.name().endsWith("LEAVES"); + return leafMaterial.name().startsWith(logPrefix) && leafMaterial.name().endsWith("LEAVES"); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java index bd3611a5c..882b1e602 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java @@ -2,29 +2,29 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public class TopCommandSetting extends Setting implements PlayerCommand { public TopCommandSetting() { - super(MenuType.SETTINGS); + super(MenuType.SETTINGS, null, new ItemStack(Material.MAGENTA_GLAZED_TERRACOTTA), "top-command-setting"); } @Override public void onCommand(@NotNull Player player, @NotNull String[] args) { if (!isEnabled()) { - Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); + MessageKey.of("feature-disabled").send(player, Prefix.CHALLENGES); SoundSample.BASS_OFF.play(player); return; } @@ -33,7 +33,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) { Environment environment = world.getEnvironment(); Location playerLocation = player.getLocation(); if (environment == Environment.NORMAL) { - Message.forName("top-to-surface").send(player, Prefix.CHALLENGES); + MessageKey.of("top-to-surface").send(player, Prefix.CHALLENGES); Location location = player.getWorld().getHighestBlockAt(playerLocation).getLocation().add(0.5, 1, 0.5); location.setYaw(playerLocation.getYaw()); @@ -42,7 +42,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) { player.teleport(location); } else { - Message.forName("top-to-overworld").send(player, Prefix.CHALLENGES); + MessageKey.of("top-to-overworld").send(player, Prefix.CHALLENGES); if (environment == Environment.NETHER) { Location location = playerLocation.clone(); @@ -65,10 +65,4 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) { } - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.MAGENTA_GLAZED_TERRACOTTA, Message.forName("top-command-setting")); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java index 520a315ee..392170d65 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java @@ -3,26 +3,19 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityResurrectEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @Since("2.0") public class TotemSaveDeathSetting extends Setting { public TotemSaveDeathSetting() { - super(MenuType.SETTINGS); - } - - @NotNull - @Override - public ItemBuilder createDisplayItem() { - return new ItemBuilder(Material.TOTEM_OF_UNDYING, Message.forName("item-totem-save-setting")); + super(MenuType.SETTINGS, null, new ItemStack(Material.TOTEM_OF_UNDYING), "setting-totem-save-death"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java deleted file mode 100644 index d51dc9156..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/EmptyChallenge.java +++ /dev/null @@ -1,98 +0,0 @@ -package net.codingarea.challenges.plugin.challenges.type; - -import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; -import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.config.Document; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class EmptyChallenge implements IChallenge { - - private final MenuType menuType; - - public EmptyChallenge(@NotNull MenuType menuType) { - this.menuType = menuType; - } - - @Override - public boolean isEnabled() { - return false; - } - - @Override - public void restoreDefaults() { - - } - - @Override - public void handleShutdown() { - - } - - @NotNull - @Override - public String getUniqueGamestateName() { - return getUniqueName(); - } - - @NotNull - @Override - public String getUniqueName() { - return "empty"; - } - - @NotNull - @Override - public MenuType getType() { - return menuType; - } - - @Nullable - @Override - public SettingCategory getCategory() { - return null; - } - - @NotNull - @Override - public ItemStack getDisplayItem() { - return new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, "§0").build(); - } - - @NotNull - @Override - public ItemStack getSettingsItem() { - return new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, "§0").build(); - } - - @Override - public void handleClick(@NotNull ChallengeMenuClickInfo info) { - SoundSample.CLICK.play(info.getPlayer()); - } - - @Override - public void writeSettings(@NotNull Document document) { - - } - - @Override - public void loadSettings(@NotNull Document document) { - - } - - @Override - public void writeGameState(@NotNull Document document) { - - } - - @Override - public void loadGameState(@NotNull Document document) { - - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java index c540894bb..916b9a58c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IChallenge.java @@ -1,15 +1,18 @@ package net.codingarea.challenges.plugin.challenges.type; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.challenges.ChallengeManager; import net.codingarea.challenges.plugin.management.challenges.entities.GamestateSaveable; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.common.config.Document; -import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.Locale; + public interface IChallenge extends GamestateSaveable { /** @@ -63,10 +66,16 @@ public interface IChallenge extends GamestateSaveable { SettingCategory getCategory(); @NotNull - ItemStack getDisplayItem(); + ItemBuilder getDisplayItem(@NotNull Locale locale); + + @NotNull + ItemBuilder getSettingsItem(@NotNull Locale locale); + + @NotNull + LocalizableMessage getChallengeName(); @NotNull - ItemStack getSettingsItem(); + LocalizableMessage getChallengeDescription(); void handleClick(@NotNull ChallengeMenuClickInfo info); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java index a9ca3c100..343ab0fb4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java @@ -1,17 +1,18 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import lombok.Getter; -import lombok.Setter; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeScoreboard; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.common.annotations.DeprecatedSince; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; @@ -19,10 +20,12 @@ import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.CheckReturnValue; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; +import java.util.Locale; import java.util.Map; import java.util.UUID; import java.util.function.Consumer; @@ -43,17 +46,24 @@ public abstract class AbstractChallenge implements IChallenge, Listener { } protected final MenuType menu; + protected final SettingCategory category; @Getter protected final ChallengeBossBar bossbar = new ChallengeBossBar(); @Getter protected final ChallengeScoreboard scoreboard = new ChallengeScoreboard(); - @Setter - protected SettingCategory category; - private String name; - private ItemStack cachedDisplayItem; + @Getter + protected ItemStack displayItemPreset; + + @Getter + private final String nameMessageKey; + private String uniqueName; - public AbstractChallenge(@NotNull MenuType menu) { + public AbstractChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { this.menu = menu; + this.category = category; + this.displayItemPreset = displayItemPreset; + this.nameMessageKey = nameMessageKey; firstInstanceByClass.put(this.getClass(), this); } @@ -62,10 +72,12 @@ public static C getFirstInstance(@NotNull Class return classOfChallenge.cast(firstInstanceByClass.get(classOfChallenge)); } + // TODO extract public static void broadcast(@NotNull Consumer action) { Bukkit.getOnlinePlayers().forEach(action); } + // TODO extract public static void broadcastFiltered(@NotNull Consumer action) { for (Player player : Bukkit.getOnlinePlayers()) { if (ignorePlayer(player)) continue; @@ -73,6 +85,7 @@ public static void broadcastFiltered(@NotNull Consumer action) { } } + // TODO extract public static void broadcastIgnored(@NotNull Consumer action) { for (Player player : Bukkit.getOnlinePlayers()) { if (!ignorePlayer(player)) continue; @@ -80,10 +93,14 @@ public static void broadcastIgnored(@NotNull Consumer action) { } } + // TODO extract + @CheckReturnValue public static boolean ignorePlayer(@NotNull Player player) { return ignoreGameMode(player.getGameMode()); } + // TODO extract + @CheckReturnValue public static boolean ignoreGameMode(@NotNull GameMode gameMode) { return (isIgnoreSpectatorPlayers() && gameMode == GameMode.SPECTATOR) || (isIgnoreCreativePlayers() && gameMode == GameMode.CREATIVE); } @@ -105,46 +122,94 @@ protected final void updateItems() { @NotNull @Override - public ItemStack getDisplayItem() { - if (cachedDisplayItem != null) return cachedDisplayItem.clone(); - cachedDisplayItem = createDisplayItem().build(); - return cachedDisplayItem.clone(); + public ItemBuilder getDisplayItem(@NotNull Locale locale) { + return new ItemBuilder(locale, displayItemPreset, MessageKey.of("challenge.display-format"), + getChallengeName(), getChallengeDescription()); + } + + /** + * @implSpec If overridden, use {@link MessageKey#withArgs(Object...)} for placeholders + */ + @NotNull + @Override + public LocalizableMessage getChallengeName() { + return getChallengeMessageKey("name"); } + /** + * @implSpec If overridden, use {@link MessageKey#withArgs(Object...)} for placeholders + */ @NotNull @Override - public ItemStack getSettingsItem() { - ItemBuilder item = createSettingsItem(); - String[] description = getSettingsDescription(); + public LocalizableMessage getChallengeDescription() { + return getChallengeMessageKey("desc"); + } + + @NotNull + protected MessageKey getChallengeMessageKey(@NotNull String messageNameSuffix) { + return MessageKey.of("challenge." + nameMessageKey + "." + messageNameSuffix); + } + + @NotNull + @Override + public ItemBuilder getSettingsItem(@NotNull Locale locale) { + ItemStack preset = isEnabled() ? getSettingsItemPreset() : getDisabledSettingsItemPreset(); + // apply formatting dynamically, to prevent duplicate format references + ItemBuilder item = new ItemBuilder(locale, preset, MessageKey.of("challenge.settings-format"), + isEnabled() ? getSettingsName() : MessageKey.of("disabled")); // no need to override disabled name/item + + LocalizableMessage description = getSettingsDescription(); if (description != null && isEnabled()) { - item.appendLore(" "); - item.appendLore(description); + item.appendLore(MessageKey.of("challenge.settings-format-lore"), description); } - return item.build(); + return item; } - @Nullable - protected String[] getSettingsDescription() { - return null; + @NotNull + protected ItemStack getDisabledSettingsItemPreset() { + return DefaultItems.createDisabledPreset(); } + /** + * @implNote Only used if {@link #isEnabled()}. + * Name/Lore will be overwritten by formatting. + * Set name in {@link #getSettingsName()} and lore in {@link #getSettingsDescription()} + */ @NotNull - public abstract ItemBuilder createDisplayItem(); + public ItemStack getSettingsItemPreset() { + return DefaultItems.createEnabledPreset(); + } + /** + * @implNote Only used if {@link #isEnabled()}, format will be applied dynamically + */ @NotNull - public abstract ItemBuilder createSettingsItem(); + public LocalizableMessage getSettingsName() { + return MessageKey.of("enabled"); + } + + /** + * @implNote Only used if {@link #isEnabled()}, format will be applied dynamically + */ + @Nullable + public LocalizableMessage getSettingsDescription() { + return null; + } + /** + * @implSpec override {@link #getUniqueName()} instead + */ @NotNull @Override - public String getUniqueGamestateName() { + public final String getUniqueGamestateName() { return getUniqueName(); } @NotNull @Override public String getUniqueName() { - return name != null ? name : (name = getClass().getSimpleName().toLowerCase() + return uniqueName != null ? uniqueName : (uniqueName = getClass().getSimpleName().toLowerCase() .replace("setting", "") .replace("challenge", "") .replace("modifier", "") @@ -176,25 +241,6 @@ protected boolean shouldExecuteEffect() { return isEnabled() && ChallengeAPI.isStarted() && !ChallengeAPI.isWorldInUse(); } - /** - * @deprecated Use {@link ChallengeHelper#kill(Player)} - */ - @Deprecated - @DeprecatedSince("2.1.0") - public void kill(@NotNull Player player) { - ChallengeHelper.kill(player); - } - - /** - * @deprecated Use {@link ChallengeHelper#kill(Player, int)} - */ - @Deprecated - @DeprecatedSince("2.1.0") - public void kill(@NotNull Player player, int delay) { - ChallengeHelper.kill(player, delay); - - } - @NotNull protected final Document getGameStateData() { return plugin.getConfigManager().getGamestateConfig().getDocument(this.getUniqueGamestateName()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java index 21c67067b..4c6c883df 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractForceChallenge.java @@ -2,36 +2,41 @@ import lombok.Setter; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.function.BiConsumer; @Setter public abstract class AbstractForceChallenge extends TimedChallenge { - public static final int WAITING = 0, - COUNTDOWN = 1; + public static final int WAITING = 0, COUNTDOWN = 1; private int state = WAITING; - public AbstractForceChallenge(@NotNull MenuType menu) { - super(menu, false); + public AbstractForceChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, false, displayItemPreset, nameMessageKey); } - public AbstractForceChallenge(@NotNull MenuType menu, int max) { - super(menu, max, false); + public AbstractForceChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, int max, @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, max, false, displayItemPreset, nameMessageKey); } - public AbstractForceChallenge(@NotNull MenuType menu, int min, int max) { - super(menu, min, max, false); + public AbstractForceChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, min, max, false, displayItemPreset, nameMessageKey); } - public AbstractForceChallenge(@NotNull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue, false); + public AbstractForceChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, int defaultValue, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, min, max, defaultValue, false, displayItemPreset, nameMessageKey); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java index 8ab7c519f..3d081dd67 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CollectionGoal.java @@ -2,12 +2,15 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.Map.Entry; @@ -19,13 +22,15 @@ public abstract class CollectionGoal extends SettingGoal { private final Map> collections = new HashMap<>(); protected Object[] target; - public CollectionGoal(@NotNull Object[] target) { - super(); + public CollectionGoal(@Nullable SettingCategory category, @NotNull ItemStack displayItemPreset, + @NotNull String nameMessageKey, @NotNull Object[] target) { + super(category, displayItemPreset, nameMessageKey); this.target = target; } - public CollectionGoal(boolean enabledByDefault, @NotNull Object[] target) { - super(enabledByDefault); + public CollectionGoal(@Nullable SettingCategory category, boolean enabledByDefault, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey, @NotNull Object[] target) { + super(category, enabledByDefault, displayItemPreset, nameMessageKey); this.target = target; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java index 0368e524f..bcf768f9a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/CompletableForceChallenge.java @@ -2,27 +2,34 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public abstract class CompletableForceChallenge extends AbstractForceChallenge { - public CompletableForceChallenge(@NotNull MenuType menu) { - super(menu); + public CompletableForceChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, displayItemPreset, nameMessageKey); } - public CompletableForceChallenge(@NotNull MenuType menu, int max) { - super(menu, max); + public CompletableForceChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, int max, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, max, displayItemPreset, nameMessageKey); } - public CompletableForceChallenge(@NotNull MenuType menu, int min, int max) { - super(menu, min, max); + public CompletableForceChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, min, max, displayItemPreset, nameMessageKey); } - public CompletableForceChallenge(@NotNull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue); + public CompletableForceChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, int defaultValue, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, min, max, defaultValue, displayItemPreset, nameMessageKey); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java index f7d079be4..6accd5a3c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/EndingForceChallenge.java @@ -3,30 +3,37 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; public abstract class EndingForceChallenge extends AbstractForceChallenge { - public EndingForceChallenge(@NotNull MenuType menu) { - super(menu); + public EndingForceChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, displayItemPreset, nameMessageKey); } - public EndingForceChallenge(@NotNull MenuType menu, int max) { - super(menu, max); + public EndingForceChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, int max, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, max, displayItemPreset, nameMessageKey); } - public EndingForceChallenge(@NotNull MenuType menu, int min, int max) { - super(menu, min, max); + public EndingForceChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, min, max, displayItemPreset, nameMessageKey); } - public EndingForceChallenge(@NotNull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue); + public EndingForceChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, int defaultValue, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, min, max, defaultValue, displayItemPreset, nameMessageKey); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java index 7cb6a5850..f11bcbdc6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FindItemGoal.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import net.codingarea.challenges.plugin.ChallengeAPI; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; @@ -10,6 +11,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; @@ -18,7 +20,9 @@ public abstract class FindItemGoal extends SettingGoal { private final Material searchedItem; - public FindItemGoal(Material searchedItem) { + public FindItemGoal(@Nullable SettingCategory category, @NotNull Material searchedItem, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(category, displayItemPreset, nameMessageKey); this.searchedItem = searchedItem; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java index 3db44282e..b94b42682 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java @@ -3,14 +3,17 @@ import lombok.Getter; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; @@ -20,6 +23,10 @@ public abstract class FirstPlayerAtHeightGoal extends SettingGoal { private int heightToGetTo; + public FirstPlayerAtHeightGoal(@Nullable SettingCategory category, @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(category, displayItemPreset, nameMessageKey); + } + @Override protected void onEnable() { bossbar.setContent((bar, player) -> { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java index 139d16b87..ec0dd1da9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java @@ -13,6 +13,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.HashMap; @@ -23,8 +24,8 @@ public abstract class ForceBattleDisplayGoal> extends F private Map displayStands; - public ForceBattleDisplayGoal(@NotNull Message title) { - super(title); + public ForceBattleDisplayGoal(@NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(displayItemPreset, nameMessageKey); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java index 4fa3c78f2..cd99c3e5d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java @@ -2,15 +2,16 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ForceTarget; +import net.codingarea.challenges.plugin.challenges.type.abstraction.menu.MenuGoal; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -45,33 +46,33 @@ public abstract class ForceBattleGoal> extends MenuGoal protected T[] targetsPossibleToFind; private ItemStack jokerItem; - public ForceBattleGoal(@NotNull Message title) { - super(MenuType.GOAL, title); - setCategory(SettingCategory.FORCE_BATTLE); - - registerSetting("jokers", new NumberSubSetting( - () -> new ItemBuilder(Material.BARRIER, Message.forName("item-force-battle-goal-jokers")), - value -> null, - value -> "§e" + value, - 1, - 32, - 5 - )); - registerSetting("showScoreboard", new BooleanSubSetting( - () -> new ItemBuilder(Material.BOOK, Message.forName("item-force-battle-show-scoreboard")), - true - )); - if (shouldRegisterDupedTargetsSetting()) { - registerSetting("dupedTargets", new BooleanSubSetting( - () -> new ItemBuilder(Material.PAPER, Message.forName("item-force-battle-duped-targets")), - true - )); - } + public ForceBattleGoal(@NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(MenuType.GOAL, SettingCategory.FORCE_BATTLE, displayItemPreset, nameMessageKey); + + // TODO ! +// registerSetting("jokers", new NumberSubSetting( +// () -> new LegacyItemBuilder(Material.BARRIER, Message.forName("item-force-battle-goal-jokers")), +// value -> null, +// value -> "§e" + value, +// 1, +// 32, +// 5 +// )); +// registerSetting("showScoreboard", new BooleanSubSetting( +// () -> new LegacyItemBuilder(Material.BOOK, Message.forName("item-force-battle-show-scoreboard")), +// true +// )); +// if (shouldRegisterDupedTargetsSetting()) { +// registerSetting("dupedTargets", new BooleanSubSetting( +// () -> new LegacyItemBuilder(Material.PAPER, Message.forName("item-force-battle-duped-targets")), +// true +// )); +// } } @Override protected void onEnable() { - jokerItem = new ItemBuilder(Material.BARRIER, "§cJoker").build(); + jokerItem = new LegacyItemBuilder(Material.BARRIER, "§cJoker").build(); targetsPossibleToFind = getTargetsPossibleToFind(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java index 67a9a2da6..99df1711e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/HydraChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDeathByPlayerEvent; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; @@ -11,16 +12,20 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public abstract class HydraChallenge extends Setting { - public HydraChallenge(@NotNull MenuType menu) { - super(menu); + public HydraChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, displayItemPreset, nameMessageKey); } - public HydraChallenge(@NotNull MenuType menu, boolean enabledByDefault) { - super(menu, enabledByDefault); + public HydraChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, boolean enabledByDefault, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, enabledByDefault, displayItemPreset, nameMessageKey); } public abstract int getNewMobsCount(@NotNull EntityType entityType); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java index 1882175b9..e4fdead75 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java @@ -2,7 +2,9 @@ import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -10,24 +12,28 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; public abstract class ItemCollectionGoal extends CollectionGoal { - public ItemCollectionGoal(@NotNull Material... target) { - super(target); + public ItemCollectionGoal(@Nullable SettingCategory category, @NotNull ItemStack displayItemPreset, + @NotNull String nameMessageKey, @NotNull Material... target) { + super(category, displayItemPreset, nameMessageKey, target); } - public ItemCollectionGoal(boolean enabledByDefault, @NotNull Material... target) { - super(enabledByDefault, target); + public ItemCollectionGoal(@Nullable SettingCategory category, boolean enabledByDefault, @NotNull ItemStack displayItemPreset, + @NotNull String nameMessageKey, @NotNull Material... target) { + super(category, enabledByDefault, displayItemPreset, nameMessageKey, target); } protected void handleCollect(@NotNull Player player, @NotNull Material material) { collect(player, material, () -> { - Message.forName("item-collected").send(player, Prefix.CHALLENGES, material); + MessageKey.of("item-collected").send(player, Prefix.CHALLENGES, material); SoundSample.PLING.play(player); }); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java index bdb27f584..3e8d9e42d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillEntityGoal.java @@ -2,6 +2,7 @@ import lombok.Setter; import net.codingarea.challenges.plugin.ChallengeAPI; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import org.bukkit.World.Environment; import org.bukkit.entity.EntityType; @@ -10,7 +11,9 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.List; @@ -23,20 +26,24 @@ public abstract class KillEntityGoal extends SettingGoal { protected boolean killerNeeded = false; protected Player winner; - public KillEntityGoal(@NotNull EntityType entity) { - this(entity, false); + public KillEntityGoal(@Nullable SettingCategory category, @NotNull EntityType entity, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + this(category, entity, false, displayItemPreset, nameMessageKey); } - public KillEntityGoal(@NotNull EntityType entity, boolean enabledByDefault) { - this(entity, null, enabledByDefault); + public KillEntityGoal(@Nullable SettingCategory category, @NotNull EntityType entity, boolean enabledByDefault, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + this(category, entity, null, enabledByDefault, displayItemPreset, nameMessageKey); } - public KillEntityGoal(EntityType entity, Environment world) { - this(entity, world, false); + public KillEntityGoal(@Nullable SettingCategory category, @NotNull EntityType entity, @Nullable Environment world, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + this(category, entity, world, false, displayItemPreset, nameMessageKey); } - public KillEntityGoal(EntityType entity, Environment world, boolean enabledByDefault) { - super(enabledByDefault); + public KillEntityGoal(@Nullable SettingCategory category, @NotNull EntityType entity, @Nullable Environment world, boolean enabledByDefault, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(category, enabledByDefault, displayItemPreset, nameMessageKey); this.entity = entity; this.environment = world; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java index 13a0e61cc..85f8cf92a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java @@ -2,7 +2,8 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.commons.common.config.Document; import org.bukkit.boss.BarColor; @@ -11,7 +12,9 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.LinkedList; import java.util.List; @@ -22,7 +25,9 @@ public abstract class KillMobsGoal extends SettingGoal { protected final List entitiesToKill; - public KillMobsGoal(List entitiesKilled) { + public KillMobsGoal(@Nullable SettingCategory category, @NotNull List entitiesKilled, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(category, displayItemPreset, nameMessageKey); this.entitiesToKill = entitiesKilled; resetEntitiesToKill(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java deleted file mode 100644 index 08a962e15..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuSetting.java +++ /dev/null @@ -1,628 +0,0 @@ -package net.codingarea.challenges.plugin.challenges.type.abstraction; - -import lombok.Getter; -import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; -import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.SettingsMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import net.codingarea.commons.bukkit.utils.menu.positions.EmptyMenuPosition; -import net.codingarea.commons.common.config.Document; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.Listener; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.*; -import java.util.Map.Entry; -import java.util.function.Function; -import java.util.function.Supplier; - -public abstract class MenuSetting extends Setting { - - private final Map settings = new LinkedHashMap<>(); - private final List inventories = new ArrayList<>(); - private final Message title; - - public MenuSetting(@NotNull MenuType menu, @NotNull Message title) { - super(menu); - this.title = title; - } - - @NotNull - public static int[] getSlots(int amount) { - switch (amount) { - default: - return new int[0]; - case 1: - return new int[]{13}; - case 2: - return new int[]{12, 14}; - case 3: - return new int[]{11, 13, 15}; - case 4: - return new int[]{10, 12, 14, 16}; - } - } - - protected final void generateInventories() { - - inventories.clear(); - - int maxRowLength = 4; - int page = 0; - int index = 0; - - Collection settings = this.settings.values(); - - int pagesTotal = settings.size() / maxRowLength; - if (settings.size() % maxRowLength != 0) pagesTotal++; - - for (SubSetting setting : settings) { - - if (index >= maxRowLength) { - index = 0; - createNewInventory(++page, pagesTotal); - } else if (inventories.isEmpty()) { - createNewInventory(page, pagesTotal); - } - - int added = page * maxRowLength + index; - int left = settings.size() - added; - int fitOnThisPage = index + left; - if (fitOnThisPage > 4) fitOnThisPage = 4; - - int[] slots = getSlots(fitOnThisPage); - - int displaySlot = slots[index]; - - setting.setPage(page); - setting.setSlot(displaySlot); - setting.updateItems(); - - index++; - - } - - InventoryUtils.setNavigationItemsToInventory(inventories, SettingsMenuGenerator.NAVIGATION_SLOTS, true); - - } - - @NotNull - private Inventory createNewInventory(int page, int pagesAmount) { - Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, SettingsMenuGenerator.SIZE, InventoryTitleManager.getMenuSettingTitle(getType(), title.asString(), page, pagesAmount > 1)); - InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); - inventories.add(inventory); - return inventory; - } - - protected final void registerSetting(@NotNull String name, @NotNull SubSetting setting) { - if (name.equals("enabled")) throw new IllegalArgumentException(); - settings.put(name, setting); - Challenges.getInstance().registerListener(setting); - } - - public final SubSetting getSetting(@NotNull String name) { - return settings.get(name); - } - - @Override - public void handleClick(@NotNull ChallengeMenuClickInfo info) { - if (info.isUpperItemClick()) { - super.handleClick(info); - } else if (isEnabled() && !info.isRightClick()) { - openMenu(info); - } else { - super.handleClick(info); - } - } - - private void openMenu(@NotNull ChallengeMenuClickInfo event) { - MenuPosition position = MenuPosition.get(event.getPlayer()); - if (position == null) position = new EmptyMenuPosition(); - Inventory inventory = event.getInventory(); - SoundSample.CLICK.play(event.getPlayer()); - open(event.getPlayer(), inventory, position, 0); - } - - private void open(@NotNull Player player, @NotNull Inventory inventory, @NotNull MenuPosition position, int page) { - if (inventories.isEmpty()) generateInventories(); - if (inventories.isEmpty()) { - SoundSample.BASS_OFF.play(player); - return; - } - if (page >= inventories.size()) page = inventories.size() - 1; - Inventory menu = inventories.get(page); - MenuPosition.set(player, new SettingMenuPosition(position, inventory, page)); - player.openInventory(menu); - } - - @NotNull - @Override - public final ItemBuilder createSettingsItem() { - return isEnabled() ? DefaultItem.customize() : DefaultItem.disabled(); - } - - @Override - public void writeSettings(@NotNull Document document) { - document.set("enabled", isEnabled()); - for (Entry entry : settings.entrySet()) { - Document subDocument = document.getDocument(entry.getKey()); - entry.getValue().writeSettings(subDocument); - } - } - - @Override - public void loadSettings(@NotNull Document document) { - setEnabled(document.getBoolean("enabled")); - for (Entry entry : settings.entrySet()) { - if (!document.contains(entry.getKey())) continue; - Document subDocument = document.getDocument(entry.getKey()); - entry.getValue().loadSettings(subDocument); - } - } - - @Override - public void restoreDefaults() { - super.restoreDefaults(); - settings.values().forEach(SubSetting::restoreDefaults); - } - - public abstract class SubSetting implements Listener { - - private int page = -1, slot = -1; - - private void setPage(int page) { - this.page = page; - } - - private void setSlot(int slot) { - this.slot = slot; - } - - public final void updateItems() { - if (inventories.isEmpty()) return; // Menu not generated yet, nothing to update here - if (page == -1 || slot == -1) return; // Invalid slots, menu not generated yet - - Inventory inventory = inventories.get(page); - - inventory.setItem(slot, getDisplayItem().hideAttributes().build()); - inventory.setItem(slot + 9, buildSettingsItem()); - } - - @NotNull - private ItemStack buildSettingsItem() { - ItemBuilder item = getSettingsItem(); - String[] description = getSettingsDescription(); - if (description != null && isEnabled()) { - item.appendLore(" "); - item.appendLore(description); - } - - return item.build(); - } - - @NotNull - public abstract ItemBuilder getDisplayItem(); - - @NotNull - public abstract ItemBuilder getSettingsItem(); - - @Nullable - protected abstract String[] getSettingsDescription(); - - public boolean isEnabled() { - return MenuSetting.this.isEnabled() && getAsBoolean(); - } - - public abstract int getAsInt(); - - public abstract boolean getAsBoolean(); - - public abstract void restoreDefaults(); - - public abstract void loadSettings(@NotNull Document document); - - public abstract void writeSettings(@NotNull Document document); - - public abstract void handleClick(@NotNull ChallengeMenuClickInfo info); - - } - - public class BooleanSubSetting extends SubSetting { - - private final Supplier item; - private final Supplier description; - private final boolean enabledByDefault; - private boolean enabled; - - public BooleanSubSetting(@NotNull Supplier item) { - this(item, () -> null); - } - - public BooleanSubSetting(@NotNull Supplier item, boolean enabledByDefault) { - this(item, () -> null, enabledByDefault); - } - - public BooleanSubSetting(@NotNull Supplier item, @NotNull Supplier description) { - this(item, description, false); - } - - public BooleanSubSetting(@NotNull Supplier item, @NotNull Supplier description, boolean enabledByDefault) { - this.item = item; - this.description = description; - this.enabledByDefault = enabledByDefault; - this.setEnabled(enabledByDefault); - } - - @NotNull - @Override - public ItemBuilder getDisplayItem() { - return item.get(); - } - - @NotNull - @Override - public ItemBuilder getSettingsItem() { - return DefaultItem.status(enabled); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return description.get(); - } - - @Override - public int getAsInt() { - return enabled ? 1 : 0; - } - - @Override - public boolean getAsBoolean() { - return enabled; - } - - @Override - public void restoreDefaults() { - this.setEnabled(enabledByDefault); - } - - @NotNull - public BooleanSubSetting setEnabled(boolean enabled) { - if (this.enabled == enabled) return this; - this.enabled = enabled; - - if (enabled) this.onEnable(); - else this.onDisable(); - - this.updateItems(); - return this; - } - - @Override - public final void handleClick(@NotNull ChallengeMenuClickInfo info) { - this.setEnabled(!enabled); - SoundSample.playStatusSound(info.getPlayer(), enabled); - } - - @Override - public void loadSettings(@NotNull Document document) { - this.setEnabled(document.getBoolean("enabled")); - } - - @Override - public void writeSettings(@NotNull Document document) { - document.set("enabled", enabled); - } - - protected void onEnable() { - } - - protected void onDisable() { - } - - } - - public class NumberSubSetting extends SubSetting { - - private final Supplier item; - private final Function description; - private final Function name; - private final int max, min; - private final int defaultValue; - @Getter - private int value; - - public NumberSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name) { - this(item, description, name, 64); - } - - public NumberSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name, int max) { - this(item, description, name, max, 1); - } - - public NumberSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name, int min, int max) { - this(item, description, name, min, max, min); - } - - public NumberSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name, int min, int max, int defaultValue) { - if (max <= min) throw new IllegalArgumentException("max <= min"); - if (min < 0) throw new IllegalArgumentException("min < 0"); - if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); - if (defaultValue < min) throw new IllegalArgumentException("defaultValue < min"); - this.value = defaultValue; - this.defaultValue = defaultValue; - this.max = max; - this.min = min; - this.item = item; - this.description = description; - this.name = name; - } - - public NumberSubSetting(@NotNull Supplier item, @NotNull Function description) { - this(item, description, null, 64, 1); - } - - public NumberSubSetting(@NotNull Supplier item, @NotNull Function description, int max) { - this(item, description, null, max, 1); - } - - public NumberSubSetting(@NotNull Supplier item, @NotNull Function description, int min, int max) { - this(item, description, null, min, max, min); - } - - public NumberSubSetting(@NotNull Supplier item, @NotNull Function description, int min, int max, int defaultValue) { - this(item, description, null, min, max, defaultValue); - } - - public NumberSubSetting(@NotNull Supplier item) { - this(item, value -> null); - } - - public NumberSubSetting(@NotNull Supplier item, int max) { - this(item, value -> null, max); - } - - public NumberSubSetting(@NotNull Supplier item, int min, int max) { - this(item, value -> null, min, max); - } - - public NumberSubSetting(@NotNull Supplier item, int min, int max, int defaultValue) { - this(item, value -> null, min, max, defaultValue); - } - - @NotNull - @Override - public ItemBuilder getDisplayItem() { - return item.get(); - } - - @NotNull - @Override - public ItemBuilder getSettingsItem() { - if (name != null) - return DefaultItem.create(Material.STONE_BUTTON, name.apply(getValue())).amount(getValue()); - - return DefaultItem.value(value); - } - - @Nullable - @Override - protected String[] getSettingsDescription() { - return description.apply(getValue()); - } - - @Override - public void restoreDefaults() { - this.setValue(defaultValue); - } - - public void setValue(int value) { - if (this.value == value) return; - this.value = value; - - updateItems(); - onValueChange(); - } - - @Override - public int getAsInt() { - return value; - } - - @Override - public boolean getAsBoolean() { - return value > 0; - } - - @Override - public void handleClick(@NotNull ChallengeMenuClickInfo info) { - int amount = info.isShiftClick() ? 10 : 1; - int newValue = value; - if (info.isRightClick()) { - newValue -= amount; - } else { - newValue += amount; - } - - if (newValue > max) - newValue = min; - if (newValue < min) - newValue = max; - - this.setValue(newValue); - SoundSample.CLICK.play(info.getPlayer()); - } - - @Override - public void loadSettings(@NotNull Document document) { - this.setValue(document.getInt("value")); - } - - @Override - public void writeSettings(@NotNull Document document) { - document.set("value", value); - } - - protected void onValueChange() { - } - - } - - public class NumberAndBooleanSubSetting extends NumberSubSetting { - - private final boolean enabledByDefault = false; // Implement in future - private boolean enabled; - - public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name) { - super(item, description, name); - } - - public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name, int max) { - super(item, description, name, max); - } - - public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name, int min, int max) { - super(item, description, name, min, max); - } - - public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description, @Nullable Function name, int min, int max, int defaultValue) { - super(item, description, name, min, max, defaultValue); - } - - public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description) { - super(item, description); - } - - public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description, int max) { - super(item, description, max); - } - - public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description, int min, int max) { - super(item, description, min, max); - } - - public NumberAndBooleanSubSetting(@NotNull Supplier item, @NotNull Function description, int min, int max, int defaultValue) { - super(item, description, min, max, defaultValue); - } - - public NumberAndBooleanSubSetting(@NotNull Supplier item) { - super(item); - } - - public NumberAndBooleanSubSetting(@NotNull Supplier item, int max) { - super(item, max); - } - - public NumberAndBooleanSubSetting(@NotNull Supplier item, int min, int max) { - super(item, min, max); - } - - @Override - public void restoreDefaults() { - super.restoreDefaults(); - this.setEnabled(enabledByDefault); - } - - public void setEnabled(boolean enabled) { - if (this.enabled == enabled) return; - this.enabled = enabled; - - if (enabled) this.onEnable(); - else this.onDisable(); - - this.updateItems(); - } - - @Override - public boolean getAsBoolean() { - return enabled; - } - - @Override - public void handleClick(@NotNull ChallengeMenuClickInfo info) { - if (info.isUpperItemClick() || !enabled) { - this.setEnabled(!enabled); - SoundSample.playStatusSound(info.getPlayer(), enabled); - } else { - super.handleClick(info); - } - } - - @Override - public void loadSettings(@NotNull Document document) { - super.loadSettings(document); - this.setEnabled(document.getBoolean("enabled")); - } - - @Override - public void writeSettings(@NotNull Document document) { - super.writeSettings(document); - document.set("enabled", enabled); - } - - protected void onEnable() { - } - - protected void onDisable() { - } - - } - - private final class SettingMenuPosition implements MenuPosition { - - private final MenuPosition before; - private final Inventory inventoryBefore; - private final int page; - - public SettingMenuPosition(@NotNull MenuPosition before, @NotNull Inventory inventoryBefore, int page) { - this.before = before; - this.inventoryBefore = inventoryBefore; - this.page = page; - } - - @Override - public void handleClick(@NotNull MenuClickInfo info) { - - if (info.getSlot() == SettingsMenuGenerator.NAVIGATION_SLOTS[0]) { - if (page == 0) { - MenuPosition.set(info.getPlayer(), before); - info.getPlayer().openInventory(inventoryBefore); - } else { - open(info.getPlayer(), inventoryBefore, before, page - 1); - } - SoundSample.CLICK.play(info.getPlayer()); - return; - } else if (info.getSlot() == SettingsMenuGenerator.NAVIGATION_SLOTS[1]) { - open(info.getPlayer(), inventoryBefore, before, page + 1); - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - for (SubSetting setting : settings.values()) { - if (setting.page != page) continue; - if (info.getSlot() != setting.slot && info.getSlot() != setting.slot + 9) continue; - - setting.handleClick(new ChallengeMenuClickInfo(info, info.getSlot() == setting.slot)); - return; - } - - SoundSample.CLICK.play(info.getPlayer()); - - } - - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java index 8761eff66..5984aa1dc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java @@ -3,12 +3,16 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.commons.common.config.Document; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public abstract class Modifier extends AbstractChallenge implements IModifier { @@ -16,20 +20,19 @@ public abstract class Modifier extends AbstractChallenge implements IModifier { private final int defaultValue; private int value; - public Modifier(@NotNull MenuType menu) { - this(menu, 64); + public Modifier(@NotNull MenuType menu, @Nullable SettingCategory category, int max, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + this(menu, category, 1, max, displayItemPreset, nameMessageKey); } - public Modifier(@NotNull MenuType menu, int max) { - this(menu, 1, max); + public Modifier(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + this(menu, category, min, max, min, displayItemPreset, nameMessageKey); } - public Modifier(@NotNull MenuType menu, int min, int max) { - this(menu, min, max, min); - } - - public Modifier(@NotNull MenuType menu, int min, int max, int defaultValue) { - super(menu); + public Modifier(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, int defaultValue, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, displayItemPreset, nameMessageKey); if (max < min) throw new IllegalArgumentException("max < min"); if (min < 0) throw new IllegalArgumentException("min < 0"); if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); @@ -42,8 +45,14 @@ public Modifier(@NotNull MenuType menu, int min, int max, int defaultValue) { @NotNull @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.value(value); + public ItemStack getSettingsItemPreset() { + return DefaultItems.createValuePreset(value); + } + + @NotNull + @Override + public LocalizableMessage getSettingsName() { + return MessageKey.of("challenge.settings-modifier-value").withArgs(value); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java index 2833b61cc..8ff1737b4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java @@ -3,9 +3,12 @@ import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.commons.common.config.Document; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public abstract class ModifierCollectionGoal extends CollectionGoal implements IModifier { @@ -13,12 +16,16 @@ public abstract class ModifierCollectionGoal extends CollectionGoal implements I private final int defaultValue; private int value; - public ModifierCollectionGoal(int min, int max, @NotNull Object[] target) { - this(min, max, min, target); + public ModifierCollectionGoal(@Nullable SettingCategory category, int min, int max, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey, + @NotNull Object[] target) { + this(category, min, max, min, displayItemPreset, nameMessageKey, target); } - public ModifierCollectionGoal(int min, int max, int defaultValue, @NotNull Object[] target) { - super(target); + public ModifierCollectionGoal(@Nullable SettingCategory category, int min, int max, int defaultValue, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey, + @NotNull Object[] target) { + super(category, displayItemPreset, nameMessageKey, target); if (max < min) throw new IllegalArgumentException("max < min"); if (min < 0) throw new IllegalArgumentException("min < 0"); if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); @@ -39,10 +46,10 @@ public void handleClick(@NotNull ChallengeMenuClickInfo info) { ChallengeHelper.handleModifierClick(info, this); } - @Override - public boolean isEnabled() { - return true; - } +// @Override // TODO why was this overridden?? +// public boolean isEnabled() { +// return true; +// } @Override public void setEnabled(boolean enabled) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java index 5b3374220..7ee9195da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java @@ -1,14 +1,16 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.common.config.Document; import org.bukkit.*; import org.bukkit.World.Environment; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -25,19 +27,20 @@ public abstract class NetherPortalSpawnSetting extends OneEnabledSetting { private final Map netherPortalsByOverworldPortals = new HashMap<>(); private final StructureType structureType; private final Collection groundMaterial; - private final String unableToFindMessage; + private final String unableToFindMessageKey; - public NetherPortalSpawnSetting(@NotNull MenuType menu, @NotNull StructureType structureType, @NotNull String unableToFindMessage, @NotNull Material... groundMaterial) { - super(menu, id); - this.structureType = structureType; - this.unableToFindMessage = unableToFindMessage; - this.groundMaterial = Arrays.asList(groundMaterial); + public NetherPortalSpawnSetting(@NotNull MenuType menu, @Nullable SettingCategory category, @NotNull StructureType structureType, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey, + @NotNull String unableToFindMessageKey, @NotNull Material... groundMaterial) { + this(menu, category, structureType, displayItemPreset, nameMessageKey, unableToFindMessageKey, Arrays.asList(groundMaterial)); } - public NetherPortalSpawnSetting(@NotNull MenuType menu, @NotNull StructureType structureType, @NotNull String unableToFindMessage, @NotNull Collection groundMaterial) { - super(menu, id); + public NetherPortalSpawnSetting(@NotNull MenuType menu, @Nullable SettingCategory category, @NotNull StructureType structureType, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey, + @NotNull String unableToFindMessageKey, @NotNull Collection groundMaterial) { + super(menu, category, id, displayItemPreset, nameMessageKey); this.structureType = structureType; - this.unableToFindMessage = unableToFindMessage; + this.unableToFindMessageKey = unableToFindMessageKey; this.groundMaterial = groundMaterial; } @@ -53,7 +56,7 @@ public void onNetherPortal(@NotNull PlayerTeleportEvent event) { World world = event.getTo().getWorld(); Location location = getNetherPortal(event.getFrom(), world); if (location == null) { - Message.forName(unableToFindMessage).send(event.getPlayer(), Prefix.CHALLENGES); + MessageKey.of(unableToFindMessageKey).send(event.getPlayer(), Prefix.CHALLENGES); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java index be28372da..ca007c171 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java @@ -2,23 +2,27 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public abstract class OneEnabledSetting extends Setting { private final String typeId; - public OneEnabledSetting(@NotNull MenuType menu, @NotNull String typeId) { - super(menu); + public OneEnabledSetting(@NotNull MenuType menu, @Nullable SettingCategory category, @NotNull String typeId, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, displayItemPreset, nameMessageKey); this.typeId = typeId; } - public OneEnabledSetting(@NotNull MenuType menu, boolean enabledByDefault, @NotNull String typeId) { - super(menu, enabledByDefault); + public OneEnabledSetting(@NotNull MenuType menu, @Nullable SettingCategory category, boolean enabledByDefault, @NotNull String typeId, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, enabledByDefault, displayItemPreset, nameMessageKey); this.typeId = typeId; } - @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java index bc1787d9f..caa8bc3fb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/PointsGoal.java @@ -1,10 +1,13 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.config.Document; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.List; @@ -16,12 +19,13 @@ public abstract class PointsGoal extends SettingGoal { private final Map points = new HashMap<>(); - public PointsGoal() { - super(); + public PointsGoal(@Nullable SettingCategory category, @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(category, displayItemPreset, nameMessageKey); } - public PointsGoal(boolean enabledByDefault) { - super(enabledByDefault); + public PointsGoal(@Nullable SettingCategory category, boolean enabledByDefault, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(category, enabledByDefault, displayItemPreset, nameMessageKey); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java index b46dd8397..4458abc21 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/RandomizerSetting.java @@ -1,24 +1,24 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.collection.SeededRandomWrapper; import net.codingarea.commons.common.config.Document; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; public abstract class RandomizerSetting extends Setting { protected IRandom random = IRandom.create(); - public RandomizerSetting(@NotNull MenuType menu) { - super(menu); - setCategory(SettingCategory.RANDOMIZER); + public RandomizerSetting(@NotNull MenuType menu, @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + super(menu, SettingCategory.RANDOMIZER, displayItemPreset, messageNameKey); } - public RandomizerSetting(@NotNull MenuType menu, boolean enabledByDefault) { - super(menu, enabledByDefault); - setCategory(SettingCategory.RANDOMIZER); + public RandomizerSetting(@NotNull MenuType menu, boolean enabledByDefault, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + super(menu, SettingCategory.RANDOMIZER, enabledByDefault, displayItemPreset, messageNameKey); } protected abstract void reloadRandomization(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java index cb34987e4..ad87f8228 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java @@ -3,12 +3,13 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public abstract class Setting extends AbstractChallenge { @@ -16,12 +17,14 @@ public abstract class Setting extends AbstractChallenge { private final boolean enabledByDefault; protected boolean enabled; - public Setting(@NotNull MenuType menu) { - this(menu, false); + public Setting(@NotNull MenuType menu, @Nullable SettingCategory category, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + this(menu, category, false, displayItemPreset, nameMessageKey); } - public Setting(@NotNull MenuType menu, boolean enabledByDefault) { - super(menu); + public Setting(@NotNull MenuType menu, @Nullable SettingCategory category, boolean enabledByDefault, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, displayItemPreset, nameMessageKey); this.enabledByDefault = enabledByDefault; setEnabled(enabledByDefault); } @@ -42,12 +45,6 @@ public void playStatusUpdateTitle() { ChallengeHelper.playToggleChallengeTitle(this); } - @NotNull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.status(enabled); - } - protected void onEnable() { } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java index f166deb25..771eb40fd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java @@ -3,18 +3,21 @@ import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class SettingGoal extends Setting implements IGoal { - public SettingGoal() { - super(MenuType.GOAL); + public SettingGoal(@Nullable SettingCategory category, @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(MenuType.GOAL, category, displayItemPreset, nameMessageKey); } - public SettingGoal(boolean enabledByDefault) { - super(MenuType.GOAL, enabledByDefault); + public SettingGoal(@Nullable SettingCategory category, boolean enabledByDefault, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(MenuType.GOAL, category, enabledByDefault, displayItemPreset, nameMessageKey); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java index 441902e25..68f55ac40 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java @@ -2,32 +2,37 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public abstract class SettingModifier extends Modifier { private boolean enabled; - public SettingModifier(@NotNull MenuType menu) { - super(menu); + public SettingModifier(@NotNull MenuType menu, @Nullable SettingCategory category, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, 64, displayItemPreset, nameMessageKey); } - public SettingModifier(@NotNull MenuType menu, int max) { - super(menu, max); + public SettingModifier(@NotNull MenuType menu, @Nullable SettingCategory category, int max, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, max, displayItemPreset, nameMessageKey); } - public SettingModifier(@NotNull MenuType menu, int min, int max) { - super(menu, min, max); + public SettingModifier(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, min, max, displayItemPreset, nameMessageKey); } - public SettingModifier(@NotNull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue); + public SettingModifier(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, int defaultValue, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, min, max, defaultValue, displayItemPreset, nameMessageKey); } @Override @@ -49,14 +54,8 @@ public void restoreDefaults() { @NotNull @Override - public ItemStack getSettingsItem() { - return isEnabled() ? super.getSettingsItem() : DefaultItem.disabled().build(); - } - - @NotNull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.enabled().amount(getValue()); + public ItemStack getSettingsItemPreset() { + return DefaultItems.createEnabledValuePreset(getValue()); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java index 20c2ac95e..f1814747b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java @@ -1,21 +1,25 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public abstract class SettingModifierCollectionGoal extends ModifierCollectionGoal { - public SettingModifierCollectionGoal(int min, int max, @NotNull Object... target) { - super(min, max, target); + public SettingModifierCollectionGoal(@Nullable SettingCategory category, int min, int max, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey, @NotNull Object... target) { + super(category, min, max, displayItemPreset, nameMessageKey, target); } - public SettingModifierCollectionGoal(int min, int max, int defaultValue, @NotNull Object... target) { - super(min, max, defaultValue, target); + public SettingModifierCollectionGoal(@Nullable SettingCategory category, int min, int max, int defaultValue, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey, @NotNull Object... target) { + super(category, min, max, defaultValue, displayItemPreset, nameMessageKey, target); } @Override @@ -35,17 +39,17 @@ public void restoreDefaults() { setEnabled(false); } - @NotNull - @Override - public ItemStack getSettingsItem() { - return isEnabled() ? super.getSettingsItem() : DefaultItem.disabled().build(); - } - - @NotNull - @Override - public ItemBuilder createSettingsItem() { - return DefaultItem.enabled().amount(getValue()); - } +// @NotNull +// @Override +// public ItemStack getSettingsItem() { +// return isEnabled() ? super.getSettingsItem() : DefaultItem.disabled().build(); +// } +// +// @NotNull +// @Override +// public LegacyItemBuilder createSettingsItem() { +// return DefaultItem.enabled().setAmount(getValue()); +// } @Override public void handleShutdown() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java index 710888da6..d1974c9b3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java @@ -4,27 +4,33 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class SettingModifierGoal extends SettingModifier implements IGoal { - public SettingModifierGoal(@NotNull MenuType menu) { - super(menu); + public SettingModifierGoal(@NotNull MenuType menu, @Nullable SettingCategory category, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + super(menu, category, displayItemPreset, messageNameKey); } - public SettingModifierGoal(@NotNull MenuType menu, int max) { - super(menu, max); + public SettingModifierGoal(@NotNull MenuType menu, @Nullable SettingCategory category, int max, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + super(menu, category, max, displayItemPreset, messageNameKey); } - public SettingModifierGoal(@NotNull MenuType menu, int min, int max) { - super(menu, min, max); + public SettingModifierGoal(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + super(menu, category, min, max, displayItemPreset, messageNameKey); } - public SettingModifierGoal(@NotNull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue); + public SettingModifierGoal(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, int defaultValue, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + super(menu, category, min, max, defaultValue, displayItemPreset, messageNameKey); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java index 619905f95..2cbe4f2ee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java @@ -2,11 +2,14 @@ import lombok.Setter; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; public abstract class TimedChallenge extends SettingModifier { @@ -17,39 +20,47 @@ public abstract class TimedChallenge extends SettingModifier { private boolean timerStatus = false; private boolean startedBefore = false; - public TimedChallenge(@NotNull MenuType menu) { - this(menu, true); + public TimedChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + this(menu, category, true, displayItemPreset, messageNameKey); } - public TimedChallenge(@NotNull MenuType menu, int max) { - this(menu, max, true); + public TimedChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, int max, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + this(menu, category, max, true, displayItemPreset, messageNameKey); } - public TimedChallenge(@NotNull MenuType menu, int min, int max) { - this(menu, min, max, true); + public TimedChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + this(menu, category, min, max, true, displayItemPreset, messageNameKey); } - public TimedChallenge(@NotNull MenuType menu, int min, int max, int defaultValue) { - this(menu, min, max, defaultValue, true); + public TimedChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, int defaultValue, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + this(menu, category, min, max, defaultValue, true, displayItemPreset, messageNameKey); } - public TimedChallenge(@NotNull MenuType menu, boolean runAsync) { - super(menu); + public TimedChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, boolean runAsync, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + super(menu, category, displayItemPreset, messageNameKey); this.runAsync = runAsync; } - public TimedChallenge(@NotNull MenuType menu, int max, boolean runAsync) { - super(menu, max); + public TimedChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, int max, boolean runAsync, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + super(menu, category, max, displayItemPreset, messageNameKey); this.runAsync = runAsync; } - public TimedChallenge(@NotNull MenuType menu, int min, int max, boolean runAsync) { - super(menu, min, max); + public TimedChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, boolean runAsync, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + super(menu, category, min, max, displayItemPreset, messageNameKey); this.runAsync = runAsync; } - public TimedChallenge(@NotNull MenuType menu, int min, int max, int defaultValue, boolean runAsync) { - super(menu, min, max, defaultValue); + public TimedChallenge(@NotNull MenuType menu, @Nullable SettingCategory category, int min, int max, int defaultValue, boolean runAsync, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + super(menu, category, min, max, defaultValue, displayItemPreset, messageNameKey); this.runAsync = runAsync; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java index 5bc55e0eb..dfdcfcf45 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/WorldDependentChallenge.java @@ -4,6 +4,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.WorldManager.WorldSettings; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.GameMode; @@ -12,6 +13,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; @@ -26,36 +28,24 @@ public abstract class WorldDependentChallenge extends TimedChallenge { private BiConsumer lastTeleport; private int teleportIndex; - public WorldDependentChallenge(@NotNull MenuType menu) { - super(menu); + public WorldDependentChallenge(@NotNull MenuType menu, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + super(menu, SettingCategory.EXTRA_WORLD, false, displayItemPreset, messageNameKey); } - public WorldDependentChallenge(@NotNull MenuType menu, int max) { - super(menu, max); + public WorldDependentChallenge(@NotNull MenuType menu, int max, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + super(menu, SettingCategory.EXTRA_WORLD, max, false, displayItemPreset, messageNameKey); } - public WorldDependentChallenge(@NotNull MenuType menu, int min, int max) { - super(menu, min, max); + public WorldDependentChallenge(@NotNull MenuType menu, int min, int max, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + super(menu, SettingCategory.EXTRA_WORLD, min, max, false, displayItemPreset, messageNameKey); } - public WorldDependentChallenge(@NotNull MenuType menu, int min, int max, int defaultValue) { - super(menu, min, max, defaultValue); - } - - public WorldDependentChallenge(@NotNull MenuType menu, boolean runAsync) { - super(menu, runAsync); - } - - public WorldDependentChallenge(@NotNull MenuType menu, int max, boolean runAsync) { - super(menu, max, runAsync); - } - - public WorldDependentChallenge(@NotNull MenuType menu, int min, int max, boolean runAsync) { - super(menu, min, max, runAsync); - } - - public WorldDependentChallenge(@NotNull MenuType menu, int min, int max, int defaultValue, boolean runAsync) { - super(menu, min, max, defaultValue, runAsync); + public WorldDependentChallenge(@NotNull MenuType menu, int min, int max, int defaultValue, + @NotNull ItemStack displayItemPreset, @NotNull String messageNameKey) { + super(menu, SettingCategory.EXTRA_WORLD, min, max, defaultValue, false, displayItemPreset, messageNameKey); } /** diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuGoal.java similarity index 71% rename from plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuGoal.java index 459f27c35..1907d3d16 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/MenuGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuGoal.java @@ -1,16 +1,19 @@ -package net.codingarea.challenges.plugin.challenges.type.abstraction; +package net.codingarea.challenges.plugin.challenges.type.abstraction.menu; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class MenuGoal extends MenuSetting implements IGoal { - public MenuGoal(@NotNull MenuType menu, @NotNull Message title) { - super(menu, title); + + public MenuGoal(@NotNull MenuType menu, @Nullable SettingCategory category, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, displayItemPreset, nameMessageKey); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java new file mode 100644 index 000000000..88efe9e42 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java @@ -0,0 +1,435 @@ +package net.codingarea.challenges.plugin.challenges.type.abstraction.menu; + +import lombok.Getter; +import lombok.Setter; +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.config.Document; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; + +public abstract class MenuSetting extends Setting { + + private final Map settings = new LinkedHashMap<>(); + private final SubSettingsMenuGenerator menuGenerator; + + public MenuSetting(@NotNull MenuType menu, @Nullable SettingCategory category, + @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { + super(menu, category, displayItemPreset, nameMessageKey); + this.menuGenerator = new SubSettingsMenuGenerator(this); + } + + protected final void registerSetting(@NotNull String name, @NotNull SubSetting setting) { + if (name.equals("enabled")) throw new IllegalArgumentException("SubSetting name 'enabled' is reserved"); + settings.put(name, setting); + menuGenerator.addToCache(setting); + Challenges.getInstance().registerListener(setting); + } + + public final SubSetting getSetting(@NotNull String name) { + return settings.get(name); + } + + @Override + public void handleClick(@NotNull ChallengeMenuClickInfo info) { + if (isEnabled() && !info.isRightClick() && info.isLowerItemClick()) { + openMenu(info); + } else { + super.handleClick(info); + } + } + + private void openMenu(@NotNull ChallengeMenuClickInfo event) { + menuGenerator.openMenu(event.getPlayer()); + } + + @NotNull + @Override + public ItemStack getSettingsItemPreset() { + return DefaultItems.createCustomizePreset(); + } + + @NotNull + @Override + public LocalizableMessage getSettingsName() { + return MessageKey.of("customize"); + } + + @Override + public void writeSettings(@NotNull Document document) { + document.set("enabled", isEnabled()); + for (Entry entry : settings.entrySet()) { + Document subDocument = document.getDocument(entry.getKey()); + entry.getValue().writeSettings(subDocument); + } + } + + @Override + public void loadSettings(@NotNull Document document) { + setEnabled(document.getBoolean("enabled")); + for (Entry entry : settings.entrySet()) { + if (!document.contains(entry.getKey())) continue; + Document subDocument = document.getDocument(entry.getKey()); + entry.getValue().loadSettings(subDocument); + } + } + + @Override + public void restoreDefaults() { + super.restoreDefaults(); + settings.values().forEach(SubSetting::restoreDefaults); + } + + public abstract class SubSetting implements Listener { + + @Setter + @Getter + private int page = -1, slot = -1; + + protected final ItemStack displayItemPreset; + + public SubSetting(@NotNull ItemStack displayItemPreset) { + this.displayItemPreset = displayItemPreset; + } + + public final void updateItems() { + menuGenerator.updateElementDisplay(this); + } + + @NotNull + public ItemBuilder getDisplayItem(@NotNull Locale locale) { + return new ItemBuilder(locale, displayItemPreset, MessageKey.of("challenge.display-format"), + getDisplayName(), getDisplayDescription()); + } + + @NotNull + public ItemBuilder getSettingsItem(@NotNull Locale locale) { + ItemStack preset = isEnabled() ? getSettingsItemPreset() : DefaultItems.createDisabledPreset(); + // apply formatting dynamically, to prevent duplicate format references + ItemBuilder item = new ItemBuilder(locale, preset, MessageKey.of("challenge.subsettings-format"), + isEnabled() ? getSettingsName() : MessageKey.of("disabled")); // no need to override disabled name/item + + LocalizableMessage description = getSettingsDescription(); + if (description != null && isEnabled()) { + item.appendLore(MessageKey.of("challenge.subsettings-format-lore"), description); + } + + return item; + } + + @NotNull + public abstract ItemStack getSettingsItemPreset(); + + @NotNull + protected abstract LocalizableMessage getDisplayName(); + + @NotNull + protected abstract LocalizableMessage getDisplayDescription(); + + @NotNull + protected LocalizableMessage getSettingsName() { + return MessageKey.of("enabled"); + } + + @Nullable + protected LocalizableMessage getSettingsDescription() { + return null; + } + + public boolean isEnabled() { + return MenuSetting.this.isEnabled() && getAsBoolean(); + } + + public abstract int getAsInt(); + + public abstract boolean getAsBoolean(); + + public abstract void restoreDefaults(); + + public abstract void loadSettings(@NotNull Document document); + + public abstract void writeSettings(@NotNull Document document); + + public abstract void handleClick(@NotNull ChallengeMenuClickInfo info); + + } + + public class BooleanSubSetting extends SubSetting { + + private final boolean enabledByDefault; + private boolean enabled; + + public BooleanSubSetting(@NotNull ItemStack displayItemPreset) { + this(displayItemPreset, false); + } + + public BooleanSubSetting(@NotNull ItemStack displayItemPreset, boolean enabledByDefault) { + super(displayItemPreset); + this.enabledByDefault = enabledByDefault; + this.setEnabled(enabledByDefault); + } + + @NotNull + @Override + public ItemStack getSettingsItemPreset() { + return DefaultItems.createEnabledPreset(); + } + + @NotNull + @Override + protected LocalizableMessage getDisplayName() { + return null; // TODO + } + + @NotNull + @Override + protected LocalizableMessage getDisplayDescription() { + return null; // TODO + } + + @Override + public int getAsInt() { + return enabled ? 1 : 0; + } + + @Override + public boolean getAsBoolean() { + return enabled; + } + + @Override + public void restoreDefaults() { + this.setEnabled(enabledByDefault); + } + + @NotNull + public BooleanSubSetting setEnabled(boolean enabled) { + if (this.enabled == enabled) return this; + this.enabled = enabled; + + if (enabled) this.onEnable(); + else this.onDisable(); + + this.updateItems(); + return this; + } + + @Override + public final void handleClick(@NotNull ChallengeMenuClickInfo info) { + this.setEnabled(!enabled); + SoundSample.playStatusSound(info.getPlayer(), enabled); + } + + @Override + public void loadSettings(@NotNull Document document) { + this.setEnabled(document.getBoolean("enabled")); + } + + @Override + public void writeSettings(@NotNull Document document) { + document.set("enabled", enabled); + } + + protected void onEnable() { + } + + protected void onDisable() { + } + + } + + public class NumberSubSetting extends SubSetting { + + // TODO name, desc + private final int max, min; + private final int defaultValue; + @Getter + private int value; + + public NumberSubSetting(@NotNull ItemStack displayItemPreset) { + this(displayItemPreset, 64); + } + + public NumberSubSetting(@NotNull ItemStack displayItemPreset, int max) { + this(displayItemPreset, max, 1); + } + + public NumberSubSetting(@NotNull ItemStack displayItemPreset, int min, int max) { + this(displayItemPreset, min, max, min); + } + + public NumberSubSetting(@NotNull ItemStack displayItemPreset, int min, int max, int defaultValue) { + if (max <= min) throw new IllegalArgumentException("max <= min"); + if (min < 0) throw new IllegalArgumentException("min < 0"); + if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); + if (defaultValue < min) throw new IllegalArgumentException("defaultValue < min"); + super(displayItemPreset); + this.value = defaultValue; + this.defaultValue = defaultValue; + this.max = max; + this.min = min; + } + + @Override + public @NotNull ItemStack getSettingsItemPreset() { + return DefaultItems.createValuePreset(value); + } + + @Override + public void restoreDefaults() { + this.setValue(defaultValue); + } + + public void setValue(int value) { + if (this.value == value) return; + this.value = value; + + updateItems(); + onValueChange(); + } + + @NotNull + @Override + protected LocalizableMessage getDisplayName() { + return null; // TODO + } + + @NotNull + @Override + protected LocalizableMessage getDisplayDescription() { + return null; // TODO + } + + + @Override + public int getAsInt() { + return value; + } + + @Override + public boolean getAsBoolean() { + return value > 0; + } + + @Override + public void handleClick(@NotNull ChallengeMenuClickInfo info) { + int amount = info.isShiftClick() ? 10 : 1; + int newValue = value; + if (info.isRightClick()) { + newValue -= amount; + } else { + newValue += amount; + } + + if (newValue > max) + newValue = min; + if (newValue < min) + newValue = max; + + this.setValue(newValue); + SoundSample.CLICK.play(info.getPlayer()); + } + + @Override + public void loadSettings(@NotNull Document document) { + this.setValue(document.getInt("value")); + } + + @Override + public void writeSettings(@NotNull Document document) { + document.set("value", value); + } + + protected void onValueChange() { + } + + } + + public class NumberAndBooleanSubSetting extends NumberSubSetting { + + private final boolean enabledByDefault = false; // Implement in future + private boolean enabled; + + public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset) { + super(displayItemPreset); + } + + public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset, int max) { + super(displayItemPreset, max); + } + + public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset, int min, int max) { + super(displayItemPreset, min, max); + } + + public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset, int min, int max, int defaultValue) { + super(displayItemPreset, min, max, defaultValue); + } + + @Override + public void restoreDefaults() { + super.restoreDefaults(); + this.setEnabled(enabledByDefault); + } + + public void setEnabled(boolean enabled) { + if (this.enabled == enabled) return; + this.enabled = enabled; + + if (enabled) this.onEnable(); + else this.onDisable(); + + this.updateItems(); + } + + @Override + public boolean getAsBoolean() { + return enabled; + } + + @Override + public void handleClick(@NotNull ChallengeMenuClickInfo info) { + if (info.isUpperItemClick() || !enabled) { + this.setEnabled(!enabled); + SoundSample.playStatusSound(info.getPlayer(), enabled); + } else { + super.handleClick(info); + } + } + + @Override + public void loadSettings(@NotNull Document document) { + super.loadSettings(document); + this.setEnabled(document.getBoolean("enabled")); + } + + @Override + public void writeSettings(@NotNull Document document) { + super.writeSettings(document); + document.set("enabled", enabled); + } + + protected void onEnable() { + } + + protected void onDisable() { + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/SubSettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/SubSettingsMenuGenerator.java new file mode 100644 index 000000000..e117f9279 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/SubSettingsMenuGenerator.java @@ -0,0 +1,159 @@ +package net.codingarea.challenges.plugin.challenges.type.abstraction.menu; + +import lombok.Getter; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.management.menu.generator.IDynamicMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.MultiPageMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengeListMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +public class SubSettingsMenuGenerator extends MultiPageMenuGenerator implements IDynamicMenuGenerator { + + public static final int SIZE = ChallengeListMenuGenerator.SIZE; + public static final int MAX_SLOTS_PER_PAGE = 4; + + public static int[] getSlots(int amount) { + return switch (amount) { + case 1 -> new int[]{13}; + case 2 -> new int[]{12, 14}; + case 3 -> new int[]{11, 13, 15}; + case 4 -> new int[]{10, 12, 14, 16}; + default -> new int[0]; // see MAX_SLOTS + }; + } + + @Getter + private final MenuSetting challenge; + private final List subSettingsCache = new ArrayList<>(); // order, random access + + public SubSettingsMenuGenerator(@NotNull MenuSetting challenge) { + this.challenge = challenge; + } + + @NotNull + @Override + public LocalizableMessage getMenuName() { + return createSubMenuTitle(challenge.getType().getMenuName(), MessageKey.of("challenge." + challenge.getNameMessageKey() + ".menu")); + } + + @Override + public void addToCache(@NotNull MenuSetting.SubSetting setting) { + subSettingsCache.add(setting); + } + + @Override + public void removeFromCache(@NotNull MenuSetting.SubSetting setting) { + subSettingsCache.remove(setting); + } + + @Override + public int getCachedCount() { + return subSettingsCache.size(); + } + + @Override + public boolean isCached(@NotNull MenuSetting.SubSetting setting) { + return subSettingsCache.contains(setting); + } + + @Override + public void resetCache() { + subSettingsCache.clear(); + } + + @Override + public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Locale locale) { + List settings = getSubSettingsForPage(page); + int[] slots = getSlots(settings.size()); + + int i = 0; + for (MenuSetting.SubSetting setting : settings) { + setting.setPage(page); + setting.setSlot(slots[i]); + setSubSettingItemsAt(setting, inventory, slots[i], locale); + i++; + } + } + + @Override + public void updateElementDisplay(@NotNull MenuSetting.SubSetting setting) { + int settingsIndex = subSettingsCache.indexOf(setting); + if (settingsIndex == -1) return; // not cached + + int page = getPageOfSubSetting(settingsIndex); + int settingsOnPage = getSubSettingsCountForPage(page); + int slotIndex = settingsIndex % settingsOnPage; + int displaySlot = getSlots(settingsOnPage)[slotIndex]; + + updatePage(page, (inventory, locale) -> setSubSettingItemsAt(setting, inventory, displaySlot, locale)); + } + + public void setSubSettingItemsAt(@NotNull MenuSetting.SubSetting setting, @NotNull Inventory inventory, int displaySlot, @NotNull Locale locale) { + inventory.setItem(displaySlot + ChallengeListMenuGenerator.SLOT_OFFSET_DISPLAY, setting.getDisplayItem(locale).build()); + inventory.setItem(displaySlot + ChallengeListMenuGenerator.SLOT_OFFSET_SETTINGS, setting.getSettingsItem(locale).build()); + } + + @NotNull + @Override + public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { + return new SubSettingsMenuPosition(page, player); + } + + @NotNull + protected List getSubSettingsForPage(int page) { + int startIndex = page * MAX_SLOTS_PER_PAGE; + int endIndex = Math.min(startIndex + MAX_SLOTS_PER_PAGE, subSettingsCache.size()); + return subSettingsCache.subList(startIndex, endIndex); + } + + protected int getSubSettingsCountForPage(int page) { + return Math.min(MAX_SLOTS_PER_PAGE, subSettingsCache.size() - page * MAX_SLOTS_PER_PAGE); + } + + protected int getPageOfSubSetting(int indexOfSetting) { + if (indexOfSetting == -1) return -1; // not cached + return (indexOfSetting / MAX_SLOTS_PER_PAGE); + } + + @Override + public int getPageCount() { + // must have at least one page + return Math.max(1, Math.ceilDiv(subSettingsCache.size(), MAX_SLOTS_PER_PAGE)); + } + + @Override + public int getInventorySize() { + return SIZE; + } + + public class SubSettingsMenuPosition extends HistoryAwareGeneratorMenuPosition { + + public SubSettingsMenuPosition(int page, @NotNull Player player) { + super(page, player); + } + + @Override + public boolean handleMenuClick(@NotNull MenuClickInfo info) { + List settings = getSubSettingsForPage(page); + for (MenuSetting.SubSetting setting : settings) { + int settingsSlot = setting.getSlot(); // TODO + if (info.getSlot() != settingsSlot && info.getSlot() != settingsSlot + 9) continue; + + setting.handleClick(new ChallengeMenuClickInfo(info, info.getSlot() == settingsSlot)); + return true; + } + + return false; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/CanInstaKillOnEnable.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/CanInstaKillOnEnable.java similarity index 77% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/CanInstaKillOnEnable.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/CanInstaKillOnEnable.java index b6c11153c..33d8707ca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/CanInstaKillOnEnable.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/CanInstaKillOnEnable.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.management.challenges.annotations; +package net.codingarea.challenges.plugin.challenges.type.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java index b3a8cb59a..514dae440 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java @@ -33,14 +33,14 @@ public static Version getUpdated(@NotNull Class clazz) { } public static boolean isNew(@NotNull IChallenge challenge) { - return isVersionNewer(getSince(challenge)); + return isVersionNew(getSince(challenge)); } public static boolean isUpdated(@NotNull IChallenge challenge) { - return isVersionNewer(getUpdated(challenge)); + return isVersionNew(getUpdated(challenge)); } - private static boolean isVersionNewer(@NotNull Version challengeVersion) { + private static boolean isVersionNew(@NotNull Version challengeVersion) { Version pluginVersion = Challenges.getInstance().getVersion(); return challengeVersion.isNewerOrEqualThan(pluginVersion); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/ExcludeFromRandomChallenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ExcludeFromRandomChallenges.java similarity index 78% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/ExcludeFromRandomChallenges.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ExcludeFromRandomChallenges.java index 3db378b57..8210e812c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/ExcludeFromRandomChallenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ExcludeFromRandomChallenges.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.management.challenges.annotations; +package net.codingarea.challenges.plugin.challenges.type.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/RequireVersion.java similarity index 84% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/RequireVersion.java index 05d0f2c5c..8b3b46d3d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/annotations/RequireVersion.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/RequireVersion.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.management.challenges.annotations; +package net.codingarea.challenges.plugin.challenges.type.annotation; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index cc986a8b2..6b99fd81b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -7,12 +7,10 @@ import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; -import net.codingarea.challenges.plugin.content.ItemDescription; +import net.codingarea.challenges.plugin.challenges.type.annotation.CanInstaKillOnEnable; +import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.challenges.annotations.CanInstaKillOnEnable; -import net.codingarea.challenges.plugin.management.challenges.annotations.ExcludeFromRandomChallenges; -import net.codingarea.challenges.plugin.management.menu.generator.ChallengeMenuGenerator; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengesMenuGenerator; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; @@ -42,11 +40,7 @@ private ChallengeHelper() { } public static void kill(@NotNull Player player) { - - if (!Bukkit.isPrimaryThread()) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> kill(player)); - return; - } + if (runSyncIfConcurrent(() -> kill(player))) return; inInstantKill = true; player.damage(Integer.MAX_VALUE); @@ -57,8 +51,16 @@ public static void kill(@NotNull Player player, int delay) { Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> kill(player), delay); } + public static boolean runSyncIfConcurrent(Runnable task) { + if (Bukkit.isPrimaryThread()) { + return false; + } + Bukkit.getScheduler().runTask(Challenges.getInstance(), task); + return true; + } + public static void updateItems(@NotNull IChallenge challenge) { - challenge.getType().executeWithGenerator(ChallengeMenuGenerator.class, gen -> gen.updateItem(challenge)); + challenge.getType().executeWithGenerator(ChallengesMenuGenerator.class, gen -> gen.updateElementDisplay(challenge)); } public static boolean canInstaKillOnEnable(@NotNull IChallenge challenge) { @@ -87,11 +89,9 @@ public static void handleModifierClick(@NotNull MenuClickInfo info, @NotNull IMo } @NotNull + @Deprecated public static String getColoredChallengeName(@NotNull AbstractChallenge challenge) { - ItemBuilder item = challenge.createDisplayItem(); - ItemDescription description = item.getBuiltByItemDescription(); - if (description == null) return Message.NULL; - return description.getOriginalName(); + return challenge.getChallengeName().getLocalizableKey().getKey(); } public static void breakBlock(@NotNull Block block, @Nullable ItemStack tool) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java index ebd859b38..2f611f2a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java @@ -6,10 +6,10 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.StructureUtils; -import net.codingarea.commons.bukkit.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder.PotionBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Material; @@ -32,20 +32,20 @@ public static ChooseMultipleItemSubSettingBuilder createEntityTypeSettingsBuilde return SubSettingsBuilder.createChooseMultipleItem(ENTITY_TYPE).fill(builder -> { if (any) { - builder.addSetting(ANY, new ItemBuilder( + builder.addSetting(ANY, new LegacyItemBuilder( Material.NETHER_STAR, Message.forName("item-custom-setting-entity_type-any")).build()); } if (player) { - builder.addSetting("PLAYER", new ItemBuilder(Material.PLAYER_HEAD, Message.forName("item-custom-setting-entity_type-player")).build()); + builder.addSetting("PLAYER", new LegacyItemBuilder(Material.PLAYER_HEAD, Message.forName("item-custom-setting-entity_type-player")).build()); } for (EntityType type : EntityType.values()) { if (!type.isSpawnable() || !type.isAlive()) continue; try { Material spawnEgg = Material.valueOf(type.name() + "_SPAWN_EGG"); - builder.addSetting(type.name(), new ItemBuilder(spawnEgg, + builder.addSetting(type.name(), new LegacyItemBuilder(spawnEgg, DefaultItem.getItemPrefix() + BukkitStringUtils.getEntityName(type).toPlainText()).build()); } catch (Exception ex) { - builder.addSetting(type.name(), new ItemBuilder(Material.STRUCTURE_VOID, + builder.addSetting(type.name(), new LegacyItemBuilder(Material.STRUCTURE_VOID, DefaultItem.getItemPrefix() + BukkitStringUtils.getEntityName(type).toPlainText())); } } @@ -54,10 +54,10 @@ public static ChooseMultipleItemSubSettingBuilder createEntityTypeSettingsBuilde public static ChooseMultipleItemSubSettingBuilder createBlockSettingsBuilder() { return SubSettingsBuilder.createChooseMultipleItem(BLOCK).fill(builder -> { - builder.addSetting(ANY, new ItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-setting-block-any")).build()); + builder.addSetting(ANY, new LegacyItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-setting-block-any")).build()); for (Material material : ExperimentalUtils.getMaterials()) { if (material.isBlock() && material.isItem() && !BukkitReflectionUtils.isAir(material)) { - builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); + builder.addSetting(material.name(), new LegacyItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); } } }); @@ -65,10 +65,10 @@ public static ChooseMultipleItemSubSettingBuilder createBlockSettingsBuilder() { public static ChooseMultipleItemSubSettingBuilder createItemSettingsBuilder() { return SubSettingsBuilder.createChooseMultipleItem(ITEM).fill(builder -> { - builder.addSetting(ANY, new ItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-setting-item-any")).build()); + builder.addSetting(ANY, new LegacyItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-setting-item-any")).build()); for (Material material : ExperimentalUtils.getMaterials()) { if (material.isItem() && !BukkitReflectionUtils.isAir(material)) { - builder.addSetting(material.name(), new ItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); + builder.addSetting(material.name(), new LegacyItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); } } }); @@ -86,27 +86,27 @@ public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean every ChooseItemSubSettingsBuilder builder = SubSettingsBuilder.createChooseItem(TARGET_ENTITY); if (console) { - builder.addSetting("console", new ItemBuilder(Material.COMMAND_BLOCK_MINECART, Message.forName("item-custom-setting-target-console"))); + builder.addSetting("console", new LegacyItemBuilder(Material.COMMAND_BLOCK_MINECART, Message.forName("item-custom-setting-target-console"))); } if (!onlyPlayer) { - builder.addSetting("current", new ItemBuilder(Material.DRAGON_HEAD, + builder.addSetting("current", new LegacyItemBuilder(Material.DRAGON_HEAD, Message.forName("item-custom-setting-target-current"))); } - builder.addSetting("current_player", new ItemBuilder(Material.PLAYER_HEAD, + builder.addSetting("current_player", new LegacyItemBuilder(Material.PLAYER_HEAD, Message.forName("item-custom-setting-target-current_player"))); - builder.addSetting("random_player", new ItemBuilder(Material.ZOMBIE_HEAD, + builder.addSetting("random_player", new LegacyItemBuilder(Material.ZOMBIE_HEAD, Message.forName("item-custom-setting-target-random_player"))); - builder.addSetting("every_player", new ItemBuilder(Material.PLAYER_HEAD, + builder.addSetting("every_player", new LegacyItemBuilder(Material.PLAYER_HEAD, Message.forName("item-custom-setting-target-every_player"))); if (everyMob && !onlyPlayer) { - builder.addSetting("every_mob", new ItemBuilder(Material.WITHER_SKELETON_SKULL, + builder.addSetting("every_mob", new LegacyItemBuilder(Material.WITHER_SKELETON_SKULL, Message.forName("item-custom-setting-target-every_mob"))); - builder.addSetting("every_mob_except_current", new ItemBuilder(Material.SKELETON_SKULL, + builder.addSetting("every_mob_except_current", new LegacyItemBuilder(Material.SKELETON_SKULL, Message.forName("item-custom-setting-target-every_mob_except_current"))); - builder.addSetting("every_mob_except_players", new ItemBuilder(Material.SKELETON_SKULL, + builder.addSetting("every_mob_except_players", new LegacyItemBuilder(Material.SKELETON_SKULL, Message.forName("item-custom-setting-target-every_mob_except_players"))); } return builder; @@ -118,13 +118,13 @@ public static SubSettingsBuilder createPotionSettingsBuilder(boolean potionType, SubSettingsBuilder potionSettings = SubSettingsBuilder.createValueItem().fill(builder -> { if (potionTime) { - builder.addModifierSetting("length", new ItemBuilder(Material.CLOCK, + builder.addModifierSetting("length", new LegacyItemBuilder(Material.CLOCK, Message.forName("item-random-effect-length-challenge")), 30, 1, 60, value -> "", value -> Message.forName(value == 1 ? "second" : "seconds").asString()); } - builder.addModifierSetting("amplifier", new ItemBuilder(Material.STONE_SWORD, + builder.addModifierSetting("amplifier", new LegacyItemBuilder(Material.STONE_SWORD, Message.forName("item-random-effect-amplifier-challenge")), 3, 1, 8, value -> Message.forName("amplifier").asString(), @@ -148,9 +148,9 @@ public static SubSettingsBuilder createPotionSettingsBuilder(boolean potionType, public static SubSettingsBuilder createStructureSettingsBuilder() { return SubSettingsBuilder.createChooseItem(STRUCTURE).fill(builder -> { - builder.addSetting("random_structure", new ItemBuilder(Material.STRUCTURE_BLOCK, Message.forName("item-custom-action-place_structure-random")).build()); + builder.addSetting("random_structure", new LegacyItemBuilder(Material.STRUCTURE_BLOCK, Message.forName("item-custom-action-place_structure-random")).build()); for (StructureType structure : StructureType.getStructureTypes().values()) { - builder.addSetting(structure.getName(), new ItemBuilder(StructureUtils.getStructureIcon(structure), DefaultItem.getItemPrefix() + StringUtils.getEnumName(structure.getName())).build()); + builder.addSetting(structure.getName(), new LegacyItemBuilder(StructureUtils.getStructureIcon(structure), DefaultItem.getItemPrefix() + StringUtils.getEnumName(structure.getName())).build()); } }); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java index 18e0976c5..3d6ca244b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java @@ -10,6 +10,7 @@ import java.util.LinkedList; import java.util.List; +@Deprecated public final class ItemDescription { private static final Document config = Challenges.getInstance().getConfigDocument().getDocument("design"); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java index d76ab1145..06dab412d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.content; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.impl.MessageManager; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.collection.IRandom; @@ -13,6 +14,7 @@ import java.util.ArrayList; import java.util.Collection; +@Deprecated public interface Message { String NULL = "§r§fN/A"; @@ -29,6 +31,7 @@ static String unknown(@NotNull String name) { @NotNull @CheckReturnValue + @Deprecated static Message forName(@NotNull String name) { return MessageManager.getOrCreateMessage(name); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java deleted file mode 100644 index 4fc52a295..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Prefix.java +++ /dev/null @@ -1,67 +0,0 @@ -package net.codingarea.challenges.plugin.content; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -public class Prefix { - - private static final Map values = new HashMap<>(); - - public static final Prefix - CHALLENGES = forName("challenges", "§6Challenges"), - CUSTOM = forName("custom", "§bCustom"), - DAMAGE = forName("damage", "§cDamage"), - POSITION = forName("position", "§9Position"), - BACKPACK = forName("backpack", "§aBackpack"), - TIMER = forName("timer", "§5Timer"); - - private final String name; - private final String defaultValue; - private String value; - - private Prefix(@NotNull String name, @NotNull String defaultValue) { - this.defaultValue = getDefaultValueFor(defaultValue); - this.name = name; - } - - @NotNull - public static Collection values() { - return Collections.unmodifiableCollection(values.values()); - } - - @NotNull - public static Prefix forName(@NotNull String name, @NotNull String defaultValue) { - return values.computeIfAbsent(name, key -> new Prefix(name, defaultValue)); - } - - @NotNull - public static Prefix forName(@NotNull String name) { - return forName(name, name); - } - - @NotNull - public static String getDefaultValueFor(@NotNull String value) { - return "§8§l┃ " + value + " §8┃ "; - } - - public void setValue(@Nullable String value) { - this.value = value == null ? null : value.endsWith(" ") ? value : value + " "; - } - - @NotNull - @Override - public String toString() { - return (value == null ? defaultValue : value) + "§7"; - } - - @NotNull - public String getName() { - return name; - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LanguageProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LanguageProvider.java new file mode 100644 index 000000000..ff58704c2 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LanguageProvider.java @@ -0,0 +1,25 @@ +package net.codingarea.challenges.plugin.content.i18n; + +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; + +public interface LanguageProvider { + + /** + * Currently only the language tag of the locale is used, country code and variant are ignored. + * Default behavior currently implements one global language set in the plugin.yml. + */ + @NotNull + Locale getPlayerLanguage(@NotNull Player player); + + /** + * Whether this provider uses the default global language set in the plugin.yml. + * Return {@code false} when implementing custom behavior. + */ + boolean isDefaultBehaviour(); + + boolean isUserSpecific(); + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java new file mode 100644 index 000000000..04e2bac62 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java @@ -0,0 +1,28 @@ +package net.codingarea.challenges.plugin.content.i18n; + +import net.codingarea.challenges.platform.message.MessageHolder; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; + +/** + * Represents a {@link MessageKey} with arguments that can be passed as a message argument. + * + * @see MessageKey#withArgs(Object...) + */ +public interface LocalizableMessage { + + @NotNull + MessageHolder localize(@NotNull Locale locale); + + @NotNull + MessageHolder localize(@NotNull Player playerLocale); + + @NotNull + MessageKey getLocalizableKey(); + + @NotNull + Object[] getLocalizableArgs(); + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java new file mode 100644 index 000000000..60107aea4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java @@ -0,0 +1,286 @@ +package net.codingarea.challenges.plugin.content.i18n; + +import net.codingarea.challenges.plugin.Challenges; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.meta.ItemMeta; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Locale; + +/** + * Identifies a translatable message using a unique name (key). + * Subdocument/-object paths may be accessed by using dots as the path delimiter. + *

+ * Provides all required helpers and accessor to utilize them directly like + *

    + *
  • {@link #send(Player, Prefix, Object...)} to send this as a chat message to a player in their language
  • + *
  • {@link #sendRandom(Player, Prefix, Object...)} to send one randomly selected chat message (of the translation array) in their language
  • + *
  • {@link #sendTitle(Player, Object...)} to send this as a title and subtitle to a player in their language, where the first line in the array in the header, and the second the subtitle
  • + *
  • {@link #sendActionBar(Player, Object...)} to send this as an action bar to a player, the translation must be one line
  • + *
  • {@link #broadcast(Prefix, Object...)} to send this as a chat message to all players in their language
  • + *
  • {@link #createInventory(Locale, int, Object...)} to create an inventory with translated title
  • + *
+ * See {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder#ItemBuilder(Locale, Material, MessageKey, Object...)} + * for creating items with translated names and descriptions. + *

+ * Due to compatibility issues we cannot expose the internally used adventure api / mini-message api to this module directly. + * + * @implSpec Do NOT store {@link MessageKey} instances {@code statically}, but rather use {@link #of(String)} to retrieve them when needed. + * @implNote Messages may use the following formats: + *

    + *
  • + * Positional Arguments: + * {@code {0}}, {@code {1}}, etc. - Replaced by corresponding arguments passed at runtime. + *
  • + *
  • + * Message References: + * {@code {@message.key}} - Dynamically embeds another message from the bundle. + * Supports multi-line resolution and gracefully handles cyclic dependencies. + * Positional arguments will be added to the root translation while the argument indices remain unmodified. + *
  • + *
  • + * Mini Message + * The system uses "Mini Messages" internally, by parsing {@code <...>} tags; + * see the MiniMessage documentation for more. + *
  • + *
  • + * Legacy Colors + * Currently, legacy colors using '§' are still supported, but it's strongly recommended to use the MiniMessage + * format instead as this implementation is subject to change + *
  • + *
  • + * Supported Argument Types + * The following argument types are currently supported by default and will automatically be formatted + * (and translated using their namespace key if possible) + *
      + *
    • {@link MessageKey} will automatically be localized into the targeted language + * (for static linking use {@code {\@x}} reference)
    • + *
    • {@link LocalizableMessage} will automatically be localized into the target language, + * it can be used to reference messages dynamically with additional object arguments using {@link MessageKey#withArgs(Object...)}
    • + *
    • {@link org.bukkit.Material}
    • + *
    • {@link org.bukkit.entity.EntityType}
    • + *
    • {@link org.bukkit.GameMode}
    • + *
    • {@link org.bukkit.entity.Player} using their name
    • + *
    • Unknown Enums will be formatted as {@code TEST_ENUM -> "Test Enum"}
    • + *
    • Unresolvable types will be serialized using {@link Object#toString()}
    • + *
    + *
  • + *
+ * @see TranslationManager TranslationManager for localization + * @see net.codingarea.challenges.platform.message.MessagePlatform MessagePlatform for implementation + * @see net.codingarea.challenges.plugin.content.i18n.impl.MessageFormatter MessageFormatter for references + */ +public interface MessageKey extends LocalizableMessage { + + /** + * @implSpec Do NOT store {@link MessageKey} instances {@code statically}, but rather retrieve them when needed. + * @see #withArgs(Object...) + */ + @NotNull + @CheckReturnValue + static MessageKey of(@NotNull String id) { + TranslationManager i18n = Challenges.getInstance().getTranslationManager(); + if (i18n == null) throw new IllegalStateException("TranslationManager not initialized yet"); + return i18n.getMessageKey(id); + } + + @NotNull + static String formatMissingTranslation(@NotNull String key, @NotNull Locale locale) { + return String.format("%s/%s", key, locale); + } + + @NotNull + String getKey(); + + boolean isCached(@NotNull Locale locale); + + void removeValue(@NotNull Locale locale); + + void setValue(@NotNull Locale locale, @NotNull String[] values); + + /** + * @param locale language to translate to + * @return the raw value of this translated message or {@link #formatMissingTranslation(String, Locale)} + * @implSpec the returned array must never be empty + */ + @NotNull + String[] localizeRawValue(@NotNull Locale locale); + + /** + * @param locale language to translate to + * @return the raw value of this translated message as one string (if it consists of only one line, + * joined by newlines {@code \n} if multiple lines) or {@link #formatMissingTranslation(String, Locale)} + */ + @NotNull + String localizeRawValueAsSingleLine(@NotNull Locale locale); + + @NotNull + LocalizableMessage withArgs(@NotNull Object... args); + + // Helpers + + /** + * If the target ({@link CommandSender}) is not an instance of {@link Player}, + * the message will be translated using the global server language set in the {@code plugin.yml} + * + * @see net.codingarea.challenges.plugin.content.loader.LanguageLoader#getConfigLanguage() + */ + void send(@NotNull CommandSender target, @Nullable Prefix prefix, @NotNull Object... args); + + void send(@NotNull Player target, @Nullable Prefix prefix, @NotNull Object... args); + + void sendRandom(@NotNull Player target, @Nullable Prefix prefix, @NotNull Object... args); + + void broadcast(@Nullable Prefix prefix, @NotNull Object... args); + + /** + * Broadcasts one of the entries in the array at random. + * All players receive the same message translated into their language set by the {@link LanguageProvider} + */ + void broadcastRandom(@Nullable Prefix prefix, @NotNull Object... args); + + void sendTitle(@NotNull Player target, @NotNull Object... args); + + void sendTitleInstantly(@NotNull Player target, @NotNull Object... args); + + void broadcastTitle(@NotNull Object... args); + + void broadcastTitleInstantly(@NotNull Object... args); + + void sendActionBar(@NotNull Player target, @NotNull Object... args); + + void broadcastActionBar(@NotNull Object... args); + + /** + * Creates a new {@link Inventory} with the title of this message translated into the given language + * (and replacing the given args) and the given size. It uses {@link net.codingarea.commons.bukkit.utils.menu.MenuPosition#HOLDER} + * as the {@link InventoryHolder}. + * + * @see org.bukkit.Bukkit#createInventory(InventoryHolder, int, String) + */ + @NotNull + @CheckReturnValue + Inventory createInventory(@NotNull Locale locale, int size, @NotNull Object... args); + + /** + * Creates a new {@link Inventory} with the title of this message translated into the Player's language + * (and replacing the given args) and the given size. It uses {@link net.codingarea.commons.bukkit.utils.menu.MenuPosition#HOLDER} + * as the {@link InventoryHolder}. + * + * @see org.bukkit.Bukkit#createInventory(InventoryHolder, int, String) + */ + @NotNull + @CheckReturnValue + default Inventory createInventory(@NotNull Player playerLocale, int size, @NotNull Object... args) { + return createInventory(findPlayerLocale(playerLocale), size, args); + } + + /** + * Creates a new {@link Inventory} with the title of this message translated into the given language + * (and replacing the given args) and the given type. It uses {@link net.codingarea.commons.bukkit.utils.menu.MenuPosition#HOLDER} + * as the {@link InventoryHolder}. + * + * @see org.bukkit.Bukkit#createInventory(InventoryHolder, InventoryType, String) + */ + @NotNull + @CheckReturnValue + Inventory createInventory(@NotNull Locale locale, @NotNull InventoryType type, @NotNull Object... args); + + /** + * Creates a new {@link Inventory} with the title of this message translated into the Player's language + * (and replacing the given args) and the given type.It uses {@link net.codingarea.commons.bukkit.utils.menu.MenuPosition#HOLDER} + * as the {@link InventoryHolder}. + * + * @see org.bukkit.Bukkit#createInventory(InventoryHolder, InventoryType, String) + */ + @NotNull + @CheckReturnValue + default Inventory createInventory(@NotNull Player playerLocale, @NotNull InventoryType type, @NotNull Object... args) { + return createInventory(findPlayerLocale(playerLocale), type, args); + } + + /** + * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. + */ + @ApiStatus.Internal + void applyAsItemNameAndLore(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args); + + /** + * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. + */ + @ApiStatus.Internal + default void applyAsItemNameAndLore(@NotNull Player playerLocale, @NotNull ItemMeta item,@NotNull Object... args) { + applyAsItemNameAndLore(findPlayerLocale(playerLocale), item, args); + } + + /** + * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. + */ + @ApiStatus.Internal + void applyAsItemName(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args); + + /** + * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. + */ + @ApiStatus.Internal + default void applyAsItemName(@NotNull Player playerLocale, @NotNull ItemMeta item, @NotNull Object... args) { + applyAsItemName(findPlayerLocale(playerLocale), item, args); + } + + /** + * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. + */ + @ApiStatus.Internal + void appendToItemName(@NotNull Locale locale, @NotNull ItemMeta item, boolean withSpace, @NotNull Object... args); + + /** + * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. + */ + @ApiStatus.Internal + default void appendToItemName(@NotNull Player playerLocale, @NotNull ItemMeta item, boolean withSpace, + @NotNull Object... args) { + appendToItemName(findPlayerLocale(playerLocale), item, withSpace, args); + } + + /** + * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. + */ + @ApiStatus.Internal + void applyAsItemLore(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args); + + /** + * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. + */ + @ApiStatus.Internal + default void applyAsItemLore(@NotNull Player playerLocale, @NotNull ItemMeta item, @NotNull Object... args) { + applyAsItemLore(findPlayerLocale(playerLocale), item, args); + } + + /** + * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. + */ + @ApiStatus.Internal + void appendToItemLore(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args); + + /** + * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. + */ + @ApiStatus.Internal + default void appendToItemLore(@NotNull Player player, @NotNull ItemMeta item, @NotNull Object... args) { + appendToItemLore(findPlayerLocale(player), item, args); + } + + @NotNull + private Locale findPlayerLocale(@NotNull Player player) { + return Challenges.getInstance().getTranslationManager().getLanguageProvider().getPlayerLanguage(player); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/Prefix.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/Prefix.java new file mode 100644 index 000000000..0f704fc4f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/Prefix.java @@ -0,0 +1,42 @@ +package net.codingarea.challenges.plugin.content.i18n; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.jetbrains.annotations.NotNull; + +@AllArgsConstructor +public class Prefix { + + public static final Prefix + CHALLENGES = create("challenges", "§6Challenges"), + CUSTOM = create("custom", "§bCustom"), + DAMAGE = create("damage", "§cDamage"), + POSITION = create("position", "§9Position"), + BACKPACK = create("backpack", "§aBackpack"), + TIMER = create("timer", "§5Timer"); + + private final String messageKey; + + @Getter + private final String legacyFallback; // will only ever be used if language files could not be loaded + + @NotNull + public MessageKey getKey() { + return MessageKey.of(messageKey); + } + + @Override + public String toString() { + return legacyFallback; + } + + public static Prefix create(@NotNull String messageKeySuffix, @NotNull String legacyFallbackFormat) { + String prefixKey = "prefix." + messageKeySuffix; + return new Prefix(prefixKey, createLegacyFallback(legacyFallbackFormat)); + } + + private static String createLegacyFallback(@NotNull String legacyPrefixFormat) { + return "§8§l┃ " + legacyPrefixFormat + " §8┃ "; + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/TranslationManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/TranslationManager.java new file mode 100644 index 000000000..9a4116539 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/TranslationManager.java @@ -0,0 +1,122 @@ +package net.codingarea.challenges.plugin.content.i18n; + +import com.google.common.base.Preconditions; +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.i18n.impl.MessageFormatter; +import net.codingarea.challenges.plugin.content.i18n.impl.MessageKeyImpl; +import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.ReflectionUtils; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +public class TranslationManager { + + public static final Locale FALLBACK_LOCALE = Locale.ENGLISH; + + // default: populated by LanguageLoader + // message name/key -> value obj + protected final Map cachedMessages = new ConcurrentHashMap<>(); + protected final Set cachedLanguages = new HashSet<>(); + + protected LanguageProvider languageProvider; // by default injected by LanguageLoader + + @NotNull + public LanguageProvider getLanguageProvider() { + if (languageProvider == null) + throw new IllegalStateException("LanguageProvider not yet set, probably accessed before LanguageLoader has been called!"); + return languageProvider; + } + + public boolean isLanguageProviderInitialized() { + // will only ever be null during onLoad cycle + return languageProvider != null; + } + + public void setLanguageProvider(@NotNull LanguageProvider languageProvider) { + Preconditions.checkNotNull(languageProvider, "Cannot set LanguageProvider to null"); + this.languageProvider = languageProvider; + } + + public MessageKey getMessageKey(@NotNull String key) { + return cachedMessages.computeIfAbsent(key, forKey -> { + Challenges.getInstance().getILogger().warn("Tried accessing unknown message '{}', called by {}", forKey, ReflectionUtils.getCallerName(3)); + return new MessageKeyImpl(forKey); + }); + } + + public boolean isLanguageCached(@NotNull Locale locale) { + boolean cachedUnnormalized = cachedLanguages.contains(locale); + if (cachedUnnormalized) return true; + return cachedLanguages.contains(normalizeLocale(locale)); + } + + public void unloadLanguage(@NotNull Locale locale) { + for (MessageKeyImpl message : cachedMessages.values()) { + message.removeValue(locale); + } + cachedLanguages.remove(normalizeLocale(locale)); + } + + public int populateLanguageFromDocument(@NotNull Locale locale, @NotNull Document document, @Nullable Document globalDocument) { + Map messageBundle = new HashMap<>(); + + if (globalDocument != null) { + extractFlattenedMessagesInto(globalDocument, messageBundle, MessageFormatter.SUB_DOCUMENT_DELIMITER, ""); + } + extractFlattenedMessagesInto(document, messageBundle, MessageFormatter.SUB_DOCUMENT_DELIMITER, ""); + + populateLanguage(locale, messageBundle); + return messageBundle.size(); + } + + private void extractFlattenedMessagesInto(@NotNull Document from, @NotNull Map into, char pathDelimiter, @NotNull String path) { + for (String key : from.keys()) { + if (from.isDocument(key)) { + extractFlattenedMessagesInto(from.getDocument(key), into, pathDelimiter, path + key + pathDelimiter); + } else { + into.put(path + key, from.getStringArray(key)); + } + } + } + + public void populateLanguage(@NotNull Locale locale, @NotNull Map messageBundle) { + // pre resolve references to improve runtime performance + // we need all translated messages beforehand, to resolve references! + for (Map.Entry entry : messageBundle.entrySet()) { + // skip meta tags, they should not be cached and inflate memory usage + // they should only ever be used in the reference/argument resolution stage + if (MessageFormatter.isMetaTag(entry.getKey())) continue; + String[] embeddedReferenced = MessageFormatter.embedReferences(entry.getValue(), entry.getKey(), messageBundle); + cachedMessages.computeIfAbsent(entry.getKey(), MessageKeyImpl::new) + .setValue(locale, embeddedReferenced); + } + cachedLanguages.add(normalizeLocale(locale)); + } + + @NotNull + @CheckReturnValue + public static Locale normalizeLocale(@Nullable Locale locale) { + if (locale == null) return FALLBACK_LOCALE; + + if (locale.getCountry().isEmpty() && + locale.getVariant().isEmpty() && + locale.getScript().isEmpty() && + locale.getExtensionKeys().isEmpty()) { + return locale; + } + + // O(1) impl for supported languages + return switch (locale.getLanguage()) { + case "en" -> Locale.ENGLISH; + case "de" -> Locale.GERMAN; + + // Locale.forLanguagerTag is expensive, use only if necessary + default -> Locale.forLanguageTag(locale.getLanguage()); + }; + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageFormatter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageFormatter.java new file mode 100644 index 000000000..0715ac5ea --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageFormatter.java @@ -0,0 +1,353 @@ +package net.codingarea.challenges.plugin.content.i18n.impl; + +import net.codingarea.commons.common.logging.ILogger; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NonNull; + +import java.util.*; + +import static net.codingarea.challenges.platform.message.MessagePlatform.*; + +public final class MessageFormatter { // pre expansion for better server runtime performance + + public static final char COLORIZE_CHAR = '*'; + public static final String COLORIZE_KEY = "*colorize"; + public static final char SUB_DOCUMENT_DELIMITER = '.'; + public static final String SUB_DOCUMENT_PATH_PATTERN = "\\."; + public static final String[] EMPTY_STRINGS = new String[0]; + + private static final ILogger logger = ILogger.forThisClass(); // logs illegal argument indices or references + + private MessageFormatter() { + } + + @CheckReturnValue + public static boolean isMetaTag(@NotNull String keyName) { + String[] subPathComponents = keyName.split(SUB_DOCUMENT_PATH_PATTERN); + String relativeKeyName = subPathComponents[subPathComponents.length - 1]; + return relativeKeyName.equals(COLORIZE_KEY); // currently only meta implemented + } + + @NotNull + @CheckReturnValue + public static String[] embedReferences(@NotNull String[] origin, @NotNull String originKey, + @NotNull Map messagesBundle) { + HashSet visited = new HashSet<>(); + visited.add(originKey); + return embedReferences(origin, originKey, messagesBundle, visited); + } + + @NotNull + private static String[] embedReferences(@NotNull String[] origin, @NotNull String originKey, + @NotNull Map messagesBundle, @NotNull Set visited) { + if (origin.length == 0) return origin; + if (messagesBundle.isEmpty()) return origin; + + String[] originSubDocumentPath = extractSubDocumentPath(originKey); // for relative references resolution + + colorize(origin, originSubDocumentPath, messagesBundle); // apply colorization if defined for this sub-document + + // if a referenced message is more than one line, the result will grow + ArrayList result = new ArrayList<>(origin.length); + // will be cleared and reused + StringBuilder builder = new StringBuilder(origin[0].length()); + StringBuilder reference = new StringBuilder(32); // usually short (e.g., @message.key) + StringBuilder referenceArgument = new StringBuilder(32); + ArrayList referenceArguments = new ArrayList<>(4); // usually few arguments + boolean inReference = false; + boolean inReferenceArguments = false; + boolean inReferenceArgument = false; + + for (String line : origin) { + int len = line.length(); + for (int i = 0; i < len; i++) { + char c = line.charAt(i); + + if (c == ESCAPE_CHAR && i + 1 < len) { + // append escaped chars normally, don't trigger reference logic + c = line.charAt(++i); + if (inReference) { + reference.append(c); + } else if (inReferenceArgument) { + referenceArgument.append(c); + } else { + builder.append(c); + } + continue; + } + + if (c == END_ARG_CHAR && inReference && !inReferenceArguments) { + inReference = false; + resolveReferenceInto(originKey, messagesBundle, visited, line, reference, originSubDocumentPath, referenceArguments, builder, result); + continue; // skip end char + } + + if (c == START_ARG_CHAR && !inReference) { + if (i + 1 < len && line.charAt(i + 1) == REFERENCE_CHAR) { + i++; // also skip ref char + inReference = true; + continue; // skip start char + } + // append normally + } + + if (c == START_REFERENCE_ARGS_CHAR && inReference && !inReferenceArguments) { + inReferenceArguments = true; + continue; // skip start char + } + if (c == REFERENCE_ARG_CHAR && inReferenceArguments) { + if (inReferenceArgument) { + String builtReferenceArgument = referenceArgument.toString(); + + referenceArguments.add(builtReferenceArgument); + referenceArgument.setLength(0); // clear and reuse + } + inReferenceArgument = !inReferenceArgument; + continue; // skip arg char + } + if (c == END_REFERENCE_ARGS_CHAR && inReferenceArguments && !inReferenceArgument) { + inReferenceArguments = false; + continue; // skip end char + } + if (inReferenceArgument) { + referenceArgument.append(c); + continue; + } + if (inReferenceArguments) { + continue; // skip ", " + } + + if (inReference) { + reference.append(c); + continue; + } + + builder.append(c); + } // end of processing this line + + if (!reference.isEmpty()) { // arg was not closed + System.err.println("Unclosed reference in '" + line + "' of " + originKey + ": '" + reference + "'"); + builder.append(START_ARG_CHAR).append(reference); + } + if (!referenceArgument.isEmpty()) { // arg was not closed + System.err.println("Unclosed reference argument in '" + line + "' of " + originKey + ": '" + referenceArgument + "'"); + builder.append(REFERENCE_ARG_CHAR).append(referenceArgument); + } + + if (!builder.isEmpty()) { // don't append if line ends with reference + result.add(builder.toString()); + } + + builder.setLength(0); // reset line for next iteration + } + return result.toArray(String[]::new); + } + + private static void resolveReferenceInto(@NotNull String originKey, @NotNull Map messagesBundle, + @NotNull Set visited, @NotNull String line, StringBuilder reference, + @NotNull String[] originSubDocumentPath, @NotNull ArrayList referenceArguments, + @NotNull StringBuilder builder, @NotNull ArrayList result) { + String relativeReferenceName = reference.toString(); + reference.setLength(0); // clear and reuse + + String qualifiedReferenceName = qualifyRelativeKey(relativeReferenceName, originSubDocumentPath, messagesBundle); + + if (visited.contains(qualifiedReferenceName)) { + logger.warn("Cyclic message reference '{}' (qualified: {}) in '{}' [visited {}]", + relativeReferenceName, qualifiedReferenceName, originKey, visited); + return; + } + + String[] rawReferenceValue = messagesBundle.get(qualifiedReferenceName); + + if (rawReferenceValue != null && rawReferenceValue.length != 0) { + // resolve nested references + visited.add(qualifiedReferenceName); + String[] referenced = embedReferences(rawReferenceValue, qualifiedReferenceName, messagesBundle, visited); + visited.remove(qualifiedReferenceName); // allow the same references multiple times + + // embed reference args + String[] embeddedReferenced = referenceArguments.isEmpty() ? referenced : embedPositionalArgs(referenced, referenceArguments.toArray()); + referenceArguments.clear(); // clear and reuses + + + System.out.println("Resolved reference '" + relativeReferenceName + "' (qualified: " + qualifiedReferenceName + ") in " + originKey + + ": " + Arrays.toString(referenced) + " -> " + Arrays.toString(embeddedReferenced)); + + // append reference message + if (referenced.length == 1) { + builder.append(embeddedReferenced[0]); + } else { + // if the reference is multiple lines + // e.g. ["Unser Text {@ref} mit Spaß", "..."] + @ref=["Zeile1", "Zeile2"] + // = ["Unser Text Zeile1", "Zeile2", " mit Spaß" "..."] + result.add(builder + embeddedReferenced[0]); + builder.setLength(0); // reset line, already added + for (int r = 1; r < embeddedReferenced.length; r++) { + result.add(embeddedReferenced[r]); + } + } + } else { + // fallback if reference is not found or empty + logger.warn("Invalid message reference '{}' (qualified: {}) in {}: '{}'", relativeReferenceName, qualifiedReferenceName, originKey, line); + builder.append(START_ARG_CHAR).append(REFERENCE_CHAR).append(qualifiedReferenceName).append(END_ARG_CHAR); + } + } + + @NotNull + @CheckReturnValue + private static String qualifyRelativeKey(@NotNull String relativeReferenceName, @NotNull String[] originSubDocumentPath, + @NonNull Map messagesBundle) { + String qualifiedReferenceName = relativeReferenceName; + for (int path = 0; path < originSubDocumentPath.length && !messagesBundle.containsKey(qualifiedReferenceName); path++) { + StringBuilder pathQualifierUntilX = new StringBuilder(originSubDocumentPath.length * 12); + for (int j = 0; j <= path; j++) { + pathQualifierUntilX.append(originSubDocumentPath[j]).append(SUB_DOCUMENT_DELIMITER); + } + String pathQualifierUntilXString = pathQualifierUntilX.toString(); + if (!qualifiedReferenceName.startsWith(pathQualifierUntilXString)) { + qualifiedReferenceName = pathQualifierUntilXString + relativeReferenceName; + } + } + return qualifiedReferenceName; + } + + private static String[] extractSubDocumentPath(@NotNull String key) { + String[] split = key.split(SUB_DOCUMENT_PATH_PATTERN); + if (split.length <= 1) return EMPTY_STRINGS; + return Arrays.copyOfRange(split, 0, split.length - 1); // drop last part (key itself) + } + + @NotNull + @CheckReturnValue + public static String[] embedPositionalArgs(@NotNull String[] origin, @NotNull Object[] args) { + String[] result = new String[origin.length]; + for (int i = 0; i < origin.length; i++) { + result[i] = embedPositionalArgs(origin[i], args); + } + return result; + } + + @NotNull + @CheckReturnValue + public static String embedPositionalArgs(@NotNull String sequence, @NotNull Object[] args) { + if (args.length == 0) return sequence; + + // faster (maybe more error-prone) impl than regex matching + boolean inArgument = false; + StringBuilder builder = new StringBuilder(sequence.length() + 16); // maybe avoid resizing + StringBuilder argument = new StringBuilder(2); // usually short (e.g., {0}, {11}) + + int len = sequence.length(); + for (int i = 0; i < len; i++) { + char c = sequence.charAt(i); + + if (c == END_ARG_CHAR && inArgument) { + inArgument = false; + + if (!argument.isEmpty() && argument.charAt(0) == REFERENCE_CHAR) { + argument.setLength(0); // clear and reuse + continue; + } + + int argIndex = parsePositiveInt(argument); + if (argIndex >= 0 && argIndex < args.length) { + builder.append(args[argIndex]); // String.valueOf + } else { + // fallback if index is invalid or out of bounds + logger.warn("Invalid argument index '{}' in '{}'", argument, sequence); + builder.append(START_ARG_CHAR).append(argument).append(END_ARG_CHAR); + } + argument.setLength(0); // clear and reuse + continue; // skip end char + } + + if (c == START_ARG_CHAR && !inArgument) { + inArgument = true; + continue; // skip start char + } + + if (inArgument) { + argument.append(c); + continue; + } + + builder.append(c); + } + + if (!argument.isEmpty()) { // arg was not closed + builder.append(START_ARG_CHAR).append(argument); + } + + return builder.toString(); + } + + private static void colorize(@NotNull String[] rawValue, @NotNull String[] originSubDocumentPath, @NotNull Map messageBundle) { + if (rawValue.length == 0) return; + + String qualifiedColorizeKey = qualifyRelativeKey(COLORIZE_KEY, originSubDocumentPath, messageBundle); + String[] colorizeValue = messageBundle.get(qualifiedColorizeKey); + if (colorizeValue == null || colorizeValue.length == 0) return; // no colorizer defined + + StringBuilder builder = new StringBuilder(rawValue[0].length() + colorizeValue[0].length()); + StringBuilder argument = new StringBuilder(32); + boolean colorizing = false; + for (int line = 0; line < rawValue.length; line++) { + String text = rawValue[line]; + int len = text.length(); + for (int i = 0; i < len; i++) { + char c = text.charAt(i); + + if (c == ESCAPE_CHAR) { + if (i < len - 1) { + c = text.charAt(++i); + } + if (colorizing) argument.append(c); + else builder.append(c); + continue; + } + + if (c == COLORIZE_CHAR) { + if (colorizing) { + colorizing = false; + String[] embeddedColorized = embedPositionalArgs(colorizeValue, new Object[]{argument.toString()}); + for (String s : embeddedColorized) { + builder.append(s); + } + argument.setLength(0); // clear and reuse + } else { + colorizing = true; + } + continue; // skip colorize char + } + + if (colorizing) { + argument.append(c); + continue; + } + builder.append(c); + } // end of line + + if (!argument.isEmpty()) { + builder.append(COLORIZE_CHAR).append(argument); + } + rawValue[line] = builder.toString(); + builder.setLength(0); // reset line for next iteration + } + } + + // helper to parse int without throwing expensive exceptions + public static int parsePositiveInt(@NotNull StringBuilder sb) { + int len = sb.length(); + if (len == 0) return -1; + int num = 0; + for (int i = 0; i < len; i++) { + char c = sb.charAt(i); + if (c < '0' || c > '9') return -1; // not a valid digit + num = num * 10 + (c - '0'); + } + return num; + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java new file mode 100644 index 000000000..f071912e4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java @@ -0,0 +1,356 @@ +package net.codingarea.challenges.plugin.content.i18n.impl; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import net.codingarea.challenges.platform.message.MessageHolder; +import net.codingarea.challenges.platform.message.MessagePlatform; +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.TranslationManager; +import net.codingarea.challenges.plugin.content.loader.LanguageLoader; +import net.codingarea.challenges.plugin.management.server.TitleManager; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import net.codingarea.commons.common.collection.IRandom; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.meta.ItemMeta; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NonNull; + +import java.util.*; + +public class MessageKeyImpl implements MessageKey { + + protected static final IRandom random = IRandom.create(); + + @Getter + protected final String key; + + @Getter + @Setter + protected Map values = new HashMap<>(); + + public MessageKeyImpl(@NotNull String key) { + this.key = key; + } + + public void setValue(@NotNull Locale locale, @NotNull String[] values) { + this.values.put(locale, values); + } + + @Override + public void removeValue(@NotNull Locale locale) { + values.remove(locale); + } + + @Override + public boolean isCached(@NotNull Locale locale) { + return values.containsKey(locale); + } + + @NotNull + @Override + public String[] localizeRawValue(@NotNull Locale locale) { + String[] value = values.get(locale); + if (value != null && value.length != 0) return value; + return new String[]{MessageKey.formatMissingTranslation(key, locale)}; + } + + @NotNull + @Override + public String localizeRawValueAsSingleLine(@NotNull Locale locale) { + String[] value = values.get(locale); + if (value == null || value.length == 0) return MessageKey.formatMissingTranslation(key, locale); + if (value.length == 1) return value[0]; + return String.join("\n", value); + } + + @NotNull + @Override + public LocalizableMessage withArgs(@NotNull Object... args) { + return new LocalizableMessageImpl(args); + } + + @NotNull + @Override + public MessageHolder localize(@NotNull Locale locale) { + return new MessageHolderImpl(localizeRawValue(locale), MessageHolderImpl.EMPTY_ARGS); + } + + @NotNull + @Override + public MessageHolder localize(@NotNull Player playerLocale) { + return localize(getPlayerLocale(playerLocale)); + } + + @NotNull + @Override + public MessageKey getLocalizableKey() { + return this; + } + + @NotNull + @Override + public Object[] getLocalizableArgs() { + return MessageHolderImpl.EMPTY_ARGS; + } + + protected void localizeArgs(@NotNull Locale locale, @NotNull Object[] args) { + for (int i = 0; i < args.length; i++) { + if (args[i] instanceof LocalizableMessage message) { + args[i] = message.localize(locale); + } + } + } + + @CheckReturnValue + protected Object[] localizeArgsAsCopy(@NotNull Locale locale, @NotNull Object[] args) { + if (args.length == 0) return args; + Object[] localizedArgs = Arrays.copyOf(args, args.length); // avoid mutating original array + localizeArgs(locale, localizedArgs); + return localizedArgs; + } + + @Override + public String toString() { + return key; + } + + @Override + public boolean equals(Object object) { + if (!(object instanceof MessageKeyImpl that)) return false; + return Objects.equals(key, that.key); + } + + @Override + public int hashCode() { + return key.hashCode(); + } + + @Nullable + protected String stringifyPrefix(@NotNull Locale locale, @Nullable Prefix prefix) { + if (prefix == null) return null; + MessageKey asKey = prefix.getKey(); + if (asKey.isCached(locale)) { + return asKey.localizeRawValueAsSingleLine(locale); + } + return prefix.getLegacyFallback(); + } + + @NotNull + protected Locale getPlayerLocale(@NotNull Player player) { + return Challenges.getInstance().getTranslationManager().getLanguageProvider().getPlayerLanguage(player); + } + + @NotNull + protected MessagePlatform getMessagePlatform() { + return Challenges.getInstance().getPlatformManager().getMessagePlatform(); + } + + + // Action Implementations + + @Override + public void send(@NotNull CommandSender target, @Nullable Prefix prefix, @NonNull @NotNull Object... args) { + if (target instanceof Player) { + send((Player) target, prefix, args); + } else { + Locale locale = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class) + .map(LanguageLoader::getConfigLanguage) + .orElse(TranslationManager.FALLBACK_LOCALE); + localizeArgs(locale, args); + getMessagePlatform().sendSenderMessage(target, stringifyPrefix(locale, prefix), localizeRawValue(locale), args); + } + } + + @Override + public void send(@NotNull Player target, @Nullable Prefix prefix, @NotNull Object... args) { + Locale locale = getPlayerLocale(target); + localizeArgs(locale, args); + getMessagePlatform().sendChatMessage(target, stringifyPrefix(locale, prefix), localizeRawValue(locale), args); + } + + @Override + public void sendRandom(@NotNull Player target, @Nullable Prefix prefix, @NotNull Object... args) { + Locale locale = getPlayerLocale(target); + localizeArgs(locale, args); + String raw = random.choose(localizeRawValue(locale)); + getMessagePlatform().sendChatMessage(target, stringifyPrefix(locale, prefix), new String[]{raw}, args); + } + + @Override + public void broadcast(@Nullable Prefix prefix, @NotNull Object... args) { + doBroadcast(prefix, args, getMessagePlatform()::sendChatMessage); + } + + @Override + public void broadcastRandom(@Nullable Prefix prefix, @NotNull Object... args) { + int index = random.nextInt(getMinValueLengthIncludingFallback()); + doBroadcast(prefix, args, (target, localizedPrefix, raw, localizedArgs) -> + getMessagePlatform().sendChatMessage(target, localizedPrefix, new String[]{raw[index]}, localizedArgs)); + } + + @Override + public void sendTitle(@NotNull Player target, @NonNull @NotNull Object... args) { + Locale locale = getPlayerLocale(target); + localizeArgs(locale, args); + getMessagePlatform().sendTitle(target, localizeRawValue(locale), args, TitleManager.FADEIN, TitleManager.DURATION, TitleManager.FADEOUT); + } + + @Override + public void sendTitleInstantly(@NotNull Player target, @NonNull @NotNull Object... args) { + Locale locale = getPlayerLocale(target); + localizeArgs(locale, args); + getMessagePlatform().sendTitle(target, localizeRawValue(locale), args, 0, TitleManager.DURATION, TitleManager.FADEOUT); + } + + @Override + public void broadcastTitle(@NotNull Object... args) { + doBroadcast(null, args, (target, _, raw, localizedArgs) -> + getMessagePlatform().sendTitle(target, raw, localizedArgs, TitleManager.FADEIN, TitleManager.DURATION, TitleManager.FADEOUT)); + } + + @Override + public void broadcastTitleInstantly(@NonNull @NotNull Object... args) { + doBroadcast(null, args, (target, _, raw, localizedArgs) -> + getMessagePlatform().sendTitle(target, raw, localizedArgs, 0, TitleManager.DURATION, TitleManager.FADEOUT)); + } + + @Override + public void sendActionBar(@NotNull Player target, @NotNull Object... args) { + Locale locale = getPlayerLocale(target); + localizeArgs(locale, args); + getMessagePlatform().sendActionBar(target, localizeRawValueAsSingleLine(locale), args); + } + + @Override + public void broadcastActionBar(@NotNull Object... args) { + // array will never be empty + doBroadcast(null, args, (target, _, raw, localizedArgs) -> + getMessagePlatform().sendActionBar(target, raw[0], localizedArgs)); + } + + @NotNull + @Override + public Inventory createInventory(@NotNull Locale locale, int size, @NotNull Object... args) { + localizeArgs(locale, args); + return getMessagePlatform().createInventory(MenuPosition.HOLDER, size, localizeRawValueAsSingleLine(locale), args); + } + + @Override + public @NotNull Inventory createInventory(@NotNull Locale locale, @NotNull InventoryType type, @NotNull Object... args) { + localizeArgs(locale, args); + return getMessagePlatform().createInventory(MenuPosition.HOLDER, type, localizeRawValueAsSingleLine(locale), args); + } + + protected void doBroadcast(@Nullable Prefix prefix, @NotNull Object[] args, @NotNull SendMessageConsumer messageSender) { + for (Player player : Bukkit.getOnlinePlayers()) { + Locale locale = getPlayerLocale(player); + messageSender.accept(player, stringifyPrefix(locale, prefix), localizeRawValue(locale), localizeArgsAsCopy(locale, args)); + } + } + + protected int getMinValueLengthIncludingFallback() { + if (values.isEmpty()) return 1; // fallback message + Iterator iterator = values.values().iterator(); + int min = iterator.next().length; + while (iterator.hasNext()) { + int length = iterator.next().length; + if (length == 0) return 1; // fallback message + if (length < min) min = length; + } + return min; // > 1 + } + + + // Item Implementations + + @Override + public void applyAsItemNameAndLore(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args) { + localizeArgs(locale, args); + + String[] rawValue = localizeRawValue(locale); // length >= 1 + if (rawValue.length == 1) { + applyAsItemName(locale, item, args); + return; + } + + String nameLine = rawValue[0]; + getMessagePlatform().applyItemName(item, nameLine, args); + + String[] loreLines = Arrays.copyOfRange(rawValue, 1, rawValue.length); + getMessagePlatform().applyItemLore(item, loreLines, args); + } + + @Override + public void applyAsItemName(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args) { + localizeArgs(locale, args); + getMessagePlatform().applyItemName(item, localizeRawValueAsSingleLine(locale), args); + } + + @Override + public void appendToItemName(@NotNull Locale locale, @NotNull ItemMeta item, boolean withSpace, @NotNull Object... args) { + String rawValue = localizeRawValueAsSingleLine(locale); + if (withSpace) rawValue = " " + rawValue; + getMessagePlatform().appendItemName(item, rawValue, args); + } + + @Override + public void applyAsItemLore(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args) { + localizeArgs(locale, args); + getMessagePlatform().applyItemLore(item, localizeRawValue(locale), args); + } + + @Override + public void appendToItemLore(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args) { + localizeArgs(locale, args); + getMessagePlatform().appendItemLore(item, localizeRawValue(locale), args); + } + + @FunctionalInterface + public interface SendMessageConsumer { + void accept(@NotNull Player target, @Nullable String localizedPrefix, @NotNull String[] raw, @NotNull Object[] localizedArgs); + } + + @AllArgsConstructor + public class LocalizableMessageImpl implements LocalizableMessage { + + private final Object[] args; + + @NotNull + @Override + public MessageHolder localize(@NotNull Locale locale) { + return new MessageHolderImpl(localizeRawValue(locale), localizeArgsAsCopy(locale, args)); + } + + @NotNull + @Override + public MessageHolder localize(@NotNull Player playerLocale) { + return localize(getPlayerLocale(playerLocale)); + } + + @Override + public @NotNull MessageKey getLocalizableKey() { + return MessageKeyImpl.this; + } + + @NotNull + @Override + public Object[] getLocalizableArgs() { + return args; + } + } + + public record MessageHolderImpl(String[] miniMessageRaw, Object[] positionalArgs) implements MessageHolder { + public static final Object[] EMPTY_ARGS = new Object[0]; + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java index a1dbc6e35..046618080 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.ItemDescription; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.misc.FontUtils; @@ -84,10 +84,7 @@ public BaseComponent asRandomComponent(@NotNull IRandom random, @NotNull Prefix public String[] asArray(@NotNull Object... args) { if (value == null) return new String[]{Message.unknown(name)}; args = BukkitStringUtils.replaceArguments(args, true); - LanguageLoader loader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); - boolean capsFont = false; - if (loader != null) capsFont = loader.isSmallCapsFont(); - return capsFont ? FontUtils.toSmallCaps(StringUtils.format(value, args)) : StringUtils.format(value, args); + return StringUtils.format(value, args); } @NotNull @@ -144,9 +141,8 @@ private void doSendLines(@NotNull Consumer sender, @NotNu } private void doSendLine(@NotNull Consumer sender, @NotNull Prefix prefix, BaseComponent component) { - LanguageLoader loader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); - boolean capsFont = false; - if (loader != null) capsFont = loader.isSmallCapsFont(); + LanguageLoader loader = Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class); + boolean capsFont = loader.isSmallCapsFont(); BaseComponent component1 = component; if (capsFont) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java index 9b1d0c285..3021dcac6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java @@ -1,8 +1,10 @@ package net.codingarea.challenges.plugin.content.impl; +import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; import org.jetbrains.annotations.NotNull; +import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -15,7 +17,12 @@ private MessageManager() { @NotNull public static Message getOrCreateMessage(@NotNull String name) { - return cache.computeIfAbsent(name, key -> new MessageImpl(key)); + return cache.computeIfAbsent(name, key -> { + MessageImpl message = new MessageImpl(key); + String[] value = Challenges.getInstance().getTranslationManager().getMessageKey(key).localizeRawValue(Locale.GERMAN); + message.setValue(value); + return message; + }); } public static boolean hasMessageInCache(@NotNull String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index 7ee18f501..63732f346 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -1,17 +1,16 @@ package net.codingarea.challenges.plugin.content.loader; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; import lombok.Getter; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.LanguageProvider; +import net.codingarea.challenges.plugin.content.i18n.TranslationManager; +import net.codingarea.challenges.plugin.management.files.ConfigManager; import net.codingarea.challenges.plugin.utils.logging.ConsolePrint; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.collection.IOUtils; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.misc.FileUtils; -import net.codingarea.commons.common.misc.GsonUtils; +import org.bukkit.entity.Player; import org.jetbrains.annotations.CheckReturnValue; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -19,111 +18,121 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.util.Collections; -import java.util.List; -import java.util.Map.Entry; -import java.util.Objects; +import java.util.*; public final class LanguageLoader extends ContentLoader { - public static final String FALLBACK_LANGUAGE = "en"; + public static final String FALLBACK_LANGUAGE = TranslationManager.FALLBACK_LOCALE.getLanguage(); - public static final String - KEY_LANGUAGE = "language", - KEY_ONLINE_UPDATE = "language-online-update", - KEY_LANGUAGE_OVERWRITE = "language-overwrite-path", - KEY_SMALL_CAPS = "small-caps"; + public static final String GLOBAL_TAG = "global"; @Getter private static volatile boolean loaded = false; @Getter - private String language; + private String configLanguageTag; // default, will be ignored if custom LanguageProvider is set in TranslationManager @Getter - private boolean smallCapsFont; + private Locale configLanguage; // default, will be ignored if custom LanguageProvider is set in TranslationManager @Getter - private boolean onlineUpdate; + @Deprecated + private final boolean smallCapsFont = false; @Getter - private boolean languageOverwrite; + private boolean onlineUpdateEnabled; + @Getter + private Set availableLanguageTags; + @Getter + private boolean skipMigration; @Override protected void load() { Document config = Challenges.getInstance().getConfigDocument(); - String languageOverwritePath = config.getString(KEY_LANGUAGE_OVERWRITE); - languageOverwrite = config.contains(KEY_LANGUAGE_OVERWRITE) && languageOverwritePath != null; - smallCapsFont = config.getBoolean(KEY_SMALL_CAPS, false); - language = config.getString(KEY_LANGUAGE, FALLBACK_LANGUAGE); - onlineUpdate = config.getBoolean(KEY_ONLINE_UPDATE, false); + onlineUpdateEnabled = config.getBoolean(ConfigManager.Keys.ONLINE_UPDATE, false); + configLanguageTag = config.getString(ConfigManager.Keys.LANGUAGE, FALLBACK_LANGUAGE); + skipMigration = config.getBoolean(ConfigManager.Keys.SKIP_LANGUAGE_MIGRATION, false); + configLanguage = Locale.forLanguageTag(configLanguageTag); + availableLanguageTags = new HashSet<>(); - if (languageOverwrite) { - loadOverwrite(languageOverwritePath); - return; - } + // extracted the language provider so it can easily be overridden + Challenges.getInstance().getTranslationManager().setLanguageProvider(new DefaultLanguageProvider()); loadDefault(); } + private void loadDefault() { + if (!skipMigration) migrateLanguages(); + discoverAvailableLanguageTagFiles(); + checkLanguageFileExists(); + readSelectedLanguage(); + } + public void changeLanguage(@NotNull String language) { - if (language.equalsIgnoreCase(this.language)) { + if (language.equalsIgnoreCase(this.configLanguageTag)) { Logger.info("Language '{}' is already selected", language); return; } - Challenges.getInstance().setValueInConfig(KEY_LANGUAGE, language); + Challenges.getInstance().setValueInConfig(ConfigManager.Keys.LANGUAGE, language); reloadWithLanguage(language); Logger.info("Language changed to '{}'", language); } - public void reloadWithLanguage(String language) { - this.language = language; - read(); - init(); + private void reloadWithLanguage(String language) { + this.configLanguageTag = language; + checkLanguageFileExists(); // do the check first, might change languageTag to fallback + this.configLanguage = Locale.forLanguageTag(configLanguageTag); + readSelectedLanguage(); // TODO async Challenges.getInstance().getScoreboardManager().updateAll(); - Challenges.getInstance().getConfigManager().getSettingsConfig().set("language", language); } - private void loadOverwrite(@NotNull String languageOverwritePath) { - Logger.info("Using direct language file '{}'", languageOverwritePath); - readLanguage(new File(languageOverwritePath)); - } - - private void loadDefault() { - migrateLanguages(onlineUpdate); - init(); - read(); - } - - private void init() { - language = Challenges.getInstance().getConfigDocument().getString("language", FALLBACK_LANGUAGE); - File file = getMessageFile(language, "json"); + private void checkLanguageFileExists() { + File file = getLanguageFile(configLanguageTag); if (!file.exists()) { - if (language.equalsIgnoreCase(FALLBACK_LANGUAGE)) return; - ConsolePrint.unknownLanguage(language); - language = FALLBACK_LANGUAGE; + if (configLanguageTag.equalsIgnoreCase(FALLBACK_LANGUAGE)) return; + ConsolePrint.unknownLanguage(configLanguageTag); + configLanguageTag = FALLBACK_LANGUAGE; } - Logger.debug("Language '{}' is currently selected", language); + Logger.debug("Language '{}' is currently selected", configLanguageTag); + } + + private void readSelectedLanguage() { + populateLanguageFromFile(configLanguage); + } + private void discoverAvailableLanguageTagFiles() { + // only .json files supported; global is not a selectable language + File[] files = getMessagesFolder() + .listFiles((_, name) -> name.endsWith(".json") && !name.startsWith(GLOBAL_TAG)); + if (files == null) return; + for (File file : files) { + if (!file.isFile()) continue; + availableLanguageTags.add(FileUtils.getFileName(file)); + } } - private void migrateLanguages(boolean onlineUpdate) { - // migrate with bundled languages + changed online translation (if enabled) + private void migrateLanguages() { + // migrate using bundled languages + changed online translations (if enabled) for (String language : loadBundledLanguageNames()) { try { Document bundledDocument = loadBundledLanguageDocument(language); if (bundledDocument == null) continue; + if (Challenges.getInstance().isDevMode()) { // overwrite all in dev mode + bundledDocument.saveToFile(getLanguageFile(language)); + continue; + } + Document migratedDocument = migrateLanguageDocument(bundledDocument, language); - Document onlineDocument = onlineUpdate ? fetchOnlineLanguageDocument(language) : null; + Document onlineDocument = onlineUpdateEnabled ? fetchOnlineLanguageDocument(language) : null; migrateLanguageFileAndSave(migratedDocument, bundledDocument, onlineDocument, language); } catch (IOException ex) { Logger.error("Could not migrate language file for {}", language, ex); } } - // pull new languages - if (onlineUpdate) { + // pull new languages / updates + if (onlineUpdateEnabled) { for (String language : fetchOnlineLanguages()) { File file = getLanguageFile(language); if (file.exists()) continue; // already exists, was migrated in previous step @@ -162,7 +171,7 @@ private Document migrateLanguageDocument(@NotNull Document bundledLanguage, @Not private void migrateLanguageFileAndSave(@NotNull Document migratedLanguage, @NotNull Document bundledLanguage, @Nullable Document onlineLanguage, @NotNull String languageName) throws IOException { File destinationFile = getLanguageFile(languageName); - if (onlineLanguage == null || Challenges.getInstance().isDevMode()) { // ignore online update in dev-mode! + if (onlineLanguage == null) { migratedLanguage.saveToFile(destinationFile); return; } @@ -183,7 +192,7 @@ private void migrateLanguageFileAndSave(@NotNull Document migratedLanguage, @Not @NotNull private List loadBundledLanguageNames() { try (InputStream in = getLanguageResourceStream("languages.json")) { - return Document.parseStringArray(IOUtils.toString(in)); + return Document.parseJsonStringArray(IOUtils.toString(in)); } catch (Exception ex) { Logger.error("Could not load bundled languages", ex); return Collections.emptyList(); @@ -213,7 +222,7 @@ private File getLanguageFile(String languageName) { @NotNull private List fetchOnlineLanguages() { try { - return Document.parseStringArray(IOUtils.toString(getGitHubUrl("language/languages.json"))); + return Document.parseJsonStringArray(IOUtils.toString(getGitHubUrl("language/languages.json"))); } catch (Exception ex) { Logger.error("Could not fetch online languages", ex); return Collections.emptyList(); @@ -231,40 +240,45 @@ private Document fetchOnlineLanguageDocument(@NotNull String languageName) { } } - private void read() { - readLanguage(getMessageFile(language, "json")); + public void populateLanguageFromFile(@NotNull Locale locale) { + populateLanguageFromFile(getLanguageFile(locale.getLanguage()), getLanguageFile(GLOBAL_TAG), locale); } - private void readLanguage(@NotNull File file) { + private void populateLanguageFromFile(@NotNull File languageFile, @NotNull File globalFile, @NotNull Locale locale) { try { - - if (!file.exists()) { + if (!languageFile.exists() || !globalFile.exists()) { ConsolePrint.unableToGetLanguages(); return; } - int messages = 0; - JsonObject read = JsonParser.parseReader(FileUtils.newBufferedReader(file)).getAsJsonObject(); // TODO fix(deps) version ambiguity - for (Entry entry : read.entrySet()) { - Message message = Message.forName(entry.getKey()); - JsonElement element = entry.getValue(); - if (element.isJsonPrimitive()) { - message.setValue(new String[]{element.getAsString()}); - messages++; - } else if (element.isJsonArray()) { - message.setValue(GsonUtils.convertJsonArrayToStringArray(element.getAsJsonArray())); - messages++; - } else { - Logger.warn("Illegal type '{}' for {}", element.getClass().getName(), message.getName()); - } - } + Document globalDocument = Document.readJsonFile(globalFile); + Document languageDocument = Document.readJsonFile(languageFile); + int messageCount = Challenges.getInstance().getTranslationManager().populateLanguageFromDocument(locale, languageDocument, globalDocument); loaded = true; - Logger.info("Successfully loaded language '{}' from config file: {} message(s)", language, messages); - + Logger.info("Successfully loaded language '{}' from config file: {} message(s)", locale, messageCount); } catch (Exception ex) { Logger.error("Could not read languages", ex); } } + public class DefaultLanguageProvider implements LanguageProvider { + + @NotNull + @Override + public Locale getPlayerLanguage(@NotNull Player player) { + return configLanguage; + } + + @Override + public boolean isDefaultBehaviour() { + return true; + } + + @Override + public boolean isUserSpecific() { + return false; + } + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java index 735e8522d..df645f7d1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java @@ -78,14 +78,19 @@ public void subscribe(@NotNull Class classOfLoader, @No execute(classOfLoader, action); } - @SuppressWarnings("unchecked") - public T getFirstLoaderByClass(@NotNull Class clazz) { + @NotNull + public Optional getFirstLoaderByClass(@NotNull Class clazz) { for (ContentLoader loader : loaders) { if (loader.getClass().equals(clazz)) { - return (T) loader; + return Optional.of(clazz.cast(loader)); } } - return null; + return Optional.empty(); + } + + @NotNull + public T findLoaderByClassOrThrow(@NotNull Class clazz) { + return getFirstLoaderByClass(clazz).orElseThrow(() -> new NoSuchElementException("No loader of type " + clazz.getSimpleName() + " found")); } private static class Subscribers { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java deleted file mode 100644 index cd8d446a1..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/PrefixLoader.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.codingarea.challenges.plugin.content.loader; - -import net.codingarea.challenges.plugin.content.Prefix; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.common.config.FileDocument; -import net.codingarea.commons.common.misc.FileUtils; - -import java.io.File; - -public final class PrefixLoader extends ContentLoader { - - @Override - protected void load() { - try { - - File file = getMessageFile("prefix", "properties"); - FileUtils.createFilesIfNecessary(file); - - FileDocument document = FileDocument.readPropertiesFile(file); - boolean changed = false; - - for (Prefix prefix : Prefix.values()) { - if (!document.contains(prefix.getName())) { - document.set(prefix.getName(), prefix.toString()); - changed = true; - continue; - } - - prefix.setValue(document.getString(prefix.getName())); - } - - if (changed) document.save(); - Logger.info("Successfully loaded {} prefixes from config file", Prefix.values().size()); - - } catch (Exception ex) { - Logger.error("Could not load prefixes", ex); - } - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java index 01a4abb3e..fe4975dc1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/blocks/BlockDropManager.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.setting.CutCleanSetting; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; -import net.codingarea.challenges.plugin.challenges.type.abstraction.MenuSetting.SubSetting; +import net.codingarea.challenges.plugin.challenges.type.abstraction.menu.MenuSetting.SubSetting; import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Material; import org.bukkit.block.Block; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java index b4156cb93..a524d65a7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/bstats/MetricsLoader.java @@ -17,12 +17,10 @@ public void start() { Challenges plugin = Challenges.getInstance(); Metrics metrics = new Metrics(plugin, 11494); - metrics.addCustomChart(new SimplePie("language", () -> { - LanguageLoader loader = Challenges.getInstance().getLoaderRegistry() - .getFirstLoaderByClass(LanguageLoader.class); - if (loader == null) return "NULL"; - return loader.getLanguage(); - })); + metrics.addCustomChart(new SimplePie("language", () -> Challenges.getInstance().getLoaderRegistry() + .getFirstLoaderByClass(LanguageLoader.class) + .map(LanguageLoader::getConfigLanguageTag) + .orElse("NULL"))); metrics.addCustomChart(new SimplePie("cloudType", () -> StringUtils.getEnumName(plugin.getCloudSupportManager().getType()))); metrics.addCustomChart(new SimplePie("databaseType", () -> StringUtils.getEnumName(plugin.getDatabaseManager().getType()))); metrics.addCustomChart(new SingleLineChart("totalMemory", this::getMemory)); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java index 67569118c..7af2dde08 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java @@ -18,7 +18,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.*; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.*; import net.codingarea.challenges.plugin.challenges.implementation.setting.*; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder.PotionBuilder; import net.codingarea.challenges.plugin.utils.misc.ArmorUtils; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java index c1b83c739..002644842 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java @@ -16,10 +16,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; +import java.util.*; import java.util.function.Predicate; public final class ChallengeManager { @@ -173,7 +170,7 @@ public void resetGamestate() { } public void saveGameStateInto(@NotNull Document config) { - LinkedList list = new LinkedList<>(challenges); + List list = new ArrayList<>(challenges); list.addAll(additionalSaver); for (GamestateSaveable challenge : list) { try { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java index a6451c62e..c8b14d236 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java @@ -8,8 +8,9 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.IChallengeTrigger; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.ChallengeMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.IMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengesMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChallengeMenuGenerator; import net.codingarea.challenges.plugin.utils.misc.MapUtils; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; @@ -52,7 +53,7 @@ public void unregisterCustomChallenge(@NotNull UUID uuid) { public void loadCustomChallengesFrom(@NotNull Document document) { customChallenges.clear(); Challenges.getInstance().getChallengeManager().unregisterIf(iChallenge -> iChallenge.getType() == MenuType.CUSTOM); - ((ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetChallengeCache(); + ((ChallengesMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetCache(); for (String key : document.keys()) { try { @@ -76,26 +77,26 @@ public void loadCustomChallengesFrom(@NotNull Document document) { } - MenuType.CUSTOM.getMenuGenerator().generateInventories(); +// MenuType.CUSTOM.getMenuGenerator().generateInventories(); TODO } public void resetChallenges() { customChallenges.clear(); Challenges.getInstance().getChallengeManager().unregisterIf(iChallenge -> iChallenge.getType() == MenuType.CUSTOM); - ((ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetChallengeCache(); + ((ChallengesMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetCache(); } private void generateCustomChallenge(CustomChallenge challenge, boolean deleted, boolean generate) { - MenuGenerator generator = challenge.getType().getMenuGenerator(); - if (generator instanceof ChallengeMenuGenerator) { + IMenuGenerator generator = challenge.getType().getMenuGenerator(); // TODO! + if (generator instanceof ChallengeMenuGenerator) { // TODO ! ChallengeMenuGenerator menuGenerator = (ChallengeMenuGenerator) generator; if (deleted) { menuGenerator.removeChallengeFromCache(challenge); - if (generate) generator.generateInventories(); + if (generate) menuGenerator.generateInventories(); } else { if (!menuGenerator.isInChallengeCache(challenge)) { menuGenerator.addChallengeToCache(challenge); - if (generate) generator.generateInventories(); + if (generate) menuGenerator.generateInventories(); } else { menuGenerator.updateItem(challenge); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java index b8b71e465..d2248ce7f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java @@ -4,8 +4,8 @@ import net.codingarea.challenges.plugin.challenges.implementation.damage.DamageRuleSetting; import net.codingarea.challenges.plugin.challenges.implementation.material.BlockMaterialSetting; import net.codingarea.challenges.plugin.challenges.type.IChallenge; -import net.codingarea.challenges.plugin.management.challenges.annotations.RequireVersion; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.challenges.type.annotation.RequireVersion; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.core.BukkitModule; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; @@ -92,11 +92,11 @@ public final void registerWithCommand(@NotNull Class class } public final void registerDamageRule(@NotNull String name, @NotNull Material material, @NotNull DamageCause... causes) { - registerDamageRule(name, new ItemBuilder(material), causes); + registerDamageRule(name, new LegacyItemBuilder(material), causes); } - public final void registerDamageRule(@NotNull String name, @NotNull ItemBuilder preset, @NotNull DamageCause... causes) { - register(DamageRuleSetting.class, new Class[]{ItemBuilder.class, String.class, DamageCause[].class}, preset, name, causes); + public final void registerDamageRule(@NotNull String name, @NotNull LegacyItemBuilder preset, @NotNull DamageCause... causes) { + register(DamageRuleSetting.class, new Class[]{LegacyItemBuilder.class, String.class, DamageCause[].class}, preset, name, causes); } public final void registerMaterialRule(@NotNull String title, @NotNull String replacement, @NotNull Material... materials) { @@ -104,11 +104,11 @@ public final void registerMaterialRule(@NotNull String title, @NotNull String re } public final void registerMaterialRule(@NotNull String name, Object[] replacements, @NotNull Material... materials) { - registerMaterialRule(name, new ItemBuilder(materials[0]), replacements, materials); + registerMaterialRule(name, new LegacyItemBuilder(materials[0]), replacements, materials); } - public final void registerMaterialRule(@NotNull String name, @NotNull ItemBuilder preset, Object[] replacements, @NotNull Material... materials) { - register(BlockMaterialSetting.class, new Class[]{String.class, ItemBuilder.class, Object[].class, Material[].class}, name, preset, replacements, materials); + public final void registerMaterialRule(@NotNull String name, @NotNull LegacyItemBuilder preset, Object[] replacements, @NotNull Material... materials) { + register(BlockMaterialSetting.class, new Class[]{String.class, LegacyItemBuilder.class, Object[].class, Material[].class}, name, preset, replacements, materials); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java index 13fcd2c1a..ca7f16ab0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.management.files; import lombok.Getter; +import lombok.experimental.UtilityClass; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.config.Document; @@ -14,6 +15,7 @@ import org.jetbrains.annotations.Nullable; import java.io.*; +import java.util.Collections; import java.util.LinkedList; import java.util.List; @@ -26,7 +28,7 @@ public final class ConfigManager { public ConfigManager() { missingConfigSettings = new LinkedList<>(); GsonDocument.setCleanupEmptyObjects(true); - GsonDocument.setCleanupEmptyObjects(true); + GsonDocument.setCleanupEmptyArrays(true); } public void loadConfigs() { @@ -49,12 +51,12 @@ public void loadConfigs() { } - public Document getDefaultConfigDocument() { + public Document getDefaultConfigDocument() { // TODO extract to BukkitModule YamlConfiguration defaultConfig = getDefaultConfig(); return defaultConfig == null ? null : new YamlDocument(defaultConfig); } - public YamlConfiguration getDefaultConfig() { + public YamlConfiguration getDefaultConfig() { // TODO remove Challenges plugin = Challenges.getInstance(); try { // Create Temp File for loading the yaml configuration @@ -103,7 +105,17 @@ private FileDocument load(@NotNull String filename) { @NotNull public List getMissingConfigSettings() { - return new LinkedList<>(missingConfigSettings); + return Collections.unmodifiableList(missingConfigSettings); + } + + @UtilityClass + public class Keys { // type safety + public final String LANGUAGE = "language"; + public final String SKIP_LANGUAGE_MIGRATION = "skip-language-migration"; // hidden + public final String ONLINE_UPDATE = "language-online-update"; + public final String NEW_SUFFIX = "challenge-updates.new.suffix"; + public final String NEW_IN_FRONT = "challenge-updates.new.in-front"; + public final String UPDATED_SUFFIX = "challenge-updates.updated.suffix"; } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java index 7239613f2..096758d81 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java @@ -4,11 +4,12 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder.SkullBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder.SkullBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.collection.pair.Triple; @@ -246,7 +247,7 @@ private Triple, String>[] createItemPairs(@NotNull P stack = new SkullBuilder(Message.forName(item.getMessage()).asString()) .setOwner(player.getUniqueId(), player.getName()).build(); } else { - stack = new ItemBuilder(item.getMaterial(), Message.forName(item.getMessage()).asString()).build(); + stack = new ItemBuilder(player, item.getMaterial(), MessageKey.of(item.getMessage())).build(); } pairs[item.getSlot()] = new Triple<>( diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java index bc11be198..1a876b4ef 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.content.Message; import org.jetbrains.annotations.NotNull; +@Deprecated public final class InventoryTitleManager { private InventoryTitleManager() { @@ -20,12 +21,12 @@ public static String getMainMenuTitle() { @NotNull public static String getTitle(@NotNull MenuType menu, int page) { - return getTitle(menu.getName(), String.valueOf(page + 1)); + return "getTitle(...)"; } @NotNull public static String getTitle(@NotNull MenuType menu, String... sub) { - return getTitle(menu.getName(), sub); + return "getTitle(...)"; } @NotNull @@ -44,7 +45,7 @@ public static String getTitleSplitter() { @NotNull public static String getMenuSettingTitle(@NotNull MenuType menu, @NotNull String name, int page, boolean showPages) { - return getTitle(menu.getName() + getTitleSplitter() + name + (showPages ? " §8• " + Message.forName("inventory-color") + (page + 1) : "")); + return getTitle("getMenuSettingTitle(...)" + getTitleSplitter() + name + (showPages ? " §8• " + Message.forName("inventory-color") + (page + 1) : "")); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java index 03d0dc50b..8c9032ff4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java @@ -4,20 +4,19 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; -import net.codingarea.challenges.plugin.management.menu.generator.ChallengeMenuGenerator; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; -import net.codingarea.commons.bukkit.utils.animation.AnimationFrame; +import net.codingarea.challenges.plugin.management.menu.generator.impl.MainMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengesMenuGenerator; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import java.util.Locale; + public final class MenuManager { public static final String MANAGE_GUI_PERMISSION = "challenges.manage"; @@ -25,83 +24,50 @@ public final class MenuManager { @Getter private final boolean displayNewInFront; private final boolean permissionToManageGUI; - private AnimatedInventory gui; private boolean generated = false; + private final MainMenuGenerator mainMenu; public MenuManager() { - ChallengeAPI.subscribeLoader(LanguageLoader.class, this::generateMenus); - ChallengeAPI.subscribeLoader(LanguageLoader.class, this::generateMainMenu); + mainMenu = new MainMenuGenerator(); displayNewInFront = Challenges.getInstance().getConfigDocument().getBoolean("challenge-updates.new.in-front"); permissionToManageGUI = Challenges.getInstance().getConfigDocument().getBoolean("manage-settings-permission"); - generateMainMenu(); - } - - public void generateMainMenu() { - - gui = new AnimatedInventory(InventoryTitleManager.getMainMenuTitle(), 5 * 9, MenuPosition.HOLDER); - gui.addFrame(new AnimationFrame(5 * 9).fill(ItemBuilder.FILL_ITEM)); - gui.cloneLastAndAdd().setAccent(39, 41); - gui.cloneLastAndAdd().setAccent(38, 42); - gui.cloneLastAndAdd().setAccent(37, 43); - gui.cloneLastAndAdd().setAccent(28, 34); - gui.cloneLastAndAdd().setAccent(27, 35); - gui.cloneLastAndAdd().setAccent(18, 26); - gui.cloneLastAndAdd().setAccent(9, 17); - gui.cloneLastAndAdd().setAccent(10, 16); - gui.cloneLastAndAdd().setAccent(1, 7); - gui.cloneLastAndAdd().setAccent(2, 6); - - MenuType[] values = MenuType.values(); - for (int i = 0; i < values.length; i += 2) { - - AnimationFrame frame = gui.getLastFrame().clone(); - - MenuType first = values[i]; - frame.setItem(GUI_SLOTS[i], new ItemBuilder(first.getDisplayItem()).name( - DefaultItem.getItemPrefix() + first.getDisplayName()).hideAttributes()); - - if (values.length > i + 1) { - MenuType second = values[i + 1]; - frame.setItem(GUI_SLOTS[i + 1], new ItemBuilder(second.getDisplayItem()).name( - DefaultItem.getItemPrefix() + second.getDisplayName()).hideAttributes()); - } - - gui.addFrame(frame); - } + ChallengeAPI.subscribeLoader(LanguageLoader.class, this::generateMenus); + ChallengeAPI.subscribeLoader(LanguageLoader.class, mainMenu::updatePages); } public void generateMenus() { - for (MenuType value : MenuType.values()) { - value.executeWithGenerator(ChallengeMenuGenerator.class, ChallengeMenuGenerator::resetChallengeCache); + value.executeWithGenerator(ChallengesMenuGenerator.class, ChallengesMenuGenerator::resetCache); } for (IChallenge challenge : Challenges.getInstance().getChallengeManager().getChallenges()) { MenuType type = challenge.getType(); - type.executeWithGenerator(ChallengeMenuGenerator.class, gen -> gen.addChallengeToCache(challenge)); + type.executeWithGenerator(ChallengesMenuGenerator.class, gen -> gen.addToCache(challenge)); } + Locale language = Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class).getConfigLanguage(); + mainMenu.updateOrGeneratePages(language); for (MenuType value : MenuType.values()) { - value.getMenuGenerator().generateInventories(); + value.getMenuGenerator().updateOrGeneratePages(language); } generated = true; } - public void openGUI(@NotNull Player player) { + public void openMainMenu(@NotNull Player player) { SoundSample.PLOP.play(player); MenuPosition.set(player, new MainMenuPosition()); - gui.open(player, Challenges.getInstance()); + mainMenu.openMenu(player); } - public void openGUIInstantly(@NotNull Player player) { + public void openMainMenuInstantly(@NotNull Player player) { MenuPosition.set(player, new MainMenuPosition()); - gui.openNotAnimated(player, true, Challenges.getInstance()); + mainMenu.openMenuInstantly(player, true); } /** - * @return If the specified menu page could be opened. + * @return If the specified menu page be opened. * The menu may not be opened, when there are no challenges registered to that menu or the languages are not loaded */ public boolean openMenu(@NotNull Player player, @NotNull MenuType type, int page) { @@ -112,14 +78,14 @@ public boolean openMenu(@NotNull Player player, @NotNull MenuType type, int page return false; } - type.getMenuGenerator().open(player, page); + type.getMenuGenerator().openMenu(player, page); return true; } public void playNoPermissionsEffect(@NotNull Player player) { SoundSample.BASS_OFF.play(player); - Message.forName("no-permission").send(player, Prefix.CHALLENGES); + MessageKey.of("no-permission").send(player, Prefix.CHALLENGES); } public boolean permissionToManageGUI() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java index e27aa78c8..190f95f07 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java @@ -1,14 +1,12 @@ package net.codingarea.challenges.plugin.management.menu; import lombok.Getter; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.CategorisedMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.categorised.SmallCategorisedMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.SettingsMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.TimerMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.MainCustomMenuGenerator; -import org.bukkit.ChatColor; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.management.menu.generator.AbstractMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.IMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.TimerMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengeListMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.categorised.CategorisedMenuGenerator; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; @@ -18,46 +16,53 @@ public enum MenuType { TIMER("timer", Material.CLOCK, new TimerMenuGenerator(), false), - GOAL("goal", Material.COMPASS, new SmallCategorisedMenuGenerator()), - DAMAGE("damage", Material.IRON_SWORD, new SettingsMenuGenerator()), - ITEMS("item_blocks", Material.STICK, new SettingsMenuGenerator()), + GOAL("goal", Material.COMPASS, new CategorisedMenuGenerator()), + DAMAGE("damage", Material.IRON_SWORD, new ChallengeListMenuGenerator()), + ITEMS("items-blocks", Material.STICK, new ChallengeListMenuGenerator()), CHALLENGES("challenges", Material.BOOK, new CategorisedMenuGenerator()), - SETTINGS("settings", Material.COMPARATOR, new SettingsMenuGenerator()), - CUSTOM("custom", Material.WRITABLE_BOOK, new MainCustomMenuGenerator()); + SETTINGS("settings", Material.COMPARATOR, new ChallengeListMenuGenerator()), + CUSTOM("custom", Material.WRITABLE_BOOK, new ChallengeListMenuGenerator()); +// CUSTOM("custom", Material.WRITABLE_BOOK, new MainCustomMenuGenerator()); private final String key; @Getter - private final Material displayItem; + private final Material displayItemMaterial; @Getter - private final MenuGenerator menuGenerator; + private final IMenuGenerator menuGenerator; @Getter private final boolean usable; - MenuType(@NotNull String key, @NotNull Material displayItem, MenuGenerator menuGenerator, boolean usable) { + MenuType(@NotNull String key, @NotNull Material displayItemMaterial, AbstractMenuGenerator menuGenerator, boolean usable) { this.key = key; - this.displayItem = displayItem; + this.displayItemMaterial = displayItemMaterial; this.menuGenerator = menuGenerator; this.usable = usable; menuGenerator.setMenuType(this); } - MenuType(@NotNull String key, @NotNull Material displayItem, MenuGenerator menuGenerator) { - this(key, displayItem, menuGenerator, true); + MenuType(@NotNull String key, @NotNull Material displayItemMaterial, AbstractMenuGenerator menuGenerator) { + this(key, displayItemMaterial, menuGenerator, true); } + /** + * Colored, translation key used in item names. + */ @NotNull - public String getName() { - return ChatColor.stripColor(getDisplayName()); + public MessageKey getDisplayName() { + return MessageKey.of("menu." + key + ".display"); // TODO =name } + /** + * Uncolored, translation key used in inventory titles. + */ @NotNull - public String getDisplayName() { - return Message.forName("menu-" + key).asString(); + public MessageKey getMenuName() { + return MessageKey.of("menu." + key + ".name"); // TODO =menu } @SuppressWarnings("unchecked") - public void executeWithGenerator(Class clazz, Consumer action) { + public void executeWithGenerator(@NotNull Class clazz, @NotNull Consumer action) { if (clazz.isAssignableFrom(menuGenerator.getClass())) { action.accept((T) menuGenerator); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/SettingCategory.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/SettingCategory.java new file mode 100644 index 000000000..b3f65104f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/SettingCategory.java @@ -0,0 +1,75 @@ +package net.codingarea.challenges.plugin.management.menu; + +import lombok.Getter; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; + +public class SettingCategory { + + // Challenges + public static final SettingCategory MISC_CHALLENGE = new SettingCategory(99, Material.MINECART, "misc_challenge"); + public static final SettingCategory RANDOMIZER = new SettingCategory(1, Material.COMMAND_BLOCK, "randomizer"); + public static final SettingCategory FORCE = new SettingCategory(2, Material.BLUE_BANNER, "force"); + public static final SettingCategory ENTITIES = new SettingCategory(3, Material.PIG_SPAWN_EGG, "entities"); + public static final SettingCategory DAMAGE = new SettingCategory(4, MinecraftNameWrapper.RED_DYE, "damage"); + public static final SettingCategory EFFECT = new SettingCategory(5, Material.FERMENTED_SPIDER_EYE, "effect"); + public static final SettingCategory WORLD = new SettingCategory(6, Material.TNT, "world"); + public static final SettingCategory INVENTORY = new SettingCategory(7, Material.CHEST, "inventory"); + public static final SettingCategory MOVEMENT = new SettingCategory(8, Material.RABBIT_FOOT, "movement"); + public static final SettingCategory LIMITED_TIME = new SettingCategory(9, Material.CLOCK, "limited_time"); + public static final SettingCategory EXTRA_WORLD = new SettingCategory(10, Material.GRASS_BLOCK, "extra_world"); + + // Goals + public static final SettingCategory MISC_GOAL = new SettingCategory(99, Material.MINECART, "misc_goal"); + public static final SettingCategory KILL_ENTITY = new SettingCategory(1, Material.BOW, "kill_entity"); + public static final SettingCategory SCORE_POINTS = new SettingCategory(2, Material.CHEST, "score_points"); + public static final SettingCategory FASTEST_TIME = new SettingCategory(3, Material.CLOCK, "fastest_time"); + public static final SettingCategory FORCE_BATTLE = new SettingCategory(4, Material.BLUE_BANNER, "force_battle"); + + @Getter + private final int priority; // Lowest priority will be displayed first + + private final String messageKey; + private final Material displayItemMaterial; + + public SettingCategory(int priority, @NotNull Material displayItemMaterial, @NotNull String messageKey) { + this.priority = priority; + this.displayItemMaterial = displayItemMaterial; + this.messageKey = messageKey; + } + + @NotNull + public ItemStack getDisplayItemPreset() { + return new ItemStack(displayItemMaterial); + } + + @NotNull + public MessageKey getDisplayName() { + return MessageKey.of("category." + messageKey + ".name"); + } + + @NotNull + public MessageKey getDescription() { + return MessageKey.of("category." + messageKey + ".desc"); + } + + @NotNull + public MessageKey getMenuName() { + return MessageKey.of("category." + messageKey + ".menu"); + } + + @NotNull + public MessageKey getDescriptionInfo() { + return MessageKey.of("category." + messageKey + ".info"); + } + + @Deprecated + public LegacyItemBuilder getDisplayItem() { + return new LegacyItemBuilder(displayItemMaterial); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java new file mode 100644 index 000000000..ca209ab05 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java @@ -0,0 +1,183 @@ +package net.codingarea.challenges.plugin.management.menu.generator; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.i18n.LanguageProvider; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Locale; + +public abstract class AbstractMenuGenerator implements IMenuGenerator { + + @Getter + @Setter + protected MenuType menuType; // injected by MenuType constructor or set manually + + @NotNull + public abstract GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player); + + @NotNull + public abstract Inventory getOrInitInventory(@NotNull Locale locale, int page); + + /** + * @implSpec multiple of 9 + */ + public abstract int getInventorySize(); + + /** + * @implSpec should not contain any colors by default, inventory title will dynamically be formatted + */ + @NotNull + public LocalizableMessage getMenuName() { + if (menuType == null) + throw new IllegalStateException("MenuType not set, was it not initialized by MenuType directly?"); + return menuType.getMenuName(); + } + + @Override + public void openMenu(@NotNull Player player, int page) { + Locale locale = findLanguageProvider().getPlayerLanguage(player); + Inventory inventory = getOrInitInventory(locale, page); + MenuPosition.set(player, createMenuPosition(page, player)); + player.openInventory(inventory); + } + + public int getNavigateNextSlot() { + return getInventorySize() - 1; // bottom right + } + + public int getNavigateBackSlot() { + return getInventorySize() - 9; // bottom left + } + + protected void setNavigationItems(@NotNull Inventory inventory, int page, @NotNull Locale locale) { + if (page < getPageCount() - 1) { + inventory.setItem(getNavigateNextSlot(), DefaultItems.createNavigateNext(locale).build()); + } + + if (page == 0) { + inventory.setItem(getNavigateBackSlot(), DefaultItems.createNavigateBackMainMenu(locale).build()); + } else { + inventory.setItem(getNavigateBackSlot(), DefaultItems.createNavigateBack(locale).build()); + } + } + + protected void handleNavigateOutOfMenu(@NotNull Player player) { + Challenges.getInstance().getMenuManager().openMainMenuInstantly(player); + } + + @NotNull + protected LanguageProvider findLanguageProvider() { + return Challenges.getInstance().getTranslationManager().getLanguageProvider(); + } + + @Getter + @AllArgsConstructor + public abstract class GeneratorMenuPosition implements MenuPosition { + + protected final int page; + + @Override + public void handleClick(@NotNull MenuClickInfo info) { + int pageCount = getPageCount(); + if (page >= pageCount) { // should not happen; dynamically calculated page count changed + SoundSample.CLICK.play(info.getPlayer()); + return; + } + + int pageSwitchAmount = info.isShiftClick() ? 5 : 1; + if (info.getSlot() == getNavigateBackSlot()) { + if (page == 0) { + SoundSample.OPEN.play(info.getPlayer()); + handleNavigateOutOfMenu(info.getPlayer()); + } else { + SoundSample.CLICK.play(info.getPlayer()); + openMenu(info.getPlayer(), Math.max(page - pageSwitchAmount, 0)); + } + return; + } else if (info.getSlot() == getNavigateNextSlot()) { + SoundSample.CLICK.play(info.getPlayer()); + int maxPageIndex = pageCount - 1; + if (page < maxPageIndex) { + openMenu(info.getPlayer(), Math.min(page + pageSwitchAmount, maxPageIndex)); + } + return; + } + + if (!handleMenuClick(info)) { + SoundSample.CLICK.play(info.getPlayer()); + } + } + + /** + * @implSpec Return {@code true} if a valid slot handled by this Position was clicked, + * otherwise return {@code false} to play default fallback behavior (click sound for invalid clicks) + */ + public abstract boolean handleMenuClick(@NotNull MenuClickInfo info); + + protected void handleNavigateOutOfMenu(@NotNull Player player) { + AbstractMenuGenerator.this.handleNavigateOutOfMenu(player); + } + + @NotNull + public AbstractMenuGenerator getGenerator() { + return AbstractMenuGenerator.this; + } + + } + + @Getter + public abstract class HistoryAwareGeneratorMenuPosition extends GeneratorMenuPosition { + + private final GeneratorMenuPosition previousPosition; + + public HistoryAwareGeneratorMenuPosition(int page, @Nullable GeneratorMenuPosition previousPosition) { + super(page); + this.previousPosition = previousPosition; + } + + public HistoryAwareGeneratorMenuPosition(int page, @NotNull Player player) { + super(page); + if (MenuPosition.get(player) instanceof GeneratorMenuPosition prevPosition) { + // skip other pages of same menu (we only care about the menu before!) + while (prevPosition.getGenerator() == AbstractMenuGenerator.this + && prevPosition instanceof HistoryAwareGeneratorMenuPosition historyAwarePosition + && historyAwarePosition.getPreviousPosition() != null) { + prevPosition = historyAwarePosition.getPreviousPosition(); + } + this.previousPosition = prevPosition; + } else { + this.previousPosition = null; + } + } + + @Override + protected void handleNavigateOutOfMenu(@NotNull Player player) { + if (previousPosition == null) { + super.handleNavigateOutOfMenu(player); + return; + } + + AbstractMenuGenerator previousMenu = previousPosition.getGenerator(); + int previousPage = previousPosition.getPage(); + int previousMenuPageCount = previousMenu.getPageCount(); + if (previousPage < previousMenuPageCount) { // dynamic page count might have changed + previousMenu.openMenu(player, previousPage); + } else { + previousMenu.openMenu(player, previousMenuPageCount - 1); + } + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IDynamicMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IDynamicMenuGenerator.java new file mode 100644 index 000000000..4a31afd3b --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IDynamicMenuGenerator.java @@ -0,0 +1,19 @@ +package net.codingarea.challenges.plugin.management.menu.generator; + +import org.jetbrains.annotations.NotNull; + +public interface IDynamicMenuGenerator extends IMenuGenerator { + + void addToCache(@NotNull T element); + + void removeFromCache(@NotNull T element); + + boolean isCached(@NotNull T element); + + int getCachedCount(); + + void resetCache(); + + void updateElementDisplay(@NotNull T element); + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IMenuGenerator.java new file mode 100644 index 000000000..71d87492e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IMenuGenerator.java @@ -0,0 +1,31 @@ +package net.codingarea.challenges.plugin.management.menu.generator; + +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; + +public interface IMenuGenerator { + + void openMenu(@NotNull Player player, int page); + + default void openMenu(@NotNull Player player) { + openMenu(player, 0); + } + + void updateOrGeneratePages(@NotNull Locale locale); + + /** + * @implSpec regenerates all pages (only for locales already generated!) + * use {@link #updateOrGeneratePages(Locale)} to create the menu for a new locale + */ + void updatePages(); + + void updatePage(int page); + + /** + * @implSpec must be at least {@code 1} + */ + int getPageCount(); + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java index 871fdf262..c12b25cdc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java @@ -1,70 +1,123 @@ package net.codingarea.challenges.plugin.management.menu.generator; -import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; +import com.google.common.base.Preconditions; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.challenges.plugin.utils.misc.InventoryUtils.InventorySetter; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import org.bukkit.Bukkit; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; +import org.jetbrains.annotations.CheckReturnValue; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; +import java.util.*; +import java.util.function.BiConsumer; -public abstract class MultiPageMenuGenerator extends MenuGenerator { +public abstract class MultiPageMenuGenerator extends AbstractMenuGenerator { - protected final List inventories = new ArrayList<>(); + // thread-safety: reads/writes only triggered by Player interaction Events on the main thread + // if any async computation is done, the write access should be handed over to the main thread + // org.bukkit.Inventory operations are also not thread-safe! + protected final Map> inventoriesCache = new HashMap<>(); - @NotNull - protected Inventory createNewInventory(int page) { - Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, getSize(), getTitle(page)); + public abstract void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Locale locale); + + public void setInventoryDecoration(@NotNull Inventory inventory, int page, @NotNull Locale locale) { InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); - inventories.add(inventory); - return inventory; } - protected String getTitle(int page) { - return InventoryTitleManager.getTitle(getMenuType(), page); + @NotNull + protected Inventory createEmptyInventory(@NotNull Locale locale, int page) { + return getMenuTitleKey().createInventory(locale, getInventorySize(), + getMenuName(), getMenuTitlePageArg(page)); } - public abstract int getSize(); + @NotNull + protected Object getMenuTitlePageArg(int page) { + return page + 1; + } - public abstract int getPagesCount(); + @NotNull + private MessageKey getMenuTitleKey() { + int pageCount = getPageCount(); + if (pageCount == 1) return MessageKey.of("menu.title-format"); + return MessageKey.of("menu.title-format-page"); + } - public abstract void generatePage(@NotNull Inventory inventory, int page); + @NotNull + protected LocalizableMessage createSubMenuTitle(@NotNull Object menuNameArg, @NotNull Object subMenuNameArg) { + return MessageKey.of("menu.title-name-format-sub").withArgs(menuNameArg, subMenuNameArg); + } - public abstract int[] getNavigationSlots(int page); + @NotNull + @CheckReturnValue + protected final List generateInventories(@NotNull Locale locale) { + List inventories = new ArrayList<>(getPageCount()); + for (int page = 0; page < getPageCount(); page++) { + Inventory inventory = createEmptyInventory(locale, page); + setInventoryDecoration(inventory, page, locale); + setNavigationItems(inventory, page, locale); + updateInventoryContent(inventory, page, locale); + inventories.add(inventory); + } + return inventories; + } + @NotNull @Override - public void generateInventories() { - inventories.clear(); + public final Inventory getOrInitInventory(@NotNull Locale locale, int page) { + Preconditions.checkArgument(page >= 0 && page < getPageCount(), "Invalid page number: %s; page count: %s", page, getPageCount()); + List inventories = inventoriesCache.computeIfAbsent(locale, this::generateInventories); + return inventories.get(page); + } - for (int page = 0; page < getPagesCount(); page++) { - Inventory inventory = createNewInventory(page); - generatePage(inventory, page); + @Override + public final void updatePages() { + Collection locales = new ArrayList<>(inventoriesCache.keySet()); // might get modified + for (Locale locale : locales) { + updateOrGeneratePages(locale); } + } - for (int i = 0; i < inventories.size(); i++) { - addNavigationItems(inventories.get(i), i); + @Override + public void updateOrGeneratePages(@NotNull Locale locale) { + int pageCount = getPageCount(); // might be dynamically calculated and changed + for (int page = 0; page < pageCount; page++) { + List inventories = inventoriesCache.get(locale); + if (inventories != null && inventories.size() < pageCount) { + updateInventoryContent(inventories.get(page), page, locale); + } else if (inventories != null && inventories.size() > pageCount) { + removePage(inventories, page, pageCount); + } else { + getOrInitInventory(locale, page); + } } + } - reopenInventoryForPlayers(); - + private void removePage(@NotNull List inventories, int page, int pageCount) { + // already checked whether page exists before! + Inventory inventory = inventories.remove(page); + for (HumanEntity viewer : inventory.getViewers()) { + if (viewer instanceof Player player && page == pageCount && pageCount != 0) { + openMenu(player, page - 1); + } else { + viewer.closeInventory(); + } + } } @Override - public List getInventories() { - return inventories; + public final void updatePage(int page) { + updatePage(page, (inventory, locale) -> updateInventoryContent(inventory, page, locale)); } - public void addNavigationItems(@NotNull Inventory inventory, int page) { - InventoryUtils.setNavigationItems(inventory, - getNavigationSlots(page), true, - InventorySetter.INVENTORY, page, inventories.size(), - DefaultItem.navigateBack().clone().setLore("", "§7Shift §8» §7-5"), - DefaultItem.navigateNext().clone().setLore("", "§7Shift §8» §7+5")); + protected void updatePage(int page, @NotNull BiConsumer updateAction) { + Preconditions.checkArgument(page >= 0 && page < getPageCount(), "Invalid page number: %s; page count: %s", page, getPageCount()); + for (Map.Entry> entry : inventoriesCache.entrySet()) { + List inventories = entry.getValue(); + updateAction.accept(inventories.get(page), entry.getKey()); + } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SingleAnimatedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SingleAnimatedMenuGenerator.java new file mode 100644 index 000000000..67479b047 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SingleAnimatedMenuGenerator.java @@ -0,0 +1,70 @@ +package net.codingarea.challenges.plugin.management.menu.generator; + +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.i18n.LanguageProvider; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.*; + +public abstract class SingleAnimatedMenuGenerator implements IMenuGenerator { + + private final Map inventoryCache = new HashMap<>(); + + @NotNull + public abstract MenuPosition createMenuPosition(); + + // TODO impl dynamic formatting as in Multi-/SinglePageMenuGenerator + @NotNull + public abstract AnimatedInventory createAnimatedInventory(@NotNull Locale locale); + + @NotNull + public AnimatedInventory getOrCreateInventory(@NotNull Locale locale) { + return inventoryCache.computeIfAbsent(locale, this::createAnimatedInventory); + } + + @Override + public void openMenu(@NotNull Player player, int page) { + Locale locale = findLanguageProvider().getPlayerLanguage(player); + AnimatedInventory inventory = getOrCreateInventory(locale); + MenuPosition.set(player, createMenuPosition()); + inventory.open(player); + } + + public void openMenuInstantly(@NotNull Player player, boolean playSound) { + Locale locale = findLanguageProvider().getPlayerLanguage(player); + AnimatedInventory inventory = getOrCreateInventory(locale); + MenuPosition.set(player, createMenuPosition()); + inventory.openNotAnimated(player, playSound); + } + + @Override + public void updateOrGeneratePages(@NotNull Locale locale) { + inventoryCache.put(locale, createAnimatedInventory(locale)); + } + + @Override + public void updatePages() { + // updating every frame of the animation is tedious, just recreate it + List locales = new ArrayList<>(inventoryCache.keySet()); + inventoryCache.clear(); + locales.forEach(this::getOrCreateInventory); // stores generated inventory + } + + @Override + public void updatePage(int page) { + updatePages(); // only one page + } + + @Override + public final int getPageCount() { + return 1; + } + + @NotNull + protected LanguageProvider findLanguageProvider() { + return Challenges.getInstance().getTranslationManager().getLanguageProvider(); + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java new file mode 100644 index 000000000..404105099 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java @@ -0,0 +1,84 @@ +package net.codingarea.challenges.plugin.management.menu.generator; + +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +public abstract class SinglePageMenuGenerator extends AbstractMenuGenerator { + + // thread-safety: reads/writes only triggered by Player interaction Events on the main thread + // if any async computation is done, the write access should be handed over to the main thread + // org.bukkit.Inventory operations are also not thread-safe! + protected final Map inventoryCache = new HashMap<>(); + + @NotNull + public abstract GeneratorMenuPosition createMenuPosition(@NotNull Player player); + + public abstract void initInventoryDecoration(@NotNull Inventory inventory, @NotNull Locale locale); + + public abstract void updateInventoryContent(@NotNull Inventory inventory, @NotNull Locale locale); + + @NotNull + protected Inventory createEmptyInventory(@NotNull Locale locale) { + return MessageKey.of("menu.title-format").createInventory(locale, getInventorySize(), + getMenuName()); + } + + @NotNull + @Override + public final GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { + return createMenuPosition(player); // ignore page; single page + } + + @NotNull + @Override + public final Inventory getOrInitInventory(@NotNull Locale locale, int page) { + return inventoryCache.computeIfAbsent(locale, this::createAndInitInventory); + } + + @Override + public final void updatePages() { + for (Map.Entry entry : inventoryCache.entrySet()) { + updateInventoryContent(entry.getValue(), entry.getKey()); + } + } + + @Override + public void updateOrGeneratePages(@NotNull Locale locale) { + Inventory inventory = inventoryCache.get(locale); + if (inventory != null) { + updateInventoryContent(inventory, locale); + } else { + getOrInitInventory(locale, 0); // will generate and cache the inventory + } + } + + @NotNull + @CheckReturnValue + protected Inventory createAndInitInventory(@NotNull Locale locale) { + Inventory inventory = createEmptyInventory(locale); + initInventoryDecoration(inventory, locale); + setNavigationItems(inventory, 0, locale); + updateInventoryContent(inventory, locale); + return inventory; + } + + @Override + public void updatePage(int page) { + if (page != 0) { + throw new IllegalArgumentException("Invalid page number for SinglePageMenuGenerator: " + page); + } + updatePages(); + } + + @Override + public final int getPageCount() { + return 1; + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java index dbb23d581..e0b117787 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java @@ -6,8 +6,9 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.menu.generator.implementation.SettingsMenuGenerator; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; @@ -58,7 +59,7 @@ public void generatePage(@NotNull Inventory inventory, int page) { SettingCategory category = entry.getKey(); CategorisedSettingsMenuGenerator generator = entry.getValue(); - ItemBuilder builder = category.getDisplayItem(); + LegacyItemBuilder builder = category.getDisplayItem(); String attachment = getLoreAttachment(generator); if (!attachment.isEmpty()) { builder.appendLore("", attachment); @@ -119,13 +120,13 @@ public int getEntriesPerPage() { } @Override - public MenuPosition getMenuPosition(int page) { + public MenuPosition createMenuPosition(int page) { return info -> { if (InventoryUtils.handleNavigationClicking(this, getNavigationSlots(page), page, info, - () -> Challenges.getInstance().getMenuManager().openGUIInstantly(info.getPlayer()))) { + () -> Challenges.getInstance().getMenuManager().openMainMenuInstantly(info.getPlayer()))) { return; } @@ -177,9 +178,7 @@ public CategorisedSettingsMenuGenerator(CategorisedMenuGenerator generator, Sett @Override protected String getTitle(int page) { - String[] strings = category.getMessageSupplier().get().asArray(); - String display = strings.length == 0 ? "" : ChatColor.stripColor(strings[0]); - return InventoryTitleManager.getTitle(getMenuType(), display, String.valueOf(page + 1)); + throw new UnsupportedOperationException("This method should not be called in CategorisedSettingsMenuGenerator"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java deleted file mode 100644 index 99a11186e..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SettingCategory.java +++ /dev/null @@ -1,49 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.categorised; - -import lombok.Getter; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import org.bukkit.Material; - -import java.util.function.Supplier; - -@Getter -public class SettingCategory { - - //Challenges - public static final SettingCategory MISC_CHALLENGE = new SettingCategory(99, Material.MINECART, () -> Message.forName("category-misc_challenge")); - public static final SettingCategory RANDOMIZER = new SettingCategory(1, Material.COMMAND_BLOCK, () -> Message.forName("category-randomizer")); - public static final SettingCategory FORCE = new SettingCategory(2, Material.BLUE_BANNER, () -> Message.forName("category-force")); - public static final SettingCategory ENTITIES = new SettingCategory(3, Material.PIG_SPAWN_EGG, () -> Message.forName("category-entities")); - public static final SettingCategory DAMAGE = new SettingCategory(4, MinecraftNameWrapper.RED_DYE, () -> Message.forName("category-damage")); - public static final SettingCategory EFFECT = new SettingCategory(5, Material.FERMENTED_SPIDER_EYE, () -> Message.forName("category-effect")); - public static final SettingCategory WORLD = new SettingCategory(6, Material.TNT, () -> Message.forName("category-world")); - public static final SettingCategory INVENTORY = new SettingCategory(7, Material.CHEST, () -> Message.forName("category-inventory")); - public static final SettingCategory MOVEMENT = new SettingCategory(8, Material.RABBIT_FOOT, () -> Message.forName("category-movement")); - public static final SettingCategory LIMITED_TIME = new SettingCategory(9, Material.CLOCK, () -> Message.forName("category-limited_time")); - public static final SettingCategory EXTRA_WORLD = new SettingCategory(10, Material.GRASS_BLOCK, () -> Message.forName("category-extra_world")); - - //Goals - public static final SettingCategory MISC_GOAL = new SettingCategory(99, Material.MINECART, () -> Message.forName("category-misc_goal")); - public static final SettingCategory KILL_ENTITY = new SettingCategory(1, Material.BOW, () -> Message.forName("category-kill_entity")); - public static final SettingCategory SCORE_POINTS = new SettingCategory(2, Material.CHEST, () -> Message.forName("category-score_points")); - public static final SettingCategory FASTEST_TIME = new SettingCategory(3, Material.CLOCK, () -> Message.forName("category-fastest_time")); - public static final SettingCategory FORCE_BATTLE = new SettingCategory(4, Material.BLUE_BANNER, () -> Message.forName("category-force_battle")); - - // Lowest priority will be displayed first - private final int priority; - private final Material material; - private final Supplier messageSupplier; - - public SettingCategory(int priority, Material material, Supplier messageSupplier) { - this.priority = priority; - this.material = material; - this.messageSupplier = messageSupplier; - } - - public ItemBuilder getDisplayItem() { - return new ItemBuilder(material, messageSupplier.get()); - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java new file mode 100644 index 000000000..09abbeaf3 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java @@ -0,0 +1,92 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl; + +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.generator.SingleAnimatedMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengesMenuGenerator; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; +import net.codingarea.commons.bukkit.utils.animation.AnimationFrame; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; + +public class MainMenuGenerator extends SingleAnimatedMenuGenerator { + + public static final int SIZE = 5 * 9; + public static final int[] GUI_SLOTS = {30, 32, 19, 25, 11, 15, 4}; + + @NotNull + @Override + public MenuPosition createMenuPosition() { + return new MainMenuPosition(); + } + + @NotNull + @Override + public AnimatedInventory createAnimatedInventory(@NotNull Locale locale) { + AnimatedInventory gui = new AnimatedInventory(SIZE, size -> MessageKey.of("menu-main-title").createInventory(locale, size)); + gui.createAndAdd().fill(ItemBuilder.FILL_ITEM); + gui.cloneLastAndAdd().setContrast(39, 41); + gui.cloneLastAndAdd().setContrast(38, 42); + gui.cloneLastAndAdd().setContrast(37, 43); + gui.cloneLastAndAdd().setContrast(28, 34); + gui.cloneLastAndAdd().setContrast(27, 35); + gui.cloneLastAndAdd().setContrast(18, 26); + gui.cloneLastAndAdd().setContrast(9, 17); + gui.cloneLastAndAdd().setContrast(10, 16); + gui.cloneLastAndAdd().setContrast(1, 7); + gui.cloneLastAndAdd().setContrast(2, 6); + + MenuType[] values = MenuType.values(); + for (int i = 0; i < values.length; i += 2) { + AnimationFrame frame = gui.cloneLastAndAdd(); + + frame.setItem(GUI_SLOTS[i], createDisplayItem(locale, values[i])); + + if (values.length > i + 1) { + frame.setItem(GUI_SLOTS[i + 1], createDisplayItem(locale, values[i + 1])); + } + } + + return gui; + } + + @NotNull + protected ItemBuilder createDisplayItem(@NotNull Locale locale, @NotNull MenuType menuType) { + ItemBuilder item = new ItemBuilder(locale, menuType.getDisplayItemMaterial(), MessageKey.of("menu.item-format"), + menuType.getDisplayName()); + + if (menuType.getMenuGenerator() instanceof ChallengesMenuGenerator generator) { + if (generator.hasAnyNewChallenges()) { + item.appendName(MessageKey.of("new-challenge-suffix")); + } else if (generator.hasAnyUpdatedChallenges()) { + item.appendName(MessageKey.of("updated-challenge-suffix")); + } + } + + return item; + } + + public class MainMenuPosition implements MenuPosition { + + @Override + public void handleClick(@NotNull MenuClickInfo info) { + SoundSample.CLICK.play(info.getPlayer()); + + for (int i = 0; i < GUI_SLOTS.length; i++) { + int current = GUI_SLOTS[i]; + if (current == info.getSlot()) { + MenuType type = MenuType.values()[i]; + Challenges.getInstance().getMenuManager().openMenu(info.getPlayer(), type, 0); + return; + } + } + } + + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/TimerMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/TimerMenuGenerator.java new file mode 100644 index 000000000..c2ff02ed7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/TimerMenuGenerator.java @@ -0,0 +1,230 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl; + +import net.codingarea.challenges.plugin.ChallengeAPI; +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.loader.LanguageLoader; +import net.codingarea.challenges.plugin.management.menu.generator.MultiPageMenuGenerator; +import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; +import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; +import net.codingarea.challenges.plugin.management.scheduler.timer.TimerFormat; +import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; +import net.codingarea.challenges.plugin.utils.item.DefaultItem; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.common.collection.pair.Tuple; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NonNull; + +import java.util.List; +import java.util.Locale; + +public class TimerMenuGenerator extends MultiPageMenuGenerator { + + public static final int SIZE = 5 * 9; + public static final int START_SLOT = 21; + public static final int MODE_SLOT = 23; + public static final int[] DAYS_SLOTS = {11, 20, 29}; + public static final int[] HOUR_SLOTS = {12, 21, 30}; + public static final int[] MINUTE_SLOTS = {14, 23, 32}; + public static final int[] SECOND_SLOTS = {15, 24, 33}; + public static final int PAGE_STATE = 0, PAGE_TIME = 1; + public static final int SHIFT_CHANGE_TIME_AMOUNT = 10; + + private static final Material MID_GOLD_ITEM = MinecraftNameWrapper.getMaterialByNames("RAW_GOLD", "GOLDEN_CARROT"); + private static final List> SLOTS_AMOUNT_MAPPING = List.of( + Tuple.of(DAYS_SLOTS, 24 * 60 * 60), + Tuple.of(HOUR_SLOTS, 60 * 60), + Tuple.of(MINUTE_SLOTS, 60), + Tuple.of(SECOND_SLOTS, 1) + ); + + public TimerMenuGenerator() { + ChallengeAPI.registerScheduler(this); + Challenges.getInstance().getLoaderRegistry().subscribe(LanguageLoader.class, this::updatePages); + } + + @TimerTask(status = {TimerStatus.PAUSED, TimerStatus.RUNNING}) + public void updateTimerStateInventory() { + updatePage(PAGE_STATE); + } + + @ScheduledTask(ticks = 20) + public void updateTimeInventory() { + updatePage(PAGE_TIME); + } + + @NotNull + @Override + public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { + return new TimerMenuPosition(page); + } + + @NotNull + @Override + protected Object getMenuTitlePageArg(int page) { + return switch (page) { + case PAGE_STATE -> MessageKey.of("menu.timer.name-state"); + case PAGE_TIME -> MessageKey.of("menu.timer.name-time"); + default -> super.getMenuTitlePageArg(page); + }; + } + + @Override + public void setInventoryDecoration(@NotNull Inventory inventory, int page, @NotNull Locale locale) { + super.setInventoryDecoration(inventory, page, locale); // background fill items + for (int i : new int[]{1, 2, 6, 7, 9, 10, 16, 17, 27, 28, 34, 35, 37, 38, 39, 41, 42, 43}) { + inventory.setItem(i, ItemBuilder.FILL_ITEM_CONTRAST); + } + } + + @Override + public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Locale locale) { + switch (page) { + case PAGE_STATE -> updateTimerStatePage(inventory, locale); + case PAGE_TIME -> updateTimePage(inventory, locale); + } + } + + @Override + public int getPageCount() { + return 2; + } + + public void updateTimerStatePage(@NotNull Inventory inventory, @NotNull Locale locale) { + inventory.setItem(START_SLOT, Challenges.getInstance().getChallengeTimer().isStarted() ? + new ItemBuilder(locale, Material.LIME_DYE, MessageKey.of("timer-is-running")).build() : + new ItemBuilder(locale, MinecraftNameWrapper.RED_DYE, MessageKey.of("timer-is-paused")).build()); + inventory.setItem(MODE_SLOT, Challenges.getInstance().getChallengeTimer().isCountingUp() ? + new ItemBuilder.SkullBuilder(locale, MessageKey.of("timer-counting-up")).setBase64Texture(DefaultItem.SkullTextures.GREEN_ARROW_UP).build() : + new ItemBuilder.SkullBuilder(locale, MessageKey.of("timer-counting-down")).setBase64Texture(DefaultItem.SkullTextures.RED_ARROW_DOWN).build()); + } + + public void updateTimePage(@NotNull Inventory inventory, @NotNull Locale locale) { + long time = Challenges.getInstance().getChallengeTimer().getTime(); + long seconds = time; + long minutes = seconds / 60; + long hours = minutes / 60; + long days = hours / 24; + seconds %= 60; + minutes %= 60; + hours %= 24; + + String format = TimerFormat.SIMPLE_FORMAT.format(time); + + setTimeItems(inventory, locale, DAYS_SLOTS, days, format, Material.GOLD_BLOCK, + MessageKey.of("menu.timer.item-days"), + MessageKey.of("menu.timer.item-days-add"), + MessageKey.of("menu.timer.item-days-subtract")); + setTimeItems(inventory, locale, HOUR_SLOTS, hours, format, MID_GOLD_ITEM, + MessageKey.of("menu.timer.item-hours"), + MessageKey.of("menu.timer.item-hours-add"), + MessageKey.of("menu.timer.item-hours-subtract")); + setTimeItems(inventory, locale, MINUTE_SLOTS, minutes, format, Material.GOLD_INGOT, + MessageKey.of("menu.timer.item-minutes"), + MessageKey.of("menu.timer.item-minutes-add"), + MessageKey.of("menu.timer.item-minutes-subtract")); + setTimeItems(inventory, locale, SECOND_SLOTS, seconds, format, Material.GOLD_NUGGET, + MessageKey.of("menu.timer.item-seconds"), + MessageKey.of("menu.timer.item-seconds-add"), + MessageKey.of("menu.timer.item-seconds-subtract")); + } + + private void setTimeItems(@NotNull Inventory inventory, @NotNull Locale locale, int[] slots, + long amount, @NotNull String timerFormat, @NotNull Material displayItemMaterial, @NotNull MessageKey stateDescription, + @NotNull MessageKey addDescription, @NotNull MessageKey subtractDescription) { + inventory.setItem(slots[1], createTimeStateItem(amount, timerFormat, displayItemMaterial, stateDescription, locale)); + inventory.setItem(slots[0], createTimeControlItem(true, amount, timerFormat, addDescription, locale)); + inventory.setItem(slots[2], createTimeControlItem(false, amount, timerFormat, subtractDescription, locale)); + } + + private ItemStack createTimeControlItem(boolean add, long amount, @NotNull String timerFormat, @NotNull MessageKey description, @NotNull Locale locale) { + return new ItemBuilder(locale, add ? Material.DARK_OAK_BUTTON : Material.STONE_BUTTON, description, amount, timerFormat, SHIFT_CHANGE_TIME_AMOUNT).build(); + } + + private ItemStack createTimeStateItem(long amount, @NotNull String timerFormat, @NotNull Material displayItemMaterial, @NotNull MessageKey description, @NotNull Locale locale) { + return new ItemBuilder(locale, displayItemMaterial, description, amount, timerFormat).setAmount((int) Math.max(amount, 1)).build(); + } + + @Override + public int getInventorySize() { + return SIZE; + } + + public class TimerMenuPosition extends GeneratorMenuPosition { + + public TimerMenuPosition(int page) { + super(page); + } + + @Override + public boolean handleMenuClick(@NotNull MenuClickInfo info) { + return switch (page) { + case PAGE_STATE -> handleTimerStateMenuClick(info); + case PAGE_TIME -> handleTimeMenuClick(info); + default -> false; + }; + } + + private boolean handleTimerStateMenuClick(@NonNull MenuClickInfo info) { + if (info.getSlot() == START_SLOT) { + if (playNoPermissionsEffect(info.getPlayer())) return true; + Challenges.getInstance().getChallengeTimer().toggle(); + return true; + } else if (info.getSlot() == MODE_SLOT) { + if (playNoPermissionsEffect(info.getPlayer())) return true; + Challenges.getInstance().getChallengeTimer().setCountingUp(!Challenges.getInstance().getChallengeTimer().isCountingUp()); + return true; + } + return false; + } + + private boolean handleTimeMenuClick(@NonNull MenuClickInfo info) { + for (Tuple mapping : SLOTS_AMOUNT_MAPPING) { + int[] slots = mapping.getFirst(); + for (int i = 0; i < 3; i++) { + if (info.getSlot() != slots[i]) continue; + if (playNoPermissionsEffect(info.getPlayer())) return true; + + if (i == 1) { + Challenges.getInstance().getChallengeTimer().reset(); + SoundSample.BASS_OFF.play(info.getPlayer()); + updateTimeInventory(); + Challenges.getInstance().getChallengeTimer().updateActionbar(); + return true; + } + + int amount = mapping.getSecond(); + boolean plus = i == 0; + if (!plus) amount = -amount; + if (info.isShiftClick()) amount *= SHIFT_CHANGE_TIME_AMOUNT; + + Challenges.getInstance().getChallengeTimer().addSeconds(amount); + updateTimeInventory(); + + SoundSample.PLOP.play(info.getPlayer()); + return true; + } + } + return false; + } + + private boolean playNoPermissionsEffect(@NotNull Player player) { + if (mayManageTimer(player)) return false; + Challenges.getInstance().getMenuManager().playNoPermissionsEffect(player); + return true; + } + + private boolean mayManageTimer(@NotNull Player player) { + return player.hasPermission("challenges.timer"); + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java new file mode 100644 index 000000000..138cb8e82 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java @@ -0,0 +1,265 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.challenge; + +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.challenges.type.IChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.ChallengeAnnotations; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.management.files.ConfigManager; +import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.common.config.Document; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NonNull; + +import java.util.*; + +public class ChallengeListMenuGenerator extends ChallengesMenuGenerator { + + public static final int SIZE = 4 * 9; + public static final int[] DISPLAY_SLOTS = {10, 11, 12, 13, 14, 15, 16}; // settings at +9 each by default + public static final int SLOT_OFFSET_UPPER = -9; + public static final int SLOT_OFFSET_DISPLAY = 0; + public static final int SLOT_OFFSET_SETTINGS = 9; + public static final int SLOT_OFFSET_LOWER = 2 * 9; + private static final int[] SLOT_OFFSETS = {SLOT_OFFSET_UPPER, SLOT_OFFSET_DISPLAY, SLOT_OFFSET_SETTINGS, SLOT_OFFSET_LOWER}; + + protected final List assignedChallengesCache = new LinkedList<>(); + + protected final boolean newSuffix; + protected final boolean updatedSuffix; + protected final boolean displayNewInFront; + + public ChallengeListMenuGenerator() { + Document config = Challenges.getInstance().getConfigDocument(); + newSuffix = config.getBoolean(ConfigManager.Keys.NEW_SUFFIX); + updatedSuffix = config.getBoolean(ConfigManager.Keys.UPDATED_SUFFIX); + displayNewInFront = config.getBoolean(ConfigManager.Keys.NEW_IN_FRONT); + } + + @Override + public void addToCache(@NotNull IChallenge challenge) { + if (displayNewInFront) { + assignedChallengesCache.add(countNewChallenges(), challenge); + } else { + assignedChallengesCache.add(challenge); + } + } + + @Override + public boolean isCached(@NonNull IChallenge challenge) { + return assignedChallengesCache.contains(challenge); + } + + @Override + public int getCachedCount() { + return assignedChallengesCache.size(); + } + + @Override + public int getEnabledCount() { + return (int) assignedChallengesCache.stream() + .filter(IChallenge::isEnabled) + .count(); + } + + @NotNull + @Override + public Optional getFirstEnabledChallenge() { + return assignedChallengesCache.stream() + .filter(IChallenge::isEnabled) + .findFirst(); + } + + @Override + public void removeFromCache(@NotNull IChallenge challenge) { + assignedChallengesCache.remove(challenge); + } + + @Override + public void resetCache() { + assignedChallengesCache.clear(); + } + + @NotNull + @Override + public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { + return new ChallengeListMenuPosition(page); + } + + /** + * @param slotOffset See {@link #SLOT_OFFSETS} + * @return Whether an action can be executed at this offset (otherwise fallback behavior/sound will be played) + */ + public boolean executeChallengeAction(@NotNull IChallenge challenge, int slotOffset, @NotNull MenuClickInfo info) { + if (slotOffset == SLOT_OFFSET_DISPLAY || slotOffset == SLOT_OFFSET_SETTINGS) { + challenge.handleClick(new ChallengeMenuClickInfo(info, slotOffset == SLOT_OFFSET_DISPLAY)); + return true; + } + return false; + } + + @Override + public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Locale locale) { + List challengesForPage = getChallengesForPage(page); + Iterator iterator = challengesForPage.iterator(); // LinkedList: poor performance for random access + for (int i = 0; iterator.hasNext(); i++) { + IChallenge challenge = iterator.next(); + updateChallengeDisplayAt(challenge, inventory, i, locale); + } + } + + @Override + public void updateElementDisplay(@NotNull IChallenge challenge) { + int challengeIndex = assignedChallengesCache.indexOf(challenge); + if (challengeIndex == -1) return; // not registered here? + + int page = getPageOfChallenge(challengeIndex); + int slotIndex = challengeIndex % DISPLAY_SLOTS.length; + + updatePage(page, (inventory, locale) -> setChallengeItemsAt(challenge, inventory, slotIndex, locale)); + } + + protected void updateChallengeDisplayAt(@NotNull IChallenge challenge, @NotNull Inventory inventory, int slotsIndex, @NotNull Locale locale) { + setChallengeItemsAt(challenge, inventory, slotsIndex, locale); + setChallengeUpdateItemsAt(challenge, inventory, slotsIndex, locale); + } + + protected void setChallengeUpdateItemsAt(@NotNull IChallenge challenge, @NotNull Inventory inventory, int slotIndex, @NotNull Locale locale) { + if (newSuffix && ChallengeAnnotations.isNew(challenge)) { + inventory.setItem(DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_UPPER, new StandardItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); + inventory.setItem(DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_LOWER, new StandardItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); + } else if (updatedSuffix && ChallengeAnnotations.isUpdated(challenge)) { + inventory.setItem(DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_UPPER, new StandardItemBuilder(Material.YELLOW_STAINED_GLASS_PANE, "§0").build()); + inventory.setItem(DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_LOWER, new StandardItemBuilder(Material.YELLOW_STAINED_GLASS_PANE, "§0").build()); + } + } + + protected void setChallengeItemsAt(@NotNull IChallenge challenge, @NotNull Inventory inventory, int slotsIndex, @NotNull Locale locale) { + inventory.setItem(DISPLAY_SLOTS[slotsIndex] + SLOT_OFFSET_DISPLAY, createChallengeDisplayItem(challenge, locale)); + inventory.setItem(DISPLAY_SLOTS[slotsIndex] + SLOT_OFFSET_SETTINGS, createChallengeSettingsItem(challenge, locale)); + // TODO might need overrideable getter for settings slot + } + + @NotNull + protected ItemStack createChallengeDisplayItem(@NotNull IChallenge challenge, @NotNull Locale locale) { + ItemBuilder item = challenge.getDisplayItem(locale); + + if (newSuffix && ChallengeAnnotations.isNew(challenge)) { + item.appendName(MessageKey.of("new-challenge-suffix")); + } else if (updatedSuffix && ChallengeAnnotations.isUpdated(challenge)) { + item.appendName(MessageKey.of("updated-challenge-suffix")); + } + + return item.build(); + } + + @NotNull + protected ItemStack createChallengeSettingsItem(@NotNull IChallenge challenge, @NotNull Locale locale) { + return challenge.getSettingsItem(locale).build(); + } + + @NotNull + protected List getChallengesForPage(int page) { + int startIndex = page * DISPLAY_SLOTS.length; + int endIndex = Math.min(startIndex + DISPLAY_SLOTS.length, assignedChallengesCache.size()); + return assignedChallengesCache.subList(startIndex, endIndex); + } + + public int getPageOfChallenge(IChallenge challenge) { + int index = assignedChallengesCache.indexOf(challenge); + return getPageOfChallenge(index); + } + + protected int getPageOfChallenge(int indexOfChallenge) { + if (indexOfChallenge == -1) return -1; // challenge not registered here? + return (indexOfChallenge / DISPLAY_SLOTS.length); + } + + @Override + public int getPageCount() { + // must have at least one page! + return Math.max(1, Math.ceilDiv(assignedChallengesCache.size(), DISPLAY_SLOTS.length)); + } + + protected int countNewChallenges() { + int count = 0; + for (IChallenge challenge : assignedChallengesCache) { + if (ChallengeAnnotations.isNew(challenge)) { + count++; + } else if (displayNewInFront) { + break; + } + } + return count; + } + + @Override + public boolean hasAnyNewChallenges() { + if (assignedChallengesCache.isEmpty()) return false; + if (displayNewInFront) { + IChallenge first = assignedChallengesCache.getFirst(); + return ChallengeAnnotations.isNew(first); + } + for (IChallenge challenge : assignedChallengesCache) { + if (ChallengeAnnotations.isNew(challenge)) { + return true; + } + } + return false; + } + + @Override + public boolean hasAnyUpdatedChallenges() { + for (IChallenge challenge : assignedChallengesCache) { + if (ChallengeAnnotations.isUpdated(challenge)) { + return true; + } + } + return false; + } + + @Override + public int getInventorySize() { + return SIZE; + } + + protected int findSlotOffset(int clickedSlot, int checkForSlot) { + for (int offset : SLOT_OFFSETS) { + if (clickedSlot == checkForSlot + offset) { + return offset; + } + } + return -1; + } + + public class ChallengeListMenuPosition extends GeneratorMenuPosition { + + public ChallengeListMenuPosition(int page) { + super(page); + } + + @Override + public boolean handleMenuClick(@NotNull MenuClickInfo info) { + for (int i = 0; i < DISPLAY_SLOTS.length; i++) { + int slot = DISPLAY_SLOTS[i]; + int offset = findSlotOffset(info.getSlot(), slot); + if (offset == -1) continue; + + int challengeIndex = page * DISPLAY_SLOTS.length + i; + if (challengeIndex >= assignedChallengesCache.size()) return false; // page not full + + IChallenge challenge = assignedChallengesCache.get(challengeIndex); // TODO slow LinkedList random access + return executeChallengeAction(challenge, offset, info); + } + + return false; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengesMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengesMenuGenerator.java new file mode 100644 index 000000000..1ff44a06a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengesMenuGenerator.java @@ -0,0 +1,26 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.challenge; + +import net.codingarea.challenges.plugin.challenges.type.IChallenge; +import net.codingarea.challenges.plugin.management.menu.generator.IDynamicMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.MultiPageMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.categorised.CategorisedMenuGenerator; +import org.jetbrains.annotations.NotNull; + +import java.util.Optional; + +/** + * @see ChallengeListMenuGenerator + * @see CategorisedMenuGenerator + */ +public abstract class ChallengesMenuGenerator extends MultiPageMenuGenerator implements IDynamicMenuGenerator { + + public abstract boolean hasAnyNewChallenges(); + + public abstract boolean hasAnyUpdatedChallenges(); + + public abstract int getEnabledCount(); + + @NotNull + public abstract Optional getFirstEnabledChallenge(); + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedListMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedListMenuGenerator.java new file mode 100644 index 000000000..a7102a90c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedListMenuGenerator.java @@ -0,0 +1,32 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.categorised; + +import lombok.Getter; +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengeListMenuGenerator; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +public class CategorisedListMenuGenerator extends ChallengeListMenuGenerator { + + @Getter + protected final SettingCategory category; + + public CategorisedListMenuGenerator(@NotNull MenuType menuType, @NotNull SettingCategory category) { + this.menuType = menuType; + this.category = category; + } + + @NotNull + @Override + public LocalizableMessage getMenuName() { + return createSubMenuTitle(super.getMenuName(), category.getMenuName()); + } + + @Override + protected void handleNavigateOutOfMenu(@NotNull Player player) { + Challenges.getInstance().getMenuManager().openMenu(player, menuType, 0); + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java new file mode 100644 index 000000000..f8f4c6019 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java @@ -0,0 +1,227 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.categorised; + +import net.codingarea.challenges.plugin.challenges.type.IChallenge; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengesMenuGenerator; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NonNull; + +import java.util.*; + +public class CategorisedMenuGenerator extends ChallengesMenuGenerator { + + public static final int SIZE = 4 * 9; + public static final int[] SLOTS = {10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25}; + + protected final Map categoryGenerators = new HashMap<>(); + protected final List orderedCategories = new ArrayList<>(); + + @Override + public void addToCache(@NotNull IChallenge challenge) { + SettingCategory category = getChallengeCategoryOrMics(challenge); + CategorisedListMenuGenerator generator = categoryGenerators.computeIfAbsent(category, forCategory -> { + orderedCategories.add(forCategory); + orderedCategories.sort(Comparator.comparingInt(SettingCategory::getPriority)); + return new CategorisedListMenuGenerator(menuType, forCategory); + }); + generator.addToCache(challenge); + } + + @Override + public void removeFromCache(@NotNull IChallenge challenge) { + SettingCategory category = getChallengeCategoryOrMics(challenge); + CategorisedListMenuGenerator generator = categoryGenerators.get(category); + if (generator != null) { + generator.removeFromCache(challenge); + } + } + + @Override + public void resetCache() { + for (CategorisedListMenuGenerator generator : categoryGenerators.values()) { + generator.resetCache(); + } + } + + @Override + public int getCachedCount() { + int count = 0; + for (CategorisedListMenuGenerator generator : categoryGenerators.values()) { + count += generator.getCachedCount(); + } + return count; + } + + @Override + public int getEnabledCount() { + int count = 0; + for (CategorisedListMenuGenerator generator : categoryGenerators.values()) { + count += generator.getEnabledCount(); + } + return count; + } + + @NotNull + @Override + public Optional getFirstEnabledChallenge() { + for (CategorisedListMenuGenerator generator : categoryGenerators.values()) { + Optional challenge = generator.getFirstEnabledChallenge(); + if (challenge.isPresent()) { + return challenge; + } + } + return Optional.empty(); + } + + @Override + public boolean isCached(@NonNull IChallenge element) { + SettingCategory category = getChallengeCategoryOrMics(element); + CategorisedListMenuGenerator generator = categoryGenerators.get(category); + return generator != null && generator.isCached(element); + } + + @Override + public void updateElementDisplay(@NotNull IChallenge challenge) { + SettingCategory category = getChallengeCategoryOrMics(challenge); + CategorisedListMenuGenerator generator = categoryGenerators.get(category); + if (generator != null) { + generator.updateElementDisplay(challenge); + + int index = orderedCategories.indexOf(category); + int[] slots = getSlots(); + int page = index / slots.length; + int slot = slots[index % slots.length]; + updatePage(page, (inventory, locale) -> inventory.setItem(slot, createCategoryDisplayItem(locale, category))); + } + } + + @Override + public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Locale locale) { + int[] slots = getSlots(); + List categories = getCategoriesForPage(page, slots); + int len = categories.size(); + for (int i = 0; i < len; i++) { + SettingCategory category = categories.get(i); + inventory.setItem(slots[i], createCategoryDisplayItem(locale, category)); + } + } + + @NotNull + protected ItemStack createCategoryDisplayItem(@NotNull Locale locale, @NotNull SettingCategory category) { + ItemBuilder item = new ItemBuilder(locale, category.getDisplayItemPreset(), MessageKey.of("challenge.display-format"), + category.getDisplayName(), category.getDescription()); + + CategorisedListMenuGenerator generator = categoryGenerators.get(category); + if (generator != null) { + if (generator.hasAnyNewChallenges()) { + item.appendName(MessageKey.of("new-challenge-suffix")); + } else if (generator.hasAnyUpdatedChallenges()) { + item.appendName(MessageKey.of("updated-challenge-suffix")); + } + + item.appendLore(category.getDescriptionInfo(), + generator.getEnabledCount(), generator.getCachedCount(), + generator.getFirstEnabledChallenge().map(IChallenge::getChallengeName).orElse(MessageKey.of("generic.disabled"))); + } + + return item.build(); + } + + @NotNull + protected List getCategoriesForPage(int page, @NotNull int[] slots) { + int startIndex = page * slots.length; + int endIndex = Math.min(startIndex + slots.length, orderedCategories.size()); + return orderedCategories.subList(startIndex, endIndex); + } + + @NotNull + protected SettingCategory getChallengeCategoryOrMics(@NotNull IChallenge challenge) { + SettingCategory category = challenge.getCategory(); + if (category != null) return category; + return getMiscCategory(); + } + + @NotNull + protected SettingCategory getMiscCategory() { + if (menuType == MenuType.GOAL) { + return SettingCategory.MISC_GOAL; + } + return SettingCategory.MISC_CHALLENGE; + } + + @NotNull + @Override + public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { + return new CategorisedOverviewMenuPosition(page); + } + + @Override + public boolean hasAnyNewChallenges() { + for (CategorisedListMenuGenerator menuGenerator : categoryGenerators.values()) { + if (menuGenerator.hasAnyNewChallenges()) { + return true; + } + } + return false; + } + + @Override + public boolean hasAnyUpdatedChallenges() { + for (CategorisedListMenuGenerator menuGenerator : categoryGenerators.values()) { + if (menuGenerator.hasAnyUpdatedChallenges()) { + return true; + } + } + return false; + } + + @NotNull + public int[] getSlots() { + return SLOTS; + } + + @Override + public int getInventorySize() { + return SIZE; + } + + @Override + public int getPageCount() { + return Math.max(1, Math.ceilDiv(categoryGenerators.size(), getSlots().length)); + } + + public class CategorisedOverviewMenuPosition extends GeneratorMenuPosition { + + public CategorisedOverviewMenuPosition(int page) { + super(page); + } + + @Override + public boolean handleMenuClick(@NotNull MenuClickInfo info) { + int[] slots = getSlots(); + for (int i = 0; i < slots.length; i++) { + if (info.getSlot() != slots[i]) continue; + + List categories = getCategoriesForPage(page, slots); + if (i >= categories.size()) return false; // empty slot; page not full + SettingCategory category = categories.get(i); + CategorisedListMenuGenerator generator = categoryGenerators.get(category); + if (generator != null) { + generator.openMenu(info.getPlayer(), 0); + SoundSample.CLICK.play(info.getPlayer()); + } + return true; + } + + return false; + } + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java index b8fe953d6..aaf64d69d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation; import net.codingarea.challenges.plugin.challenges.type.IChallenge; -import net.codingarea.challenges.plugin.management.menu.generator.ChallengeMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChallengeMenuGenerator; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java deleted file mode 100644 index 832938d1f..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/TimerMenuGenerator.java +++ /dev/null @@ -1,227 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.implementation; - -import net.codingarea.challenges.plugin.ChallengeAPI; -import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.loader.LanguageLoader; -import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; -import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; -import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; -import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder.PotionBuilder; -import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import org.bukkit.Bukkit; -import org.bukkit.Color; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -import java.util.ArrayList; -import java.util.List; - -public class TimerMenuGenerator extends MenuGenerator { // TODO discussion: reason for not using MultiPageMenuGenerator - - public static final int SIZE = 5 * 9; - public static final int[] NAVIGATION_SLOTS = {36, 44}; - public static final int START_SLOT = 21; - public static final int MODE_SLOT = 23; - public static final int[] HOUR_SLOTS = {11, 20, 29}; - public static final int[] MINUTE_SLOTS = {13, 22, 31}; - public static final int[] SECOND_SLOTS = {15, 24, 33}; - - private final List inventories = new ArrayList<>(); - - public TimerMenuGenerator() { - ChallengeAPI.registerScheduler(this); - Challenges.getInstance().getLoaderRegistry().subscribe(LanguageLoader.class, this::generateInventories); - } - - @TimerTask(status = {TimerStatus.PAUSED, TimerStatus.RUNNING}) - public void updateInventories() { - updateFirstPage(); - updateSecondPage(); - } - - public void updateFirstPage() { - Inventory inventory = inventories.get(0); - inventory.setItem(START_SLOT, Challenges.getInstance().getChallengeTimer().isStarted() ? - new ItemBuilder(Material.LIME_DYE).name(Message.forName("timer-is-running")).build() : - new ItemBuilder(MinecraftNameWrapper.RED_DYE).name(Message.forName("timer-is-paused")).build()); - inventory.setItem(MODE_SLOT, Challenges.getInstance().getChallengeTimer().isCountingUp() ? - new PotionBuilder(Material.TIPPED_ARROW).setColor(Color.LIME).name(Message.forName("timer-counting-up")).hideAttributes().build() : - new PotionBuilder(Material.TIPPED_ARROW).setColor(Color.RED).name(Message.forName("timer-counting-down")).hideAttributes().build()); - } - - @ScheduledTask(ticks = 20) - public void updateSecondPage() { - setTimeNavigation(HOUR_SLOTS, Message.forName("hour"), Message.forName("hours")); - setTimeNavigation(MINUTE_SLOTS, Message.forName("minute"), Message.forName("minutes")); - setTimeNavigation(SECOND_SLOTS, Message.forName("second"), Message.forName("seconds")); - - long seconds = Challenges.getInstance().getChallengeTimer().getTime(); - long minutes = seconds / 60; - long hours = minutes / 60; - seconds %= 60; - minutes %= 60; - - Inventory inventory = inventories.get(1); - inventory.setItem(HOUR_SLOTS[1], getTimeItem(hours, Message.forName("hour"), Message.forName("hours"))); - inventory.setItem(MINUTE_SLOTS[1], getTimeItem(minutes, Message.forName("minute"), Message.forName("minutes"))); - inventory.setItem(SECOND_SLOTS[1], getTimeItem(seconds, Message.forName("second"), Message.forName("seconds"))); - } - - private void setTimeNavigation(int[] slots, @NotNull Message singular, @NotNull Message plural) { - Inventory inventory = inventories.get(1); - inventory.setItem(slots[0], getNavigationItem(true, singular, plural)); - inventory.setItem(slots[2], getNavigationItem(false, singular, plural)); - } - - @NotNull - private ItemStack getNavigationItem(boolean up, @NotNull Message singular, @NotNull Message plural) { - return new ItemBuilder(up ? Material.DARK_OAK_BUTTON : Material.STONE_BUTTON).name( - " ", - "§7§o[Click] §8» §" + (up ? "a+" : "c-") + "1 " + singular, - "§7§o[Shift-Click] §8» §" + (up ? "a+" : "c-") + "10 " + plural, - " " - ).hideAttributes().build(); - } - - @NotNull - private ItemStack getTimeItem(long value, @NotNull Message singular, @NotNull Message plural) { - return new ItemBuilder(Material.CLOCK).name( - "§8» §7" + (value == 1 ? singular : plural) + ": §e" + value, - " ", - "§7§o[Click] §8» §cReset §7timer", - " " - ).hideAttributes().amount((int) Math.max(value, 1)).build(); - } - - @NotNull - private Inventory createNewInventory(int page) { - Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, SIZE, InventoryTitleManager.getTitle(MenuType.TIMER, page)); - InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); - for (int i : new int[]{1, 2, 6, 7, 9, 10, 16, 17, 27, 28, 34, 35, 37, 38, 39, 41, 42, 43}) { - inventory.setItem(i, ItemBuilder.FILL_ITEM_2); - } - inventories.add(inventory); - return inventory; - } - - private void setNavigation() { - InventoryUtils.setNavigationItemsToInventory(inventories, NAVIGATION_SLOTS); - } - - @Override - public void generateInventories() { - inventories.clear(); - createNewInventory(0); - createNewInventory(1); - setNavigation(); - updateInventories(); - } - - @Override - public List getInventories() { - return inventories; - } - - @Override - public MenuPosition getMenuPosition(int page) { - return new TimerMenuPosition(page); - } - - private class TimerMenuPosition implements MenuPosition { - - private final int page; - - public TimerMenuPosition(int page) { - this.page = page; - } - - @Override - public void handleClick(@NotNull MenuClickInfo info) { - - if (info.getSlot() == NAVIGATION_SLOTS[0]) { - SoundSample.CLICK.play(info.getPlayer()); - if (page == 0) { - Challenges.getInstance().getMenuManager().openGUIInstantly(info.getPlayer()); - } else { - open(info.getPlayer(), page - 1); - } - return; - } else if (info.getSlot() == NAVIGATION_SLOTS[1]) { - SoundSample.CLICK.play(info.getPlayer()); - if (page < (inventories.size() - 1)) - open(info.getPlayer(), page + 1); - return; - } - - if (page == 0) { - if (info.getSlot() == START_SLOT) { - if (playNoPermissionsEffect(info.getPlayer())) return; - if (Challenges.getInstance().getChallengeTimer().isStarted()) { - Challenges.getInstance().getChallengeTimer().pause(true); - } else { - Challenges.getInstance().getChallengeTimer().resume(); - } - return; - } else if (info.getSlot() == MODE_SLOT) { - if (playNoPermissionsEffect(info.getPlayer())) return; - Challenges.getInstance().getChallengeTimer().setCountingUp(!Challenges.getInstance().getChallengeTimer().isCountingUp()); - return; - } - } else if (page == 1) { - for (int[] slots : new int[][]{HOUR_SLOTS, MINUTE_SLOTS, SECOND_SLOTS}) { - for (int i = 0; i < 3; i++) { - - if (info.getSlot() != slots[i]) continue; - if (playNoPermissionsEffect(info.getPlayer())) return; - - if (i == 1) { - Challenges.getInstance().getChallengeTimer().reset(); - SoundSample.BASS_OFF.play(info.getPlayer()); - updateInventories(); - Challenges.getInstance().getChallengeTimer().updateActionbar(); - return; - } - - int amount = (slots == HOUR_SLOTS ? 60 * 60 : (slots == MINUTE_SLOTS ? 60 : 1)); - if (info.isShiftClick()) amount *= 10; - - boolean plus = i == 0; - - Challenges.getInstance().getChallengeTimer().addSeconds(plus ? +amount : -amount); - updateInventories(); - - SoundSample.PLOP.play(info.getPlayer()); - return; - } - } - } - - SoundSample.CLICK.play(info.getPlayer()); - - } - - private boolean playNoPermissionsEffect(@NotNull Player player) { - if (mayManageTimer(player)) return false; - Challenges.getInstance().getMenuManager().playNoPermissionsEffect(player); - return true; - } - - private boolean mayManageTimer(@NotNull Player player) { - return player.hasPermission("challenges.timer"); - } - - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java index 3aad5dcf6..480b9bd64 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.IChallengeSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.management.menu.generator.ChooseItemGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChooseItemGenerator; import net.codingarea.challenges.plugin.utils.misc.MapUtils; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java index 4edcf7353..39cf9f31e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java @@ -9,14 +9,15 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.ChallengeMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChallengeMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; import net.codingarea.challenges.plugin.spigot.listener.ChatInputListener; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils.InventorySetter; @@ -93,7 +94,7 @@ public static List getSubSettingsDisplay(SubSettingsBuilder builder, Map @Override public void generateInventories() { inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(MenuType.CUSTOM, "Info")); - InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); + InventoryUtils.fillInventory(inventory, LegacyItemBuilder.FILL_ITEM); updateItems(); @@ -105,11 +106,11 @@ public void updateItems() { String none = Message.forName("none").asString(); // Save / Delete Item - inventory.setItem(DELETE_SLOT, new ItemBuilder(Material.BARRIER, Message.forName("item-custom-info-delete")).build()); - inventory.setItem(SAVE_SLOT, new ItemBuilder(Material.LIME_DYE, Message.forName("item-custom-info-save")).build()); + inventory.setItem(DELETE_SLOT, new LegacyItemBuilder(Material.BARRIER, Message.forName("item-custom-info-delete")).build()); + inventory.setItem(SAVE_SLOT, new LegacyItemBuilder(Material.LIME_DYE, Message.forName("item-custom-info-save")).build()); // Trigger Item - ItemBuilder triggerItem = new ItemBuilder(Material.WITHER_SKELETON_SKULL, + LegacyItemBuilder triggerItem = new LegacyItemBuilder(Material.WITHER_SKELETON_SKULL, Message.forName("item-custom-info-trigger")) .appendLore( currently + (trigger != null ? Message.forName(trigger.getMessage()) : none)); @@ -119,7 +120,7 @@ public void updateItems() { inventory.setItem(CONDITION_SLOT, triggerItem.build()); // Action Item - ItemBuilder actionItem = new ItemBuilder(Material.NETHER_STAR, + LegacyItemBuilder actionItem = new LegacyItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-info-action")) .appendLore(currently + (action != null ? Message.forName(action.getMessage()) : none)); if (action != null) { @@ -128,11 +129,11 @@ public void updateItems() { inventory.setItem(ACTION_SLOT, actionItem.build()); // Display Item - inventory.setItem(MATERIAL_SLOT, new ItemBuilder(material == null ? Material.BARRIER : material, Message.forName("item-custom-info-material")) + inventory.setItem(MATERIAL_SLOT, new LegacyItemBuilder(material == null ? Material.BARRIER : material, Message.forName("item-custom-info-material")) .appendLore(currently + (material != null ? BukkitStringUtils.getItemName(material).toPlainText() : none)).build()); // Name Item - inventory.setItem(NAME_SLOT, new ItemBuilder(Material.NAME_TAG, Message.forName("item-custom-info-name")) + inventory.setItem(NAME_SLOT, new LegacyItemBuilder(Material.NAME_TAG, Message.forName("item-custom-info-name")) .appendLore(currently + "§7" + name).build()); } @@ -142,7 +143,7 @@ public List getInventories() { } @Override - public MenuPosition getMenuPosition(int page) { + public MenuPosition createMenuPosition(int page) { return new InfoMenuPosition(page, this); } @@ -230,7 +231,7 @@ public void handleClick(@NotNull MenuClickInfo info) { switch (info.getSlot()) { case DELETE_SLOT: if (!Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().containsKey(uuid)) { - Message.forName("custom-not-deleted").send(player, Prefix.CUSTOM); + MessageKey.of("custom-not-deleted").send(player, Prefix.CUSTOM); SoundSample.BASS_OFF.play(player); break; } @@ -243,16 +244,16 @@ public void handleClick(@NotNull MenuClickInfo info) { String defaults = new InfoMenuGenerator().toString(); String current = InfoMenuGenerator.this.toString(); if (defaults.equals(current)) { - Message.forName("custom-no-changes").send(player, Prefix.CUSTOM); + MessageKey.of("custom-no-changes").send(player, Prefix.CUSTOM); SoundSample.BASS_OFF.play(player); return; } save(); openChallengeMenu(player); - Message.forName("custom-saved").send(player, Prefix.CUSTOM); + MessageKey.of("custom-saved").send(player, Prefix.CUSTOM); if (savePlayerChallenges) { - Message.forName("custom-saved-db").send(player, Prefix.CUSTOM); + MessageKey.of("custom-saved-db").send(player, Prefix.CUSTOM); } SoundSample.LEVEL_UP.play(player); break; @@ -274,14 +275,14 @@ public void handleClick(@NotNull MenuClickInfo info) { break; case NAME_SLOT: - Message.forName("custom-name-info").send(player, Prefix.CUSTOM); + MessageKey.of("custom-name-info").send(player, Prefix.CUSTOM); player.closeInventory(); ChatInputListener.setInputAction(player, event -> { int maxNameLength = Challenges.getInstance().getCustomChallengesLoader() .getMaxNameLength(); if (event.getMessage().length() > maxNameLength) { - Message.forName("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxNameLength); + MessageKey.of("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxNameLength); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java index 7dfcea904..4910edfab 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java @@ -4,12 +4,13 @@ import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; -import net.codingarea.challenges.plugin.management.menu.generator.ChallengeMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChallengeMenuGenerator; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import org.bukkit.Material; @@ -55,8 +56,8 @@ public void executeClickAction(@NotNull IChallenge challenge, @NotNull MenuClick @Override public void generatePage(@NotNull Inventory inventory, int page) { if (page == 0) { - inventory.setItem(VIEW_SLOT, new ItemBuilder(Material.BOOK, Message.forName("custom-main-view-challenges")).build()); - inventory.setItem(CREATE_SLOT, new ItemBuilder(Material.WRITABLE_BOOK, Message.forName("custom-main-create-challenge")).build()); + inventory.setItem(VIEW_SLOT, new LegacyItemBuilder(Material.BOOK, Message.forName("custom-main-view-challenges")).build()); + inventory.setItem(CREATE_SLOT, new LegacyItemBuilder(Material.WRITABLE_BOOK, Message.forName("custom-main-create-challenge")).build()); } } @@ -64,7 +65,7 @@ public void generatePage(@NotNull Inventory inventory, int page) { public void onPreChallengePageClicking(@NotNull MenuClickInfo info, int page) { if (info.getSlot() == VIEW_SLOT) { if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().isEmpty()) { - Message.forName("custom-not-loaded").send(info.getPlayer(), Prefix.CUSTOM); + MessageKey.of("custom-not-loaded").send(info.getPlayer(), Prefix.CUSTOM); return; } open(info.getPlayer(), 1); @@ -74,7 +75,7 @@ public void onPreChallengePageClicking(@NotNull MenuClickInfo info, int page) { return; } if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() > maxCustomChallenges) { - Message.forName("custom-limit").send(info.getPlayer(), Prefix.CUSTOM, maxCustomChallenges); + MessageKey.of("custom-limit").send(info.getPlayer(), Prefix.CUSTOM, maxCustomChallenges); SoundSample.BASS_OFF.play(info.getPlayer()); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java index 86fb6663c..15906a42b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; -import net.codingarea.challenges.plugin.management.menu.generator.ChooseItemGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChooseItemGenerator; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.MapUtils; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java index e02dd6e66..cba7b6bf6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; -import net.codingarea.challenges.plugin.management.menu.generator.ChooseItemGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChooseItemGenerator; import net.codingarea.challenges.plugin.utils.misc.MapUtils; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java index aa84364ad..d1d63b7be 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; -import net.codingarea.challenges.plugin.management.menu.generator.ChooseMultipleItemGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChooseMultipleItemGenerator; import net.codingarea.challenges.plugin.utils.misc.MapUtils; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java index 1e7c300c7..d7921816c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; -import net.codingarea.challenges.plugin.management.menu.generator.ValueMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.ValueMenuGenerator; import org.bukkit.entity.Player; import java.util.HashMap; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChallengeMenuGenerator.java similarity index 85% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChallengeMenuGenerator.java index db7ea257b..f13f153fd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChallengeMenuGenerator.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.management.menu.generator; +package net.codingarea.challenges.plugin.management.menu.generator.legacy; import com.google.common.collect.ImmutableList; import net.codingarea.challenges.plugin.Challenges; @@ -6,8 +6,8 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.ChallengeAnnotations; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuManager; -import net.codingarea.challenges.plugin.management.menu.position.GeneratorMenuPosition; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.management.menu.position.LegacyGeneratorMenuPosition; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.logging.Logger; @@ -42,7 +42,7 @@ public ChallengeMenuGenerator(int startPage, Consumer onLeaveClick) { } public ChallengeMenuGenerator(int startPage) { - this(startPage, player -> Challenges.getInstance().getMenuManager().openGUIInstantly(player)); + this(startPage, player -> Challenges.getInstance().getMenuManager().openMainMenuInstantly(player)); } public ChallengeMenuGenerator() { @@ -62,8 +62,8 @@ private static boolean mayManageSettings(@NotNull Player player) { } @Override - public MenuPosition getMenuPosition(int page) { - return new ChallengeMenuPositionGenerator(this, page); + public MenuPosition createMenuPosition(int page) { + return new ChallengeMenuPositionLegacyGenerator(this, page); } @Override @@ -100,11 +100,11 @@ public void updateItem(IChallenge challenge) { setSettingsItems(inventory, challenge, slot); if (newSuffix && ChallengeAnnotations.isNew(challenge)) { - inventory.setItem(slot + 1, new ItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); - inventory.setItem(slot + 28, new ItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); + inventory.setItem(slot + 1, new LegacyItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); + inventory.setItem(slot + 28, new LegacyItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); } else if (updatedSuffix && ChallengeAnnotations.isUpdated(challenge)) { - inventory.setItem(slot + 1, new ItemBuilder(Material.YELLOW_STAINED_GLASS_PANE, "§0").build()); - inventory.setItem(slot + 28, new ItemBuilder(Material.YELLOW_STAINED_GLASS_PANE, "§0").build()); + inventory.setItem(slot + 1, new LegacyItemBuilder(Material.YELLOW_STAINED_GLASS_PANE, "§0").build()); + inventory.setItem(slot + 28, new LegacyItemBuilder(Material.YELLOW_STAINED_GLASS_PANE, "§0").build()); } } @@ -147,9 +147,9 @@ protected ItemStack getDisplayItem(@NotNull IChallenge challenge) { return getDisplayItemBuilder(challenge).build(); } - protected ItemBuilder getDisplayItemBuilder(@NotNull IChallenge challenge) { + protected LegacyItemBuilder getDisplayItemBuilder(@NotNull IChallenge challenge) { try { - ItemBuilder item = new ItemBuilder(challenge.getDisplayItem()).hideAttributes(); + LegacyItemBuilder item = new LegacyItemBuilder(challenge.getDisplayItem(null).build()).hideAttributes(); if (newSuffix && ChallengeAnnotations.isNew(challenge)) { return item.appendName(" " + Message.forName("new-challenge")); } else if (updatedSuffix && ChallengeAnnotations.isUpdated(challenge)) { @@ -159,17 +159,17 @@ protected ItemBuilder getDisplayItemBuilder(@NotNull IChallenge challenge) { } } catch (Exception ex) { Logger.error("Error while generating challenge display item for challenge {}", challenge.getClass().getSimpleName(), ex); - return new ItemBuilder(); + return new LegacyItemBuilder(); } } protected ItemStack getSettingsItem(@NotNull IChallenge challenge) { try { - ItemBuilder item = new ItemBuilder(challenge.getSettingsItem()).hideAttributes(); + LegacyItemBuilder item = new LegacyItemBuilder(challenge.getSettingsItem(null).build()).hideAttributes(); return item.build(); } catch (Exception ex) { Logger.error("Error while generating challenge settings item for challenge {}", challenge.getClass().getSimpleName(), ex); - return new ItemBuilder().build(); + return new LegacyItemBuilder().build(); } } @@ -189,9 +189,9 @@ public List getChallenges() { return ImmutableList.copyOf(challenges); } - private class ChallengeMenuPositionGenerator extends GeneratorMenuPosition { + private class ChallengeMenuPositionLegacyGenerator extends LegacyGeneratorMenuPosition { - public ChallengeMenuPositionGenerator(MenuGenerator generator, int page) { + public ChallengeMenuPositionLegacyGenerator(MenuGenerator generator, int page) { super(generator, page); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseItemGenerator.java similarity index 95% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseItemGenerator.java index 9bc7961ff..d241f4286 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseItemGenerator.java @@ -1,9 +1,9 @@ -package net.codingarea.challenges.plugin.management.menu.generator; +package net.codingarea.challenges.plugin.management.menu.generator.legacy; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.MainCustomMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.position.GeneratorMenuPosition; +import net.codingarea.challenges.plugin.management.menu.position.LegacyGeneratorMenuPosition; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; @@ -38,8 +38,8 @@ private static boolean isTopOrBottomSlot(int slot) { } @Override - public MenuPosition getMenuPosition(int page) { - return new GeneratorMenuPosition(this, page) { + public MenuPosition createMenuPosition(int page) { + return new LegacyGeneratorMenuPosition(this, page) { @Override public void handleClick(@NotNull MenuClickInfo info) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseMultipleItemGenerator.java similarity index 93% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseMultipleItemGenerator.java index 22b1bb908..3103bc16f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ChooseMultipleItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseMultipleItemGenerator.java @@ -1,12 +1,12 @@ -package net.codingarea.challenges.plugin.management.menu.generator; +package net.codingarea.challenges.plugin.management.menu.generator.legacy; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.MainCustomMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.position.GeneratorMenuPosition; +import net.codingarea.challenges.plugin.management.menu.position.LegacyGeneratorMenuPosition; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -49,8 +49,8 @@ private static boolean isTopOrBottomSlot(int slot) { } @Override - public MenuPosition getMenuPosition(int page) { - return new GeneratorMenuPosition(this, page) { + public MenuPosition createMenuPosition(int page) { + return new LegacyGeneratorMenuPosition(this, page) { @Override public void handleClick(@NotNull MenuClickInfo info) { @@ -117,7 +117,7 @@ public void generatePage(@NotNull Inventory inventory, int page) { int startIndex = getItemsPerPage() * page; for (int i = startIndex; i < startIndex + getItemsPerPage() && i < items.size(); i++) { String key = items.keySet().toArray(new String[0])[i]; - ItemBuilder itemBuilder = new ItemBuilder(items.get(key)).clone(); + LegacyItemBuilder itemBuilder = new LegacyItemBuilder(items.get(key)).clone(); itemBuilder.hideAttributes(); if (selectedKeys.contains(key)) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/MenuGenerator.java similarity index 79% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/MenuGenerator.java index 2882170ed..6884e41c3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/MenuGenerator.java @@ -1,9 +1,9 @@ -package net.codingarea.challenges.plugin.management.menu.generator; +package net.codingarea.challenges.plugin.management.menu.generator.legacy; import lombok.Getter; import lombok.Setter; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.position.GeneratorMenuPosition; +import net.codingarea.challenges.plugin.management.menu.position.LegacyGeneratorMenuPosition; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; import org.bukkit.Bukkit; @@ -25,19 +25,20 @@ public abstract class MenuGenerator { public abstract List getInventories(); - public abstract MenuPosition getMenuPosition(int page); + @NotNull + public abstract MenuPosition createMenuPosition(int page); public boolean hasInventoryOpen(Player player) { MenuPosition menuPosition = MenuPosition.get(player); - return menuPosition instanceof GeneratorMenuPosition + return menuPosition instanceof LegacyGeneratorMenuPosition && CompatibilityUtils.getTopInventory(player).getType() != InventoryType.CRAFTING - && ((GeneratorMenuPosition) menuPosition).getGenerator() == this; + && ((LegacyGeneratorMenuPosition) menuPosition).getGenerator() == this; } public int getPage(Player player) { MenuPosition menuPosition = MenuPosition.get(player); - if (menuPosition instanceof GeneratorMenuPosition) - return ((GeneratorMenuPosition) menuPosition).getPage(); + if (menuPosition instanceof LegacyGeneratorMenuPosition) + return ((LegacyGeneratorMenuPosition) menuPosition).getPage(); return 0; } @@ -55,7 +56,7 @@ public void open(@NotNull Player player, int page) { if (inventories == null || inventories.isEmpty()) return; if (page >= inventories.size()) page = inventories.size() - 1; Inventory inventory = inventories.get(page); - MenuPosition.set(player, getMenuPosition(page)); + MenuPosition.set(player, createMenuPosition(page)); player.openInventory(inventory); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/MultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/MultiPageMenuGenerator.java new file mode 100644 index 000000000..c7bcd3490 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/MultiPageMenuGenerator.java @@ -0,0 +1,70 @@ +package net.codingarea.challenges.plugin.management.menu.generator.legacy; + +import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; +import net.codingarea.challenges.plugin.utils.item.DefaultItem; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.challenges.plugin.utils.misc.InventoryUtils.InventorySetter; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import org.bukkit.Bukkit; +import org.bukkit.inventory.Inventory; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.List; + +public abstract class MultiPageMenuGenerator extends MenuGenerator { + + protected final List inventories = new ArrayList<>(); + + @NotNull + protected Inventory createNewInventory(int page) { + Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, getSize(), getTitle(page)); + InventoryUtils.fillInventory(inventory, LegacyItemBuilder.FILL_ITEM); + inventories.add(inventory); + return inventory; + } + + protected String getTitle(int page) { + return InventoryTitleManager.getTitle(getMenuType(), page); + } + + public abstract int getSize(); + + public abstract int getPagesCount(); + + public abstract void generatePage(@NotNull Inventory inventory, int page); + + public abstract int[] getNavigationSlots(int page); + + @Override + public void generateInventories() { + inventories.clear(); + + for (int page = 0; page < getPagesCount(); page++) { + Inventory inventory = createNewInventory(page); + generatePage(inventory, page); + } + + for (int i = 0; i < inventories.size(); i++) { + addNavigationItems(inventories.get(i), i); + } + + reopenInventoryForPlayers(); + + } + + @Override + public List getInventories() { + return inventories; + } + + public void addNavigationItems(@NotNull Inventory inventory, int page) { + InventoryUtils.setNavigationItems(inventory, + getNavigationSlots(page), true, + InventorySetter.INVENTORY, page, inventories.size(), + DefaultItem.navigateBack().clone().setLore("", "§7Shift §8» §7-5"), + DefaultItem.navigateNext().clone().setLore("", "§7Shift §8» §7+5")); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ValueMenuGenerator.java similarity index 96% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ValueMenuGenerator.java index 3b29c4fa6..a00bf5db9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/ValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ValueMenuGenerator.java @@ -1,11 +1,11 @@ -package net.codingarea.challenges.plugin.management.menu.generator; +package net.codingarea.challenges.plugin.management.menu.generator.legacy; import lombok.Getter; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.position.GeneratorMenuPosition; +import net.codingarea.challenges.plugin.management.menu.position.LegacyGeneratorMenuPosition; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -30,8 +30,8 @@ public ValueMenuGenerator(Map settings) { } @Override - public MenuPosition getMenuPosition(int page) { - return new GeneratorMenuPosition(this, page) { + public MenuPosition createMenuPosition(int page) { + return new LegacyGeneratorMenuPosition(this, page) { @Override public void handleClick(@NotNull MenuClickInfo info) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/LegacyGeneratorMenuPosition.java similarity index 67% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/LegacyGeneratorMenuPosition.java index 613cd9766..3875ca0ee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/GeneratorMenuPosition.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/LegacyGeneratorMenuPosition.java @@ -1,16 +1,16 @@ package net.codingarea.challenges.plugin.management.menu.position; import lombok.Getter; -import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; @Getter -public abstract class GeneratorMenuPosition implements MenuPosition { +public abstract class LegacyGeneratorMenuPosition implements MenuPosition { protected final MenuGenerator generator; protected final int page; - public GeneratorMenuPosition(MenuGenerator generator, int page) { + public LegacyGeneratorMenuPosition(MenuGenerator generator, int page) { this.generator = generator; this.page = page; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java index eae28ddf6..119b91a2e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java @@ -5,11 +5,10 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; -import net.codingarea.challenges.plugin.content.loader.LanguageLoader; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.TimerMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.TimerMenuGenerator; import net.codingarea.challenges.plugin.management.scheduler.policy.PlayerCountPolicy; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; @@ -18,8 +17,6 @@ import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.FileDocument; -import net.md_5.bungee.api.ChatMessageType; -import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.*; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -28,7 +25,6 @@ public final class ChallengeTimer { @Getter private final TimerFormat format; - private final Message stoppedMessage, upMessage, downMessage; private final boolean specificStartSounds, defaultStartSound; @Getter private long time = 0; @@ -45,13 +41,7 @@ public ChallengeTimer() { specificStartSounds = pluginConfig.getBoolean("enable-specific-start-sounds"); defaultStartSound = pluginConfig.getBoolean("enable-default-start-sounds"); - // Load format + messages - Document timerConfig = pluginConfig.getDocument("timer"); - stoppedMessage = Message.forName("stopped-message"); - upMessage = Message.forName("count-up-message"); - downMessage = Message.forName("count-down-message"); - - Document formatConfig = timerConfig.getDocument("format"); + Document formatConfig = pluginConfig.getDocument("timer.format"); format = new TimerFormat(formatConfig); Challenges.getInstance().getScheduler().register(this); @@ -107,9 +97,9 @@ public void resume() { updateActionbar(); updateTimeRule(); - Message.forName("timer-was-started").broadcast(Prefix.TIMER); + MessageKey.of("timer-was-started").broadcast(Prefix.TIMER); Challenges.getInstance().getScheduler().fireTimerStatusChange(); - Challenges.getInstance().getTitleManager().sendTimerStatusTitle(Message.forName("title-timer-started")); + Challenges.getInstance().getTitleManager().sendTimerStatusTitle(MessageKey.of("title-timer-started")); Challenges.getInstance().getServerManager().setNotFresh(); for (Player player : Bukkit.getOnlinePlayers()) { @@ -135,12 +125,20 @@ public void pause(boolean playInGameEffects) { Challenges.getInstance().getScheduler().fireTimerStatusChange(); if (playInGameEffects) { - Challenges.getInstance().getTitleManager().sendTimerStatusTitle(Message.forName("title-timer-paused")); - Message.forName("timer-was-paused").broadcast(Prefix.TIMER); + Challenges.getInstance().getTitleManager().sendTimerStatusTitle(MessageKey.of("title-timer-paused")); + MessageKey.of("timer-was-paused").broadcast(Prefix.TIMER); SoundSample.BASS_OFF.broadcast(); } } + public void toggle() { + if (isStarted()) { + pause(true); + } else { + resume(); + } + } + public void reset() { if (!countingUp) pause(true); time = 0; @@ -152,24 +150,15 @@ public void updateActionbar() { if (sentEmpty && hidden) return; if (hidden) sentEmpty = true; if (!hidden) { - for (Player player : Bukkit.getOnlinePlayers()) { - player.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(getActionbar())); - } + this.getCurrentActionbarMessage().broadcastActionBar(getFormattedTime()); } - } @NotNull - private String getActionbar() { - Message message = !paused || (!countingUp && time > 0) ? (countingUp ? upMessage : downMessage) : stoppedMessage; - String time = getFormattedTime(); - return message.asString(time); - } - - private boolean isSmallCaps() { - LanguageLoader languageLoader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); - if (languageLoader == null) return false; - return languageLoader.isSmallCapsFont(); + private MessageKey getCurrentActionbarMessage() { + if (paused) return MessageKey.of("stopped-message"); + if (countingUp) return MessageKey.of("count-up-message"); + return MessageKey.of("count-down-message"); } public synchronized void loadSession() { @@ -225,8 +214,8 @@ public void setCountingUp(boolean countingUp) { this.countingUp = countingUp; updateActionbar(); TimerMenuGenerator menuGenerator = (TimerMenuGenerator) MenuType.TIMER.getMenuGenerator(); - menuGenerator.updateFirstPage(); - Message.forName("timer-mode-set-" + (countingUp ? "up" : "down")).broadcast(Prefix.TIMER); + menuGenerator.updatePage(TimerMenuGenerator.PAGE_STATE); + MessageKey.of("timer-mode-set-" + (countingUp ? "up" : "down")).broadcast(Prefix.TIMER); SoundSample.BASS_ON.broadcast(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java index 6c141ecb4..a059e9075 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java @@ -5,6 +5,8 @@ public final class TimerFormat { + public static final TimerFormat SIMPLE_FORMAT = new TimerFormat(); + private final String seconds, minutes, hours, day, days; public TimerFormat(@NotNull Document document) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/PlatformManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/PlatformManager.java new file mode 100644 index 000000000..896710622 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/PlatformManager.java @@ -0,0 +1,49 @@ +package net.codingarea.challenges.plugin.management.server; + +import net.codingarea.challenges.platform.message.MessagePlatform; +import net.codingarea.challenges.platform.message.legacy.LegacyMiniMessagePlatform; +import net.codingarea.challenges.platform.message.paper.NativePaperMessagePlatform; +import net.codingarea.challenges.platform.message.paper.NativePaperMessagePlatformChecker; +import net.codingarea.challenges.plugin.Challenges; +import org.jetbrains.annotations.NotNull; + +import java.util.Objects; + +public final class PlatformManager { + + private MessagePlatform messagePlatform; + + public void createPlatforms() { + messagePlatform = createMessagePlatform(); + } + + public void enablePlatforms() { + messagePlatform.enable(); + } + + public void disablePlatforms() { + if (messagePlatform != null) messagePlatform.disable(); + } + + @NotNull + public MessagePlatform getMessagePlatform() { + if (messagePlatform == null) + throw new IllegalStateException("PlatformManager not loaded yet (MessagePlatform uninitialized)"); + return messagePlatform; + } + + public void setMessagePlatform(@NotNull MessagePlatform messagePlatform) { + Objects.requireNonNull(messagePlatform, "messagePlatform cannot be null"); + this.messagePlatform = messagePlatform; + } + + private static MessagePlatform createMessagePlatform() { + if (NativePaperMessagePlatformChecker.isAvailable()) { + Challenges.getInstance().getILogger().debug("Found and using native Paper message API"); + return new NativePaperMessagePlatform(); + } + Challenges.getInstance().getILogger().debug("Using legacy fallback message API"); + return new LegacyMiniMessagePlatform(Challenges.getInstance()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java index d724a466c..e727f351d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java @@ -3,13 +3,14 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.commons.common.config.Document; +import net.codingarea.commons.common.misc.ReflectionUtils; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Bukkit; import org.bukkit.GameMode; @@ -21,6 +22,7 @@ import java.util.LinkedList; import java.util.List; +import java.util.concurrent.Callable; import java.util.function.Supplier; public final class ServerManager { @@ -29,7 +31,7 @@ public final class ServerManager { private final boolean dropItemsOnEnd; private final boolean winSounds; - private boolean isFresh; // This indicated if the timer was never started before + private boolean isFresh; // indicates if the timer was never started before private boolean hasCheated; public ServerManager() { @@ -62,8 +64,19 @@ public boolean hasCheated() { } public void endChallenge(@NotNull ChallengeEndCause endCause, Supplier> winnerGetter) { +// if (!Bukkit.isPrimaryThread()) { // TODO +// // calling end challenge logic async results in all kinds of issues as bukkit/paper does not allow certain actions +// // to be performed async (in some versions): PlayerGameModeChangeEvent may only be triggered synchronously +// Logger.debug("End challenge called from async thread, scheduling sync task (Caller: {}", ReflectionUtils.getCallerName(1)); +// Bukkit.getScheduler().callSyncMethod(Challenges.getInstance(), (Callable) () -> { +// endChallenge(endCause, winnerGetter); +// return null; +// }); +// return; +// } + if (ChallengeAPI.isPaused()) { - Logger.warn("Tried to end challenge while timer was paused"); + Logger.warn("{} tried to end challenge while timer was paused", ReflectionUtils.getCallerName(1)); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java index 43653fe91..0d836fceb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java @@ -3,6 +3,7 @@ import lombok.Getter; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.commons.common.config.Document; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -10,7 +11,7 @@ @Getter public final class TitleManager { - private static final int fadein = 5, duration = 20, fadeout = 10; + public static final int FADEIN = 5, DURATION = 20, FADEOUT = 10; private final boolean timerStatusEnabled; private final boolean challengeStatusEnabled; @@ -21,7 +22,7 @@ public TitleManager() { challengeStatusEnabled = config.getBoolean("challenge-status"); } - public void sendTimerStatusTitle(@NotNull Message message) { + public void sendTimerStatusTitle(@NotNull MessageKey message) { if (!timerStatusEnabled) return; message.broadcastTitle(); } @@ -31,12 +32,14 @@ public void sendChallengeStatusTitle(@NotNull Message message, @NotNull Object.. message.broadcastTitle(args); } + @Deprecated public void sendTitle(@NotNull Player player, @NotNull String title, @NotNull String subtitle) { - player.sendTitle(title, subtitle, fadein, duration, fadeout); + player.sendTitle(title, subtitle, FADEIN, DURATION, FADEOUT); } + @Deprecated public void sendTitleInstant(@NotNull Player player, @NotNull String title, @NotNull String subtitle) { - player.sendTitle(title, subtitle, 0, duration, fadeout); + player.sendTitle(title, subtitle, 0, DURATION, FADEOUT); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java index c873d768f..fae421d1c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java @@ -86,7 +86,7 @@ public void prepareWorldReset(@Nullable CommandSender requestedBy, @Nullable Lon resetConfigs(seed); String requester = requestedBy instanceof Player ? NameHelper.getName((Player) requestedBy) : "§4§lConsole"; - String kickMessage = Message.forName("server-reset").asString(requester); + String kickMessage = Message.forName(restartOnReset ? "server-reset-restart" : "server-reset-stop").asString(requester); Bukkit.getOnlinePlayers().forEach(player -> player.kickPlayer(kickMessage)); Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), this::stopServerNow, 3); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/CBossBar.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/CBossBar.java new file mode 100644 index 000000000..943fb4b11 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/CBossBar.java @@ -0,0 +1,16 @@ +package net.codingarea.challenges.plugin.management.server.scoreboard; + +import org.bukkit.entity.Player; + +import java.util.function.BiConsumer; + +public class CBossBar { + + private final BiConsumer content = (bar, player) -> { + }; + + interface BossBarInstance { + + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java index 8f6e7e695..5f27c624f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java @@ -5,7 +5,8 @@ import net.codingarea.challenges.plugin.challenges.implementation.setting.PregameMovementSetting; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import org.bukkit.GameMode; import org.bukkit.Location; @@ -39,7 +40,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc count = Integer.parseInt(args[0]); } } catch (NumberFormatException formatException) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "back [count]"); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "back [count]"); return; } @@ -48,7 +49,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc int savedCount = list.size(); if (savedCount == 0) { - Message.forName("command-back-no-locations").send(player, Prefix.CHALLENGES); + MessageKey.of("command-back-no-locations").send(player, Prefix.CHALLENGES); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java index 1cb20040a..ca29de20d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; @@ -20,7 +20,7 @@ public class ChallengesCommand implements PlayerCommand, Completer { @Override public void onCommand(@NotNull Player player, @NotNull String[] args) { if (args.length > 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "challenges [menu]"); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "challenges [menu]"); return; } @@ -30,12 +30,12 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) { MenuType menuType = MenuType.valueOf(menuName); Challenges.getInstance().getMenuManager().openMenu(player, menuType, 0); } catch (IllegalArgumentException exception) { - Challenges.getInstance().getMenuManager().openGUI(player); + Challenges.getInstance().getMenuManager().openMainMenu(player); } return; } - Challenges.getInstance().getMenuManager().openGUI(player); + Challenges.getInstance().getMenuManager().openMainMenu(player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java index 802a7b6db..8133b2c89 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java @@ -2,8 +2,8 @@ import com.google.common.collect.Lists; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -35,7 +35,7 @@ public DatabaseCommand() { public void save(Player player) throws Exception { if (checkFeatureDisabled(savePlayerConfigs, player)) return; Challenges.getInstance().getChallengeManager().saveSettings(player); - Message.forName("player-config-loaded").send(player, Prefix.CHALLENGES); + MessageKey.of("player-config-loaded").send(player, Prefix.CHALLENGES); } @Override @@ -47,7 +47,7 @@ public void load(Player player) throws Exception { .where("uuid", player.getUniqueId()) .execute().firstOrEmpty().getDocument("config"); Challenges.getInstance().getChallengeManager().loadSettings(config); - Message.forName("player-config-loaded").send(player, Prefix.CHALLENGES); + MessageKey.of("player-config-loaded").send(player, Prefix.CHALLENGES); } @Override @@ -57,7 +57,7 @@ public void reset(Player player) throws Exception { .where("uuid", player.getUniqueId()) .set("config", null) .execute(); - Message.forName("player-config-reset").send(player, Prefix.CHALLENGES); + MessageKey.of("player-config-reset").send(player, Prefix.CHALLENGES); } }); databaseExecutors.put("customs", new DatabaseCommandExecutor() { @@ -66,7 +66,7 @@ public void reset(Player player) throws Exception { public void save(Player player) throws Exception { if (checkFeatureDisabled(savePlayerChallenges, player)) return; Challenges.getInstance().getChallengeManager().saveCustomChallenges(player); - Message.forName("player-custom_challenges-saved").send(player, Prefix.CHALLENGES); + MessageKey.of("player-custom_challenges-saved").send(player, Prefix.CHALLENGES); } @Override @@ -78,7 +78,7 @@ public void load(Player player) throws Exception { .where("uuid", player.getUniqueId()) .execute().firstOrEmpty().getDocument("custom_challenges"); Challenges.getInstance().getChallengeManager().loadCustomChallenges(config); - Message.forName("player-custom_challenges-loaded").send(player, Prefix.CHALLENGES); + MessageKey.of("player-custom_challenges-loaded").send(player, Prefix.CHALLENGES); } @Override @@ -88,7 +88,7 @@ public void reset(Player player) throws Exception { .where("uuid", player.getUniqueId()) .set("custom_challenges", null) .execute(); - Message.forName("player-custom_challenges-reset").send(player, Prefix.CHALLENGES); + MessageKey.of("player-custom_challenges-reset").send(player, Prefix.CHALLENGES); } }); } @@ -101,7 +101,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc } if (args.length != 2 || !databaseExecutors.containsKey(args[1])) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "database "); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "database "); return; } @@ -119,7 +119,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc executor.reset(player); break; default: - Message.forName("syntax").send(player, Prefix.CHALLENGES, "database "); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "database "); } } @@ -129,7 +129,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc */ private boolean checkFeatureDisabled(boolean enabled, @NotNull Player player) { if (!enabled) { - Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); + MessageKey.of("feature-disabled").send(player, Prefix.CHALLENGES); SoundSample.BASS_OFF.play(player); return true; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java index 5cde1bc1a..6de840741 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; @@ -28,14 +28,14 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr } if (targets.isEmpty()) { - Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); + MessageKey.of("command-no-target").send(sender, Prefix.CHALLENGES); return; } boolean otherPlayers = false; for (Player target : targets) { target.setFoodLevel(20); - Message.forName("command-feed-fed").send(target, Prefix.CHALLENGES); + MessageKey.of("command-feed-fed").send(target, Prefix.CHALLENGES); if (target != sender) otherPlayers = true; @@ -43,7 +43,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr } if (otherPlayers) - Message.forName("command-feed-others").send(sender, Prefix.CHALLENGES, targets.size()); + MessageKey.of("command-feed-others").send(sender, Prefix.CHALLENGES, targets.size()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java index e9c6cb455..659517856 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; @@ -28,7 +28,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr } if (targets.isEmpty()) { - Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); + MessageKey.of("command-no-target").send(sender, Prefix.CHALLENGES); return; } @@ -36,9 +36,9 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr for (Player target : targets) { if (target.getAllowFlight()) { - Message.forName("command-fly-disabled").send(target, Prefix.CHALLENGES); + MessageKey.of("command-fly-disabled").send(target, Prefix.CHALLENGES); } else { - Message.forName("command-fly-enabled").send(target, Prefix.CHALLENGES); + MessageKey.of("command-fly-enabled").send(target, Prefix.CHALLENGES); } target.setAllowFlight(!target.getAllowFlight()); @@ -48,7 +48,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr } if (otherPlayers) - Message.forName("command-fly-toggled-others").send(sender, Prefix.CHALLENGES, targets.size()); + MessageKey.of("command-fly-toggled-others").send(sender, Prefix.CHALLENGES, targets.size()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java index 439135eb5..99e2f49b6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; @@ -22,14 +22,14 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr List targets = new ArrayList<>(); if (args.length == 0) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); + MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); return; } GameMode gamemode = getGameMode(args[0]); if (gamemode == null) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); + MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); return; } @@ -41,21 +41,21 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr } if (targets.isEmpty()) { - Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); + MessageKey.of("command-no-target").send(sender, Prefix.CHALLENGES); return; } boolean otherPlayers = false; for (Player player : targets) { - Message.forName("command-gamemode-gamemode-changed").send(player, Prefix.CHALLENGES, gamemode); + MessageKey.of("command-gamemode-gamemode-changed").send(player, Prefix.CHALLENGES, gamemode); player.setGameMode(gamemode); if (player != sender) otherPlayers = true; } if (otherPlayers) { - Message.forName("command-gamemode-gamemode-changed-others").send(sender, Prefix.CHALLENGES, gamemode, targets.size()); + MessageKey.of("command-gamemode-gamemode-changed-others").send(sender, Prefix.CHALLENGES, gamemode, targets.size()); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java index 92409f1d4..26c92c8ba 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; @@ -20,7 +20,7 @@ public class GamestateCommand implements SenderCommand, Completer { public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (args.length != 1) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gamestate "); + MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "gamestate "); return; } @@ -30,15 +30,15 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr gamestate.clear(); Challenges.getInstance().getChallengeManager().resetGamestate(); Challenges.getInstance().getScoreboardManager().updateAll(); - Message.forName("command-gamestate-reset").send(sender, Prefix.CHALLENGES); + MessageKey.of("command-gamestate-reset").send(sender, Prefix.CHALLENGES); break; case "reload": Challenges.getInstance().getChallengeManager().loadGamestate(gamestate.readonly()); Challenges.getInstance().getScoreboardManager().updateAll(); - Message.forName("command-gamestate-reload").send(sender, Prefix.CHALLENGES); + MessageKey.of("command-gamestate-reload").send(sender, Prefix.CHALLENGES); break; default: - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "gamestate "); + MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "gamestate "); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java index fcdf0397b..c397fc8d5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; @@ -36,7 +36,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr } if (targets.isEmpty()) { - Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); + MessageKey.of("command-no-target").send(sender, Prefix.CHALLENGES); return; } @@ -44,10 +44,10 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr for (Player target : targets) { if (godModePlayers.contains(target.getUniqueId())) { godModePlayers.remove(target.getUniqueId()); - Message.forName("command-god-mode-disabled").send(target, Prefix.CHALLENGES); + MessageKey.of("command-god-mode-disabled").send(target, Prefix.CHALLENGES); } else { godModePlayers.add(target.getUniqueId()); - Message.forName("command-god-mode-enabled").send(target, Prefix.CHALLENGES); + MessageKey.of("command-god-mode-enabled").send(target, Prefix.CHALLENGES); target.setFoodLevel(20); } @@ -57,7 +57,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr } if (otherPlayers) - Message.forName("command-god-mode-toggled-others").send(sender, Prefix.CHALLENGES, targets.size()); + MessageKey.of("command-god-mode-toggled-others").send(sender, Prefix.CHALLENGES, targets.size()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java index f6ce46c5d..4e0f4e229 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; @@ -30,13 +30,13 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { } if (targets.isEmpty()) { - Message.forName("command-no-target").send(sender, Prefix.CHALLENGES); + MessageKey.of("command-no-target").send(sender, Prefix.CHALLENGES); return; } boolean otherPlayers = false; for (Player player : targets) { - Message.forName("command-heal-healed").send(player, Prefix.CHALLENGES); + MessageKey.of("command-heal-healed").send(player, Prefix.CHALLENGES); AttributeInstance attribute = player.getAttribute(MinecraftNameWrapper.MAX_HEALTH); if (attribute == null) { player.setHealth(20); @@ -54,7 +54,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { } if (otherPlayers) - Message.forName("command-heal-healed-others").send(sender, Prefix.CHALLENGES, targets.size()); + MessageKey.of("command-heal-healed-others").send(sender, Prefix.CHALLENGES, targets.size()); } @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java index 5b0f63c79..35411c6f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java @@ -2,11 +2,12 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.commons.bukkit.utils.menu.positions.SlottedMenuPosition; @@ -45,20 +46,20 @@ public class InvseeCommand implements PlayerCommand, Listener { public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (args.length < 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "invsee "); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "invsee "); return; } Player target = Bukkit.getPlayer(args[0]); if (target == null) { - Message.forName("command-no-target").send(player, Prefix.CHALLENGES); + MessageKey.of("command-no-target").send(player, Prefix.CHALLENGES); return; } player.openInventory(getInventory(target)); MenuPosition.set(player, new SlottedMenuPosition()); - Message.forName("command-invsee-open").send(player, Prefix.CHALLENGES, NameHelper.getName(target)); + MessageKey.of("command-invsee-open").send(player, Prefix.CHALLENGES, NameHelper.getName(target)); } public Inventory getInventory(@NotNull Player player) { @@ -68,8 +69,7 @@ public Inventory getInventory(@NotNull Player player) { Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(Message.forName("inventory-color").asString() + NameHelper.getName(player))); inventories.put(player, inventory); - MenuPosition.set(player, event -> { - }); + MenuPosition.setEmpty(player); updateInventoryContents(inventory, player.getInventory()); return inventory; } @@ -78,7 +78,7 @@ public void updateInventoryContents(@NotNull Inventory inventory, @NotNull Playe inventory.clear(); for (int slot = startBottom; slot <= endBottom; slot++) { - inventory.setItem(slot, ItemBuilder.FILL_ITEM); + inventory.setItem(slot, LegacyItemBuilder.FILL_ITEM); } inventory.setItem(helmetSlot, playerInventory.getHelmet()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java index 0b10f5325..ad558a6c8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; @@ -12,29 +12,28 @@ import org.jetbrains.annotations.Nullable; import java.util.List; -import java.util.Objects; public class LanguageCommand implements SenderCommand, Completer { @Override public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (args.length < 1) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "setlang "); + MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "setlang "); return; } switch (args[0].toLowerCase()) { case "german": case "deutsch": case "de": - Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("de"); + Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class).changeLanguage("de"); break; case "english": case "englisch": case "en": - Objects.requireNonNull(Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class)).changeLanguage("en"); + Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class).changeLanguage("en"); break; default: - Message.forName("unsuported-language").send(sender, Prefix.CHALLENGES, args[0]); + MessageKey.of("unsuported-language").send(sender, Prefix.CHALLENGES, args[0]); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java index b9f1ae311..bd2d1178a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java @@ -2,14 +2,15 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.cloud.CloudSupportManager; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.stats.PlayerStats; import net.codingarea.challenges.plugin.management.stats.Statistic; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder.SkullBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder.SkullBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.StatsHelper; import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; @@ -32,17 +33,17 @@ public class LeaderboardCommand implements PlayerCommand { static { loadingInventory = new AnimatedInventory(InventoryTitleManager.getLeaderboardTitle(), 6 * 9, MenuPosition.HOLDER).setEndSound(null).setFrameSound(null); - loadingInventory.createAndAdd().fill(ItemBuilder.FILL_ITEM).setItem(31, new ItemBuilder(Material.BARRIER, "§8» §cLoading..")); + loadingInventory.createAndAdd().fill(LegacyItemBuilder.FILL_ITEM).setItem(31, new LegacyItemBuilder(Material.BARRIER, "§8» §cLoading..")); } @Override public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (!Challenges.getInstance().getStatsManager().isEnabled()) { - Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); + MessageKey.of("feature-disabled").send(player, Prefix.CHALLENGES); SoundSample.BASS_OFF.play(player); return; } else if (!Challenges.getInstance().getStatsManager().hasDatabaseConnection()) { - Message.forName("no-database-connection").send(player, Prefix.CHALLENGES); + MessageKey.of("no-database-connection").send(player, Prefix.CHALLENGES); SoundSample.BASS_OFF.play(player); return; } @@ -58,7 +59,7 @@ public AnimatedInventory createInventory(@NotNull Player player) { SlottedMenuPosition position = new SlottedMenuPosition(); for (int i = 0; i < Statistic.values().length; i++) { Statistic statistic = Statistic.values()[i]; - ItemBuilder item = new ItemBuilder(StatsHelper.getMaterial(statistic), "§8» " + StatsHelper.getNameMessage(statistic).asString()); + LegacyItemBuilder item = new LegacyItemBuilder(StatsHelper.getMaterial(statistic), "§8» " + StatsHelper.getNameMessage(statistic).asString()); inventory.cloneLastAndAdd().setItem(slots[i], item.hideAttributes()); position.setAction(slots[i], () -> openMenu(player, statistic, 0, false)); } @@ -84,7 +85,7 @@ private void openMenu0(@NotNull Player player, @NotNull Statistic statistic, int String statisticName = StatsHelper.getNameMessage(statistic).asString(); AnimatedInventory inventory = new AnimatedInventory(InventoryTitleManager.getLeaderboardTitle(ChatColor.stripColor(statisticName), page + 1), 6 * 9, MenuPosition.HOLDER); - inventory.createAndAdd().fill(ItemBuilder.FILL_ITEM); + inventory.createAndAdd().fill(LegacyItemBuilder.FILL_ITEM); List leaderboard = Challenges.getInstance().getStatsManager().getLeaderboard(statistic); int pages = leaderboard.size() / slots.length; @@ -99,7 +100,7 @@ private void openMenu0(@NotNull Player player, @NotNull Statistic statistic, int int slot = slots[i - offset]; PlayerStats stats = leaderboard.get(i); String coloredName = cloudSupport.isNameSupport() && cloudSupport.hasNameFor(stats.getPlayerUUID()) ? cloudSupport.getColoredName(stats.getPlayerUUID()) : stats.getPlayerName(); - ItemBuilder item = new SkullBuilder().setOwner(stats.getPlayerUUID(), stats.getPlayerName()) + LegacyItemBuilder item = new SkullBuilder().setOwner(stats.getPlayerUUID(), stats.getPlayerName()) .setName(Message.forName("stats-leaderboard-display") .asArray(coloredName, statistic.formatChat(stats.getStatisticValue(statistic)), statisticName, i + 1)); inventory.cloneLastAndAdd().setItem(slot, item.hideAttributes()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java index 849ce5776..3eaec7367 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java @@ -4,7 +4,8 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; @@ -43,19 +44,19 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { } if (!Challenges.getInstance().getWorldManager().isEnableFreshReset() && ChallengeAPI.isFresh()) { - Message.forName("no-fresh-reset").send(sender, Prefix.CHALLENGES); + MessageKey.of("no-fresh-reset").send(sender, Prefix.CHALLENGES); SoundSample.BASS_OFF.playIfPlayer(sender); return; } if (confirmReset) { - Message.forName("confirm-reset").send(sender, Prefix.CHALLENGES, "reset confirm"); + MessageKey.of("confirm-reset").send(sender, Prefix.CHALLENGES, "reset confirm"); return; } } if (!Challenges.getInstance().getWorldManager().isEnableFreshReset() && ChallengeAPI.isFresh()) { - Message.forName("no-fresh-reset").send(sender, Prefix.CHALLENGES); + MessageKey.of("no-fresh-reset").send(sender, Prefix.CHALLENGES); SoundSample.BASS_OFF.playIfPlayer(sender); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java index 975ef57f6..3498fb983 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java @@ -4,8 +4,8 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.entity.Player; @@ -15,7 +15,7 @@ public class ResultCommand implements PlayerCommand { @Override public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (ChallengeAPI.isPaused()) { - Message.forName("timer-not-started").send(player, Prefix.CHALLENGES); + MessageKey.of("timer-not-started").send(player, Prefix.CHALLENGES); SoundSample.BASS_OFF.play(player); return; } @@ -28,6 +28,6 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc return; } - Message.forName("command-result-no-battle-active").send(player, Prefix.CHALLENGES); + MessageKey.of("command-result-no-battle-active").send(player, Prefix.CHALLENGES); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java index dea9ecf4a..38c7a396d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.RegisteredDrops; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; @@ -28,7 +28,7 @@ public class SearchCommand implements SenderCommand, Completer { public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (args.length == 0) { - Message.forName("syntax").send(sender, Prefix.CHALLENGES, "search "); + MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "search "); return; } @@ -36,11 +36,11 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr Material material = Utils.getMaterial(input); if (material == null) { - Message.forName("no-such-material").send(sender, Prefix.CHALLENGES); + MessageKey.of("no-such-material").send(sender, Prefix.CHALLENGES); return; } if (!material.isItem()) { - Message.forName("not-an-item").send(sender, Prefix.CHALLENGES, material); + MessageKey.of("not-an-item").send(sender, Prefix.CHALLENGES, material); return; } @@ -54,9 +54,9 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr } if (blocks.isEmpty()) { - Message.forName("command-search-nothing").send(sender, Prefix.CHALLENGES, material); + MessageKey.of("command-search-nothing").send(sender, Prefix.CHALLENGES, material); } else { - Message.forName("command-search-result").send(sender, Prefix.CHALLENGES, material, StringUtils.getIterableAsString(blocks, ", ", StringUtils::getEnumName)); + MessageKey.of("command-search-result").send(sender, Prefix.CHALLENGES, material, StringUtils.getIterableAsString(blocks, ", ", StringUtils::getEnumName)); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java index 236caeb6e..136805033 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java @@ -2,15 +2,16 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.cloud.CloudSupportManager; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.stats.LeaderboardInfo; import net.codingarea.challenges.plugin.management.stats.PlayerStats; import net.codingarea.challenges.plugin.management.stats.Statistic; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder.SkullBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder.SkullBuilder; import net.codingarea.challenges.plugin.utils.misc.StatsHelper; import net.codingarea.challenges.plugin.utils.misc.Utils; import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; @@ -32,11 +33,11 @@ public class StatsCommand implements PlayerCommand { @Override public void onCommand(@NotNull Player player, @NotNull String[] args) { if (!Challenges.getInstance().getStatsManager().isEnabled()) { - Message.forName("feature-disabled").send(player, Prefix.CHALLENGES); + MessageKey.of("feature-disabled").send(player, Prefix.CHALLENGES); SoundSample.BASS_OFF.play(player); return; } else if (!Challenges.getInstance().getStatsManager().hasDatabaseConnection()) { - Message.forName("no-database-connection").send(player, Prefix.CHALLENGES); + MessageKey.of("no-database-connection").send(player, Prefix.CHALLENGES); SoundSample.BASS_OFF.play(player); return; } @@ -49,15 +50,15 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) { switch (args.length) { case 0: - Message.forName("fetching-data").send(player, Prefix.CHALLENGES); + MessageKey.of("fetching-data").send(player, Prefix.CHALLENGES); handleCommand(player); break; case 1: - Message.forName("fetching-data").send(player, Prefix.CHALLENGES); + MessageKey.of("fetching-data").send(player, Prefix.CHALLENGES); handleCommand(player, args[0]); break; default: - Message.forName("syntax").send(player, Prefix.CHALLENGES, "stats [player]"); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "stats [player]"); } } @@ -111,7 +112,7 @@ private void createInventory(@NotNull PlayerStats stats, @NotNull LeaderboardInf double value = stats.getStatisticValue(statistic); String format = statistic.formatChat(value); - ItemBuilder item = new ItemBuilder(StatsHelper.getMaterial(statistic), StatsHelper.getNameMessage(statistic).asString()).setLore(Message.forName("stats-display").asArray(format, info.getPlace(statistic))).hideAttributes(); + LegacyItemBuilder item = new LegacyItemBuilder(StatsHelper.getMaterial(statistic), StatsHelper.getNameMessage(statistic).asString()).setLore(Message.forName("stats-display").asArray(format, info.getPlace(statistic))).hideAttributes(); inventory.cloneLastAndAdd().setItem(slots[i], item); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java index dc02a1bc8..e0d5b1d03 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java @@ -1,7 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; @@ -31,7 +32,7 @@ public TimeCommand() { public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (args.length == 0) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time "); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "time "); return; } World world = player.getWorld(); @@ -51,32 +52,32 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc break; case "set": { if (args.length == 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time set "); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "time set "); break; } long time = getTime(args[1]); if (time < 0) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time set "); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "time set "); break; } world.setTime(time); if (names.containsKey(time)) { String timeName = names.get(time).toLowerCase(); String timeTranslation = Message.forName("command-time-" + timeName).asString(); - Message.forName("command-time-set-exact").send(player, Prefix.CHALLENGES, timeTranslation, time); + MessageKey.of("command-time-set-exact").send(player, Prefix.CHALLENGES, timeTranslation, time); } else { - Message.forName("command-time-set").send(player, Prefix.CHALLENGES, time, getNearestTime(world)); + MessageKey.of("command-time-set").send(player, Prefix.CHALLENGES, time, getNearestTime(world)); } break; } case "add": { if (args.length == 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time add "); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "time add "); break; } long time = getLongFromString(args[1]); if (time < 0) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time add "); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "time add "); break; } player.performCommand("time set " + (world.getTime() + time)); @@ -84,19 +85,19 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc } case "subtract": { if (args.length == 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time subtract "); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "time subtract "); break; } long time = getLongFromString(args[1]); if (time < 0) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "time subtract "); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "time subtract "); break; } player.performCommand("time set " + (world.getTime() - time)); break; } case "query": { - Message.forName("command-time-query").send(player, Prefix.CHALLENGES, NumberFormatter.MIDDLE_NUMBER.format(world.getFullTime()), world.getFullTime() / 24000, NumberFormatter.MIDDLE_NUMBER.format(world.getTime()), getNearestTime(world)); + MessageKey.of("command-time-query").send(player, Prefix.CHALLENGES, NumberFormatter.MIDDLE_NUMBER.format(world.getFullTime()), world.getFullTime() / 24000, NumberFormatter.MIDDLE_NUMBER.format(world.getTime()), getNearestTime(world)); break; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java index 64490235f..c6fb1cc9c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java @@ -2,8 +2,8 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; @@ -35,12 +35,12 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { switch (args[0].toLowerCase()) { default: - Message.forName("syntax").send(sender, Prefix.TIMER, "timer "); + MessageKey.of("syntax").send(sender, Prefix.TIMER, "timer "); return; case "resume": case "start": if (ChallengeAPI.isStarted()) { - Message.forName("timer-already-started").send(sender, Prefix.TIMER); + MessageKey.of("timer-already-started").send(sender, Prefix.TIMER); SoundSample.BASS_OFF.playIfPlayer(sender); break; } @@ -49,7 +49,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { case "stop": case "pause": if (ChallengeAPI.isPaused()) { - Message.forName("timer-already-paused").send(sender, Prefix.TIMER); + MessageKey.of("timer-already-paused").send(sender, Prefix.TIMER); SoundSample.BASS_OFF.playIfPlayer(sender); break; } @@ -64,7 +64,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { seconds = Integer.MAX_VALUE; } Challenges.getInstance().getChallengeTimer().setSeconds(seconds); - Message.forName("timer-was-set").send(sender, Prefix.TIMER, Challenges.getInstance().getChallengeTimer().getFormattedTime()); + MessageKey.of("timer-was-set").send(sender, Prefix.TIMER, Challenges.getInstance().getChallengeTimer().getFormattedTime()); break; case "show": Challenges.getInstance().getChallengeTimer().setHidden(false); @@ -74,7 +74,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { break; case "mode": if (args.length != 2) { - Message.forName("syntax").send(sender, Prefix.TIMER, "timer mode "); + MessageKey.of("syntax").send(sender, Prefix.TIMER, "timer mode "); break; } switch (args[1].toLowerCase()) { @@ -88,7 +88,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { Challenges.getInstance().getChallengeTimer().setCountingUp(false); break; default: - Message.forName("syntax").send(sender, Prefix.TIMER, "timer mode "); + MessageKey.of("syntax").send(sender, Prefix.TIMER, "timer mode "); break; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java index 8d59317ce..acd7a35c7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Bukkit; @@ -16,13 +16,13 @@ public class VillageCommand implements PlayerCommand { @Override public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { player.setNoDamageTicks(10); - Message.forName("command-village-search").send(player, Prefix.CHALLENGES); + MessageKey.of("command-village-search").send(player, Prefix.CHALLENGES); Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { Location village = player.getWorld().locateNearestStructure(player.getLocation(), StructureType.VILLAGE, 5000, true); if (village == null) { - Message.forName("command-village-not-found").send(player, Prefix.CHALLENGES); + MessageKey.of("command-village-not-found").send(player, Prefix.CHALLENGES); return; } @@ -33,7 +33,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> { player.teleport(finalVillage); SoundSample.TELEPORT.play(player); - Message.forName("command-village-teleport").send(player, Prefix.CHALLENGES); + MessageKey.of("command-village-teleport").send(player, Prefix.CHALLENGES); }, 20 /* run after 1 second to give the chunks/world time to load/generate */); }); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java index be2494ca3..04295220e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; @@ -20,7 +20,7 @@ public class WeatherCommand implements PlayerCommand, Completer { public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (args.length == 0) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "weather "); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "weather "); return; } @@ -32,20 +32,20 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc case "sun": world.setStorm(false); world.setThundering(false); - Message.forName("command-weather-set-clear").send(player, Prefix.CHALLENGES); + MessageKey.of("command-weather-set-clear").send(player, Prefix.CHALLENGES); break; case "rain": world.setThundering(false); world.setStorm(true); - Message.forName("command-weather-set-rain").send(player, Prefix.CHALLENGES); + MessageKey.of("command-weather-set-rain").send(player, Prefix.CHALLENGES); break; case "thunder": world.setStorm(true); world.setThundering(true); - Message.forName("command-weather-set-thunder").send(player, Prefix.CHALLENGES); + MessageKey.of("command-weather-set-thunder").send(player, Prefix.CHALLENGES); break; default: - Message.forName("syntax").send(player, Prefix.CHALLENGES, "weather "); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "weather "); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java index 1dd6a6130..512d2d746 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java @@ -3,8 +3,8 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.implementation.setting.PositionSetting; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; import org.bukkit.Location; @@ -25,7 +25,7 @@ public class WorldCommand implements PlayerCommand, TabCompleter { public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (args.length < 1) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "world "); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "world "); return; } @@ -35,19 +35,19 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc boolean targetIsVoidMap = worldName.equalsIgnoreCase("void"); if (environment == null && !targetIsVoidMap) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "world "); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "world "); return; } World world = targetIsVoidMap ? Challenges.getInstance().getGameWorldStorage().getOrCreateVoidWorld() : ChallengeAPI.getGameWorld(environment); if (world == null) { - Message.forName("syntax").send(player, Prefix.CHALLENGES, "world "); + MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "world "); return; } Location location = getSpawn(world, player); - Message.forName("command-world-teleport").send(player, Prefix.CHALLENGES, targetIsVoidMap ? "Void" : getWorldName(location)); + MessageKey.of("command-world-teleport").send(player, Prefix.CHALLENGES, targetIsVoidMap ? "Void" : getWorldName(location)); player.teleport(location); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java index fe1bd2994..eb0d458fc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java index 85fe5178e..4cd37dfad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.listener; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.utils.misc.FontUtils; import org.bukkit.command.CommandSender; @@ -48,13 +48,8 @@ public void onCommand(@NotNull PlayerCommandPreprocessEvent event) { } - public void sendMessage(CommandSender sender, String msg) { - LanguageLoader languageLoader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class); - if (languageLoader != null && languageLoader.isSmallCapsFont()) { - msg = FontUtils.toSmallCaps(msg); - } - sender.sendMessage(Prefix.CHALLENGES + msg); - + protected void sendMessage(@NotNull CommandSender sender, @NotNull String line) { + sender.sendMessage(Prefix.CHALLENGES + line); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index df133833c..fa39ab0ae 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -3,7 +3,8 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.loader.UpdateLoader; import net.codingarea.challenges.plugin.utils.misc.DatabaseHelper; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; @@ -40,9 +41,25 @@ public PlayerConnectionListener() { restoreDefaultsOnLastQuit = config.getBoolean("restore-defaults-on-last-leave"); } +// @EventHandler(priority = EventPriority.LOWEST) +// public void onLogin(@NotNull PlayerLoginEvent event) { +// // DISCUSSION: really necessary? not implemented by default - extract? +// TranslationManager i18n = Challenges.getInstance().getTranslationManager(); +// if (!i18n.isLanguageProviderInitialized()) return; +// +// LanguageProvider provider = i18n.getLanguageProvider(); +// if (provider.isDefaultBehaviour() || !provider.isUserSpecific()) return; +// +// Locale playerLanguage = provider.getPlayerLanguage(event.getPlayer()); +// if (i18n.isLanguageCached(playerLanguage)) return; +// +// LanguageLoader loader = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class).orElse(null); +// if (loader == null) return; +// Challenges.getInstance().runAsync(() -> loader.populateLanguageFromFile(playerLanguage)); +// } + @EventHandler(priority = EventPriority.HIGH) public void onJoin(@NotNull PlayerJoinEvent event) { - Player player = event.getPlayer(); player.getLocation().getChunk().load(true); @@ -51,7 +68,7 @@ public void onJoin(@NotNull PlayerJoinEvent event) { Challenges.getInstance().getScoreboardManager().handleJoin(player); if (Challenges.getInstance().isFirstInstall() && !player.hasPermission("challenges.gui")) { - Message.forName("not-op").send(player, Prefix.CHALLENGES); + MessageKey.of("not-op").send(player, Prefix.CHALLENGES); } if (player.hasPermission("challenges.gui")) { @@ -64,13 +81,13 @@ public void onJoin(@NotNull PlayerJoinEvent event) { if (timerPausedInfo && !startTimerOnJoin && ChallengeAPI.isPaused()) { player.sendMessage(""); - Message.forName("timer-paused-message").send(player, Prefix.CHALLENGES); + MessageKey.of("timer-paused-message").send(player, Prefix.CHALLENGES); } } if (Challenges.getInstance().getStatsManager().isNoStatsAfterCheating() && Challenges.getInstance().getServerManager().hasCheated()) { player.sendMessage(""); - Message.forName("cheats-already-detected").send(player, Prefix.CHALLENGES); + MessageKey.of("cheats-already-detected").send(player, Prefix.CHALLENGES); } @@ -82,28 +99,29 @@ public void onJoin(@NotNull PlayerJoinEvent event) { if (player.hasPermission("challenges.gui")) { if (!UpdateLoader.isNewestConfigVersion()) { player.sendMessage(""); - Message.forName("deprecated-config-version").send(player, Prefix.CHALLENGES, UpdateLoader.getDefaultConfigVersion().format(), UpdateLoader.getCurrentConfigVersion().format()); + MessageKey.of("deprecated-config-version").send(player, Prefix.CHALLENGES, UpdateLoader.getDefaultConfigVersion().format(), UpdateLoader.getCurrentConfigVersion().format()); } List missingConfigSettings = Challenges.getInstance().getConfigManager().getMissingConfigSettings(); if (!missingConfigSettings.isEmpty()) { player.sendMessage(""); String separator = Message.forName("missing-config-settings-separator").asString(); - Message.forName("missing-config-settings").send(player, Prefix.CHALLENGES, String.join(separator, missingConfigSettings)); + MessageKey.of("missing-config-settings").send(player, Prefix.CHALLENGES, String.join(separator, missingConfigSettings)); } else if (!UpdateLoader.isNewestConfigVersion()) { player.sendMessage(""); - Message.forName("no-missing-config-settings").send(player, Prefix.CHALLENGES, UpdateLoader.getDefaultConfigVersion().format()); + MessageKey.of("no-missing-config-settings").send(player, Prefix.CHALLENGES, UpdateLoader.getDefaultConfigVersion().format()); } if (!UpdateLoader.isNewestPluginVersion()) { player.sendMessage(""); - Message.forName("deprecated-plugin-version").send(player, Prefix.CHALLENGES, "spigotmc.org/resources/" + UpdateLoader.RESOURCE_ID); + MessageKey.of("deprecated-plugin-version").send(player, Prefix.CHALLENGES, "spigotmc.org/resources/" + UpdateLoader.RESOURCE_ID); } } if (messages) { + event.setJoinMessage(null); player.sendMessage(""); - event.setJoinMessage(Prefix.CHALLENGES + Message.forName("join-message").asString(NameHelper.getName(event.getPlayer()))); + MessageKey.of("join-message").broadcast(Prefix.CHALLENGES, event.getPlayer()); // TODO name color } if (Challenges.getInstance().getDatabaseManager().isConnected()) { @@ -124,7 +142,7 @@ public void onQuit(@NotNull PlayerQuitEvent event) { event.setQuitMessage(null); } else if (messages) { event.setQuitMessage(null); - Message.forName("quit-message").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + MessageKey.of("quit-message").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); } } catch (Exception exception) { Challenges.getInstance().getILogger().error("Error while handling disconnect", exception); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java index e6050d843..6a185f8ee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.utils.bukkit.command; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; @@ -21,7 +21,7 @@ default boolean onCommand(@NotNull CommandSender sender, @NotNull Command comman Logger.error("Something went wrong while processing the command '{}'", label, ex); } } else { - Message.forName("player-command").send(sender, Prefix.CHALLENGES); + MessageKey.of("player-command").send(sender, Prefix.CHALLENGES); } return true; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java index c94470132..f9965697c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/SenderCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.bukkit.command; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java index 09563e29b..ddf90965e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.bukkit.misc; -import net.codingarea.challenges.plugin.content.Prefix; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.commons.common.collection.WrappedException; import net.codingarea.commons.common.logging.ILogger; @@ -204,6 +204,16 @@ public static BaseComponent getItemComponent(@NotNull Material material) { return component; } +// public static BaseComponent getServerSideItemComponent(@NotNull Material material) { +// BaseComponent component = getItemComponent(material); +// BaseComponent smithingTemplateName = getSmithingTemplateName(material); +// if (smithingTemplateName != null) { +// component.addExtra(" ("); +// component.addExtra(smithingTemplateName); +// component.addExtra(")"); +// } +// return component; +// } public static TranslatableComponent getEntityName(@NotNull EntityType type) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java index fccfd0b95..96c21e7d5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java @@ -1,15 +1,23 @@ package net.codingarea.challenges.plugin.utils.item; import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder.SkullBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder.SkullBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; public final class DefaultItem { - private static final String ARROW_LEFT = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjAwNmVjMWVjYTJmMjY4NWY3MGU2NTQxMWNmZTg4MDhhMDg4ZjdjZjA4MDg3YWQ4ZWVjZTk2MTgzNjEwNzBlMyJ9fX0=", - ARROW_RIGHT = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZmY5ZTE5ZTVmMmNlMzQ4OGMyOTU4MmI2ZDI2MDE1MDA2MjZlOGRiMmE4OGNkMTgxNjQ0MzJmZWYyZTM0ZGU2YiJ9fX0="; + public static final class SkullTextures { + public static final String + ARROW_LEFT = "e3RleHR1cmVzOntTS0lOOnt1cmw6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYjI1YWQwOTgxNmY1Yjc1ZTcyMzUwNzFlODdiYmZmOGYxYmVlMjZmMDVkNDQwMWFjNGRmOTI1YTA3MDE5In19fQ==", + ARROW_RIGHT = "e3RleHR1cmVzOntTS0lOOnt1cmw6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMWI2ZjFhMjViNmJjMTk5OTQ2NDcyYWVkYjM3MDUyMjU4NGZmNmY0ZTgzMjIxZTU5NDZiZDJlNDFiNWNhMTNiIn19fQ==", + GREEN_ARROW_UP = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNWRhMDI3NDc3MTk3YzZmZDdhZDMzMDE0NTQ2ZGUzOTJiNGE1MWM2MzRlYTY4YzhiN2JjYzAxMzFjODNlM2YifX19", + RED_ARROW_DOWN = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTM4NTJiZjYxNmYzMWVkNjdjMzdkZTRiMGJhYTJjNWY4ZDhmY2E4MmU3MmRiY2FmY2JhNjY5NTZhODFjNCJ9fX0="; + + private SkullTextures() { + } + } @NotNull public static String getItemPrefix() { @@ -17,58 +25,58 @@ public static String getItemPrefix() { } @NotNull - public static ItemBuilder navigateBack() { - return new SkullBuilder().setBase64Texture(ARROW_LEFT).setName(Message.forName("navigate-back")).hideAttributes(); + public static LegacyItemBuilder navigateBack() { + return new SkullBuilder().setBase64Texture(SkullTextures.ARROW_LEFT).setName(Message.forName("navigate-back")).hideAttributes(); } @NotNull - public static ItemBuilder navigateNext() { - return new SkullBuilder().setBase64Texture(ARROW_RIGHT).setName(Message.forName("navigate-next")).hideAttributes(); + public static LegacyItemBuilder navigateNext() { + return new SkullBuilder().setBase64Texture(SkullTextures.ARROW_RIGHT).setName(Message.forName("navigate-next")).hideAttributes(); } @NotNull - public static ItemBuilder navigateBackMainMenu() { - return new ItemBuilder(Material.DARK_OAK_DOOR).setName(Message.forName("navigate-back")).hideAttributes(); + public static LegacyItemBuilder navigateBackMainMenu() { + return new LegacyItemBuilder(Material.DARK_OAK_DOOR).setName(Message.forName("navigate-back")).hideAttributes(); } @NotNull - public static ItemBuilder status(boolean enabled) { + public static LegacyItemBuilder status(boolean enabled) { return enabled ? enabled() : disabled(); } @NotNull - public static ItemBuilder enabled() { - return new ItemBuilder(Material.LIME_DYE).setName(getTitle(Message.forName("enabled"))).hideAttributes(); + public static LegacyItemBuilder enabled() { + return new LegacyItemBuilder(Material.LIME_DYE).setName(getTitle(Message.forName("enabled"))).hideAttributes(); } @NotNull - public static ItemBuilder disabled() { - return new ItemBuilder(MinecraftNameWrapper.RED_DYE).setName(getTitle(Message.forName("disabled"))).hideAttributes(); + public static LegacyItemBuilder disabled() { + return new LegacyItemBuilder(MinecraftNameWrapper.RED_DYE).setName(getTitle(Message.forName("disabled"))).hideAttributes(); } @NotNull - public static ItemBuilder customize() { - return new ItemBuilder(MinecraftNameWrapper.SIGN).setName(getTitle(Message.forName("customize"))).hideAttributes(); + public static LegacyItemBuilder customize() { + return new LegacyItemBuilder(MinecraftNameWrapper.SIGN).setName(getTitle(Message.forName("customize"))).hideAttributes(); } @NotNull - public static ItemBuilder value(int value) { + public static LegacyItemBuilder value(int value) { return value(value, "§e"); } @NotNull - public static ItemBuilder value(int value, @NotNull String prefix) { - return create(Material.STONE_BUTTON, prefix + value).amount(Math.max(value, 1)); + public static LegacyItemBuilder value(int value, @NotNull String prefix) { + return create(Material.STONE_BUTTON, prefix + value).setAmount(Math.max(value, 1)); } @NotNull - public static ItemBuilder create(@NotNull Material material, @NotNull String name) { - return new ItemBuilder(material, getTitle(name)); + public static LegacyItemBuilder create(@NotNull Material material, @NotNull String name) { + return new LegacyItemBuilder(material, getTitle(name)); } @NotNull - public static ItemBuilder create(@NotNull Material material, @NotNull Message message) { - ItemBuilder itemBuilder = new ItemBuilder(material, message); + public static LegacyItemBuilder create(@NotNull Material material, @NotNull Message message) { + LegacyItemBuilder itemBuilder = new LegacyItemBuilder(material, message); return itemBuilder.setName(getTitle(message)); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java new file mode 100644 index 000000000..8eaf942ff --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java @@ -0,0 +1,57 @@ +package net.codingarea.challenges.plugin.utils.item; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class DefaultItems { + + @NoArgsConstructor(access = AccessLevel.PRIVATE) + public static final class SkullTextures { + public static final String + ARROW_LEFT = "e3RleHR1cmVzOntTS0lOOnt1cmw6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYjI1YWQwOTgxNmY1Yjc1ZTcyMzUwNzFlODdiYmZmOGYxYmVlMjZmMDVkNDQwMWFjNGRmOTI1YTA3MDE5In19fQ==", + ARROW_RIGHT = "e3RleHR1cmVzOntTS0lOOnt1cmw6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMWI2ZjFhMjViNmJjMTk5OTQ2NDcyYWVkYjM3MDUyMjU4NGZmNmY0ZTgzMjIxZTU5NDZiZDJlNDFiNWNhMTNiIn19fQ==", + GREEN_ARROW_UP = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNWRhMDI3NDc3MTk3YzZmZDdhZDMzMDE0NTQ2ZGUzOTJiNGE1MWM2MzRlYTY4YzhiN2JjYzAxMzFjODNlM2YifX19", + RED_ARROW_DOWN = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTM4NTJiZjYxNmYzMWVkNjdjMzdkZTRiMGJhYTJjNWY4ZDhmY2E4MmU3MmRiY2FmY2JhNjY5NTZhODFjNCJ9fX0="; + } + + public static ItemBuilder createNavigateNext(@NotNull Locale locale) { + return new ItemBuilder.SkullBuilder(locale, MessageKey.of("navigate-next")).setBase64Texture(DefaultItem.SkullTextures.ARROW_RIGHT); + } + + public static ItemBuilder createNavigateBack(@NotNull Locale locale) { + return new ItemBuilder.SkullBuilder(locale, MessageKey.of("navigate-back")).setBase64Texture(SkullTextures.ARROW_LEFT); + } + + public static ItemBuilder createNavigateBackMainMenu(@NotNull Locale locale) { + return new ItemBuilder(locale, Material.DARK_OAK_DOOR, MessageKey.of("navigate-back")); + } + + public static ItemStack createEnabledPreset() { + return new ItemStack(Material.LIME_DYE); + } + + public static ItemStack createEnabledValuePreset(int amount) { + return new ItemStack(Material.LIME_DYE, amount); + } + + public static ItemStack createDisabledPreset() { + return new ItemStack(MinecraftNameWrapper.RED_DYE); + } + + public static ItemStack createValuePreset(int value) { + return new ItemStack(Material.STONE_BUTTON, Math.max(value, 1)); + } + + public static ItemStack createCustomizePreset() { + return new ItemStack(MinecraftNameWrapper.SIGN); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index 331ddb148..8a2abec7d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -1,435 +1,345 @@ package net.codingarea.challenges.plugin.utils.item; -import com.google.gson.JsonParser; -import net.codingarea.challenges.plugin.content.ItemDescription; -import net.codingarea.challenges.plugin.content.Message; +import com.google.common.base.Preconditions; +import lombok.Getter; +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.commons.bukkit.utils.item.BannerPattern; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; +import net.codingarea.commons.common.config.Document; import org.bukkit.*; import org.bukkit.block.banner.Pattern; import org.bukkit.block.banner.PatternType; import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.*; +import org.bukkit.inventory.meta.BannerMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.profile.PlayerProfile; import org.bukkit.profile.PlayerTextures; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NonNull; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Collection; -import java.util.List; -import java.util.UUID; +import java.util.*; -public class ItemBuilder extends net.codingarea.commons.bukkit.utils.item.ItemBuilder { +public class ItemBuilder extends StandardItemBuilder { - public static final ItemStack BLOCKED_ITEM = new ItemBuilder(Material.BARRIER, "§cBlocked").build(); + @Getter + private final Locale locale; - protected ItemDescription builtByItemDescription; - - public ItemBuilder(@NotNull ItemStack item) { - super(item); - } - - public ItemBuilder(@NotNull ItemStack item, @Nullable ItemMeta meta) { - super(item, meta); - } - - public ItemBuilder() { - this(Material.BARRIER, ItemDescription.empty()); - } - - public ItemBuilder(@NotNull Material material) { + public ItemBuilder(@NotNull Locale locale, @NotNull Material material, @NotNull MessageKey nameAndLoreKey, @NotNull Object... args) { + Preconditions.checkNotNull(locale, "Cannot create ItemBuilder from null Locale"); super(material); + this.locale = locale; + resetToNameAndLore(nameAndLoreKey, args); } - public ItemBuilder(@NotNull Material material, @NotNull Message message) { - this(material, message.asItemDescription()); - } - - public ItemBuilder(@NotNull Material material, @NotNull Message message, Object... args) { - this(material, message.asItemDescription(args)); - } - - public ItemBuilder(@NotNull Material material, @NotNull ItemDescription description) { - this(material); - applyFormat(description); - } - - public ItemBuilder(@NotNull Material material, @NotNull String name) { - super(material, name); - } - - public ItemBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { - super(material, name, lore); + public ItemBuilder(@NotNull Locale locale, @NotNull ItemStack item, @NotNull MessageKey nameAndLoreKey, @NotNull Object... args) { + Preconditions.checkNotNull(locale, "Cannot create ItemBuilder from null Locale"); + super(item); + this.locale = locale; + resetToNameAndLore(nameAndLoreKey, args); } - public ItemBuilder(@NotNull Material material, @NotNull String name, int amount) { - super(material, name, amount); + public ItemBuilder(@NotNull Locale locale, @NotNull StandardItemBuilder item, @NotNull MessageKey nameAndLoreKey, @NotNull Object... args) { + this(locale, item.build(), nameAndLoreKey, args); } - @NotNull - public ItemBuilder setLore(@NotNull Message message) { - return setLore(message.asArray()); + public ItemBuilder(@NotNull Player playerLocale, @NotNull Material material, @NotNull MessageKey nameAndLoreKey, @NotNull Object... args) { + this(Challenges.getInstance().getTranslationManager().getLanguageProvider().getPlayerLanguage(playerLocale), material, nameAndLoreKey, args); } - @NotNull - public ItemBuilder setLore(@NotNull List lore) { - return (ItemBuilder) super.setLore(lore); + public ItemBuilder(@NotNull Locale locale, @NotNull ItemStack item) { + Preconditions.checkNotNull(locale, "Cannot create ItemBuilder from null Locale"); + super(item); + this.locale = locale; } - @NotNull - public ItemBuilder setLore(@NotNull String... lore) { - return (ItemBuilder) super.setLore(lore); + protected void resetToNameAndLore(@NotNull MessageKey nameAndLoreKey, @NotNull Object... args) { + nameAndLoreKey.applyAsItemNameAndLore(locale, getItemMeta(), args); + hideAttributes(); } @NotNull - public ItemBuilder appendLore(@NotNull String... lore) { - return (ItemBuilder) super.appendLore(lore); + public ItemBuilder appendNameWithSpace(@NotNull MessageKey key, @NotNull Object... args) { + key.appendToItemName(locale, getItemMeta(), true, args); + return this; } @NotNull - public ItemBuilder appendLore(@NotNull Collection lore) { - return (ItemBuilder) super.appendLore(lore); + public ItemBuilder appendName(@NotNull MessageKey key, @NotNull Object... args) { + key.appendToItemName(locale, getItemMeta(), false, args); + return this; } @NotNull - public ItemBuilder setName(@Nullable String name) { - return (ItemBuilder) super.setName(name); + public ItemBuilder appendLore(@NotNull MessageKey key, @NotNull Object... args) { + key.appendToItemLore(locale, getItemMeta(), args); + return this; } @NotNull - public ItemBuilder setName(@Nullable Object name) { - return (ItemBuilder) super.setName(name); + public ItemBuilder appendLore(@NotNull LocalizableMessage localizable) { + return this.appendLore(localizable.getLocalizableKey(), localizable.getLocalizableArgs()); } @NotNull - public ItemBuilder setName(@NotNull String... content) { - return (ItemBuilder) super.setName(content); + public ItemBuilder appendLoreWithEmptyLine(@NotNull MessageKey key, @NotNull Object... args) { + super.appendLore(" "); + return this.appendLore(key, args); } @NotNull - public ItemBuilder appendName(@Nullable Object sequence) { - return (ItemBuilder) super.appendName(sequence); + public ItemBuilder appendLoreWithEmptyLine(@NotNull LocalizableMessage localizable) { + return this.appendLoreWithEmptyLine(localizable.getLocalizableKey(), localizable.getLocalizableArgs()); } - @NotNull - public ItemBuilder name(@Nullable Object name) { - return (ItemBuilder) super.name(name); - } - @NotNull - public ItemBuilder name(@NotNull String... content) { - return (ItemBuilder) super.name(content); - } + // Overrides @NotNull + @Override public ItemBuilder addEnchantment(@NotNull Enchantment enchantment, int level) { return (ItemBuilder) super.addEnchantment(enchantment, level); } @NotNull - public ItemBuilder enchant(@NotNull Enchantment enchantment, int level) { - return (ItemBuilder) super.enchant(enchantment, level); - } - - @NotNull - public ItemBuilder addFlag(@NotNull ItemFlag... flags) { + @Override + public ItemBuilder addFlag(@NonNull @NotNull ItemFlag... flags) { return (ItemBuilder) super.addFlag(flags); } @NotNull - public ItemBuilder removeFlag(@NotNull ItemFlag... flags) { + @Override + public ItemBuilder removeFlag(@NonNull @NotNull ItemFlag... flags) { return (ItemBuilder) super.removeFlag(flags); } @NotNull + @Override public ItemBuilder hideAttributes() { return (ItemBuilder) super.hideAttributes(); } @NotNull + @Override public ItemBuilder showAttributes() { return (ItemBuilder) super.showAttributes(); } @NotNull + @Override public ItemBuilder setUnbreakable(boolean unbreakable) { return (ItemBuilder) super.setUnbreakable(unbreakable); } @NotNull - public ItemBuilder unbreakable() { - return (ItemBuilder) super.unbreakable(); + @Override + public ItemBuilder setAmount(int amount) { + return (ItemBuilder) super.setAmount(amount); } @NotNull - public ItemBuilder breakable() { - return (ItemBuilder) super.breakable(); + @Override + public ItemBuilder setDamage(int damage) { + return (ItemBuilder) super.setDamage(damage); } @NotNull - public ItemBuilder setAmount(int amount) { - return (ItemBuilder) super.setAmount(amount); + @Override + public ItemBuilder setMaterial(@NotNull Material material) { + return (ItemBuilder) super.setMaterial(material); } + + // Unstable + @NotNull - public ItemBuilder amount(int amount) { - return (ItemBuilder) super.amount(amount); + @Override + @Deprecated + public StandardItemBuilder setLore(@NotNull List lore) { + return super.setLore(lore); } @NotNull - public ItemBuilder setDamage(int damage) { - return (ItemBuilder) super.setDamage(damage); + @Override + @Deprecated + public StandardItemBuilder setLore(@NonNull @NotNull String... lore) { + return super.setLore(lore); } @NotNull - public ItemBuilder damage(int damage) { - return (ItemBuilder) super.damage(damage); + @Override + @Deprecated + public StandardItemBuilder appendLore(@NonNull @NotNull String... lore) { + return super.appendLore(lore); } @NotNull - public ItemBuilder setType(@NotNull Material material) { - return (ItemBuilder) super.setType(material); + @Override + @Deprecated + public StandardItemBuilder appendLore(@NotNull Collection lore) { + return super.appendLore(lore); } @NotNull - public ItemBuilder applyFormat(@NotNull ItemDescription description) { - builtByItemDescription = description; - setName(description.getName()); - setLore(description.getLore()); - return this; + @Override + @Deprecated + public StandardItemBuilder setName(@Nullable String name) { + return super.setName(name); } - @Nullable - public ItemDescription getBuiltByItemDescription() { - return builtByItemDescription; + @NotNull + @Override + @Deprecated + public StandardItemBuilder setName(@Nullable Object name) { + return super.setName(name); } + @NotNull @Override - public ItemBuilder clone() { - ItemBuilder builder = new ItemBuilder(item.clone(), getMeta().clone()); - builder.builtByItemDescription = builtByItemDescription; - return builder; + @Deprecated + public StandardItemBuilder setName(@NonNull @NotNull String... content) { + return super.setName(content); } - public static class BannerBuilder extends ItemBuilder { - - public BannerBuilder(@NotNull Material material) { - super(material); - } - - public BannerBuilder(@NotNull Material material, @NotNull Message message) { - super(material, message); - } - - public BannerBuilder(@NotNull Material material, @NotNull ItemDescription description) { - super(material, description); - } - - public BannerBuilder(@NotNull Material material, @NotNull String name) { - super(material, name); - } - - public BannerBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { - super(material, name, lore); - } + @NotNull + @Override + @Deprecated + public StandardItemBuilder appendName(@Nullable String sequence) { + return super.appendName(sequence); + } - public BannerBuilder(@NotNull Material material, @NotNull String name, int amount) { - super(material, name, amount); - } + public static class BannerBuilder extends ItemBuilder { - public BannerBuilder(@NotNull ItemStack item) { - super(item); + public BannerBuilder(@NotNull Locale locale, @NotNull Material material, @NotNull MessageKey nameAndLoreKey, @NonNull Object... args) { + super(locale, material, nameAndLoreKey, args); } @NotNull - public ItemBuilder.BannerBuilder addPattern(@NotNull BannerPattern pattern, @NotNull DyeColor color) { + public BannerBuilder addPattern(@NotNull BannerPattern pattern, @NotNull DyeColor color) { return addPattern(pattern.getPatternType(), color); } @NotNull - public ItemBuilder.BannerBuilder addPattern(@NotNull PatternType pattern, @NotNull DyeColor color) { - getMeta().addPattern(new Pattern(color, pattern)); + public BannerBuilder addPattern(@NotNull PatternType pattern, @NotNull DyeColor color) { + getItemMeta().addPattern(new Pattern(color, pattern)); return this; } @NotNull @Override - public BannerMeta getMeta() { - return getCastedMeta(); + public BannerMeta getItemMeta() { + return getItemMetaAs(); } } public static class SkullBuilder extends ItemBuilder { - public SkullBuilder() { - super(Material.PLAYER_HEAD); - } - - public SkullBuilder(Message message) { - super(Material.PLAYER_HEAD, message); - } - - public SkullBuilder(String name, String... lore) { - super(Material.PLAYER_HEAD, name, lore); + public SkullBuilder(@NotNull Locale locale, @NotNull MessageKey nameAndLoreKey, @NonNull Object... args) { + super(locale, Material.PLAYER_HEAD, nameAndLoreKey, args); } @NotNull - public ItemBuilder.SkullBuilder setOwner(@NotNull OfflinePlayer owner) { - getMeta().setOwningPlayer(owner); + public SkullBuilder setOwner(@NotNull OfflinePlayer owner) { + getItemMeta().setOwningPlayer(owner); return this; } @NotNull - public ItemBuilder.SkullBuilder setOwner(@NotNull UUID uuid, @NotNull String name) { - PlayerProfile profile = Bukkit.createPlayerProfile(uuid, name); - getMeta().setOwnerProfile(profile); + public SkullBuilder setOwner(@NotNull UUID uuid, @NotNull String name) { + PlayerProfile profile = Bukkit.createPlayerProfile(uuid, name); // TODO compatibility 1.17 + getItemMeta().setOwnerProfile(profile); return this; } - public ItemBuilder.SkullBuilder setTexture(@NotNull String textureUrl) { + @NotNull + public SkullBuilder setTexture(@NotNull String textureUrl) { UUID uuid = UUID.nameUUIDFromBytes(textureUrl.getBytes()); - PlayerProfile profile = Bukkit.createPlayerProfile(uuid); + PlayerProfile profile = Bukkit.createPlayerProfile(uuid); // TODO does not exist 1.17.1 PlayerTextures texture = profile.getTextures(); try { - texture.setSkin(new URL(textureUrl)); + texture.setSkin(new URL(textureUrl)); // URI.create(textureUrl).toURL() } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid texture url", e); } profile.setTextures(texture); - getMeta().setOwnerProfile(profile); + getItemMeta().setOwnerProfile(profile); return this; } - public ItemBuilder.SkullBuilder setBase64Texture(@NotNull String base64Texture) { - String textureUrlJson = new String(Base64.getDecoder().decode(base64Texture), - StandardCharsets.UTF_8); - - String textureUrl = JsonParser.parseString(textureUrlJson) // TODO fix(deps) version ambiguity - .getAsJsonObject() - .get("textures").getAsJsonObject() - .get("SKIN").getAsJsonObject() - .get("url").getAsString(); - + public SkullBuilder setBase64Texture(@NotNull String base64Texture) { + String textureUrlJson = new String(Base64.getDecoder().decode(base64Texture), StandardCharsets.UTF_8); + String textureUrl = Document.parseJson(textureUrlJson) + .getString("textures.SKIN.url"); + if (textureUrl == null) return this; // TODO return setTexture(textureUrl); } @NotNull @Override - public SkullMeta getMeta() { - return getCastedMeta(); + public SkullMeta getItemMeta() { + return getItemMetaAs(); } } public static class PotionBuilder extends ItemBuilder { - public PotionBuilder(@NotNull Material material) { - super(material); - } - - public PotionBuilder(@NotNull Material material, @NotNull Message message) { - super(material, message); - } - - public PotionBuilder(@NotNull Material material, @NotNull String name) { - super(material, name); - } - - public PotionBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { - super(material, name, lore); - } - - public PotionBuilder(@NotNull Material material, @NotNull String name, int amount) { - super(material, name, amount); - } - - public PotionBuilder(@NotNull ItemStack item) { - super(item); - } - - @NotNull - public static ItemBuilder createWaterBottle() { - return new ItemBuilder.PotionBuilder(Material.POTION).setColor(Color.BLUE).hideAttributes(); + public PotionBuilder(@NotNull Locale locale, @NotNull Material material, @NotNull MessageKey titleAndLoreKey, @NonNull Object... args) { + super(locale, material, titleAndLoreKey, args); } @NotNull - public ItemBuilder.PotionBuilder addEffect(@NotNull PotionEffect effect) { - getMeta().addCustomEffect(effect, true); + public PotionBuilder addEffect(@NotNull PotionEffect effect) { + getItemMeta().addCustomEffect(effect, true); return this; } @NotNull - public ItemBuilder.PotionBuilder setColor(@NotNull Color color) { - getMeta().setColor(color); + public PotionBuilder setColor(@NotNull Color color) { + getItemMeta().setColor(color); return this; } - @NotNull - public ItemBuilder.PotionBuilder color(@NotNull Color color) { - return setColor(color); - } - @NotNull @Override - public PotionMeta getMeta() { - return getCastedMeta(); + public PotionMeta getItemMeta() { + return getItemMetaAs(); } } public static class LeatherArmorBuilder extends ItemBuilder { - public LeatherArmorBuilder(@NotNull Material material) { - super(material); - } - - public LeatherArmorBuilder(@NotNull Material material, @NotNull Message message) { - super(material, message); - } - - public LeatherArmorBuilder(@NotNull Material material, @NotNull String name) { - super(material, name); - } - - public LeatherArmorBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { - super(material, name, lore); - } - - public LeatherArmorBuilder(@NotNull Material material, @NotNull String name, int amount) { - super(material, name, amount); - } - - public LeatherArmorBuilder(@NotNull ItemStack item) { - super(item); + public LeatherArmorBuilder(@NotNull Locale locale, @NotNull Material material, @NotNull MessageKey titleAndLoreKey, @NotNull Object... args) { + super(locale, material, titleAndLoreKey, args); } @NotNull - public ItemBuilder.LeatherArmorBuilder setColor(@NotNull Color color) { - getMeta().setColor(color); + public LeatherArmorBuilder setColor(@NotNull Color color) { + getItemMeta().setColor(color); return this; } - @NotNull - public ItemBuilder.LeatherArmorBuilder color(@NotNull Color color) { - return setColor(color); - } - @NotNull @Override - public LeatherArmorMeta getMeta() { - return getCastedMeta(); + public LeatherArmorMeta getItemMeta() { + return getItemMetaAs(); } } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/LegacyItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/LegacyItemBuilder.java new file mode 100644 index 000000000..32a7a5f22 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/LegacyItemBuilder.java @@ -0,0 +1,401 @@ +package net.codingarea.challenges.plugin.utils.item; + +import net.codingarea.challenges.plugin.content.ItemDescription; +import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.commons.bukkit.utils.item.BannerPattern; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; +import net.codingarea.commons.common.config.Document; +import org.bukkit.*; +import org.bukkit.block.banner.Pattern; +import org.bukkit.block.banner.PatternType; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.*; +import org.bukkit.potion.PotionEffect; +import org.bukkit.profile.PlayerProfile; +import org.bukkit.profile.PlayerTextures; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Collection; +import java.util.List; +import java.util.UUID; + +@Deprecated +public class LegacyItemBuilder extends StandardItemBuilder { + + public static final ItemStack BLOCKED_ITEM = new LegacyItemBuilder(Material.BARRIER, "§cBlocked").build(); + + protected ItemDescription builtByItemDescription; + + public LegacyItemBuilder(@NotNull ItemStack item) { + super(item); + } + + public LegacyItemBuilder(@NotNull ItemStack item, @Nullable ItemMeta meta) { + super(item, meta); + } + + public LegacyItemBuilder() { + this(Material.BARRIER, ItemDescription.empty()); + } + + public LegacyItemBuilder(@NotNull Material material) { + super(material); + } + + public LegacyItemBuilder(@NotNull Material material, @NotNull Message message) { + this(material, message.asItemDescription()); + } + + public LegacyItemBuilder(@NotNull Material material, @NotNull Message message, Object... args) { + this(material, message.asItemDescription(args)); + } + + public LegacyItemBuilder(@NotNull Material material, @NotNull ItemDescription description) { + this(material); + applyFormat(description); + } + + public LegacyItemBuilder(@NotNull Material material, @NotNull String name) { + super(material, name); + } + + public LegacyItemBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { + super(material, name, lore); + } + + public LegacyItemBuilder(@NotNull Material material, @NotNull String name, int amount) { + super(material, name, amount); + } + + @NotNull + public LegacyItemBuilder setLore(@NotNull Message message) { + return setLore(message.asArray()); + } + + @NotNull + public LegacyItemBuilder setLore(@NotNull List lore) { + return (LegacyItemBuilder) super.setLore(lore); + } + + @NotNull + public LegacyItemBuilder setLore(@NotNull String... lore) { + return (LegacyItemBuilder) super.setLore(lore); + } + + @NotNull + public LegacyItemBuilder appendLore(@NotNull String... lore) { + return (LegacyItemBuilder) super.appendLore(lore); + } + + @NotNull + public LegacyItemBuilder appendLore(@NotNull Collection lore) { + return (LegacyItemBuilder) super.appendLore(lore); + } + + @NotNull + public LegacyItemBuilder setName(@Nullable String name) { + return (LegacyItemBuilder) super.setName(name); + } + + @NotNull + public LegacyItemBuilder setName(@Nullable Object name) { + return (LegacyItemBuilder) super.setName(name); + } + + @NotNull + public LegacyItemBuilder setName(@NotNull String... content) { + return (LegacyItemBuilder) super.setName(content); + } + + @NotNull + public LegacyItemBuilder appendName(@Nullable String sequence) { + return (LegacyItemBuilder) super.appendName(sequence); + } + + @NotNull + public LegacyItemBuilder addEnchantment(@NotNull Enchantment enchantment, int level) { + return (LegacyItemBuilder) super.addEnchantment(enchantment, level); + } + + @NotNull + public LegacyItemBuilder addFlag(@NotNull ItemFlag... flags) { + return (LegacyItemBuilder) super.addFlag(flags); + } + + @NotNull + public LegacyItemBuilder removeFlag(@NotNull ItemFlag... flags) { + return (LegacyItemBuilder) super.removeFlag(flags); + } + + @NotNull + public LegacyItemBuilder hideAttributes() { + return (LegacyItemBuilder) super.hideAttributes(); + } + + @NotNull + public LegacyItemBuilder showAttributes() { + return (LegacyItemBuilder) super.showAttributes(); + } + + @NotNull + public LegacyItemBuilder setUnbreakable(boolean unbreakable) { + return (LegacyItemBuilder) super.setUnbreakable(unbreakable); + } + + @NotNull + public LegacyItemBuilder setAmount(int amount) { + return (LegacyItemBuilder) super.setAmount(amount); + } + + @NotNull + public LegacyItemBuilder setDamage(int damage) { + return (LegacyItemBuilder) super.setDamage(damage); + } + + @NotNull + public LegacyItemBuilder setMaterial(@NotNull Material material) { + return (LegacyItemBuilder) super.setMaterial(material); + } + + @NotNull + public LegacyItemBuilder applyFormat(@NotNull ItemDescription description) { + builtByItemDescription = description; + hideAttributes(); + setName(description.getName()); + setLore(description.getLore()); + return this; + } + + @Nullable + public ItemDescription getBuiltByItemDescription() { + return builtByItemDescription; + } + + @Override + public LegacyItemBuilder clone() { + LegacyItemBuilder builder = new LegacyItemBuilder(item.clone(), getItemMeta().clone()); + builder.builtByItemDescription = builtByItemDescription; + return builder; + } + + public static class BannerBuilder extends LegacyItemBuilder { + + public BannerBuilder(@NotNull Material material) { + super(material); + } + + public BannerBuilder(@NotNull Material material, @NotNull Message message) { + super(material, message); + } + + public BannerBuilder(@NotNull Material material, @NotNull ItemDescription description) { + super(material, description); + } + + public BannerBuilder(@NotNull Material material, @NotNull String name) { + super(material, name); + } + + public BannerBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { + super(material, name, lore); + } + + public BannerBuilder(@NotNull Material material, @NotNull String name, int amount) { + super(material, name, amount); + } + + public BannerBuilder(@NotNull ItemStack item) { + super(item); + } + + @NotNull + public LegacyItemBuilder.BannerBuilder addPattern(@NotNull BannerPattern pattern, @NotNull DyeColor color) { + return addPattern(pattern.getPatternType(), color); + } + + @NotNull + public LegacyItemBuilder.BannerBuilder addPattern(@NotNull PatternType pattern, @NotNull DyeColor color) { + getItemMeta().addPattern(new Pattern(color, pattern)); + return this; + } + + @NotNull + @Override + public BannerMeta getItemMeta() { + return getItemMetaAs(); + } + + } + + public static class SkullBuilder extends LegacyItemBuilder { + + public SkullBuilder() { + super(Material.PLAYER_HEAD); + } + + public SkullBuilder(Message message) { + super(Material.PLAYER_HEAD, message); + } + + public SkullBuilder(String name, String... lore) { + super(Material.PLAYER_HEAD, name, lore); + } + + @NotNull + public LegacyItemBuilder.SkullBuilder setOwner(@NotNull OfflinePlayer owner) { + getItemMeta().setOwningPlayer(owner); + return this; + } + + @NotNull + public LegacyItemBuilder.SkullBuilder setOwner(@NotNull UUID uuid, @NotNull String name) { +// PlayerProfile profile = Bukkit.createPlayerProfile(uuid, name); + PlayerProfile profile = Bukkit.createPlayerProfile(uuid); + getItemMeta().setOwnerProfile(profile); + return this; + } + + public LegacyItemBuilder.SkullBuilder setTexture(@NotNull String textureUrl) { + UUID uuid = UUID.nameUUIDFromBytes(textureUrl.getBytes()); + + if (true) return this; // TODO QUICKFIX 1.17.1 + + PlayerProfile profile = Bukkit.createPlayerProfile(uuid); // does not exist 1.17.1 + PlayerTextures texture = profile.getTextures(); + + try { + texture.setSkin(new URL(textureUrl)); + } catch (MalformedURLException e) { + throw new IllegalArgumentException("Invalid texture url", e); + } + + profile.setTextures(texture); + getItemMeta().setOwnerProfile(profile); + return this; + } + + public LegacyItemBuilder.SkullBuilder setBase64Texture(@NotNull String base64Texture) { + String textureUrlJson = new String(Base64.getDecoder().decode(base64Texture), StandardCharsets.UTF_8); + String textureUrl = Document.parseJson(textureUrlJson) + .getString("textures.SKIN.url"); + if (textureUrl == null) return this; // TODO + return setTexture(textureUrl); + } + + @NotNull + @Override + public SkullMeta getItemMeta() { + return getItemMetaAs(); + } + + } + + public static class PotionBuilder extends LegacyItemBuilder { + + public PotionBuilder(@NotNull Material material) { + super(material); + } + + public PotionBuilder(@NotNull Material material, @NotNull Message message) { + super(material, message); + } + + public PotionBuilder(@NotNull Material material, @NotNull String name) { + super(material, name); + } + + public PotionBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { + super(material, name, lore); + } + + public PotionBuilder(@NotNull Material material, @NotNull String name, int amount) { + super(material, name, amount); + } + + public PotionBuilder(@NotNull ItemStack item) { + super(item); + } + + @NotNull + public static LegacyItemBuilder createWaterBottle() { + return new LegacyItemBuilder.PotionBuilder(Material.POTION).setColor(Color.BLUE).hideAttributes(); + } + + @NotNull + public LegacyItemBuilder.PotionBuilder addEffect(@NotNull PotionEffect effect) { + getItemMeta().addCustomEffect(effect, true); + return this; + } + + @NotNull + public LegacyItemBuilder.PotionBuilder setColor(@NotNull Color color) { + getItemMeta().setColor(color); + return this; + } + + @NotNull + public LegacyItemBuilder.PotionBuilder color(@NotNull Color color) { + return setColor(color); + } + + @NotNull + @Override + public PotionMeta getItemMeta() { + return getItemMetaAs(); + } + + } + + public static class LeatherArmorBuilder extends LegacyItemBuilder { + + public LeatherArmorBuilder(@NotNull Material material) { + super(material); + } + + public LeatherArmorBuilder(@NotNull Material material, @NotNull Message message) { + super(material, message); + } + + public LeatherArmorBuilder(@NotNull Material material, @NotNull String name) { + super(material, name); + } + + public LeatherArmorBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { + super(material, name, lore); + } + + public LeatherArmorBuilder(@NotNull Material material, @NotNull String name, int amount) { + super(material, name, amount); + } + + public LeatherArmorBuilder(@NotNull ItemStack item) { + super(item); + } + + @NotNull + public LegacyItemBuilder.LeatherArmorBuilder setColor(@NotNull Color color) { + getItemMeta().setColor(color); + return this; + } + + @NotNull + public LegacyItemBuilder.LeatherArmorBuilder color(@NotNull Color color) { + return setColor(color); + } + + @NotNull + @Override + public LeatherArmorMeta getItemMeta() { + return getItemMetaAs(); + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java index db768d90a..7cc322ba1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.utils.misc; import net.codingarea.challenges.plugin.ChallengeAPI; -import net.codingarea.challenges.plugin.management.menu.generator.MenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.AnimationFrame; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; @@ -79,9 +79,9 @@ public static void setNavigationItems(@NotNull I inventory, @NotNull int[] n setNavigationItems(inventory, navigationSlots, goBackExit, setter, index, size, DefaultItem.navigateBack(), DefaultItem.navigateNext()); } - public static void setNavigationItems(@NotNull I inventory, @NotNull int[] navigationSlots, boolean goBackExit, @NotNull InventorySetter setter, int index, int size, ItemBuilder navigateBack, ItemBuilder navigateNext) { + public static void setNavigationItems(@NotNull I inventory, @NotNull int[] navigationSlots, boolean goBackExit, @NotNull InventorySetter setter, int index, int size, LegacyItemBuilder navigateBack, LegacyItemBuilder navigateNext) { if (navigationSlots.length >= 1) { - ItemBuilder left = index == 0 && goBackExit ? DefaultItem.navigateBackMainMenu() : navigateBack; + LegacyItemBuilder left = index == 0 && goBackExit ? DefaultItem.navigateBackMainMenu() : navigateBack; setter.set(inventory, navigationSlots[0], left); } if (navigationSlots.length >= 2 && index < (size - 1)) @@ -114,7 +114,7 @@ public static int getRandomFullSlot(@NotNull Inventory inventory) { for (int slot = 0; slot < inventory.getSize(); slot++) { ItemStack item = inventory.getItem(slot); - if (item != null && !item.isSimilar(ItemBuilder.BLOCKED_ITEM)) { + if (item != null && !item.isSimilar(LegacyItemBuilder.BLOCKED_ITEM)) { fullSlots.add(slot); } } @@ -129,7 +129,7 @@ public static int getRandomSlot(@NotNull Inventory inventory) { for (int slot = 0; slot < inventory.getSize(); slot++) { ItemStack item = inventory.getItem(slot); - if (item != null && item.isSimilar(ItemBuilder.BLOCKED_ITEM)) continue; + if (item != null && item.isSimilar(LegacyItemBuilder.BLOCKED_ITEM)) continue; slots.add(slot); } @@ -218,7 +218,7 @@ public interface InventorySetter { InventorySetter FRAME = AnimationFrame::setItem; InventorySetter INVENTORY = (inventory, slot, item) -> inventory.setItem(slot, item.build()); - void set(@NotNull I inventory, int slot, @NotNull ItemBuilder item); + void set(@NotNull I inventory, int slot, @NotNull LegacyItemBuilder item); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java index 59351e1da..a8c0157bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java @@ -62,37 +62,37 @@ private MinecraftNameWrapper() { } @NotNull - private static Material getMaterialByNames(@NotNull String... names) { + public static Material getMaterialByNames(@NotNull String... names) { return ReflectionUtils.getFirstEnumByNames(Material.class, names); } @NotNull - private static EntityType getEntityByNames(@NotNull String... names) { + public static EntityType getEntityByNames(@NotNull String... names) { return ReflectionUtils.getFirstEnumByNames(EntityType.class, names); } @NotNull - private static Particle getParticleByNames(@NotNull String... names) { + public static Particle getParticleByNames(@NotNull String... names) { return ReflectionUtils.getFirstEnumByNames(Particle.class, names); } @NotNull - private static PotionEffectType getPotionByNames(@NotNull String... names) { + public static PotionEffectType getPotionByNames(@NotNull String... names) { return getFirstConstantByNames(PotionEffectType.class, names); } @NotNull - private static Enchantment getEnchantByNames(@NotNull String... names) { + public static Enchantment getEnchantByNames(@NotNull String... names) { return getFirstConstantByNames(Enchantment.class, names); } @NotNull - private static Attribute getAttributeByNames(@NotNull String... names) { + public static Attribute getAttributeByNames(@NotNull String... names) { return getFirstConstantByNames(Attribute.class, names); } @NotNull - private static GameRule getGameRuleByNames(@NotNull String... names) { + public static GameRule getGameRuleByNames(@NotNull String... names) { return getFirstConstantByNames(GameRule.class, names); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java index ac7d6228a..220ea64cf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.stats.Statistic; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; @@ -22,13 +22,13 @@ public static int[] getSlots(int row) { } public static void setAccent(@NotNull AnimatedInventory inventory, int row) { - inventory.createAndAdd().fill(ItemBuilder.FILL_ITEM); + inventory.createAndAdd().fill(LegacyItemBuilder.FILL_ITEM); int offset = row * 9; - inventory.cloneLastAndAdd().setAccent(offset, offset + 8); - inventory.cloneLastAndAdd().setAccent(offset + 1, offset + 7); - inventory.cloneLastAndAdd().setAccent(offset + 10, offset + 16); - inventory.cloneLastAndAdd().setAccent(offset + 11, offset + 15); - inventory.cloneLastAndAdd().setAccent(offset + 12, offset + 14); + inventory.cloneLastAndAdd().setContrast(offset, offset + 8); + inventory.cloneLastAndAdd().setContrast(offset + 1, offset + 7); + inventory.cloneLastAndAdd().setContrast(offset + 10, offset + 16); + inventory.cloneLastAndAdd().setContrast(offset + 11, offset + 15); + inventory.cloneLastAndAdd().setContrast(offset + 12, offset + 14); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java index 9445ccb0e..e4b3c26b3 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java @@ -270,8 +270,7 @@ public final void registerListener(@NotNull Listener... listeners) { } private void registerListener0(@NotNull Listener listener) { - if (listener instanceof ActionListener) { - ActionListener actionListener = (ActionListener) listener; + if (listener instanceof ActionListener actionListener) { getServer().getPluginManager().registerEvent( actionListener.getClassOfEvent(), actionListener, actionListener.getPriority(), new SimpleEventExecutor(actionListener.getClassOfEvent(), actionListener.getListener()), this, actionListener.isIgnoreCancelled() diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java index f0a917a0e..81e1df0f3 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimationFrame.java @@ -1,6 +1,6 @@ package net.codingarea.commons.bukkit.utils.animation; -import net.codingarea.commons.bukkit.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @@ -28,15 +28,15 @@ public AnimationFrame fill(@NotNull ItemStack item) { } @NotNull - public AnimationFrame setAccent(int... slots) { + public AnimationFrame setContrast(int... slots) { for (int slot : slots) { - content[slot] = ItemBuilder.FILL_ITEM_2; + content[slot] = StandardItemBuilder.FILL_ITEM_CONTRAST; } return this; } @NotNull - public AnimationFrame setItem(int slot, @NotNull ItemBuilder item) { + public AnimationFrame setItem(int slot, @NotNull StandardItemBuilder item) { return setItem(slot, item.build()); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java index bbfa1a881..d11e8dc77 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java @@ -13,7 +13,7 @@ public final class SoundSample { public static final SoundSample CLICK = new SoundSample().addSound(Sound.BLOCK_WOODEN_BUTTON_CLICK_ON, 0.5f), - BASS_OFF = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BASS, 0.5F), + BASS_OFF = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BASS, 0.6F), BASS_ON = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_PLING, 0.5F), PLING = new SoundSample().addSound(Sound.BLOCK_NOTE_BLOCK_BELL, 1), KLING = new SoundSample().addSound(Sound.ENTITY_PLAYER_LEVELUP, 0.6F, 2), @@ -25,7 +25,7 @@ public final class SoundSample { OPEN = new SoundSample().addSound(KLING).addSound(PLOP), EAT = new SoundSample().addSound(Sound.ENTITY_PLAYER_BURP, 1), BLAST = new SoundSample().addSound(Sound.ENTITY_FIREWORK_ROCKET_LARGE_BLAST, 1), - BREAK = new SoundSample().addSound(Sound.ENTITY_WITHER_BREAK_BLOCK, 0.7f), + BREAK = new SoundSample().addSound(Sound.ENTITY_WITHER_BREAK_BLOCK, 0.6f), WIN = new SoundSample().addSound(Sound.UI_TOAST_CHALLENGE_COMPLETE, 1), DRAGON_BREATH = new SoundSample().addSound(Sound.ENTITY_ENDER_DRAGON_GROWL, 0.5F); @@ -98,8 +98,8 @@ public void play(@NotNull Player player, @NotNull Location location) { } public void playIfPlayer(@NotNull Object target) { - if (target instanceof Player) - play((Player) target); + if (target instanceof Player player) + play(player); } public void broadcast() { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/StandardItemBuilder.java similarity index 61% rename from plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java rename to plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/StandardItemBuilder.java index ac089d643..e8bec5461 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/StandardItemBuilder.java @@ -23,76 +23,76 @@ import java.util.Collection; import java.util.List; -public class ItemBuilder { +public class StandardItemBuilder { - public static final ItemStack FILL_ITEM = new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE).setName("§0").build(), - FILL_ITEM_2 = new ItemBuilder(Material.BLACK_STAINED_GLASS_PANE).setName("§0").build(), - BLOCKED_ITEM = new ItemBuilder(Material.BARRIER, "§cBlocked").build(), + public static final ItemStack + FILL_ITEM = new StandardItemBuilder(Material.GRAY_STAINED_GLASS_PANE).setName("§0").build(), + FILL_ITEM_CONTRAST = new StandardItemBuilder(Material.BLACK_STAINED_GLASS_PANE).setName("§0").build(), AIR = new ItemStack(Material.AIR); protected ItemStack item; protected ItemMeta meta; - public ItemBuilder(@NotNull ItemStack item) { + public StandardItemBuilder(@NotNull ItemStack item) { this(item, item.getItemMeta()); } - public ItemBuilder(@NotNull ItemStack item, @Nullable ItemMeta meta) { + public StandardItemBuilder(@NotNull ItemStack item, @Nullable ItemMeta meta) { this.item = item; this.meta = meta; } - public ItemBuilder(@NotNull Material material) { + public StandardItemBuilder(@NotNull Material material) { this(new ItemStack(material)); } - public ItemBuilder(@NotNull Material material, @NotNull String name) { + public StandardItemBuilder(@NotNull Material material, @NotNull String name) { this(material); setName(name); } - public ItemBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { + public StandardItemBuilder(@NotNull Material material, @NotNull String name, @NotNull String... lore) { this(material); setName(name); setLore(lore); } - public ItemBuilder(@NotNull Material material, @NotNull String name, int amount) { + public StandardItemBuilder(@NotNull Material material, @NotNull String name, int amount) { this(material); setName(name); setAmount(amount); } @NotNull - public ItemMeta getMeta() { - return getCastedMeta(); + public ItemMeta getItemMeta() { + return getItemMetaAs(); } @NotNull @SuppressWarnings("unchecked") - public final M getCastedMeta() { + public final M getItemMetaAs() { return (M) (meta == null ? meta = item.getItemMeta() : meta); } @NotNull - public ItemBuilder setLore(@NotNull List lore) { - getMeta().setLore(lore); + public StandardItemBuilder setLore(@NotNull List lore) { + getItemMeta().setLore(lore); return this; } @NotNull - public ItemBuilder setLore(@NotNull String... lore) { + public StandardItemBuilder setLore(@NotNull String... lore) { return setLore(Arrays.asList(lore)); } @NotNull - public ItemBuilder appendLore(@NotNull String... lore) { + public StandardItemBuilder appendLore(@NotNull String... lore) { return appendLore(Arrays.asList(lore)); } @NotNull - public ItemBuilder appendLore(@NotNull Collection lore) { - List newLore = getMeta().getLore(); + public StandardItemBuilder appendLore(@NotNull Collection lore) { + List newLore = getItemMeta().getLore(); if (newLore == null) newLore = new ArrayList<>(); newLore.addAll(lore); setLore(newLore); @@ -100,74 +100,49 @@ public ItemBuilder appendLore(@NotNull Collection lore) { } @NotNull - public ItemBuilder lore(@NotNull String... lore) { - return setLore(lore); - } - - @NotNull - public ItemBuilder setName(@Nullable String name) { - getMeta().setDisplayName(name); + public StandardItemBuilder setName(@Nullable String name) { + getItemMeta().setDisplayName(name); return this; } @NotNull - public ItemBuilder setName(@Nullable Object name) { + public StandardItemBuilder setName(@Nullable Object name) { return setName(name == null ? null : name.toString()); } @NotNull - public ItemBuilder setName(@NotNull String... content) { + public StandardItemBuilder setName(@NotNull String... content) { if (content.length > 0) setName(content[0]); if (content.length > 1) setLore(Arrays.copyOfRange(content, 1, content.length)); return this; } @NotNull - public ItemBuilder appendName(@Nullable Object sequence) { - String name = getMeta().getDisplayName(); + public StandardItemBuilder appendName(@Nullable String sequence) { + String name = getItemMeta().getDisplayName(); return setName(name + sequence); } @NotNull - public ItemBuilder name(@Nullable Object name) { - return setName(name); - } - - @NotNull - public ItemBuilder name(@NotNull String... content) { - return setName(content); - } - - @NotNull - public ItemBuilder addEnchantment(@NotNull Enchantment enchantment, int level) { - getMeta().addEnchant(enchantment, level, true); + public StandardItemBuilder addEnchantment(@NotNull Enchantment enchantment, int level) { + getItemMeta().addEnchant(enchantment, level, true); return this; } @NotNull - public ItemBuilder enchant(@NotNull Enchantment enchantment, int level) { - return addEnchantment(enchantment, level); - } - - @NotNull - public ItemBuilder addFlag(@NotNull ItemFlag... flags) { - getMeta().addItemFlags(flags); + public StandardItemBuilder addFlag(@NotNull ItemFlag... flags) { + getItemMeta().addItemFlags(flags); return this; } @NotNull - public ItemBuilder flag(@NotNull ItemFlag... flags) { - return addFlag(flags); - } - - @NotNull - public ItemBuilder removeFlag(@NotNull ItemFlag... flags) { - getMeta().removeItemFlags(flags); + public StandardItemBuilder removeFlag(@NotNull ItemFlag... flags) { + getItemMeta().removeItemFlags(flags); return this; } @NotNull - public ItemBuilder hideAttributes() { + public StandardItemBuilder hideAttributes() { applyDummyAttributeModifier(); return addFlag(ItemFlag.values()); } @@ -178,7 +153,7 @@ protected void applyDummyAttributeModifier() { // hacky fix to make paper hide damage attributes (only works with custom modifiers), "Vanilla behavior since 1.20.5" // see https://github.com/PaperMC/Paper/issues/11224 Attribute dummyAttribute = Attribute.LUCK; - Collection modifiers = getMeta().getAttributeModifiers(dummyAttribute); + Collection modifiers = getItemMeta().getAttributeModifiers(dummyAttribute); if (modifiers == null || modifiers.isEmpty()) { meta.addAttributeModifier(dummyAttribute, new AttributeModifier( @@ -193,50 +168,30 @@ protected void applyDummyAttributeModifier() { } @NotNull - public ItemBuilder showAttributes() { + public StandardItemBuilder showAttributes() { return removeFlag(ItemFlag.values()); } @NotNull - public ItemBuilder setUnbreakable(boolean unbreakable) { - getMeta().setUnbreakable(unbreakable); + public StandardItemBuilder setUnbreakable(boolean unbreakable) { + getItemMeta().setUnbreakable(unbreakable); return this; } @NotNull - public ItemBuilder unbreakable() { - return setUnbreakable(true); - } - - @NotNull - public ItemBuilder breakable() { - return setUnbreakable(false); - } - - @NotNull - public ItemBuilder setAmount(int amount) { - item.setAmount(Math.min(Math.max(amount, 0), 64)); + public StandardItemBuilder setAmount(int amount) { + item.setAmount(Math.clamp(amount, 0, 64)); return this; } @NotNull - public ItemBuilder amount(int amount) { - return setAmount(amount); - } - - @NotNull - public ItemBuilder setDamage(int damage) { - this.getCastedMeta().setDamage(damage); + public StandardItemBuilder setDamage(int damage) { + this.getItemMetaAs().setDamage(damage); return this; } @NotNull - public ItemBuilder damage(int damage) { - return setDamage(damage); - } - - @NotNull - public ItemBuilder setType(@NotNull Material material) { + public StandardItemBuilder setMaterial(@NotNull Material material) { item.setType(material); meta = item.getItemMeta(); return this; @@ -244,12 +199,12 @@ public ItemBuilder setType(@NotNull Material material) { @NotNull public String getName() { - return getMeta().getDisplayName(); + return getItemMeta().getDisplayName(); } @NotNull public List getLore() { - List lore = getMeta().getLore(); + List lore = getItemMeta().getLore(); return lore == null ? new ArrayList<>() : lore; } @@ -263,12 +218,12 @@ public int getAmount() { } public int getDamage() { - return this.getCastedMeta().getDamage(); + return this.getItemMetaAs().getDamage(); } @NotNull public ItemStack build() { - item.setItemMeta(getMeta()); // Call to getter to prevent null value + item.setItemMeta(getItemMeta()); // Call to getter to prevent null value return item; } @@ -278,11 +233,11 @@ public ItemStack toItem() { } @Override - public ItemBuilder clone() { - return new ItemBuilder(item.clone(), getMeta().clone()); + public StandardItemBuilder clone() { + return new StandardItemBuilder(item.clone(), getItemMeta().clone()); } - public static class BannerBuilder extends ItemBuilder { + public static class BannerBuilder extends StandardItemBuilder { public BannerBuilder(@NotNull Material material) { super(material); @@ -311,19 +266,19 @@ public BannerBuilder addPattern(@NotNull BannerPattern pattern, @NotNull DyeColo @NotNull public BannerBuilder addPattern(@NotNull PatternType pattern, @NotNull DyeColor color) { - getMeta().addPattern(new Pattern(color, pattern)); + getItemMeta().addPattern(new Pattern(color, pattern)); return this; } @NotNull @Override - public BannerMeta getMeta() { - return getCastedMeta(); + public BannerMeta getItemMeta() { + return getItemMetaAs(); } } - public static class SkullBuilder extends ItemBuilder { + public static class SkullBuilder extends StandardItemBuilder { public SkullBuilder() { super(Material.PLAYER_HEAD); @@ -340,22 +295,22 @@ public SkullBuilder(@NotNull String owner, @NotNull String name, @NotNull String } public SkullBuilder setOwner(@NotNull String owner) { - getMeta().setOwner(owner); + getItemMeta().setOwner(owner); return this; } @NotNull @Override - public SkullMeta getMeta() { - return getCastedMeta(); + public SkullMeta getItemMeta() { + return getItemMetaAs(); } } - public static class PotionBuilder extends ItemBuilder { + public static class PotionBuilder extends StandardItemBuilder { @NotNull - public static ItemBuilder createWaterBottle() { + public static StandardItemBuilder createWaterBottle() { return new PotionBuilder(Material.POTION).setColor(Color.BLUE).hideAttributes(); } @@ -381,13 +336,13 @@ public PotionBuilder(@NotNull ItemStack item) { @NotNull public PotionBuilder addEffect(@NotNull PotionEffect effect) { - getMeta().addCustomEffect(effect, true); + getItemMeta().addCustomEffect(effect, true); return this; } @NotNull public PotionBuilder setColor(@NotNull Color color) { - getMeta().setColor(color); + getItemMeta().setColor(color); return this; } @@ -398,13 +353,13 @@ public PotionBuilder color(@NotNull Color color) { @NotNull @Override - public PotionMeta getMeta() { - return getCastedMeta(); + public PotionMeta getItemMeta() { + return getItemMetaAs(); } } - public static class LeatherArmorBuilder extends ItemBuilder { + public static class LeatherArmorBuilder extends StandardItemBuilder { public LeatherArmorBuilder(@NotNull Material material) { super(material); @@ -428,7 +383,7 @@ public LeatherArmorBuilder(@NotNull ItemStack item) { @NotNull public LeatherArmorBuilder setColor(@NotNull Color color) { - getMeta().setColor(color); + getItemMeta().setColor(color); return this; } @@ -439,8 +394,8 @@ public LeatherArmorBuilder color(@NotNull Color color) { @NotNull @Override - public LeatherArmorMeta getMeta() { - return getCastedMeta(); + public LeatherArmorMeta getItemMeta() { + return getItemMetaAs(); } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java index 49c2e9b1e..907d0b2a5 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java @@ -16,8 +16,7 @@ public final class MenuPositionListener implements Listener { public void onClick(@NotNull InventoryClickEvent event) { HumanEntity human = event.getWhoClicked(); - if (!(human instanceof Player)) return; - Player player = (Player) human; + if (!(human instanceof Player player)) return; Inventory inventory = event.getClickedInventory(); if (inventory == null) return; diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java index 44a10f22c..52f7fd296 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java @@ -77,7 +77,7 @@ public static > E getFirstEnumByNames(@NotNull Class classO for (String name : names) { try { return Enum.valueOf(classOfEnum, name); - } catch (IllegalArgumentException | NoSuchFieldError ex) { + } catch (IllegalArgumentException | NoSuchFieldError _) { } } throw new IllegalArgumentException("No enum found in " + classOfEnum.getName() + " for " + Arrays.toString(names)); diff --git a/plugin/src/main/resources/config.yml b/plugin/src/main/resources/config.yml index 04d3cfd49..6a3b9657d 100644 --- a/plugin/src/main/resources/config.yml +++ b/plugin/src/main/resources/config.yml @@ -32,12 +32,6 @@ language: "de" # Whether the plugin should pull newer/missing translations from https://github.com/anweisen/Challenges # on every load. Defaults to off so the plugin doesn't make outbound HTTP calls without consent. language-online-update: false -# If you want to use a custom translations file, you can specify the path to the folder where the file is located. -language-overwrite-path: null - -# Makes text from the plugin appear in the 'small caps' font -# Example: ᴛʜɪs ɪs sᴍᴀʟʟ ᴄᴀᴘs -small-caps: false timer: format: @@ -46,6 +40,9 @@ timer: hours: "{hh}:{mm}:{ss}" day: "{d} day {hh}:{mm}:{ss}" days: "{d} days {hh}:{mm}:{ss}" + gradient: + enabled: false + duration: 20 # When the worlds are reset using /reset, the given seed will be used, if enabled, to generate the new worlds # When a seed is written in the reset command, the seed of the command will be taken @@ -75,11 +72,6 @@ custom-challenge-settings: # Commands MUST be in lowercase allowed-commands-to-execute: [ "give", "item", "fill", "setblock", "summon", "kill", "worldborder", "time", "weather", "teleport", "tp", "difficulty", "playsound", "xp" ] -# This will change the item design in the challenges menu -design: - empty-line-above: true - empty-line-underneath: true - # Toggles join and quit messages # These can be edited in the corresponding language file join-quit-messages: true diff --git a/settings.gradle.kts b/settings.gradle.kts index cd5191dda..886cc4630 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -3,6 +3,7 @@ rootProject.name = "Challenges" include("plugin", "mongo-connector") includeSubmodules("cloud-support") +includeSubmodules("platform") fun includeSubmodules(parentDirName: String) { val parentDir = File(settingsDir, parentDirName) From 10f8d64d7994401789f7447192243a7216e0c8d3 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Sun, 5 Jul 2026 03:47:24 +0200 Subject: [PATCH 098/119] feat: use native paper adventure api [BREAKING] - plugin now requires paper server - only supports 1.18.2+ --- build.gradle.kts | 2 + gradle/libs.versions.toml | 9 +- language/files/de.json | 176 +++++++--- language/files/en.json | 4 - language/files/global.json | 104 ++++-- platform/api/build.gradle.kts | 13 - .../platform/message/MessageHolder.java | 13 - .../platform/message/MessagePlatform.java | 66 ---- .../message/wrapper/MessageBossBar.java | 27 -- platform/common/build.gradle.kts | 24 -- .../common/AbstractMiniMessagePlatform.java | 331 ------------------ .../common/BukkitTranslationKeyExtractor.java | 24 -- .../common/TranslatableComponents.java | 60 ---- .../wrapper/AdventureMessageBossBar.java | 73 ---- platform/legacy/build.gradle.kts | 62 ---- .../legacy/LegacyMiniMessagePlatform.java | 129 ------- platform/paper/build.gradle.kts | 19 - .../paper/NativePaperMessagePlatform.java | 120 ------- .../NativePaperMessagePlatformChecker.java | 30 -- plugin/build.gradle.kts | 12 +- .../challenges/plugin/ChallengeAPI.java | 5 +- .../challenges/plugin/Challenges.java | 7 - .../challenges/custom/CustomChallenge.java | 4 +- .../settings/action/ChallengeAction.java | 2 +- .../action/impl/BoostEntityInAirAction.java | 2 +- .../action/impl/ChangeWorldBorderAction.java | 2 +- .../action/impl/ModifyMaxHealthAction.java | 2 +- .../settings/sub/SubSettingsBuilder.java | 4 +- .../ChooseMultipleItemSubSettingBuilder.java | 2 +- .../sub/builder/ValueSubSettingsBuilder.java | 4 +- .../settings/trigger/ChallengeTrigger.java | 2 +- .../trigger/impl/EntityDamageTrigger.java | 2 +- .../trigger/impl/IntervallTrigger.java | 2 +- .../challenge/DamageTeleportChallenge.java | 4 +- .../challenge/ZeroHeartsChallenge.java | 7 +- .../damage/DelayDamageChallenge.java | 3 +- .../challenge/damage/JumpDamageChallenge.java | 5 +- .../damage/SneakDamageChallenge.java | 2 +- .../PermanentEffectOnDamageChallenge.java | 6 +- .../entities/MobSightDamageChallenge.java | 4 - .../entities/MobTransformationChallenge.java | 8 +- .../entities/MobsRespawnInEndChallenge.java | 8 +- .../extraworld/JumpAndRunChallenge.java | 19 +- .../challenge/force/ForceBiomeChallenge.java | 14 +- .../challenge/force/ForceBlockChallenge.java | 10 +- .../challenge/force/ForceHeightChallenge.java | 14 +- .../challenge/force/ForceItemChallenge.java | 12 +- .../challenge/force/ForceMobChallenge.java | 16 +- .../DamageInventoryClearChallenge.java | 6 +- .../inventory/MissingItemsChallenge.java | 6 +- .../MovementItemRemovingChallenge.java | 6 +- .../inventory/NoDupedItemsChallenge.java | 2 +- .../inventory/PickupItemLaunchChallenge.java | 4 +- .../inventory/UncraftItemsChallenge.java | 4 - .../miscellaneous/EnderGamesChallenge.java | 3 - .../miscellaneous/FoodLaunchChallenge.java | 6 +- .../miscellaneous/FoodOnceChallenge.java | 6 +- .../miscellaneous/InvertHealthChallenge.java | 5 +- .../miscellaneous/LowDropRateChallenge.java | 2 +- .../miscellaneous/NoExpChallenge.java | 2 +- .../movement/DontStopRunningChallenge.java | 9 +- .../movement/FiveHundredBlocksChallenge.java | 4 +- .../challenge/movement/MoveMouseDamage.java | 5 +- .../challenge/movement/OnlyDirtChallenge.java | 2 +- .../challenge/movement/OnlyDownChallenge.java | 2 +- .../movement/TrafficLightChallenge.java | 11 +- .../challenge/quiz/QuizChallenge.java | 11 +- .../randomizer/RandomChallengeChallenge.java | 22 +- .../randomizer/RandomEventChallenge.java | 4 +- .../challenge/time/MaxBiomeTimeChallenge.java | 8 +- .../time/MaxHeightTimeChallenge.java | 8 +- .../challenge/world/BedrockWallChallenge.java | 3 - .../world/ChunkDeletionChallenge.java | 7 +- .../challenge/world/IceFloorChallenge.java | 5 +- .../challenge/world/LevelBorderChallenge.java | 2 +- .../challenge/world/LoopChallenge.java | 2 +- .../challenge/world/SnakeChallenge.java | 2 +- .../challenge/world/SurfaceHoleChallenge.java | 3 - .../challenge/world/TsunamiChallenge.java | 7 +- .../goal/AllAdvancementGoal.java | 2 +- .../goal/CollectAllItemsGoal.java | 45 +-- .../goal/CollectMostItemsGoal.java | 6 +- .../implementation/goal/CollectWoodGoal.java | 3 - .../goal/KillAllBossesGoal.java | 2 +- .../goal/KillAllBossesNewGoal.java | 2 +- .../implementation/goal/KillAllMobsGoal.java | 2 +- .../goal/KillAllMonsterGoal.java | 2 +- .../implementation/goal/MostOresGoal.java | 2 - .../implementation/goal/RaceGoal.java | 8 +- .../forcebattle/ExtremeForceBattleGoal.java | 2 +- .../ForceAdvancementBattleGoal.java | 2 +- .../forcebattle/ForceBiomeBattleGoal.java | 2 +- .../forcebattle/ForceBlockBattleGoal.java | 2 +- .../forcebattle/ForceDamageBattleGoal.java | 2 +- .../forcebattle/ForceHeightBattleGoal.java | 2 +- .../goal/forcebattle/ForceItemBattleGoal.java | 2 +- .../goal/forcebattle/ForceMobBattleGoal.java | 2 +- .../forcebattle/ForcePositionBattleGoal.java | 2 +- .../targets/AdvancementTarget.java | 2 +- .../goal/forcebattle/targets/BiomeTarget.java | 2 +- .../goal/forcebattle/targets/BlockTarget.java | 2 +- .../forcebattle/targets/DamageTarget.java | 2 +- .../goal/forcebattle/targets/ForceTarget.java | 2 +- .../forcebattle/targets/HeightTarget.java | 2 +- .../goal/forcebattle/targets/ItemTarget.java | 2 +- .../goal/forcebattle/targets/MobTarget.java | 2 +- .../forcebattle/targets/PositionTarget.java | 2 +- .../setting/BackpackSetting.java | 10 +- .../setting/BastionSpawnSetting.java | 2 +- .../setting/CutCleanSetting.java | 3 +- .../setting/DamageDisplaySetting.java | 55 +-- .../setting/DamageMultiplierModifier.java | 16 +- .../setting/DeathMessageSetting.java | 43 ++- .../setting/DifficultySetting.java | 75 ++-- .../setting/FortressSpawnSetting.java | 3 - .../setting/HardcoreHeartsSetting.java | 87 +++++ .../setting/ImmediateRespawnSetting.java | 2 - .../setting/KeepInventorySetting.java | 5 +- .../setting/LanguageSetting.java | 134 +++++-- .../setting/MaxHealthSetting.java | 8 +- .../setting/MobGriefingSetting.java | 3 - .../setting/NoHitDelaySetting.java | 2 - .../setting/NoItemDamageSetting.java | 3 - .../implementation/setting/OldPvPSetting.java | 2 - .../setting/OneTeamLifeSetting.java | 2 - .../setting/PositionSetting.java | 6 +- .../setting/PregameMovementSetting.java | 63 +++- .../implementation/setting/PvPSetting.java | 2 - .../setting/RegenerationSetting.java | 6 +- .../implementation/setting/SoupSetting.java | 3 - .../implementation/setting/TimberSetting.java | 6 +- .../type/abstraction/AbstractChallenge.java | 13 +- .../abstraction/FirstPlayerAtHeightGoal.java | 2 +- .../abstraction/ForceBattleDisplayGoal.java | 1 - .../type/abstraction/ForceBattleGoal.java | 2 +- .../type/abstraction/ItemCollectionGoal.java | 2 +- .../type/abstraction/KillMobsGoal.java | 5 +- .../challenges/type/abstraction/Modifier.java | 9 +- .../abstraction/ModifierCollectionGoal.java | 2 +- .../type/abstraction/OneEnabledSetting.java | 2 +- .../challenges/type/abstraction/Setting.java | 2 +- .../type/abstraction/SettingModifier.java | 2 +- .../type/abstraction/menu/MenuSetting.java | 5 +- .../type/annotation/ChallengeAnnotations.java | 7 + .../type/annotation/RequireDepend.java | 14 + .../type/helper/ChallengeHelper.java | 50 ++- .../challenges/type/helper/GoalHelper.java | 2 +- .../type/helper/SubSettingsHelper.java | 2 +- .../plugin/content/i18n/ArgumentFormat.java | 98 ++++++ .../plugin/content/i18n/LanguageProvider.java | 2 +- .../content/i18n/LocalizableMessage.java | 53 ++- .../plugin/content/i18n/MessageHolder.java | 15 + .../plugin/content/i18n/MessageKey.java | 149 ++------ .../content/i18n/TranslationManager.java | 4 +- .../impl/DynamicLocalizableMessageImpl.java | 44 +++ .../content/i18n/impl/JoinedMessageImpl.java | 50 +++ .../i18n/impl/LocalizableMessageImpl.java | 41 +++ .../content/i18n/impl/MessageKeyImpl.java | 237 +++++-------- .../i18n/impl/format/ComponentArguments.java | 116 ++++++ .../i18n/impl/format/ComponentFormatter.java | 150 ++++++++ .../i18n/impl/format}/ComponentSplitter.java | 5 +- .../impl/{ => format}/MessageFormatter.java | 55 +-- .../content/{ => legacy}/ItemDescription.java | 2 +- .../plugin/content/{ => legacy}/Message.java | 3 +- .../content/{impl => legacy}/MessageImpl.java | 26 +- .../{impl => legacy}/MessageManager.java | 4 +- .../plugin/content/loader/LanguageLoader.java | 27 +- .../plugin/content/loader/LoaderRegistry.java | 2 +- .../challenges/ChallengeLoader.java | 9 +- .../challenges/ModuleChallengeLoader.java | 11 + .../management/files/ConfigManager.java | 1 + .../inventory/PlayerInventoryManager.java | 2 +- .../menu/InventoryTitleManager.java | 2 +- .../plugin/management/menu/MenuManager.java | 15 + .../generator/MultiPageMenuGenerator.java | 9 +- .../generator/SinglePageMenuGenerator.java | 5 +- .../categorised/CategorisedMenuGenerator.java | 4 +- .../generator/impl/MainMenuGenerator.java | 2 +- .../generator/impl/TimerMenuGenerator.java | 51 +-- .../challenge/ChallengeListMenuGenerator.java | 35 +- .../categorised/CategorisedMenuGenerator.java | 42 ++- .../custom/InfoMenuGenerator.java | 2 +- .../custom/MainCustomMenuGenerator.java | 2 +- .../legacy/ChallengeMenuGenerator.java | 2 +- .../legacy/ChooseMultipleItemGenerator.java | 2 +- .../generator/legacy/ValueMenuGenerator.java | 2 +- .../scheduler/timer/ChallengeTimer.java | 103 ++++-- .../scheduler/timer/TimerFormat.java | 192 +++++++--- .../management/server/ChallengeEndCause.java | 2 +- .../management/server/PlatformManager.java | 49 --- .../management/server/ScoreboardManager.java | 30 +- .../management/server/ServerManager.java | 10 +- .../management/server/TitleManager.java | 26 +- .../management/server/WorldManager.java | 14 +- .../server/scoreboard/CBossBar.java | 16 - .../server/scoreboard/ChallengeActionBar.java | 54 +++ .../server/scoreboard/ChallengeBossBar.java | 94 ++--- .../scoreboard/ChallengeScoreboard.java | 11 +- .../plugin/spigot/command/BackCommand.java | 2 +- .../plugin/spigot/command/InvseeCommand.java | 7 +- .../spigot/command/LanguageCommand.java | 45 --- .../spigot/command/LeaderboardCommand.java | 2 +- .../plugin/spigot/command/ResetCommand.java | 2 +- .../spigot/command/SkipTimerCommand.java | 25 +- .../plugin/spigot/command/StatsCommand.java | 2 +- .../plugin/spigot/command/TimeCommand.java | 2 +- .../plugin/spigot/listener/CheatListener.java | 2 +- .../listener/PlayerConnectionListener.java | 2 +- .../plugin/utils/item/DefaultItem.java | 2 +- .../plugin/utils/item/ItemBuilder.java | 116 +++--- .../plugin/utils/item/LegacyItemBuilder.java | 4 +- .../plugin/utils/misc/ExperimentalUtils.java | 8 +- .../utils/misc/MinecraftNameWrapper.java | 4 +- .../plugin/utils/misc/NameHelper.java | 2 + .../plugin/utils/misc/StatsHelper.java | 2 +- .../utils/animation/AnimatedInventory.java | 11 +- .../bukkit/utils/animation/SoundSample.java | 22 +- .../bukkit/utils/item/BannerPattern.java | 5 - .../commons/bukkit/utils/item/ItemUtils.java | 2 + .../utils/item/StandardItemBuilder.java | 100 ++++-- .../utils/misc/BukkitReflectionUtils.java | 3 +- .../bukkit/utils/misc/MinecraftVersion.java | 10 +- .../commons/common/collection/IRandom.java | 3 + .../commons/common/misc/ReflectionUtils.java | 2 +- .../commons/common/version/Version.java | 37 +- .../common/version/VersionComparator.java | 2 +- .../commons/common/version/VersionInfo.java | 22 +- plugin/src/main/resources/config.yml | 7 +- plugin/src/main/resources/plugin.yml | 1 + settings.gradle.kts | 1 - 230 files changed, 2346 insertions(+), 2405 deletions(-) delete mode 100644 platform/api/build.gradle.kts delete mode 100644 platform/api/src/main/java/net/codingarea/challenges/platform/message/MessageHolder.java delete mode 100644 platform/api/src/main/java/net/codingarea/challenges/platform/message/MessagePlatform.java delete mode 100644 platform/api/src/main/java/net/codingarea/challenges/platform/message/wrapper/MessageBossBar.java delete mode 100644 platform/common/build.gradle.kts delete mode 100644 platform/common/src/main/java/net/codingarea/challenges/platform/message/common/AbstractMiniMessagePlatform.java delete mode 100644 platform/common/src/main/java/net/codingarea/challenges/platform/message/common/BukkitTranslationKeyExtractor.java delete mode 100644 platform/common/src/main/java/net/codingarea/challenges/platform/message/common/TranslatableComponents.java delete mode 100644 platform/common/src/main/java/net/codingarea/challenges/platform/message/common/wrapper/AdventureMessageBossBar.java delete mode 100644 platform/legacy/build.gradle.kts delete mode 100644 platform/legacy/src/main/java/net/codingarea/challenges/platform/message/legacy/LegacyMiniMessagePlatform.java delete mode 100644 platform/paper/build.gradle.kts delete mode 100644 platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatform.java delete mode 100644 platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatformChecker.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HardcoreHeartsSetting.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/RequireDepend.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageHolder.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/DynamicLocalizableMessageImpl.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/JoinedMessageImpl.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java rename {platform/common/src/main/java/net/codingarea/challenges/platform/message/common => plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format}/ComponentSplitter.java (96%) rename plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/{ => format}/MessageFormatter.java (86%) rename plugin/src/main/java/net/codingarea/challenges/plugin/content/{ => legacy}/ItemDescription.java (98%) rename plugin/src/main/java/net/codingarea/challenges/plugin/content/{ => legacy}/Message.java (95%) rename plugin/src/main/java/net/codingarea/challenges/plugin/content/{impl => legacy}/MessageImpl.java (85%) rename plugin/src/main/java/net/codingarea/challenges/plugin/content/{impl => legacy}/MessageManager.java (88%) delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/server/PlatformManager.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/CBossBar.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeActionBar.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java diff --git a/build.gradle.kts b/build.gradle.kts index 2e109c434..db44eb4bc 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -6,6 +6,7 @@ allprojects { repositories { mavenCentral() maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/") + maven("https://repo.papermc.io/repository/maven-public/") maven("https://libraries.minecraft.net/") maven("https://jitpack.io") } @@ -27,6 +28,7 @@ subprojects { tasks.withType().configureEach { options.encoding = "UTF-8" + options.compilerArgs.add("-Xlint:-removal") // TODO } tasks.named("processResources") { diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index a82874719..6a036156d 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -4,11 +4,11 @@ java = "25" # minecraft spigot = "26.1.2-R0.1-SNAPSHOT" -paper = "26.1.2.build.+" +paper = "26.2.build.+" # 1.21.4-R0.1-SNAPSHOT authlib = "1.5.21" -adventure = "4.26.1" -adventure-bukkit = "4.4.1" +adventure = "4.8.0" +protocol-lib = "5.4.0" # utilities slf4j = "1.7.32" @@ -37,9 +37,10 @@ spigot-api = { group = "org.spigotmc", name = "spigot-api", version.ref = "spigo paper-api = { group = "io.papermc.paper", name = "paper-api", version.ref = "paper" } authlib = { group = "com.mojang", name = "authlib", version.ref = "authlib" } +protocol-lib = { group = "net.dmulloy2", name = "ProtocolLib", version.ref = "protocol-lib" } + adventure-text-minimessage = { module = "net.kyori:adventure-text-minimessage", version.ref = "adventure" } adventure-text-serializer-legacy = { module = "net.kyori:adventure-text-serializer-legacy", version.ref = "adventure" } -adventure-platform-bukkit = { module = "net.kyori:adventure-platform-bukkit", version.ref = "adventure-bukkit" } # utilities slf4j-api = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" } diff --git a/language/files/de.json b/language/files/de.json index d7d50fc9c..eeb8f31ea 100644 --- a/language/files/de.json +++ b/language/files/de.json @@ -1,9 +1,34 @@ { "generic": { + "undefined": "undefiniert", + "unknown": "unbekannt", "disabled": "Deaktiviert", "enabled": "Aktiviert", "customized": "Anpassen" }, + "language": { + "de": "Deutsch", + "en": "Englisch" + }, + "timer": { + "bar": { + "up": "{@actionbar.format('Zeit: {0}')}", + "down": "{@actionbar.format('Zeit: {0}')}", + "paused": "{@actionbar.format('Timer pausiert')}", + "format": { + "day": "{d} Tag {hh}:{mm}:{ss}", + "days": "{d} Tage {hh}:{mm}:{ss}" + } + }, + "messages": { + "started": "Der Timer wurde gestartet", + "paused": "Der Timer wurde pausiert", + "counting-up": "Der Timer zählt nun hoch", + "counting-down": "Der Timer zählt nun runter", + "hidden": "Der Timer ist nun versteckt", + "shown": "Der Timer ist nun sichtbar" + } + }, "menu": { "generic": { "click-prefix": "[Klick] {@symbol.arrow} ", @@ -15,18 +40,48 @@ "name": "Timer", "name-state": "Status", "name-time": "Zeit", + "item-paused": [ + "{@item-format('Timer ist pausiert')}", + " ", + "{@generic.click-prefix}Timer fortsetzen" + ], + "item-started": [ + "{@item-format('Timer ist gestartet')}", + " ", + "{@generic.click-prefix}Timer pausieren" + ], + "item-hidden": [ + "{@item-format('Timer ist versteckt')}", + " ", + "{@generic.click-prefix}Timer anzeigen" + ], + "item-shown": [ + "{@item-format('Timer ist sichtbar')}", + " ", + "{@generic.click-prefix}Timer verstecken" + ], + "item-counting-up": [ + "{@item-format('Timer zählt hoch')}", + " ", + "{@generic.click-prefix}Timer auf runterzählen stellen" + ], + "item-counting-down": [ + "{@item-format('Timer zählt runter')}", + " ", + "{@generic.click-prefix}Timer auf hochzählen stellen" + ], "item-name-format": "{@item-format('{0}: {1} ({2})')}", "item-add-format": [ "{@item-name-format('{4}', '{0}', '{1}')}", " ", - "{@generic.click-prefix}+1 {3}", - "{@generic.shift-click-prefix}{@symbol.arrow} +{2} {4}" + "{@generic.click-prefix}+1 {3}", + "{@generic.shift-click-prefix}+{2} {4}" ], "item-subtract-format": [ "{@item-name-format('{4}', '{0}', '{1}')}", " ", - "{@generic.click-prefix}-1 {3}", - "{@generic.shift-click-prefix} -{2} {4}" + "{@generic.click-prefix}-1 {3}", + "{@generic.shift-click-prefix}-{2} {4}" ], "item-state-format": [ "{@item-name-format('{2}', '{0}', '{1}')}", @@ -66,6 +121,10 @@ } }, "category": { + "desc-most-points": [ + "Der Spieler mit den *meisten Punkten*", + "*gewinnt*, wenn der Timer *abläuft*" + ], "misc_challenge": { "menu": "Sonstige", "desc": [ @@ -165,8 +224,7 @@ "Erziele die *meisten Punkte* in", "einem *bestimmten Bereich*", " ", - "Der Spieler mit den *meisten Punkten*", - "gewinnt, wenn der *Timer abläuft*" + "{@desc-most-points}" ] }, "fastest_time": { @@ -182,18 +240,61 @@ "Erfülle die *vorgegebenen Zwischenziele*,", "um Punkte zu erhalten.", " ", - "Der Spieler mit den *meisten Punkten*", - "*gewinnt* die Challenge wenn der Timer *abläuft*" + "{@desc-most-points}" ] } }, "challenge": { + "language": { + "name": "*Sprache*", + "desc": [ + "Ändert die *Sprache* des Plugins" + ], + "command-disabled": "Diese Funktion ist derzeit deaktiviert", + "command-unknown": "Diese Sprache ({0}) wird nicht unterstützt", + "command-current": "Die derzeitige Sprache ist {0}", + "command-changing": "Die Sprache wird geändert...", + "command-changed": "Die Sprache wurde auf {0} ({1}) gesetzt" + }, + "pregame-movement": { + "name": "*Pregame Movement*", + "desc": [ + "Du kannst dich *bewegen*,", + "bevor der Timer *gestartet* wurde" + ], + "title": [ + "Warte..", + "{@symbol.arrow} Der Timer ist gestoppt.." + ] + }, + "difficulty": { + "name": "*Schwierigkeit*", + "desc": [ + "Ändert die *Schwierigkeit*", + "(*Difficulty*) des Spiels" + ], + "command-set": "Schwierigkeit auf {0} geändert", + "command-current": "Die derzeitige Schwierigkeit ist {0}" + }, + "hardcore-hearts": { + "name": "*Hardcore Herzen*", + "desc": [ + "Die *Herzen* werden im *Hardcore-Stil* angezeigt", + "Um die Änderung zu sehen, *musst* du *rejoinen*" + ] + }, "random-challenge": { "name": "*Random Challenge*", "desc": [ "In einem *gesetzten Intervall*", "wird eine *zufällige Challenge* aktiviert" - ] + ], + "challenge-enabled": [ + "Die Challenge {0} wurde aktiviert", + "{1}" + ], + "bossbar-waiting": "{@bossbar.format('Warten auf neue Challenge..')}", + "bossbar-current": "{@bossbar.format('Challenge {0}')}" }, "randomized-hp": { "name": "*Zufällige HP*", @@ -202,6 +303,15 @@ "sind *zufällig*" ] }, + "jump-and-run": { + "name": "*JumpAndRun*", + "desc": [ + "In einem gesetzten *Intervall* muss ein", + "*zufälliger Spieler* ein *JumpAndRun* absolvieren", + "Schafft er es *nicht*, *stirbt* er" + ], + "actionbar": "{@actionbar.format('*Jump & Run* {@symbol.vertical} {0} / {1}')}" + }, "goal-ender-dragon": { "name": "*Enderdrache*", "desc": [ @@ -256,7 +366,7 @@ ], "challenge-enabled": [ "{0}", - "{@symbol.check} {@symbol.vertical} Aktiviert" + "{@symbol.check} {@symbol.vertical} Aktiviert" ], "challenge-disabled": [ "{0}", @@ -265,8 +375,22 @@ "challenge-value-changed": [ "{0}", "{@symbol.arrow} {1}" + ], + "goal-enabled": [ + "{0}", + "{@symbol.check} {@symbol.vertical} Ziel gewählt" + ], + "goal-disabled": [ + "{0}", + "{@symbol.x} Ziel deaktiviert" ] }, + "command": { + "skip-timer": { + "none": "Es ist keine Challenge aktiviert, dessen Timer übersprungen werden könnte", + "done": "Die Timer folgender Challenges wurden übersprungen: {0}" + } + }, "syntax": "Bitte nutze §e/{0}", "reload": "Challenges Plugin wird neu geladen...", "reload-failed": "Ein §cFehler §7ist während dem Reload aufgetreten", @@ -290,10 +414,6 @@ "player": "§6Aktiver Spieler", "none": "Nichts", "inventory-color": "§9", - "timer-counting-up": "§8» §7Timer zählt §ahoch", - "timer-counting-down": "§8» §7Timer zählt §crunter", - "timer-is-paused": "§8» §7Timer ist §cpausiert", - "timer-is-running": "§8» §7Timer ist §agestartet", "confirm-reset": "Bestätige den Reset mit §e/{0}", "no-fresh-reset": [ "Der Server kann §cnicht resettet §7werden", @@ -303,12 +423,7 @@ "updated-challenge-suffix": "{@challenge.suffix-format('Update!')}", "feature-disabled": "Diese Funktion ist derzeit §cdeaktiviert", "challenge-disabled": "Diese Challenge ist derzeit §cdeaktiviert", - "stopped-message": "§8• §7Timer §c§lpausiert §8•", - "count-up-message": "§8• §7Time: §a§l{0} §8•", - "count-down-message": "§8• §7Time: §c§l{0} §8•", "timer-not-started": "Der Timer wurde noch §cnicht gestartet", - "timer-was-started": "Der Timer wurde §agestartet", - "timer-was-paused": "Der Timer wurde §cpausiert", "timer-was-set": "Der Timer wurde auf §e§l{0} §7gesetzt", "timer-already-started": "Der Timer §cläuft bereits", "timer-already-paused": "Der Timer ist §cbereits pausiert", @@ -316,7 +431,6 @@ "timer-mode-set-up": "Der Timer zählt nun §ahoch", "no-database-connection": "Es gibt §ckeine §7Datenbankverbindung", "fetching-data": "Daten werden abgerufen..", - "undefined": "undefiniert", "no-such-material": "Dieses Material gibt es nicht", "not-an-item": "§e{0} §7ist kein Item", "no-such-entity": "Dieses Entity existiert nicht", @@ -413,8 +527,6 @@ "command-weather-set-thunder": "Wetter zu §estürmisch §7geändert", "command-invsee-open": "Inventar von §e{0} §7geöffnet", "command-enderchest-open": "Du hast deine §5Enderchest §7geöffnet", - "command-difficulty-change": "Schwierigkeit auf {0} §7geändert", - "command-difficulty-current": "Die derzeitige Schwierigkeit ist {0}", "command-search-nothing": "§e{0} §7wird durch keinen speziellen Block gedroppt", "command-search-result": "§e{0} §7droppt aus §e{1}", "command-searchloot-disabled": "Die Entity Loot Randomizer Challenge ist aktuell §cdeaktiviert", @@ -477,7 +589,6 @@ "food-once-new-food": "§eDu §7hast §e{1} §7gegessen", "sneak-damage-failed": "§e{0} §7ist geschlichen", "jump-damage-failed": "§e{0} §7ist gesprungen", - "random-challenge-enabled": "Die Challenge §e{0} §7wurde §aaktiviert", "all-items-skipped": "Item §e{0} §7geskippt", "all-items-already-finished": "Es wurden bereits alle Items gefunden", "all-items-found": "Das Item §e{0} §7wurde von §e{1} §7registriert", @@ -597,8 +708,6 @@ "bossbar-biome-time-left": "§8» §7Zeit übrig in §e{0} §8§l┃ §a{1}s", "bossbar-height-time-left": "§8» §7Zeit übrig auf §e{0} §8§l┃ §a{1}s", "bossbar-zero-hearts": "§8» §7Schutzzeit §8§l┃ §a{0}s", - "bossbar-random-challenge-waiting": "§8» §7Warten auf neue Challenge..", - "bossbar-random-challenge-current": "§8» §7Challenge §e{0}", "bossbar-all-items-current-max": "§8» §f{0} §8┃ §7{1} §8/ §7{2}", "bossbar-all-items-finished": "§8» §7Alle Items gefunden", "bossbar-force-height-waiting": "§8» §7Warten auf nächste Höhe..", @@ -709,10 +818,6 @@ "§e{0}", "§8» §e{1}" ], - "title-pregame-movement-setting": [ - "§cWarte..", - "§8» §7Der Timer ist gestoppt.." - ], "item-menu-start": "§8• §aStart Challenge §8┃ §e/start §8•", "item-menu-challenges": "§8• §cChallenges §8┃ §e/challenge §8•", "item-menu-timer": "§8• §5Timer §8┃ §e/timer §8•", @@ -764,10 +869,6 @@ ], "item-language-setting-german": "§fDeutsch", "item-language-setting-english": "§fEnglish", - "item-difficulty-setting": [ - "§aSchwierigkeit", - "Stellt die *Schwierigkeitsstufe* ein" - ], "item-one-life-setting": [ "§cEin Teamleben", "*Jeder* stirbt, wenn *einer stirbt*" @@ -863,11 +964,6 @@ "§cKein Hunger", "Du bekommst keinen *Hunger*" ], - "pregame-movement-setting": [ - "§6Pregame Movement", - "Du kannst dich *bewegen*, bevor", - "das Spiel *gestartet* hat" - ], "item-no-hit-delay-setting": [ "§fNoHitDelay", "Nachdem du *Schaden* genommen hast,", @@ -1972,10 +2068,6 @@ "§9Water MLG", "Alle Spieler müssen einen Water MLG machen" ], - "item-custom-action-jnr": [ - "§6Jump And Run", - "Ein zufälliger Spieler muss ein Jump And Run machen" - ], "item-custom-action-win": [ "§6Gewinnen", "Die Challenge wird von *bestimmten Spielern* gewonnen" diff --git a/language/files/en.json b/language/files/en.json index bd468e1f8..6cd0b8c6c 100644 --- a/language/files/en.json +++ b/language/files/en.json @@ -438,10 +438,6 @@ "§e{0}", "§8» §e{1}" ], - "title-pregame-movement-setting": [ - "§cWarte..", - "§8» §7Timer is stopped.." - ], "item-menu-start": "§8• §aStart Challenge §8┃ §e/start §8•", "item-menu-challenges": "§8• §cChallenges §8┃ §e/challenge §8•", "item-menu-timer": "§8• §5Timer §8┃ §e/timer §8•", diff --git a/language/files/global.json b/language/files/global.json index 7cefbd5e0..e47971c7b 100644 --- a/language/files/global.json +++ b/language/files/global.json @@ -1,11 +1,10 @@ { "symbol": { - "p": "➟ ➡ ➛ ➜ ➸ › ► ▶ ▷ ⇒ →", "arrow-back": "«", "arrow": "»", "chevron": "›", "chevron-back": "‹", - "dart": "▷", + "dart": "→", "vertical": "┃", "cross": "✞", "check": "✔", @@ -15,8 +14,18 @@ "circle": "●", "altert": "⚠", "flag": "⚐", + "infinity": "∞", "lock": "\uD83D\uDD12" }, + "generic": { + "delimiter": ", " + }, + "arg-format": { + "hp": "{0} HP ({1} {@symbol.heart})", + "hearts": "{0} {@symbol.heart}", + "damage-cause": "{0}", + "damage-cause-source": "{0} ({1})" + }, "prefix": { "format": "{@symbol.vertical} {0} {@symbol.vertical} ", "challenges": "{@format('Challenges')}", @@ -26,6 +35,27 @@ "damage": "{@format('Damage')}", "custom": "{@format('Custom')}" }, + "item": { + "format": "{@symbol.dot} {0} {@symbol.dot}", + "format-with-command": "{@format('{0} {@symbol.vertical} {1}')}" + }, + "actionbar": { + "format": "{@symbol.dot} {0} {@symbol.dot}" + }, + "bossbar": { + "format": "{@symbol.arrow} {0}" + }, + "timer": { + "bar": { + "format": { + "seconds": "{mm}:{ss}", + "minutes": "{mm}:{ss}", + "hours": "{hh}:{mm}:{ss}", + "day": "{d}:{hh}:{mm}:{ss}", + "days": "{d}:{hh}:{mm}:{ss}" + } + } + }, "menu": { "title-prefix": "{@symbol.arrow} ", "title-delimiter": " {@symbol.vertical} ", @@ -62,88 +92,84 @@ "{0} {@symbol.circle} {1}" ], "misc_challenge": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*" }, "randomizer": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*", "info": "{@misc_challenge.info}" }, "limited_time": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*", "info": "{@misc_challenge.info}" }, "force": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*", "info": "{@misc_challenge.info}" }, "world": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*", "info": "{@misc_challenge.info}" }, "damage": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*", "info": "{@misc_challenge.info}" }, "effect": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*", "info": "{@misc_challenge.info}" }, "inventory": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*", "info": "{@misc_challenge.info}" }, "movement": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*", "info": "{@misc_challenge.info}" }, "entities": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*", "info": "{@misc_challenge.info}" }, "extra_world": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*", "info": "{@misc_challenge.info}" }, "misc_goal": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*" }, "kill_entity": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*", "info": "{@misc_goal.info}" }, "score_points": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*", "info": "{@misc_goal.info}" }, "fastest_time": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*", "info": "{@misc_goal.info}" }, "force_battle": { - "*colorize": "{0}", + "*colorize*": "{0}", "name": "*{@menu}*", "info": "{@misc_goal.info}" } }, - "item": { - "format": "{@symbol.dot} {0} {@symbol.dot}", - "format-with-command": "{@format('{0} {@symbol.vertical} {1}')}" - }, "challenge": { "display-format": [ "{@symbol.arrow} {0}", @@ -161,29 +187,47 @@ "settings-modifier-value": "{0}", "settings-modifier-multiplier": "{0}x", "settings-modifier-health": "{0} HP ({1} {@symbol.heart})", + "language": { + "*colorize*": "{0}" + }, + "damage-display": { + "*colorize*": "{0}" + }, + "pregame-movement": { + "*colorize*": "{0}" + }, + "difficulty": { + "*colorize*": "{0}" + }, + "hardcore-hearts": { + "*colorize*": "{0}" + }, "random-challenge": { - "*colorize": "{0}" + "*colorize*": "{0}" }, "randomized-hp": { - "*colorize": "{0}" + "*colorize*": "{0}" + }, + "jump-and-run": { + "*colorize*": "{0}" }, "goal-ender-dragon": { - "*colorize": "{0}" + "*colorize*": "{0}" }, "goal-wither": { - "*colorize": "{0}" + "*colorize*": "{0}" }, "goal-elder-guardian": { - "*colorize": "{0}" + "*colorize*": "{0}" }, "goal-warden": { - "*colorize": "{0}" + "*colorize*": "{0}" }, "goal-all-bosses": { - "*colorize": "{0}" + "*colorize*": "{0}" }, "goal-all-bosses-new": { - "*colorize": "{0}" + "*colorize*": "{0}" } } } diff --git a/platform/api/build.gradle.kts b/platform/api/build.gradle.kts deleted file mode 100644 index ea667470c..000000000 --- a/platform/api/build.gradle.kts +++ /dev/null @@ -1,13 +0,0 @@ -plugins { - id("java-library") -} - -dependencies { - compileOnly(libs.spigot.api) -} - -tasks { - jar { - archiveClassifier = "plain" - } -} diff --git a/platform/api/src/main/java/net/codingarea/challenges/platform/message/MessageHolder.java b/platform/api/src/main/java/net/codingarea/challenges/platform/message/MessageHolder.java deleted file mode 100644 index df059b32b..000000000 --- a/platform/api/src/main/java/net/codingarea/challenges/platform/message/MessageHolder.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.codingarea.challenges.platform.message; - -import org.jetbrains.annotations.NotNull; - -public interface MessageHolder { - - @NotNull - String[] miniMessageRaw(); - - @NotNull - Object[] positionalArgs(); - -} diff --git a/platform/api/src/main/java/net/codingarea/challenges/platform/message/MessagePlatform.java b/platform/api/src/main/java/net/codingarea/challenges/platform/message/MessagePlatform.java deleted file mode 100644 index 29674a3b7..000000000 --- a/platform/api/src/main/java/net/codingarea/challenges/platform/message/MessagePlatform.java +++ /dev/null @@ -1,66 +0,0 @@ -package net.codingarea.challenges.platform.message; - -import com.google.errorprone.annotations.CheckReturnValue; -import net.codingarea.challenges.platform.message.wrapper.MessageBossBar; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.meta.ItemMeta; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.regex.Pattern; - -public interface MessagePlatform { - - Pattern POS_ARG_PATTERN = Pattern.compile("\\{(\\d+)\\}"); - - char ESCAPE_CHAR = '\\'; - char START_ARG_CHAR = '{'; - char END_ARG_CHAR = '}'; - char REFERENCE_CHAR = '@'; - char START_REFERENCE_ARGS_CHAR = '('; - char END_REFERENCE_ARGS_CHAR = ')'; - char REFERENCE_ARG_CHAR = '\''; - - void enable(); - - void disable(); - - void sendSenderMessage(@NotNull CommandSender sender, @Nullable String miniMessagePrefix, - @NotNull String[] miniMessageTextLines, @NotNull Object[] positionalArgs); - - void sendChatMessage(@NotNull Player player, @Nullable String miniMessagePrefix, - @NotNull String[] miniMessageTextLines, @NotNull Object[] positionalArgs); - - void sendActionBar(@NotNull Player player, @NotNull String miniMessageText, @NotNull Object[] positionalArgs); - - void sendTitle(@NotNull Player player, @NotNull String[] miniMessageTitleAndSubtitle, @NotNull Object[] positionalArgs); - - void sendTitle(@NotNull Player player, @NotNull String[] miniMessageTitleAndSubtitle, @NotNull Object[] positionalArgs, - int fadeInTicks, int stayTicks, int fadeOutTicks); - - @NotNull - @CheckReturnValue - Inventory createInventory(@NotNull InventoryHolder owner, int size, - @NotNull String miniMessageTitle, @NotNull Object[] positionalArgs); - - @NotNull - @CheckReturnValue - Inventory createInventory(@NotNull InventoryHolder owner, @NotNull InventoryType type, - @NotNull String miniMessageTitle, @NotNull Object[] positionalArgs); - - void applyItemName(@NotNull ItemMeta item, @NotNull String miniMessageDisplayName, @NotNull Object[] positionalArgs); - - void appendItemName(@NotNull ItemMeta item, @NotNull String miniMessageDisplayNameSuffix, @NotNull Object[] positionalArgs); - - void applyItemLore(@NotNull ItemMeta item, @NotNull String[] miniMessageLore, @NotNull Object[] positionalArgs); - - void appendItemLore(@NotNull ItemMeta item, @NotNull String[] miniMessageLore, @NotNull Object[] positionalArgs); - - @NotNull - MessageBossBar createBossBar(@NotNull MessageHolder initialTitle); - -} diff --git a/platform/api/src/main/java/net/codingarea/challenges/platform/message/wrapper/MessageBossBar.java b/platform/api/src/main/java/net/codingarea/challenges/platform/message/wrapper/MessageBossBar.java deleted file mode 100644 index 886a2da03..000000000 --- a/platform/api/src/main/java/net/codingarea/challenges/platform/message/wrapper/MessageBossBar.java +++ /dev/null @@ -1,27 +0,0 @@ -package net.codingarea.challenges.platform.message.wrapper; - -import net.codingarea.challenges.platform.message.MessageHolder; -import org.bukkit.boss.BarColor; -import org.bukkit.boss.BarStyle; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - -/** - * Wrapper for underlying boss bar api (bukkit or adventure). - * We cannot expose the adventure api BossBar due to incompatibilities. - */ -public interface MessageBossBar { - - void show(@NotNull Player player); - - void hide(@NotNull Player player); - - void setText(@NotNull MessageHolder text); - - void setColor(@NotNull BarColor color); - - void setStyle(@NotNull BarStyle style); - - void setProgress(float progress); - -} diff --git a/platform/common/build.gradle.kts b/platform/common/build.gradle.kts deleted file mode 100644 index 88bcb035f..000000000 --- a/platform/common/build.gradle.kts +++ /dev/null @@ -1,24 +0,0 @@ -plugins { - id("java-library") -} - -dependencies { - api(project(":platform:api")) - - compileOnly(libs.spigot.api) - - // safe to use here, as it will either be used as the reloaced or native variant (this module will get duplicated) - // but it would NOT be safe to access from the main "plugin" module - compileOnly(libs.adventure.text.minimessage) - compileOnly(libs.adventure.text.serializer.legacy) - - compileOnly(libs.lombok) - - annotationProcessor(libs.lombok) -} - -tasks { - jar { - archiveClassifier = "plain" - } -} diff --git a/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/AbstractMiniMessagePlatform.java b/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/AbstractMiniMessagePlatform.java deleted file mode 100644 index 22323602b..000000000 --- a/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/AbstractMiniMessagePlatform.java +++ /dev/null @@ -1,331 +0,0 @@ -package net.codingarea.challenges.platform.message.common; - -import lombok.AllArgsConstructor; -import net.codingarea.challenges.platform.message.MessageHolder; -import net.codingarea.challenges.platform.message.MessagePlatform; -import net.codingarea.challenges.platform.message.common.wrapper.AdventureMessageBossBar; -import net.kyori.adventure.bossbar.BossBar; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.ComponentLike; -import net.kyori.adventure.text.TextComponent; -import net.kyori.adventure.text.TextReplacementConfig; -import net.kyori.adventure.text.format.TextDecoration; -import net.kyori.adventure.text.minimessage.MiniMessage; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import net.kyori.adventure.title.Title; -import net.kyori.adventure.translation.Translatable; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.meta.ItemMeta; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jspecify.annotations.NonNull; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Common base for implementations of MiniMessage preventing duplicate code. - * This class will be duplicated at compile time and relocated inside the legacy module for compatibility with - * relocated adventure lib. The original version (not relocated) will be used by the native impl. - *

- * Due to version/classpath incompatibility we have to abstract all calls to the adventure api. - * - * @see #convertToComponent(Object) for compatible argument types - */ -@AllArgsConstructor -public abstract class AbstractMiniMessagePlatform implements MessagePlatform { - - protected final Map prefixCache = new ConcurrentHashMap<>(); // messages may be sent concurrently - protected final MiniMessage miniMessage; - protected final LegacyComponentSerializer legacySerializer; - - public abstract void sendSenderComponent(@NotNull CommandSender sender, @NotNull Component component); - - public abstract void sendChatComponent(@NotNull Player player, @NotNull Component component); - - public abstract void sendActionBarComponent(@NotNull Player player, @NotNull Component component); - - public abstract void sendAdventureTitle(@NotNull Player player, @NotNull Title title); - - @NotNull - public abstract Inventory createInventoryTitled(@NotNull InventoryHolder owner, int size, @NotNull Component titleComponent); - - @NotNull - public abstract Inventory createInventoryTitled(@NotNull InventoryHolder owner, @NotNull InventoryType type, - @NotNull Component titleComponent); - - @NotNull - public abstract Component getPlayerNameComponent(@NotNull Player player); - - public abstract void applyItemNameComponent(@NotNull ItemMeta meta, @NotNull Component nameComponent); - - public abstract void appendItemNameComponent(@NotNull ItemMeta meta, @NotNull Component nameComponent); - - public abstract void applyItemLoreComponent(@NotNull ItemMeta meta, @NotNull List loreComponentLines); - - public abstract void appendItemLoreComponent(@NotNull ItemMeta meta, @NotNull List loreComponentLines); - - public abstract void showAdventureBossBar(@NotNull Player player, @NotNull BossBar bar); - - public abstract void hideAdventureBossBar(@NotNull Player player, @NotNull BossBar bar); - - @Override - public void sendSenderMessage(@NotNull CommandSender sender, @Nullable String miniMessagePrefix, - @NotNull String[] miniMessageTextLines, @NotNull Object[] positionalArgs) { - if (miniMessageTextLines.length == 0) return; - sendSenderComponent(sender, deserializeLinesWithArgs(miniMessagePrefix, miniMessageTextLines, positionalArgs)); - } - - @Override - public void sendChatMessage(@NotNull Player player, @Nullable String miniMessagePrefix, - @NotNull String[] miniMessageTextLines, @NotNull Object[] positionalArgs) { - if (miniMessageTextLines.length == 0) return; - sendChatComponent(player, deserializeLinesWithArgs(miniMessagePrefix, miniMessageTextLines, positionalArgs)); - } - - @Override - public void sendActionBar(@NotNull Player player, @NotNull String miniMessageText, @NotNull Object[] positionalArgs) { - sendActionBarComponent(player, deserializeLineWithArgs(miniMessageText, positionalArgs)); - } - - @Override - public void sendTitle(@NotNull Player player, @NotNull String[] miniMessageTitleAndSubtitle, @NotNull Object[] positionalArgs) { - sendAdventureTitle(player, Title.title(deserializeTitleWithArgs(miniMessageTitleAndSubtitle, positionalArgs), - deserializeSubtitle(miniMessageTitleAndSubtitle, positionalArgs))); - } - - @Override - public void sendTitle(@NotNull Player player, @NotNull String[] miniMessageTitleAndSubtitle, @NotNull Object[] positionalArgs, - int fadeInTicks, int stayTicks, int fadeOutTicks) { - sendAdventureTitle(player, Title.title(deserializeTitleWithArgs(miniMessageTitleAndSubtitle, positionalArgs), - deserializeSubtitle(miniMessageTitleAndSubtitle, positionalArgs), fadeInTicks, stayTicks, fadeOutTicks)); - } - - @NotNull - @Override - public Inventory createInventory(@NotNull InventoryHolder owner, int size, @NotNull String miniMessageTitle, @NotNull Object[] positionalArgs) { - return createInventoryTitled(owner, size, deserializeLineWithArgs(miniMessageTitle, positionalArgs)); - } - - @NotNull - @Override - public Inventory createInventory(@NotNull InventoryHolder owner, @NotNull InventoryType type, - @NotNull String miniMessageTitle, @NotNull Object[] positionalArgs) { - return createInventoryTitled(owner, type, deserializeLineWithArgs(miniMessageTitle, positionalArgs)); - } - - @Override - public void applyItemName(@NotNull ItemMeta item, @NotNull String miniMessageDisplayName, @NotNull Object[] positionalArgs) { - applyItemNameComponent(item, deserializeLineWithArgs(miniMessageDisplayName, positionalArgs)); - } - - @Override - public void appendItemName(@NotNull ItemMeta item, @NotNull String miniMessageDisplayNameSuffix, @NotNull Object[] positionalArgs) { - appendItemNameComponent(item, deserializeLineWithArgs(miniMessageDisplayNameSuffix, positionalArgs)); - } - - @Override - public void applyItemLore(@NotNull ItemMeta item, @NotNull String[] miniMessageLore, @NotNull Object[] positionalArgs) { - applyItemLoreComponent(item, deserializeLinesAsListWithArgs(miniMessageLore, positionalArgs)); - } - - @Override - public void appendItemLore(@NotNull ItemMeta item, @NotNull String[] miniMessageLore, @NotNull Object[] positionalArgs) { - appendItemLoreComponent(item, deserializeLinesAsListWithArgs(miniMessageLore, positionalArgs)); - } - - @NotNull - @Override - public AdventureMessageBossBar createBossBar(@NonNull MessageHolder initialTitle) { - Component initialTitleComponent = convertMessageHolderToComponent(initialTitle); - return new AdventureMessageBossBar(this, createDefaultAdventureBossBar(initialTitleComponent)); - } - - @NotNull - protected Component deserializeTitleWithArgs(@NotNull String[] titleAndSubtitle, @NotNull Object[] positionalArgs) { - if (titleAndSubtitle.length == 0) return Component.empty(); - return deserializeLineWithArgs(titleAndSubtitle[0], positionalArgs); - } - - @NotNull - protected Component deserializeSubtitle(@NotNull String[] titleAndSubtitle, @NotNull Object[] positionalArgs) { - if (titleAndSubtitle.length < 1) return Component.empty(); - return deserializeLineWithArgs(titleAndSubtitle[1], positionalArgs); - } - - @NotNull - protected Component deserializeLinesWithArgs(@Nullable String prefix, @NotNull String[] textLines, @NotNull Object[] positionalArgs) { - return replacePositionalArgs(deserializeLines(prefix, textLines), positionalArgs); - } - - @NotNull - protected Component deserializeLineWithArgs(@NotNull String line, @NotNull Object[] positionalArgs) { - return replacePositionalArgs(deserializeText(line), positionalArgs); - } - - @NotNull - protected Component deserializeLines(@Nullable String prefix, @NotNull String[] textLines) { - if (textLines.length == 0) return Component.empty(); - - TextComponent.Builder rootBuilder = Component.text(); - Component prefixComponent = (prefix != null && !prefix.isEmpty()) ? - prefixCache.computeIfAbsent(prefix, this::deserializeText) : null; - - // DISCUSSION: performance trade off for caching frequently used components vs. parsing on the fly - for (int i = 0; i < textLines.length; i++) { - if (textLines[i].isEmpty() || textLines[i].isBlank()) { // no prefix for empty lines - rootBuilder.append(Component.newline()); - continue; - } - - Component lineComponent = deserializeText(textLines[i]); - - if (prefixComponent != null) { - rootBuilder.append(prefixComponent).append(lineComponent); - } else { - rootBuilder.append(lineComponent); - } - - if (i < textLines.length - 1) { - rootBuilder.append(Component.newline()); - } - } - - return rootBuilder.build(); - } - - @NotNull - protected List deserializeLinesAsListWithArgs(@NotNull String[] textLines, @NotNull Object[] args) { - if (textLines.length == 0) return Collections.emptyList(); - - boolean hasArgs = args.length > 0; // don't waste time on processing otherwise - List components = new ArrayList<>(textLines.length + args.length); // might grow with args; extending is more expensive - for (String textLine : textLines) { - Component line = deserializeText(textLine); - if (hasArgs) { - List replaced = replacePositionalArgsAsList(line, args); - components.addAll(replaced); - } else { - components.add(line); - } - } - return components; - } - - @NotNull - protected Component replacePositionalArgs(@NotNull Component component, @Nullable Object[] positionalArgs) { - if (positionalArgs == null || positionalArgs.length == 0) { - return component; - } - - return component.replaceText(TextReplacementConfig.builder() - .match(POS_ARG_PATTERN) - .replacement((matchResult, builder) -> { - int index = Integer.parseInt(matchResult.group(1)); - if (index >= 0 && index < positionalArgs.length) { - return convertToComponent(positionalArgs[index]); - } - return builder; // or else leave as is, no runtime exceptions - }).build()); - } - - @NotNull - protected List replacePositionalArgsAsList(@NotNull Component component, @Nullable Object[] positionalArgs) { - if (positionalArgs == null || positionalArgs.length == 0) { - return List.of(component); - } - - Component replaced = replacePositionalArgs(component, positionalArgs); - return ComponentSplitter.split(replaced, "\\n"); - } - - protected Component convertToComponent(@Nullable Object obj) { - return switch (obj) { - case null -> Component.empty(); - case Component component -> component; - case ComponentLike like -> like.asComponent(); - case MessageHolder holder -> convertMessageHolderToComponent(holder); - case Translatable translatable -> // net.kyori.adventure.translation.Translatable - Component.translatable(translatable); - case String string -> Component.text(string); // literal escaped text; not deserializeText - case Material material -> TranslatableComponents.fromMaterial(material); - case EntityType entityType -> TranslatableComponents.fromEntityType(entityType); - case GameMode gameMode -> TranslatableComponents.fromGameMode(gameMode); - case Player player -> getPlayerNameComponent(player); - case Object _ when TranslatableComponents.isBukkitTranslatable(obj) -> // org.bukkit.Translatable - TranslatableComponents.fromBukkitTranslatable(obj); - case Enum enumObj -> Component.text(stringifyFallbackEnumName(enumObj.name())); - default -> Component.text(obj.toString()); - }; - } - - @NotNull - public Component convertMessageHolderToComponent(@NotNull MessageHolder holder) { - return deserializeLinesWithArgs(null, holder.miniMessageRaw(), holder.positionalArgs()); - } - - @NotNull - protected Component deserializeText(@NotNull String textLine) { - return deserializeText0(textLine) - .decorationIfAbsent(TextDecoration.ITALIC, TextDecoration.State.FALSE); - } - - @NotNull - protected Component deserializeText0(@NotNull String textLine) { - if (isProbablyLegacyText(textLine)) { - return legacySerializer.deserialize(textLine); - } - try { - return miniMessage.deserialize(textLine); - } catch (Exception ex) { // maybe heuristic failed, try legacy again - return legacySerializer.deserialize(textLine); - } - } - - @NotNull - protected BossBar createDefaultAdventureBossBar(@NotNull Component initialText) { - return BossBar.bossBar(initialText, 1f, BossBar.Color.WHITE, BossBar.Overlay.PROGRESS); - } - - protected boolean isProbablyLegacyText(@NotNull String text) { - // legacy texts often start/end with a '§' color; heuristic so we don't have to check the full string - if (text.length() < 2) return false; - if (text.charAt(0) == '§') return true; - return text.charAt(text.length() - 2) == '§'; - } - - protected String stringifyFallbackEnumName(@NotNull String enumName) { - // EXAMPLE_ENUM -> "Example Enum" - int len = enumName.length(); - if (len == 0) return ""; - - char[] result = new char[len]; - boolean nextUpperCase = true; - for (int i = 0; i < len; i++) { - char letter = enumName.charAt(i); - if (letter == '_') { - result[i] = ' '; - nextUpperCase = true; - } else { - if (nextUpperCase) { - result[i] = (letter >= 'a' && letter <= 'z') ? (char) (letter - 32) : letter; // to uppercase - } else { - result[i] = (letter >= 'A' && letter <= 'Z') ? (char) (letter + 32) : letter; // to lowercase - } - nextUpperCase = false; - } - } - return new String(result); - } - -} diff --git a/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/BukkitTranslationKeyExtractor.java b/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/BukkitTranslationKeyExtractor.java deleted file mode 100644 index f59d582d8..000000000 --- a/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/BukkitTranslationKeyExtractor.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.codingarea.challenges.platform.message.common; - -import org.bukkit.Translatable; -import org.jetbrains.annotations.NotNull; - -// org.bukitt.Translatable available since 1.19.3 -// LinkageError due to Translatable not existing -> the whole class may not be loadable -// therefore we encapsulate it which is preferred compared to expesive reflection calls to Translatable -final class BukkitTranslationKeyExtractor { - - private BukkitTranslationKeyExtractor() { - } - - static boolean isTranslationKeyAvailable(@NotNull Object obj) throws LinkageError { - return obj instanceof Translatable; - } - - static String extractTranslationKey(@NotNull Object obj) throws LinkageError { - if (obj instanceof Translatable translatable) - return translatable.getTranslationKey(); - throw new IllegalArgumentException("Object " + obj.getClass() + " is not a org.bukkit.Translatable"); - } - -} diff --git a/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/TranslatableComponents.java b/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/TranslatableComponents.java deleted file mode 100644 index 02287b199..000000000 --- a/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/TranslatableComponents.java +++ /dev/null @@ -1,60 +0,0 @@ -package net.codingarea.challenges.platform.message.common; - -import net.kyori.adventure.text.Component; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.entity.EntityType; -import org.jetbrains.annotations.NotNull; - -public final class TranslatableComponents { - - private TranslatableComponents() { - } - - // org.bukkit.Translatable available since 1.19.3, but we want to provide compatibility with older versions - public static boolean isBukkitTranslatable(@NotNull Object translatable) { - try { - return BukkitTranslationKeyExtractor.isTranslationKeyAvailable(translatable); - } catch (Throwable ex) { - return false; - } - } - - @NotNull - public static Component fromBukkitTranslatable(@NotNull Object translatable) { - // must check isBukkitTranslatable first - try { - return Component.translatable(BukkitTranslationKeyExtractor.extractTranslationKey(translatable)); - } catch (Throwable ex) { - // ignore and fallback to toString silently instead of runtime exception - return Component.translatable(translatable.toString()); - } - } - - @NotNull - public static Component fromMaterial(@NotNull Material material) { - try { - return Component.translatable(material.getTranslationKey()); // 1.19.3+ - } catch (NoSuchMethodError ex) { - // hopefully this is the correct key... use namespace key instead? - String prefix = material.isItem() ? "block.minecraft." : "item.minecraft."; - return Component.translatable(prefix + material.name().toLowerCase()); - } - } - - @NotNull - public static Component fromEntityType(@NotNull EntityType entityType) { - try { - return Component.translatable(entityType.getTranslationKey()); // 1.19.3+ - } catch (NoSuchMethodError ex) { - // hopefully this is the correct key... use namespace key instead? - return Component.translatable("entity.minecraft." + entityType.name().toLowerCase()); - } - } - - @NotNull - public static Component fromGameMode(@NotNull GameMode gameMode) { - return Component.translatable("selectWorld.gameMode." + gameMode.name().toLowerCase()); - } - -} diff --git a/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/wrapper/AdventureMessageBossBar.java b/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/wrapper/AdventureMessageBossBar.java deleted file mode 100644 index 97b0e4cb5..000000000 --- a/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/wrapper/AdventureMessageBossBar.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.codingarea.challenges.platform.message.common.wrapper; - -import lombok.RequiredArgsConstructor; -import net.codingarea.challenges.platform.message.MessageHolder; -import net.codingarea.challenges.platform.message.common.AbstractMiniMessagePlatform; -import net.codingarea.challenges.platform.message.wrapper.MessageBossBar; -import net.kyori.adventure.bossbar.BossBar; -import org.bukkit.boss.BarColor; -import org.bukkit.boss.BarStyle; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; - -@RequiredArgsConstructor -public class AdventureMessageBossBar implements MessageBossBar { - - protected final AbstractMiniMessagePlatform platform; - protected final BossBar bar; - - @Override - public void setText(@NonNull MessageHolder text) { - bar.name(platform.convertMessageHolderToComponent(text)); - } - - @Override - public void setColor(@NonNull BarColor color) { - bar.color(convertColor(color)); - } - - @Override - public void setStyle(@NonNull BarStyle style) { - bar.overlay(convertStyle(style)); - } - - @Override - public void setProgress(float progress) { - bar.progress(progress); - } - - @Override - public void show(@NonNull Player player) { - platform.showAdventureBossBar(player, bar); - } - - @Override - public void hide(@NonNull Player player) { - platform.hideAdventureBossBar(player, bar); - } - - @NotNull - protected static BossBar.Overlay convertStyle(@NotNull BarStyle style) { - return switch (style) { - case SEGMENTED_6 -> BossBar.Overlay.NOTCHED_6; - case SEGMENTED_10 -> BossBar.Overlay.NOTCHED_10; - case SEGMENTED_12 -> BossBar.Overlay.NOTCHED_12; - case SEGMENTED_20 -> BossBar.Overlay.NOTCHED_20; - default -> BossBar.Overlay.PROGRESS; - }; - } - - @NotNull - protected static BossBar.Color convertColor(@NotNull BarColor color) { - return switch (color) { - case PINK -> BossBar.Color.PINK; - case BLUE -> BossBar.Color.BLUE; - case RED -> BossBar.Color.RED; - case GREEN -> BossBar.Color.GREEN; - case YELLOW -> BossBar.Color.YELLOW; - case PURPLE -> BossBar.Color.PURPLE; - default -> BossBar.Color.WHITE; - }; - } -} diff --git a/platform/legacy/build.gradle.kts b/platform/legacy/build.gradle.kts deleted file mode 100644 index 73f773673..000000000 --- a/platform/legacy/build.gradle.kts +++ /dev/null @@ -1,62 +0,0 @@ -plugins { - id("java-library") - alias(libs.plugins.shadow) -} - -dependencies { - compileOnly(libs.spigot.api) - - implementation(project(":platform:common")) - - // in paper - // - since 1.16.5: adventure-api is bundled (but not minimessage) - // - since 1.18.2: minimessage is bundled in paper - // - since 1.20.5: paper migrated internal systems to minimessages, mojang rewrote internals - // breaking shaded impl - implementation(libs.adventure.text.minimessage) - // has been discontinued, but avilable implementations for legacy versions are still available and functional - // we only use it for legacy support making this a practical solution - implementation(libs.adventure.platform.bukkit) - - // not available by default - implementation(libs.adventure.text.serializer.legacy) - - // NOTE: shadow(..) does somehow not work, requiring exlusion of net.kyori.* when importing to prevent Gradle - // from bundling it twice (once relocated and once default), just using implementation for now -} - -tasks { - - jar { - archiveClassifier = "plain" - } - - shadowJar { - archiveClassifier = "" - - // relocate adventure lib (inclduing legacy bukkit platform) for compatibilty with legacy platforms - // including spigot and paper pre-1.18.2 - // - if adventure lib is fully bundled natively (e.g. modern paper version) it will use the available api - // as the shadowed adventure lib version (might) be incompatible with newer minecraft versions - // like post-1.20.5 as the component system was overhauled - // (provided and used by :platform:legacy) - relocate("net.kyori", "net.codingarea.challenges.relocate") - - // force Gradle to relocate common module for compatibility with relocated adventure lib. - // hacky & ugly fix but necessary for compatibility with older versions and prevents writing/maintating the same code twice. - relocate("net.codingarea.challenges.platform.message.common", "net.codingarea.challenges.platform.message.legacy") - } - -} - -// make Gradle expose the shadowed JAR to other projects by default -configurations { - apiElements { - outgoing.artifacts.clear() - outgoing.artifact(tasks.shadowJar) - } - runtimeElements { - outgoing.artifacts.clear() - outgoing.artifact(tasks.shadowJar) - } -} diff --git a/platform/legacy/src/main/java/net/codingarea/challenges/platform/message/legacy/LegacyMiniMessagePlatform.java b/platform/legacy/src/main/java/net/codingarea/challenges/platform/message/legacy/LegacyMiniMessagePlatform.java deleted file mode 100644 index 285689f22..000000000 --- a/platform/legacy/src/main/java/net/codingarea/challenges/platform/message/legacy/LegacyMiniMessagePlatform.java +++ /dev/null @@ -1,129 +0,0 @@ -package net.codingarea.challenges.platform.message.legacy; - -import net.codingarea.challenges.platform.message.common.AbstractMiniMessagePlatform; -import net.codingarea.challenges.platform.message.common.wrapper.AdventureMessageBossBar; -import net.kyori.adventure.bossbar.BossBar; -import net.kyori.adventure.platform.bukkit.BukkitAudiences; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.minimessage.MiniMessage; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import net.kyori.adventure.title.Title; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.plugin.java.JavaPlugin; -import org.jetbrains.annotations.NotNull; - -import java.util.List; - -/** - * Adds support for MiniMessages if there is no native implementation found, like on spigot or older paper versions. - * It uses a bundled and relocated version of the adventure dependency. - */ -public class LegacyMiniMessagePlatform extends AbstractMiniMessagePlatform { - - protected final JavaPlugin plugin; - protected BukkitAudiences audiences; - - public LegacyMiniMessagePlatform(@NotNull JavaPlugin plugin) { - super(MiniMessage.miniMessage(), LegacyComponentSerializer.legacySection()); - this.plugin = plugin; - } - - @Override - public void enable() { - // lib will try to register a PlayerJoinListener which is only possible once the plugin is enabled - this.audiences = BukkitAudiences.create(plugin); - } - - @Override - public void disable() { - audiences.close(); - } - - @Override - public void sendSenderComponent(@NotNull CommandSender sender, @NotNull Component component) { - audiences.sender(sender).sendMessage(component); - } - - @Override - public void sendChatComponent(@NotNull Player player, @NotNull Component component) { - audiences.player(player).sendMessage(component); - } - - @Override - public void sendActionBarComponent(@NotNull Player player, @NotNull Component component) { - audiences.player(player).sendActionBar(component); - } - - @Override - public void sendAdventureTitle(@NotNull Player player, @NotNull Title title) { - audiences.player(player).showTitle(title); - } - - @NotNull - @Override - public Inventory createInventoryTitled(@NotNull InventoryHolder owner, int size, @NotNull Component titleComponent) { - return Bukkit.createInventory(owner, size, legacySerializer.serialize(titleComponent)); - } - - @NotNull - @Override - public Inventory createInventoryTitled(@NotNull InventoryHolder owner, @NotNull InventoryType type, @NotNull Component titleComponent) { - return Bukkit.createInventory(owner, type, legacySerializer.serialize(titleComponent)); - } - - @NotNull - @Override - public Component getPlayerNameComponent(@NotNull Player player) { - return legacySerializer.deserialize(player.getDisplayName()); - } - - @Override - public void applyItemNameComponent(@NotNull ItemMeta meta, @NotNull Component nameComponent) { - meta.setDisplayName(legacySerializer.serialize(nameComponent)); - } - - @Override - public void appendItemNameComponent(@NotNull ItemMeta meta, @NotNull Component nameComponent) { - String existingName = meta.hasDisplayName() ? meta.getDisplayName() : ""; - meta.setDisplayName(existingName + legacySerializer.serialize(nameComponent)); - } - - @Override - public void applyItemLoreComponent(@NotNull ItemMeta meta, @NotNull List loreComponentLines) { - meta.setLore(componentsToLegacyStrings(loreComponentLines)); - } - - @Override - public void appendItemLoreComponent(@NotNull ItemMeta meta, @NotNull List loreComponentLines) { - List existingLore = meta.getLore(); - if (existingLore == null) { - applyItemLoreComponent(meta, loreComponentLines); - return; - } - existingLore.addAll(componentsToLegacyStrings(loreComponentLines)); - meta.setLore(existingLore); - } - - @Override - public void showAdventureBossBar(@NotNull Player player, @NotNull BossBar bar) { - audiences.player(player).showBossBar(bar); - } - - @Override - public void hideAdventureBossBar(@NotNull Player player, @NotNull BossBar bar) { - audiences.player(player).hideBossBar(bar); - } - - @NotNull - protected List componentsToLegacyStrings(@NotNull List components) { - return components.stream() - .map(legacySerializer::serialize) - .toList(); - } -} diff --git a/platform/paper/build.gradle.kts b/platform/paper/build.gradle.kts deleted file mode 100644 index 30a8b43e8..000000000 --- a/platform/paper/build.gradle.kts +++ /dev/null @@ -1,19 +0,0 @@ -plugins { - id("java-library") -} - -dependencies { - compileOnly(libs.paper.api) - - implementation(project(":platform:common")) -} - -repositories { - maven("https://repo.papermc.io/repository/maven-public/") -} - -tasks { - jar { - archiveClassifier = "plain" - } -} diff --git a/platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatform.java b/platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatform.java deleted file mode 100644 index ab43cacbb..000000000 --- a/platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatform.java +++ /dev/null @@ -1,120 +0,0 @@ -package net.codingarea.challenges.platform.message.paper; - -import net.codingarea.challenges.platform.message.common.AbstractMiniMessagePlatform; -import net.kyori.adventure.bossbar.BossBar; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.minimessage.MiniMessage; -import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; -import net.kyori.adventure.title.Title; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.meta.ItemMeta; -import org.jetbrains.annotations.NotNull; - -import java.util.List; - -/** - * Allows for native calls to paper/adventure api bundled by modern paper-like servers, - * removing the need for slower reflection wrappers with just a small overhead. - */ -public class NativePaperMessagePlatform extends AbstractMiniMessagePlatform { - - public NativePaperMessagePlatform() { - super(MiniMessage.miniMessage(), LegacyComponentSerializer.legacySection()); - } - - @Override - public void enable() { - // no initialization required - } - - @Override - public void disable() { - // no cleanup required - } - - @Override - public void sendSenderComponent(@NotNull CommandSender sender, @NotNull Component component) { - sender.sendMessage(component); - } - - @Override - public void sendChatComponent(@NotNull Player player, @NotNull Component component) { - player.sendMessage(component); - } - - @Override - public void sendActionBarComponent(@NotNull Player player, @NotNull Component component) { - player.sendActionBar(component); - } - - @Override - public void sendAdventureTitle(@NotNull Player player, @NotNull Title title) { - player.showTitle(title); - } - - @NotNull - @Override - public Inventory createInventoryTitled(@NotNull InventoryHolder owner, int size, @NotNull Component titleComponent) { - return Bukkit.createInventory(owner, size, titleComponent); - } - - @NotNull - @Override - public Inventory createInventoryTitled(@NotNull InventoryHolder owner, @NotNull InventoryType type, - @NotNull Component titleComponent) { - return Bukkit.createInventory(owner, type, titleComponent); - } - - @NotNull - @Override - public Component getPlayerNameComponent(@NotNull Player player) { - return player.displayName(); - } - - @Override - public void applyItemNameComponent(@NotNull ItemMeta meta, @NotNull Component nameComponent) { - meta.displayName(nameComponent); - } - - @Override - public void appendItemNameComponent(@NotNull ItemMeta meta, @NotNull Component nameComponent) { - Component existingName = meta.displayName(); - if (existingName == null) { - meta.displayName(nameComponent); - return; - } - - meta.displayName(existingName.append(nameComponent)); - } - - @Override - public void applyItemLoreComponent(@NotNull ItemMeta meta, @NotNull List loreComponentLines) { - meta.lore(loreComponentLines); - } - - @Override - public void appendItemLoreComponent(@NotNull ItemMeta meta, @NotNull List loreComponentLines) { - List existingLore = meta.lore(); - if (existingLore == null) { - meta.lore(loreComponentLines); - return; - } - existingLore.addAll(loreComponentLines); // meta.lore() is always modifiable? - meta.lore(existingLore); - } - - @Override - public void showAdventureBossBar(@NotNull Player player, @NotNull BossBar bar) { - player.showBossBar(bar); - } - - @Override - public void hideAdventureBossBar(@NotNull Player player, @NotNull BossBar bar) { - player.hideBossBar(bar); - } -} diff --git a/platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatformChecker.java b/platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatformChecker.java deleted file mode 100644 index 6ac4a4c89..000000000 --- a/platform/paper/src/main/java/net/codingarea/challenges/platform/message/paper/NativePaperMessagePlatformChecker.java +++ /dev/null @@ -1,30 +0,0 @@ -package net.codingarea.challenges.platform.message.paper; - -import org.jetbrains.annotations.NotNull; - -public final class NativePaperMessagePlatformChecker { - - private NativePaperMessagePlatformChecker() { - } - - public static boolean isAvailable() { - try { - // test if Paper's native MiniMessage is present on the classpath - Class.forName(buildClassName("net", "kyori", "adventure", "text", "minimessage", "MiniMessage")); - // impl version we use internally; fallback if it has changed as it would lead to errors - Class.forName(buildClassName("net", "kyori", "adventure", "text", "minimessage", "MiniMessageImpl")); - // required translation api - Class.forName(buildClassName("net", "kyori", "adventure", "translation", "Translatable")); - return true; - } catch (Throwable ex) { - return false; - } - } - - private static String buildClassName(@NotNull String... location) { - // use string builder to avoid constants being remapped due to relocation - // as we don't care about our shaded impl but the native one bundled by paper - return String.join(".", location); - } - -} diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index 2564b66e1..c22543d48 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -27,8 +27,9 @@ repositories { dependencies { compileOnly(libs.slf4j.api) - compileOnly(libs.spigot.api) + compileOnly(libs.paper.api) compileOnly(libs.authlib) + compileOnly(libs.protocol.lib) compileOnly(libs.jetbrains.annotations) compileOnly(libs.lombok) @@ -44,14 +45,8 @@ dependencies { // TODO abstract to register dynamically implementation(project(":cloud-support:cloudnet2")) implementation(project(":cloud-support:cloudnet3")) - - api(project(":platform:api")) - implementation(project(":platform:common")) - implementation(project(":platform:paper")) - implementation(project(":platform:legacy")) { - exclude("net.kyori") // see platform/legacy/build.gradle.kts - } } + tasks { processResources { @@ -87,7 +82,6 @@ tasks { archiveVersion = "" // no explicit dependencies block - bundle "implementation" deps by default - // relocated adventure-lib in :platform:legacy } build { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java b/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java index f09a08ea5..64c74b812 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/ChallengeAPI.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.loader.ContentLoader; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; @@ -88,8 +89,8 @@ public static boolean getItemsDirectIntoInventory() { } @NotNull - public static String formatTime(long seconds) { - return Challenges.getInstance().getChallengeTimer().getFormat().format(seconds); + public static LocalizableMessage formatTime(long seconds) { + return Challenges.getInstance().getChallengeTimer().getFormattedTimeFor(seconds); } /** diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java index f7640f2b5..99bc9ac2d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java @@ -55,7 +55,6 @@ public final class Challenges extends BukkitModule { private GeneratorWorldPortalManager generatorWorldPortalManager; private TeamProvider teamProvider; private TranslationManager translationManager; - private PlatformManager platformManager; @NotNull public static Challenges getInstance() { @@ -95,7 +94,6 @@ private void createManagers() { new UpdateLoader() ); - platformManager = new PlatformManager(); databaseManager = new DatabaseManager(); worldManager = new WorldManager(); serverManager = new ServerManager(); @@ -120,14 +118,12 @@ private void createManagers() { } private void loadManagers() { - platformManager.createPlatforms(); loaderRegistry.load(); worldManager.load(); challengeTimer.loadSession(); } private void enableManagers() { - platformManager.enablePlatforms(); gameWorldStorage.enable(); challengeLoader.enable(); customSettingsLoader.enable(); @@ -177,7 +173,6 @@ private void registerCommands() { registerCommand(new ForwardingCommand("time set midnight"), "midnight"); registerCommand(new ResultCommand(), "result"); registerCommand(new SkipTimerCommand(), "skiptimer"); - registerCommand(new LanguageCommand(), "setlanguage"); registerListenerCommand(new GodModeCommand(), "godmode"); } @@ -221,8 +216,6 @@ protected void handleDisable() { } challengeManager.clearChallengeCache(); } - - if (platformManager != null) platformManager.disablePlatforms(); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index 42c2a63ff..752edd81d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -7,7 +7,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.InfoMenuGenerator; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; @@ -15,9 +15,7 @@ import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Locale; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java index e3cc0f668..5f328bd73 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.common.collection.IRandom; import org.bukkit.inventory.ItemStack; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java index 60a8f7397..6933e3526 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; import net.codingarea.commons.bukkit.utils.logging.Logger; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java index 026852ffc..8193c7cd3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java index 72ebe9818..4f0dfb8c1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java @@ -5,7 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java index 4c1946bc2..3907b45de 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java @@ -2,8 +2,8 @@ import lombok.Getter; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.*; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.impl.MessageManager; +import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.legacy.MessageManager; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java index 5850b96e1..d8a2686a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java @@ -3,7 +3,7 @@ import com.google.common.collect.Lists; import lombok.Getter; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.SubSettingChooseMultipleMenuGenerator; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java index 07b5f7f4a..aef10415f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java @@ -6,8 +6,8 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl.BooleanSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl.ModifierSetting; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.impl.MessageManager; +import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.legacy.MessageManager; import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.SubSettingValueMenuGenerator; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java index bb8a8c981..f5dc512bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.inventory.ItemStack; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java index 818c3b4f0..a3350862e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder.PotionBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java index 222ed95c5..99f016c15 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.PlayerCountPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java index 0689d19e5..ad425afbe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import org.bukkit.Location; import org.bukkit.Material; @@ -38,7 +38,7 @@ public DamageTeleportChallenge() { @Override public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 0 ? Message.forName("everyone").asString() : Message.forName("player").asString()); + ChallengeHelper.playChallengeValueTitle(this, getValue() == 0 ? Message.forName("everyone").asString() : Message.forName("player").asString()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index 1a2ff3106..f9507c6e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -5,13 +5,14 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; @@ -39,7 +40,7 @@ protected void onEnable() { int currentTime = getCurrentTime(); int maxTime = getValue() * 60; bossbar.setTitle(Message.forName("bossbar-zero-hearts").asString(maxTime - currentTime)); - bossbar.setColor(BarColor.GREEN); + bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(1 - ((float) currentTime / maxTime)); }); bossbar.show(); @@ -100,7 +101,7 @@ public void onEntityPotionEffect(@NotNull EntityPotionEffectEvent event) { if (!(event.getEntity() instanceof Player player)) return; if (ignorePlayer(player)) return; ChallengeHelper.kill(player); - MessageKey.of("zero-hearts-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + MessageKey.of("zero-hearts-failed").broadcast(Prefix.CHALLENGES, player); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java index 5b6f18e64..0356fca35 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -14,7 +14,6 @@ import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java index 2d5b74749..dde622ca8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java @@ -3,7 +3,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -39,7 +40,7 @@ public void playValueChangeTitle() { public void onSneak(@NotNull PlayerJumpEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; - Message.forName("jump-damage-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + MessageKey.of("jump-damage-failed").broadcast(Prefix.CHALLENGES, event.getPlayer()); event.getPlayer().setNoDamageTicks(0); event.getPlayer().damage(getValue()); event.getPlayer().setNoDamageTicks(0); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java index a760ee461..8c205848b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java index b1ab2729b..da7eeac65 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -248,9 +248,9 @@ protected void onValueChange() { @Override public void playValueChangeTitle() { if (GLOBAL_EFFECT == getValue()) { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("everyone").asString()); + ChallengeHelper.playChallengeValueTitle(this, Message.forName("everyone").asString()); } else { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("player").asString()); + ChallengeHelper.playChallengeValueTitle(this, Message.forName("player").asString()); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java index 6f488e6d7..64ce4e70b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java @@ -3,11 +3,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; @@ -16,8 +14,6 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.util.BoundingBox; import org.bukkit.util.RayTraceResult; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @Since("2.0") public class MobSightDamageChallenge extends SettingModifier { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java index 087bfe33e..4a4d70c9d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java @@ -2,10 +2,12 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDamageByPlayerEvent; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.EnderDragon; @@ -28,10 +30,10 @@ public MobTransformationChallenge() { @Override protected void onEnable() { bossbar.setContent((bossbar, player) -> { - bossbar.setColor(BarColor.GREEN); + bossbar.setColor(BossBar.Color.GREEN); EntityType type = getPlayerData(player).getEnum("type", EntityType.class); Object typeName = type == null ? "None" : type; - bossbar.setTitle(Message.forName("bossbar-mob-transformation").asString(typeName)); + bossbar.setTitle(MessageKey.of("bossbar-mob-transformation"), typeName); }); bossbar.show(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java index ccbcc4a5b..66f1e2982 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java @@ -4,12 +4,14 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDeathByPlayerEvent; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; @@ -39,8 +41,8 @@ public MobsRespawnInEndChallenge() { @Override protected void onEnable() { bossbar.setContent((bar, player) -> { - bar.setColor(BarColor.PURPLE); - bar.setTitle(Message.forName("bossbar-respawn-end").asString(totalMobsInEnd)); + bar.setColor(BossBar.Color.PURPLE); + bar.setTitle(MessageKey.of("bossbar-respawn-end"), totalMobsInEnd); }); bossbar.show(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java index 692fc8618..226169565 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java @@ -5,7 +5,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.WorldDependentChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Updated; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; @@ -17,7 +16,6 @@ import net.codingarea.challenges.plugin.utils.bukkit.jumpgeneration.RandomJumpGenerator; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; @@ -30,11 +28,9 @@ import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; -import java.util.Optional; import java.util.UUID; @Updated("2.4") @@ -44,7 +40,7 @@ public class JumpAndRunChallenge extends WorldDependentChallenge { private int jumps = 4; private int currentJump; - private int jumpsDone; + private int jumpAndRunsDone; private Block targetBlock; private Block lastBlock; @@ -52,7 +48,7 @@ public class JumpAndRunChallenge extends WorldDependentChallenge { private UUID currentPlayer; public JumpAndRunChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, new ItemStack(Material.ACACIA_STAIRS), "item-jump-and-run-challenge"); + super(MenuType.CHALLENGES, 1, 10, 5, new ItemStack(Material.ACACIA_STAIRS), "jump-and-run"); } @Override @@ -109,6 +105,9 @@ protected void startJumpAndRun() { currentPlayer = getNextPlayer().getUniqueId(); lastPlayers.add(currentPlayer); + actionbar.setContent(player -> getChallengeMessageKey("actionbar").withArgs(currentJump, jumps)); + actionbar.show(); + buildNextJump(); teleportToWorld(true, (player, index) -> { player.setGameMode(player.getUniqueId().equals(currentPlayer) ? GameMode.SURVIVAL : GameMode.SPECTATOR); @@ -158,7 +157,7 @@ protected Player getNextPlayer() { protected void finishJumpAndRun(@NotNull Player player) { jumps++; - jumpsDone++; + jumpAndRunsDone++; MessageKey.of("jnr-finished").broadcast(Prefix.CHALLENGES, player); exitJumpAndRun(); @@ -167,6 +166,7 @@ protected void finishJumpAndRun(@NotNull Player player) { protected void exitJumpAndRun() { currentPlayer = null; + actionbar.hide(); teleportBack(); breakJumpAndRun(); restartTimer(); @@ -184,14 +184,14 @@ protected void breakJumpAndRun() { public void writeGameState(@NotNull Document document) { super.writeGameState(document); document.set("jumps", jumps); - document.set("jumpsDone", jumpsDone); + document.set("jumpsDone", jumpAndRunsDone); } @Override public void loadGameState(@NotNull Document document) { super.loadGameState(document); jumps = document.getInt("jumps", jumps); - jumpsDone = document.getInt("jumpsDone", jumpsDone); + jumpAndRunsDone = document.getInt("jumpsDone", jumpAndRunsDone); } @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.ALWAYS, worldPolicy = ExtraWorldPolicy.USED) @@ -213,6 +213,7 @@ public void onMove(@NotNull PlayerMoveEvent event) { finishJumpAndRun(event.getPlayer()); // is currentPlayer } else { SoundSample.PLOP.broadcast(); + actionbar.send(); buildNextJump(); } } else if (event.getTo().getBlockY() < targetBlock.getY() - 2) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java index 18f98201d..1b08b0857 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java @@ -5,7 +5,8 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -13,6 +14,7 @@ import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.common.config.Document; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.Registry; @@ -55,24 +57,24 @@ public void playValueChangeTitle() { protected BiConsumer setupBossbar() { return (bossbar, player) -> { if (getState() == WAITING) { - bossbar.setTitle(Message.forName("bossbar-force-biome-waiting").asString()); + bossbar.setTitle(MessageKey.of("bossbar-force-biome-waiting")); return; } - bossbar.setColor(BarColor.GREEN); + bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-force-biome-instruction").asComponent(biome, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); + bossbar.setTitle(MessageKey.of("bossbar-force-biome-instruction"), biome, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); }; } @Override protected void broadcastFailedMessage() { - Message.forName("force-biome-fail").broadcast(Prefix.CHALLENGES, BukkitStringUtils.getBiomeName(biome)); + MessageKey.of("force-biome-fail").broadcast(Prefix.CHALLENGES, biome); } @Override protected void broadcastSuccessMessage(@NotNull Player player) { - Message.forName("force-biome-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), BukkitStringUtils.getBiomeName(biome)); + MessageKey.of("force-biome-success").broadcast(Prefix.CHALLENGES, player, biome); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java index 42e733231..c2e1a247e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java @@ -4,7 +4,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -14,6 +15,7 @@ import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.item.ItemUtils; import net.codingarea.commons.common.config.Document; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; @@ -48,13 +50,13 @@ public void playValueChangeTitle() { protected BiConsumer setupBossbar() { return (bossbar, player) -> { if (getState() == WAITING) { - bossbar.setTitle(Message.forName("bossbar-force-block-waiting").asString()); + bossbar.setTitle(MessageKey.of("bossbar-force-block-waiting")); return; } - bossbar.setColor(BarColor.GREEN); + bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-force-block-instruction").asComponent(block, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); + bossbar.setTitle(MessageKey.of("bossbar-force-block-instruction"), block, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); }; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java index 838251906..ca52866a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java @@ -4,7 +4,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -12,6 +13,7 @@ import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.commons.common.config.Document; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; @@ -47,13 +49,13 @@ public void playValueChangeTitle() { protected BiConsumer setupBossbar() { return (bossbar, player) -> { if (getState() == WAITING) { - bossbar.setTitle(Message.forName("bossbar-force-height-waiting").asString()); + bossbar.setTitle(MessageKey.of("bossbar-force-height-waiting")); return; } - bossbar.setColor(BarColor.GREEN); + bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-force-height-instruction").asString(height, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); + bossbar.setTitle(MessageKey.of("bossbar-force-height-instruction"), height, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); }; } @@ -64,12 +66,12 @@ protected boolean isFailing(@NotNull Player player) { @Override protected void broadcastFailedMessage(@NotNull Player player) { - Message.forName("force-height-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), player.getLocation().getBlockY()); + MessageKey.of("force-height-fail").broadcast(Prefix.CHALLENGES, player, player.getLocation().getBlockY()); } @Override protected void broadcastSuccessMessage() { - Message.forName("force-height-success").broadcast(Prefix.CHALLENGES); + MessageKey.of("force-height-success").broadcast(Prefix.CHALLENGES); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java index 6c100416c..542acc94e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java @@ -4,7 +4,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -12,12 +13,12 @@ import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.item.ItemUtils; import net.codingarea.commons.common.config.Document; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.boss.BarColor; @@ -27,7 +28,6 @@ import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Arrays; @@ -60,13 +60,13 @@ public void playValueChangeTitle() { protected BiConsumer setupBossbar() { return (bossbar, player) -> { if (getState() == WAITING) { - bossbar.setTitle(Message.forName("bossbar-force-item-waiting").asString()); + bossbar.setTitle(MessageKey.of("bossbar-force-item-waiting")); return; } - bossbar.setColor(BarColor.GREEN); + bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-force-item-instruction").asComponent(item, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); + bossbar.setTitle(MessageKey.of("bossbar-force-item-instruction"), item, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); }; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java index 7a33d2cea..b5fb9da46 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java @@ -3,16 +3,17 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.Utils; import net.codingarea.commons.common.config.Document; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.EntityType; @@ -23,7 +24,6 @@ import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Arrays; @@ -55,24 +55,24 @@ public void playValueChangeTitle() { protected BiConsumer setupBossbar() { return (bossbar, player) -> { if (getState() == WAITING) { - bossbar.setTitle(Message.forName("bossbar-force-mob-waiting").asString()); + bossbar.setTitle(MessageKey.of("bossbar-force-mob-waiting")); return; } - bossbar.setColor(BarColor.GREEN); + bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-force-mob-instruction").asComponent(entity, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation()))); + bossbar.setTitle(MessageKey.of("bossbar-force-mob-instruction"), entity, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); }; } @Override protected void broadcastFailedMessage() { - Message.forName("force-mob-fail").broadcast(Prefix.CHALLENGES, entity); + MessageKey.of("force-mob-fail").broadcast(Prefix.CHALLENGES, entity); } @Override protected void broadcastSuccessMessage(@NotNull Player player) { - Message.forName("force-mob-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), entity); + MessageKey.of("force-mob-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), entity); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java index d3ca55ea8..1275730c8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/DamageInventoryClearChallenge.java @@ -2,11 +2,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -47,7 +45,7 @@ public void onDamage(@NotNull EntityDamageEvent event) { @Override public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 0 ? Message.forName("everyone").asString() : Message.forName("player").asString()); + ChallengeHelper.playChallengeValueTitle(this, getValue() == 0 ? Message.forName("everyone").asString() : Message.forName("player").asString()); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java index b18a19b55..e2c921710 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -198,8 +198,8 @@ private ItemStack getRandomItem(@NotNull ItemStack blacklisted) { Material material = globalRandom.choose(materials); ItemStack itemStack = new ItemStack(material); - if (itemStack.getItemMeta() instanceof Damageable && 1 < material.getMaxDurability()) { - ((Damageable) itemStack.getItemMeta()).setDamage(globalRandom.range(1, material.getMaxDurability())); + if (itemStack.getItemMeta() instanceof Damageable damageable && 1 < material.getMaxDurability()) { + damageable.setDamage(globalRandom.range(1, material.getMaxDurability())); } else if (1 < itemStack.getMaxStackSize() && globalRandom.nextInt(100) <= 20) { itemStack.setAmount(globalRandom.range(1, itemStack.getMaxStackSize())); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java index 9293c2e2a..1a54651de 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; @@ -36,9 +36,9 @@ public MovementItemRemovingChallenge() { @Override public void playValueChangeTitle() { if (getValue() == BLOCK) - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-block-chunk-item-remove-challenge-block")); + ChallengeHelper.playChallengeValueTitle(this, Message.forName("item-block-chunk-item-remove-challenge-block")); else - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-block-chunk-item-remove-challenge-chunk")); + ChallengeHelper.playChallengeValueTitle(this, Message.forName("item-block-chunk-item-remove-challenge-chunk")); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java index afe6430b7..b383c9206 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.CanInstaKillOnEnable; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java index b7d07b745..610ba2b7d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; @@ -30,7 +30,7 @@ public PickupItemLaunchChallenge() { @Override public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-launcher-description").asString(getValue())); + ChallengeHelper.playChallengeValueTitle(this, Message.forName("subtitle-launcher-description").asString(getValue())); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java index 2711a0f73..2ea295558 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java @@ -2,10 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Bukkit; @@ -13,7 +10,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.*; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 32ed6d162..0bc7c4931 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -3,11 +3,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -17,7 +15,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.stream.Collectors; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java index 1a9c05368..07e2be89c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java @@ -3,9 +3,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; @@ -14,7 +13,6 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @Since("2.0.2") public class FoodLaunchChallenge extends SettingModifier { @@ -31,7 +29,7 @@ public FoodLaunchChallenge() { @Override public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-launcher-description").asString(getValue())); + ChallengeHelper.playChallengeValueTitle(this, Message.forName("subtitle-launcher-description").asString(getValue())); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java index d76155e31..bbf43804b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java @@ -2,12 +2,10 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -40,7 +38,7 @@ public FoodOnceChallenge() { @Override public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 1 ? Message.forName("item-food-once-challenge-player") : Message.forName("item-food-once-challenge-everyone")); + ChallengeHelper.playChallengeValueTitle(this, getValue() == 1 ? Message.forName("item-food-once-challenge-player") : Message.forName("item-food-once-challenge-everyone")); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java index b64ea9f4b..8a427506d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java @@ -3,18 +3,15 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @Since("2.0") @ExcludeFromRandomChallenges diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java index 552167c72..df72ff330 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java @@ -30,7 +30,7 @@ public LowDropRateChallenge() { @Override public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() * 10 + "%"); + ChallengeHelper.playChallengeValueTitle(this, getValue() * 10 + "%"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java index 221ec64bf..82735684a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.misc.NameHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java index 565558436..2691d42bb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java @@ -3,12 +3,13 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; @@ -39,9 +40,9 @@ protected void onEnable() { int count = playerStandingCount.getOrDefault(player, 1); int timeLeft = getValue() - count + 1; - if (timeLeft <= RED) bossbar.setColor(BarColor.RED); - else if (timeLeft <= YELLOW) bossbar.setColor(BarColor.YELLOW); - else bossbar.setColor(BarColor.GREEN); + if (timeLeft <= RED) bossbar.setColor(BossBar.Color.RED); + else if (timeLeft <= YELLOW) bossbar.setColor(BossBar.Color.YELLOW); + else bossbar.setColor(BossBar.Color.GREEN); String time = "§e" + timeLeft + " §7" + (timeLeft == 1 ? Message.forName("second").asString() : Message.forName("seconds").asString()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java index 6ede84852..2723f38a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; @@ -76,7 +76,7 @@ protected void onDisable() { @Override public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-blocks").asString(getBlocksToWalk())); + ChallengeHelper.playChallengeValueTitle(this, Message.forName("subtitle-blocks").asString(getBlocksToWalk())); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java index 032157177..7679c77ce 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java @@ -3,20 +3,17 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.AbstractMap.SimpleEntry; import java.util.HashMap; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java index 702b9d95c..72c25fc61 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.CanInstaKillOnEnable; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java index f91cbdc86..6be7f4fa6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java index d9eb5c97d..e00999f87 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java @@ -3,14 +3,14 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; @@ -19,7 +19,6 @@ import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @Since("1.3") public class TrafficLightChallenge extends TimedChallenge { @@ -48,15 +47,15 @@ public void onEnable() { bossbar.setContent((bossbar, player) -> { // TODO format switch (state) { case GREEN: - bossbar.setColor(BarColor.GREEN); + bossbar.setColor(BossBar.Color.GREEN); bossbar.setTitle("§8{ §a§l■■■ §8} §8{ §7§l■■■ §8} §8{ §7§l■■■ §8}"); break; case YELLOW: - bossbar.setColor(BarColor.YELLOW); + bossbar.setColor(BossBar.Color.YELLOW); bossbar.setTitle("§8{ §7§l■■■ §8} §8{ §e§l■■■ §8} §8{ §7§l■■■ §8}"); break; case RED: - bossbar.setColor(BarColor.RED); + bossbar.setColor(BossBar.Color.RED); bossbar.setTitle("§8{ §7§l■■■ §8} §8{ §7§l■■■ §8} §8{ §c§l■■■ §8}"); break; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index 046c41026..53d28252a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -5,7 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -21,6 +21,7 @@ import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.misc.StringUtils; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; import org.bukkit.boss.BarColor; @@ -72,17 +73,17 @@ public QuizChallenge() { protected void onEnable() { bossbar.setContent((bossbar, player) -> { if (currentQuestion == null) { - bossbar.setColor(BarColor.YELLOW); - bossbar.setTitle(Message.forName("bossbar-quiz-waiting").asString()); + bossbar.setColor(BossBar.Color.YELLOW); + bossbar.setTitle(MessageKey.of("bossbar-quiz-waiting")); return; } String time = "§e" + timeLeft + " §7" + (timeLeft == 1 ? Message.forName("second").asString() : Message.forName("seconds").asString()); if (currentQuestionedPlayer != player) { - bossbar.setColor(BarColor.GREEN); + bossbar.setColor(BossBar.Color.GREEN); bossbar.setTitle(Message.forName("bossbar-quiz-question-other").asString(time, NameHelper.getName(currentQuestionedPlayer))); return; } - bossbar.setColor(BarColor.RED); + bossbar.setColor(BossBar.Color.RED); bossbar.setTitle(Message.forName("bossbar-quiz-question").asString(time)); }); bossbar.show(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java index 333429606..3a1bee28b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java @@ -6,9 +6,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.ChallengeAnnotations; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -43,11 +43,11 @@ public void playValueChangeTitle() { protected void onEnable() { bossbar.setContent((bossbar, player) -> { if (lastUsed == null) { - bossbar.setTitle(Message.forName("bossbar-random-challenge-waiting").asString()); + bossbar.setTitle(getChallengeMessageKey("bossbar-waiting")); return; } bossbar.setProgress(getProgress()); - bossbar.setTitle(Message.forName("bossbar-random-challenge-current").asString(ChallengeHelper.getColoredChallengeName(lastUsed))); + bossbar.setTitle(getChallengeMessageKey("bossbar-current"), lastUsed.getChallengeName()); }); bossbar.show(); } @@ -84,14 +84,13 @@ protected void onTimeActivation() { challenges.remove(this); challenges.removeIf(challenge -> challenge.getType() != MenuType.CHALLENGES); challenges.removeIf(challenge -> !(challenge instanceof AbstractChallenge)); - challenges.removeIf(ChallengeHelper::canInstaKillOnEnable); - challenges.removeIf(ChallengeHelper::isExcludedFromRandomChallenges); + challenges.removeIf(ChallengeAnnotations::isCanInstaKillOnEnable); + challenges.removeIf(ChallengeAnnotations::isExcludedFromRandomChallenges); challenges.removeIf(IChallenge::isEnabled); if (challenges.isEmpty()) return; AbstractChallenge challenge = (AbstractChallenge) globalRandom.choose(challenges); - String name = ChallengeHelper.getColoredChallengeName(challenge); - Message.forName("random-challenge-enabled").broadcast(Prefix.CHALLENGES, name); + getChallengeMessageKey("challenge-enabled").broadcast(Prefix.CHALLENGES, challenge.getChallengeName(), challenge.getChallengeDescription()); setEnabled(challenge, true); lastUsed = challenge; @@ -100,17 +99,14 @@ protected void onTimeActivation() { } private void setEnabled(@NotNull IChallenge challenge, boolean enabled) { - if (challenge instanceof Setting) { - Setting setting = (Setting) challenge; + if (challenge instanceof Setting setting) { setting.setEnabled(enabled); } - if (challenge instanceof SettingModifier) { - SettingModifier setting = (SettingModifier) challenge; + if (challenge instanceof SettingModifier setting) { setting.setEnabled(enabled); } - if (enabled && challenge instanceof TimedChallenge) { - TimedChallenge timedChallenge = (TimedChallenge) challenge; + if (enabled && challenge instanceof TimedChallenge timedChallenge) { if (timedChallenge.isTimerRunning()) { int seconds = globalRandom.range(10, 20); if (seconds < timedChallenge.getSecondsLeftUntilNextActivation()) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java index da9bde90c..eb402d913 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java @@ -3,11 +3,10 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; @@ -22,7 +21,6 @@ import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @Since("2.0") public class RandomEventChallenge extends TimedChallenge { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java index e170b2336..27ff693b5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java @@ -3,13 +3,13 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; import org.bukkit.block.Biome; -import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; @@ -28,8 +28,8 @@ protected void onEnable() { bossbar.setContent((bossbar, player) -> { int currentTime = getCurrentTime(player); int maxTime = (getValue() * 60); - bossbar.setTitle(Message.forName("bossbar-biome-time-left").asComponent(getBiome(player), maxTime - currentTime)); - bossbar.setColor(BarColor.GREEN); + bossbar.setTitle(MessageKey.of("bossbar-biome-time-left"), getBiome(player), maxTime - currentTime); + bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(1 - ((float) currentTime / maxTime)); }); bossbar.show(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java index c4484b187..4ed019479 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java @@ -3,10 +3,12 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.boss.BarColor; @@ -28,8 +30,8 @@ protected void onEnable() { bossbar.setContent((bossbar, player) -> { int currentTime = getCurrentTime(player); int maxTime = (getValue() * 60); - bossbar.setTitle(Message.forName("bossbar-height-time-left").asString(player.getLocation().getBlockY(), maxTime - currentTime)); - bossbar.setColor(BarColor.GREEN); + bossbar.setTitle(MessageKey.of("bossbar-height-time-left"), player.getLocation().getBlockY(), maxTime - currentTime); + bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(1 - ((float) currentTime / maxTime)); }); bossbar.show(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java index 1749a7028..1838330b2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java @@ -1,10 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.*; @@ -13,7 +11,6 @@ import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java index fa492eea1..7b632b032 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java @@ -1,11 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.commons.common.collection.pair.Tuple; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.*; import org.bukkit.World.Environment; import org.bukkit.block.Block; @@ -37,7 +38,7 @@ public ChunkDeletionChallenge() { protected void onEnable() { bossbar.setContent((bossbar, player) -> { Message message = Message.forName("bossbar-chunk-deletion"); - bossbar.setColor(BarColor.PINK); + bossbar.setColor(BossBar.Color.PINK); if (!checkIfAllowed(player)) { Tuple taskTuple = chunks.get(player.getLocation().getChunk()); if (taskTuple != null) { @@ -54,7 +55,7 @@ protected void onEnable() { long remainingTime = calculateRemainingTime(timeStamp); bossbar.setTitle(message.asString(remainingTime)); - bossbar.setProgress((double) remainingTime / getValue()); + bossbar.setProgress((float) remainingTime / getValue()); }); bossbar.show(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java index 2de35e5ac..d7c2835f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java @@ -3,10 +3,11 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; @@ -36,7 +37,7 @@ public IceFloorChallenge() { protected void onEnable() { bossbar.setContent((bossbar, player) -> { bossbar.setTitle(Message.forName("bossbar-ice-floor").asString(ignoreIce(player) ? Message.forName("disabled") : Message.forName("enabled"))); - bossbar.setColor(ignoreIce(player) ? BarColor.RED : BarColor.GREEN); + bossbar.setColor(ignoreIce(player) ? BossBar.Color.RED : BossBar.Color.GREEN); }); bossbar.show(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java index 0b1299752..dc9490c4c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java @@ -5,7 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index 55260e723..98862406b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index 49041194e..bedb5949a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java index 1fca0c5f6..07c0fe756 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java @@ -1,10 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.*; @@ -13,7 +11,6 @@ import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java index 2202e4439..d3435aa78 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java @@ -4,12 +4,13 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.commons.common.config.Document; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Material; @@ -70,10 +71,10 @@ protected void onEnable() { bossbar.setProgress(getProgress()); if (environment == Environment.NORMAL) { - bossbar.setColor(BarColor.BLUE); + bossbar.setColor(BossBar.Color.BLUE); bossbar.setTitle(Message.forName("bossbar-tsunami-water").asString(waterHeight)); } else if (environment == Environment.NETHER) { - bossbar.setColor(BarColor.RED); + bossbar.setColor(BossBar.Color.RED); bossbar.setTitle(Message.forName("bossbar-tsunami-lava").asString(lavaHeight)); } else { bossbar.setVisible(false); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java index 502c80daa..9f774fb35 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index c6e9fb467..29c69d305 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -4,9 +4,9 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; @@ -17,6 +17,7 @@ import net.codingarea.commons.bukkit.utils.item.ItemUtils; import net.codingarea.commons.common.collection.SeededRandomWrapper; import net.codingarea.commons.common.config.Document; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.command.CommandSender; @@ -32,7 +33,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.stream.Collectors; @Since("2.0") public class CollectAllItemsGoal extends SettingGoal implements SenderCommand { @@ -78,13 +78,12 @@ private void nextItem() { protected void onEnable() { bossbar.setContent((bossbar, player) -> { if (currentItem == null) { - bossbar.setTitle(Message.forName("bossbar-all-items-finished").asString()); + bossbar.setTitle(MessageKey.of("bossbar-all-items-finished")); + bossbar.setColor(BossBar.Color.GREEN); return; } - bossbar.setTitle(Message.forName("bossbar-all-items-current-max").asComponent( - getItemDisplayName(currentItem), - totalItemsCount - itemsToFind.size() + 1, - totalItemsCount)); + int foundItemsCount = totalItemsCount - itemsToFind.size() + 1; + bossbar.setTitle(MessageKey.of("bossbar-all-items-current-max"), currentItem, foundItemsCount, totalItemsCount); }); bossbar.show(); } @@ -107,7 +106,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr return; } - MessageKey.of("all-items-skipped").broadcast(Prefix.CHALLENGES, getItemDisplayName(currentItem)); + MessageKey.of("all-items-skipped").broadcast(Prefix.CHALLENGES, currentItem); SoundSample.PLING.broadcast(); nextItem(); bossbar.update(); @@ -141,7 +140,7 @@ protected void handleNewItem(@Nullable Material material, @NotNull Player player if (!shouldExecuteEffect()) return; if (ignorePlayer(player)) return; if (currentItem != material) return; - Message.forName("all-items-found").broadcast(Prefix.CHALLENGES, getItemDisplayName(currentItem), NameHelper.getName(player)); + MessageKey.of("all-items-found").broadcast(Prefix.CHALLENGES, currentItem, player); SoundSample.PLING.broadcast(); nextItem(); bossbar.update(); @@ -167,32 +166,4 @@ public void writeGameState(@NotNull Document document) { document.set("seed", random.getSeed()); document.set("found", totalItemsCount - itemsToFind.size()); } - - private String getItemDisplayName(@Nullable Material material) { - if (material == null) return "Unbekannt"; - - String name = material.name(); - - if (name.contains("SMITHING_TEMPLATE")) { - String prefix = name.replace("_SMITHING_TEMPLATE", ""); - String formattedPrefix = Arrays.stream(prefix.split("_")) - .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) - .collect(Collectors.joining(" ")); - - return formattedPrefix + " Smithing template"; - } - - if (name.endsWith("_BANNER_PATTERN")) { - String prefix = name.replace("_BANNER_PATTERN", ""); - String formattedPrefix = Arrays.stream(prefix.split("_")) - .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) - .collect(Collectors.joining(" ")); - - return formattedPrefix + " Banner Pattern"; - } - - return Arrays.stream(name.split("_")) - .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) - .collect(Collectors.joining(" ")); - } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java index 9176ae11a..480d902fa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java @@ -25,9 +25,8 @@ public CollectMostItemsGoal() { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPickUp(@NotNull EntityPickupItemEvent event) { if (!isEnabled()) return; - if (!(event.getEntity() instanceof Player)) return; + if (!(event.getEntity() instanceof Player player)) return; - Player player = (Player) event.getEntity(); ItemStack item = event.getItem().getItemStack(); handleNewItem(item.getType(), player); } @@ -35,9 +34,8 @@ public void onPickUp(@NotNull EntityPickupItemEvent event) { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onClick(@NotNull InventoryClickEvent event) { if (!shouldExecuteEffect()) return; - if (!(event.getWhoClicked() instanceof Player)) return; + if (!(event.getWhoClicked() instanceof Player player)) return; - Player player = (Player) event.getWhoClicked(); ItemStack item = event.getCurrentItem(); if (item == null) return; if (!ItemUtils.isObtainableInSurvival(item.getType())) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java index 363703726..ef0d52271 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java @@ -1,15 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierCollectionGoal; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java index 219d72768..567dfd441 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesGoal.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java index bd77fbf0a..5d5b8a4d9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllBossesNewGoal.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.RequireVersion; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java index d337fe4e1..ae596c6e8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java index 0c044d35d..7aa9481c6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.KillMobsGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java index 4e5a8371e..5b2e76173 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java @@ -2,11 +2,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.SettingCategory; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Material; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java index 1af043688..7ea4574c6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java @@ -5,7 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -17,13 +17,13 @@ import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.config.Document; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Particle.DustOptions; import org.bukkit.World; import org.bukkit.World.Environment; -import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -47,7 +47,7 @@ public RaceGoal() { @Override public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("subtitle-range-blocks").asString(getValue() * 100)); + ChallengeHelper.playChallengeValueTitle(this, Message.forName("subtitle-range-blocks").asString(getValue() * 100)); } // @Nullable @@ -64,7 +64,7 @@ public void getWinnersOnEnd(@NotNull List winners) { protected void onEnable() { reloadGoalLocation(); bossbar.setContent((bar, player) -> { - bar.setColor(BarColor.GREEN); + bar.setColor(BossBar.Color.GREEN); if (player.getWorld() == goal.getWorld()) { Location relativeGoal = goal.clone(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java index eaa0c73ce..53da4a1ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.*; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java index b63db7b42..844a81597 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.AdvancementTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java index f02e6cbeb..4ac5bd82f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.BiomeTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.commons.common.config.Document; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java index bfda815a8..9d833b4ea 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.BlockTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java index bb95de040..47f0e6e24 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.DamageTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java index 41517f417..9e37253f1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.HeightTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java index f0fd80075..bd047049d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ItemTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java index 582c8d3bc..a229923e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.MobTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; import org.bukkit.entity.EntityType; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java index 02b666faa..ba518f7de 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.PositionTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.commons.common.config.Document; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java index 2cc333635..fe3986630 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import org.bukkit.Bukkit; import org.bukkit.advancement.Advancement; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java index ddf3035f0..4f3d71899 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import org.bukkit.block.Biome; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java index 088da9146..f7e1464c3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java index 9ac2322ed..c991be1be 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import org.bukkit.entity.Player; public class DamageTarget extends ForceTarget { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java index 7e7f2de90..c4d99aabb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java @@ -2,7 +2,7 @@ import lombok.Getter; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import org.bukkit.Material; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java index efd616946..d4f38e9de 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import org.bukkit.entity.Player; public class HeightTarget extends ForceTarget { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java index d775f5a09..f2b345c2c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.commons.bukkit.utils.item.ItemUtils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java index ba9f60a2c..b0eb6d41e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; import net.codingarea.challenges.plugin.utils.misc.Utils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java index 43b898f20..3b6634bc9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.commons.common.config.Document; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java index dd75e4816..eee7396d2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java @@ -5,15 +5,13 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeConfigHelper; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.bukkit.container.BukkitSerialization; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; @@ -61,13 +59,13 @@ public ItemStack getSettingsItemPreset() { public void playValueChangeTitle() { switch (getValue()) { case SHARED: - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-backpack-setting-team")); + ChallengeHelper.playChallengeValueTitle(this, Message.forName("item-backpack-setting-team")); break; case PLAYER: - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-backpack-setting-player")); + ChallengeHelper.playChallengeValueTitle(this, Message.forName("item-backpack-setting-player")); break; default: - ChallengeHelper.playToggleChallengeTitle(this, false); + ChallengeHelper.playChallengeToggleTitle(this, false); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java index 212e885ee..887b3b079 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BastionSpawnSetting.java @@ -18,7 +18,7 @@ public class BastionSpawnSetting extends NetherPortalSpawnSetting { public BastionSpawnSetting() { - super(MenuType.SETTINGS, null, StructureType.BASTION_REMNANT, new ItemStack(Material.NETHER_BRICK_STAIRS), + super(MenuType.SETTINGS, null, StructureType.BASTION_REMNANT, new ItemStack(Material.POLISHED_BLACKSTONE_BRICKS), "bastion-spawn", "unable-to-find-bastion", Arrays.stream(ExperimentalUtils.getMaterials()).filter(material -> material.name().contains("BASALT")).collect(Collectors.toList())); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java index 2898f3f8b..3ce398337 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java @@ -4,10 +4,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.menu.MenuSetting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.DropPriority; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java index faae3fc69..1140d1a4e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java @@ -3,24 +3,18 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.stats.Statistic.Display; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; -import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Material; -import org.bukkit.entity.Entity; import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; -import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.inventory.ItemStack; -import org.bukkit.projectiles.ProjectileSource; import org.jetbrains.annotations.NotNull; public class DamageDisplaySetting extends Setting { @@ -29,43 +23,6 @@ public DamageDisplaySetting() { super(MenuType.SETTINGS, null, true, new ItemStack(Material.COMMAND_BLOCK), "damage-display"); } - public static String getCause(@NotNull EntityDamageEvent event) { - - if (event.getCause() == DamageCause.CUSTOM) return Message.forName("undefined").asString(); - String cause = StringUtils.getEnumName(event.getCause()); - - if (event instanceof EntityDamageByEntityEvent) { - - EntityDamageByEntityEvent damageEvent = (EntityDamageByEntityEvent) event; - if (damageEvent.getDamager() instanceof Player) { - Player damager = (Player) damageEvent.getDamager(); - cause += " §8(§7" + NameHelper.getName(damager) + "§8)"; - } else if (damageEvent.getDamager() instanceof Projectile) { - Projectile projectile = (Projectile) damageEvent.getDamager(); - cause = StringUtils.getEnumName(projectile.getType()); - String damager = ""; - ProjectileSource shooter = projectile.getShooter(); - if (shooter instanceof Entity) { - Entity entity = (Entity) shooter; - if (entity instanceof Player) { - Player playerDamager = (Player) entity; - damager = NameHelper.getName(playerDamager); - } else { - damager = StringUtils.getEnumName(entity.getType()); - } - } - - if (!cause.contains(damager)) - cause += " §8(§7" + damager + "§8)"; - } else { - String damager = StringUtils.getEnumName(damageEvent.getDamager().getType()); - if (!cause.contains(damager)) - cause += " §8(§7" + damager + "§8)"; - } - } - return cause; - } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onDamage(@NotNull EntityDamageEvent event) { if (ChallengeAPI.isPaused() || event.getCause() == DamageCause.CUSTOM || !isEnabled()) @@ -73,8 +30,8 @@ public void onDamage(@NotNull EntityDamageEvent event) { if (!(event.getEntity() instanceof Player)) return; if (ChallengeHelper.finalDamageIsNull(event)) return; - double damage = event.getFinalDamage(); - String damageDisplay = damage >= 1000 ? "∞" : Display.HEARTS.formatChat(damage); - Message.forName("player-damage-display").broadcast(Prefix.DAMAGE, NameHelper.getName((Player) event.getEntity()), damageDisplay, getCause(event)); + LocalizableMessage damageDisplay = ArgumentFormat.HEARTS_LIMITED.apply(event.getFinalDamage()); + LocalizableMessage causeDisplay = ArgumentFormat.DAMAGE_CAUSE.apply(event); + MessageKey.of("player-damage-display").broadcast(Prefix.DAMAGE, event.getEntity(), damageDisplay, causeDisplay); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java index c9fd8a10e..f58e2fbde 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java @@ -2,11 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -21,11 +17,11 @@ public DamageMultiplierModifier() { super(MenuType.SETTINGS, null, 10, new ItemStack(Material.STONE_SWORD), "damage-multiplier-setting"); } - @NotNull - @Override - public LocalizableMessage getSettingsName() { - return super.getSettingsName(); // TODO format - } +// @NotNull +// @Override +// public LocalizableMessage getSettingsName() { +// return super.getSettingsName(); // TODO format +// } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onDamage(@NotNull EntityDamageEvent event) { @@ -35,7 +31,7 @@ public void onDamage(@NotNull EntityDamageEvent event) { @Override public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() + "x"); + ChallengeHelper.playChallengeValueTitle(this, getValue() + "x"); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java index 854143a0b..1ba0d43d9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java @@ -2,14 +2,14 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.DefaultItems; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -47,37 +47,44 @@ public ItemStack getSettingsItemPreset() { public void playValueChangeTitle() { switch (getValue()) { case ENABLED: - ChallengeHelper.playToggleChallengeTitle(this, true); + ChallengeHelper.playChallengeToggleTitle(this, true); return; case VANILLA: - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName("item-death-message-setting-vanilla")); + ChallengeHelper.playChallengeValueTitle(this, Message.forName("item-death-message-setting-vanilla")); return; default: - ChallengeHelper.playToggleChallengeTitle(this, false); + ChallengeHelper.playChallengeToggleTitle(this, false); } } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onDeath(@NotNull PlayerDeathEvent event) { - event.setDeathMessage(null); - if (hide) return; + if (hide) { + event.deathMessage(null); + return; + } - String original = event.getDeathMessage(); - Player entity = event.getEntity(); + Player player = event.getEntity(); switch (getValue()) { - case ENABLED: - EntityDamageEvent cause = entity.getLastDamageCause(); + case ENABLED -> { + EntityDamageEvent cause = player.getLastDamageCause(); if (cause != null && cause.getCause() != DamageCause.CUSTOM) { - Message.forName("death-message-cause").broadcast(Prefix.CHALLENGES, NameHelper.getName(entity), DamageDisplaySetting.getCause(cause)); + MessageKey.of("death-message-cause").broadcast(Prefix.CHALLENGES, player, ArgumentFormat.DAMAGE_CAUSE.apply(cause)); } else { - Message.forName("death-message").broadcast(Prefix.CHALLENGES, NameHelper.getName(entity)); + MessageKey.of("death-message").broadcast(Prefix.CHALLENGES, player); } - return; - case VANILLA: + } + case VANILLA -> { + Component original = event.deathMessage(); if (original != null) { - Bukkit.broadcastMessage(Prefix.CHALLENGES + "§7" + original); + for (Player target : Bukkit.getOnlinePlayers()) { + target.sendMessage(Component.text().append(Prefix.CHALLENGES.getKey().asComponent(player)).append(original)); + } } + } } + + event.deathMessage(null); } public void setHideMessagesTemporarily(boolean hide) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java index 70901043f..1c18390e4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java @@ -3,19 +3,15 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; -import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.common.config.Document; -import net.md_5.bungee.api.ChatColor; -import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TranslatableComponent; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextColor; import org.bukkit.Bukkit; import org.bukkit.Difficulty; import org.bukkit.Material; @@ -41,30 +37,28 @@ public DifficultySetting() { @NotNull @Override public ItemStack getSettingsItemPreset() { - switch (getValue()) { - case 0: - return DefaultItem.create(Material.LIME_DYE, getDifficultyName()).build(); - case 1: - return DefaultItem.create(MinecraftNameWrapper.GREEN_DYE, getDifficultyName()).build(); - case 2: - return DefaultItem.create(Material.ORANGE_DYE, getDifficultyName()).build(); - default: - return DefaultItem.create(MinecraftNameWrapper.RED_DYE, getDifficultyName()).build(); - } + return switch (getDifficultyByValue(getValue())) { + case PEACEFUL -> new ItemStack(Material.LIME_DYE); + case EASY -> new ItemStack(MinecraftNameWrapper.GREEN_DYE); + case NORMAL -> new ItemStack(Material.ORANGE_DYE); + case HARD -> new ItemStack(MinecraftNameWrapper.RED_DYE); + }; } + @NotNull @Override - protected void onValueChange() { - setDifficulty(getDifficultyByValue(getValue())); + public Component getSettingsName() { + return getDifficultyComponent(); } - private String getDifficultyName() { - return getDifficultyComponent().toLegacyText(); + @Override + protected void onValueChange() { + setDifficulty(getDifficultyByValue(getValue())); } @Override public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getDifficultyName()); + ChallengeHelper.playChallengeValueTitle(this, getDifficultyComponent()); } private void setDifficulty(Difficulty difficulty) { @@ -98,7 +92,7 @@ public void loadSettings(@NotNull Document document) { public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (args.length == 0) { - MessageKey.of("command-difficulty-current").send(sender, Prefix.CHALLENGES, getDifficultyComponent()); + getChallengeMessageKey("command-current").send(sender, Prefix.CHALLENGES, getDifficultyComponent()); return; } @@ -109,27 +103,24 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr } setValue(difficulty); - Message.forName("command-difficulty-change").broadcast(Prefix.CHALLENGES, getDifficultyComponent()); + getChallengeMessageKey("command-set").broadcast(Prefix.CHALLENGES, getDifficultyComponent()); + playValueChangeTitle(); + } + @NotNull + private Component getDifficultyComponent() { + Difficulty difficulty = getDifficultyByValue(getValue()); + return Component.translatable(difficulty).color(getDifficultyColor(difficulty)); } - private BaseComponent getDifficultyComponent() { - TranslatableComponent name = BukkitStringUtils.getDifficultyName(getDifficultyByValue(getValue())); - switch (getValue()) { - case 0: - name.setColor(ChatColor.GREEN); - break; - case 1: - name.setColor(ChatColor.DARK_GREEN); - break; - case 2: - name.setColor(ChatColor.GOLD); - break; - default: - name.setColor(ChatColor.RED); - break; - } - return name; + @NotNull + private TextColor getDifficultyColor(@NotNull Difficulty difficulty) { + return switch (difficulty) { + case PEACEFUL -> NamedTextColor.DARK_GREEN; + case EASY -> NamedTextColor.GREEN; + case NORMAL -> NamedTextColor.GOLD; + case HARD -> NamedTextColor.RED; + }; } @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java index 2a893a977..f10af5a85 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/FortressSpawnSetting.java @@ -2,13 +2,10 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.NetherPortalSpawnSetting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Material; import org.bukkit.StructureType; import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; @Since("2.0") public class FortressSpawnSetting extends NetherPortalSpawnSetting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HardcoreHeartsSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HardcoreHeartsSetting.java new file mode 100644 index 000000000..066f4a9eb --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HardcoreHeartsSetting.java @@ -0,0 +1,87 @@ +package net.codingarea.challenges.plugin.challenges.implementation.setting; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.*; +import com.comphenix.protocol.reflect.accessors.FieldAccessor; +import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.RequireDepend; +import net.codingarea.challenges.plugin.challenges.type.annotation.Since; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.lang.reflect.Field; +import java.util.List; + +@Since("2.4") +@RequireDepend(plugin = "ProtocolLib") +public class HardcoreHeartsSetting extends Setting { + + private PacketListener packetListener; + + public HardcoreHeartsSetting() { + super(MenuType.SETTINGS, null, true, new ItemStack(Material.RED_CANDLE), "hardcore-hearts"); + } + + @Override + protected void onEnable() { + ProtocolManager manager = ProtocolLibrary.getProtocolManager(); + manager.addPacketListener(packetListener = createPacketListener()); + } + + @Override + protected void onDisable() { + if (packetListener != null) { + ProtocolManager manager = ProtocolLibrary.getProtocolManager(); + manager.removePacketListener(packetListener); + } + } + + private PacketAdapter createPacketListener() { + return new PacketAdapter(plugin, ListenerPriority.NORMAL, + PacketType.Play.Server.LOGIN, PacketType.Play.Server.RESPAWN) { + + @Override + public void onPacketSending(PacketEvent event) { + PacketContainer packet = event.getPacket(); + + // Dynamically look up the index for safety + int hardcoreIndex = getHardcoreFieldIndex(packet); + + if (hardcoreIndex != -1) { + // Found it cleanly by name! + packet.getBooleans().write(hardcoreIndex, true); + } else { + // Fallback default just in case a future mapping changes things + if (packet.getBooleans().size() > 0) { + packet.getBooleans().write(0, true); + } + } + } + }; + } + + /** + * Finds the ProtocolLib boolean index for the 'hardcore' flag. + * * @param packet The packet container to scan (e.g., LOGIN or RESPAWN) + * @return The integer index for .getBooleans(), or -1 if not found. + */ + public int getHardcoreFieldIndex(PacketContainer packet) { + // Grab the internal list of fields filtered down to just booleans + List booleanFields = packet.getBooleans().getFields(); + + for (int i = 0; i < booleanFields.size(); i++) { + Field field = booleanFields.get(i).getField(); + + // Match against Mojang official field name + if (field.getName().equals("hardcore")) { + return i; + } + } + + // Field wasn't found by name + return -1; + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java index 45c32a9c8..92514f061 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java @@ -2,9 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Bukkit; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java index cb22597da..0867c5d1c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java @@ -2,10 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.management.menu.MenuType; -import org.bukkit.Bukkit; -import org.bukkit.GameRule; -import org.bukkit.Material; -import org.bukkit.World; +import org.bukkit.*; import org.bukkit.inventory.ItemStack; public class KeepInventorySetting extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java index 995157a0b..5bec83fe3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java @@ -3,58 +3,142 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.LanguageProvider; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; +import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; +import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; +import net.codingarea.challenges.plugin.utils.misc.Utils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; +import net.codingarea.commons.common.config.Document; +import net.kyori.adventure.text.Component; import org.bukkit.Material; +import org.bukkit.command.CommandSender; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -public class LanguageSetting extends Modifier { +import java.util.List; +import java.util.Map; + +public class LanguageSetting extends Modifier implements SenderCommand, Completer { public static final int ENGLISH = 1; public static final int GERMAN = 2; + // TODO centralize registry using LanguageLoader + private static final Map TAG_TO_VALUE = Map.of("en", ENGLISH, "de", GERMAN); + private static final Map VALUE_TO_TAG = Map.of(ENGLISH, "en", GERMAN, "de"); + public static final String GERMAN_SKULL = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNWU3ODk5YjQ4MDY4NTg2OTdlMjgzZjA4NGQ5MTczZmU0ODc4ODY0NTM3NzQ2MjZiMjRiZDhjZmVjYzc3YjNmIn19fQ", ENGLISH_SKULL = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvODgzMWM3M2Y1NDY4ZTg4OGMzMDE5ZTI4NDdlNDQyZGZhYTg4ODk4ZDUwY2NmMDFmZDJmOTE0YWY1NDRkNTM2OCJ9fX0"; public LanguageSetting() { - super(MenuType.SETTINGS, null, 1, 2, ENGLISH, new ItemStack(Material.KNOWLEDGE_BOOK), "language-setting"); + super(MenuType.SETTINGS, null, 1, TAG_TO_VALUE.size(), ENGLISH, new ItemStack(Material.KNOWLEDGE_BOOK), "language"); } @NotNull @Override public ItemStack getSettingsItemPreset() { - return super.getSettingsItemPreset(); + return switch (getValue()) { + case GERMAN -> new StandardItemBuilder.SkullBuilder().setBase64Texture(GERMAN_SKULL).build(); + case ENGLISH -> new StandardItemBuilder.SkullBuilder().setBase64Texture(ENGLISH_SKULL).build(); + default -> new ItemStack(Material.BARRIER); + }; + } + + @NotNull + @Override + public LocalizableMessage getSettingsName() { + String languageTag = VALUE_TO_TAG.get(getValue()); + if (languageTag == null) return MessageKey.of("generic.unknown"); + return getLanguageName(languageTag); } -// @NotNull -// @Override -// public LegacyItemBuilder createSettingsItem() { -// String texture = getValue() == GERMAN ? GERMAN_SKULL : ENGLISH_SKULL; -// return new LegacyItemBuilder.SkullBuilder(DefaultItem.getItemPrefix() + Message.forName(getSettingName())).setBase64Texture(texture).hideAttributes(); -// } + @NotNull + private MessageKey getLanguageName(@NotNull String languageTag) { + return MessageKey.of("language." + languageTag); + } @Override public void playValueChangeTitle() { - switch (getValue()) { - case GERMAN: - Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class).changeLanguage("de"); - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName(getSettingName())); - break; - case ENGLISH: - Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class).changeLanguage("en"); - ChallengeHelper.playChangeChallengeValueTitle(this, Message.forName(getSettingName())); - break; - default: - ChallengeHelper.playToggleChallengeTitle(this, false); + ChallengeHelper.playChallengeValueTitle(this, getSettingsName()); + } + + @Override + public void handleClick(@NotNull ChallengeMenuClickInfo info) { + LanguageProvider languageProvider = Challenges.getInstance().getTranslationManager().getLanguageProvider(); + if (!languageProvider.isDefaultBehaviour()) { + getChallengeMessageKey("command-disabled").send(info.getPlayer(), Prefix.CHALLENGES); + SoundSample.BASS_OFF.play(info.getPlayer()); + return; } + + super.handleClick(info); + } + + @Override + protected void onValueChange() { + LanguageLoader languageLoader = Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class); + String languageTag = VALUE_TO_TAG.get(getValue()); + if (languageTag == null) return; + + Challenges.getInstance().runAsync(() -> { + languageLoader.changeLanguage(languageTag); + getChallengeMessageKey("command-changed").broadcast(Prefix.CHALLENGES, getLanguageName(languageTag), languageTag); + }); } - private String getSettingName() { - return getValue() == GERMAN ? "item-language-setting-german" : "item-language-setting-english"; + @Override + public void loadSettings(@NotNull Document document) { + // will be saved in plugin.yml + LanguageLoader languageLoader = Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class); + Integer value = TAG_TO_VALUE.get(languageLoader.getConfigLanguageTag()); + if (value == null) return; + overwriteValue(value); // don't trigger change language logic! + } + + @Override + public void writeSettings(@NotNull Document document) { + // will be saved in plugin.yml (saved by LanguageLoader) + } + + @Override + public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { + if (args.length < 1) { + MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "setlang "); + return; + } + + LanguageProvider languageProvider = Challenges.getInstance().getTranslationManager().getLanguageProvider(); + if (!languageProvider.isDefaultBehaviour()) { + getChallengeMessageKey("command-disabled").send(sender, Prefix.CHALLENGES); + return; + } + + String languageTag; + switch (args[0].toLowerCase()) { + case "german", "deutsch", "de" -> languageTag = "de"; + case "english", "englisch", "en" -> languageTag = "en"; + default -> { + getChallengeMessageKey("command-unknown").send(sender, Prefix.CHALLENGES, Component.text(args[0])); + return; + } + } + + getChallengeMessageKey("command-changing").send(sender, Prefix.CHALLENGES, languageTag); + + int value = TAG_TO_VALUE.get(languageTag); + setValue(value); // trigger change language logic } + @Override + public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { + return Utils.filterRecommendations(args[0], "german", "english"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index 23847f498..3cfcfa797 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -2,12 +2,10 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.commons.common.config.Document; @@ -36,7 +34,7 @@ public MaxHealthSetting() { @NotNull @Override public LocalizableMessage getSettingsName() { - return MessageKey.of("").withArgs(getValue(), getValue() / 2); // TODO + return ArgumentFormat.HP.apply(getValue()); } @Override @@ -86,7 +84,7 @@ private void updateHealth(Player player) { if (oldMaxHealth < newMaxHealth) { double oldHealth = player.getHealth(); double newHealth = oldHealth + (newMaxHealth - oldMaxHealth); - player.setHealth(Math.min(Math.max(newHealth, 0), newMaxHealth)); + player.setHealth(Math.clamp(newHealth, 0, newMaxHealth)); } if (MinecraftVersion.current().isNewerThan(MinecraftVersion.V1_19)) { player.sendHealthUpdate(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java index ded42a6df..736464f25 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MobGriefingSetting.java @@ -1,15 +1,12 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Bukkit; import org.bukkit.GameRule; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; public class MobGriefingSetting extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java index 43f4d76d5..e05fe9679 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoHitDelaySetting.java @@ -2,9 +2,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.LivingEntity; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java index ae8fdc1c3..46157e4eb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoItemDamageSetting.java @@ -1,14 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerItemDamageEvent; import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; public class NoItemDamageSetting extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java index a8df39eb4..0ecee1bdc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OldPvPSetting.java @@ -2,9 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java index 07203d2c3..e14df1b2a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/OneTeamLifeSetting.java @@ -3,9 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java index 2aab9801b..362d0004d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java @@ -4,12 +4,11 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeConfigHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; @@ -73,7 +72,6 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) { .filter(entry -> player.getWorld() == entry.getValue().getWorld()) .sorted(Comparator.>comparingDouble(entry -> entry.getValue().distance(player.getLocation())).reversed()) .forEach(entry -> { - Location location = entry.getValue(); MessageKey.of("position").send(player, Prefix.POSITION, location.getBlockX(), location.getBlockY(), location.getBlockZ(), getWorldName(location), entry.getKey(), (int) location.distance(player.getLocation())); }); @@ -93,7 +91,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) { SoundSample.BASS_OFF.play(player); } else { positions.put(name, position = player.getLocation()); - Message.forName("position-set").broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, NameHelper.getName(player)); + MessageKey.of("position-set").broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, player); SoundSample.BASS_ON.play(player); broadcastParticleLine(position); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java index 8b51b3c42..6eeac99af 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PregameMovementSetting.java @@ -2,18 +2,24 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.challenges.type.annotation.Updated; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.block.Block; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; +import java.util.Collection; + +@Updated("2.4") public class PregameMovementSetting extends Setting { public PregameMovementSetting() { @@ -32,20 +38,59 @@ public void onMove(@NotNull PlayerMoveEvent event) { Location target = event.getFrom().clone(); target.setY(target.getBlockY()); - findNearestBlock(target); - target.add(0, 1, 0); + + BoundingBox playerBoundingBox = event.getPlayer().getBoundingBox(); + if (event.getPlayer().getLocation().equals(event.getTo())) { + Vector shiftVector = event.getFrom().toVector().subtract(event.getPlayer().getLocation().toVector()); + playerBoundingBox = playerBoundingBox.clone().shift(shiftVector); + } + findMaxBlockHeightBelow(target, playerBoundingBox); target.setPitch(to.getPitch()); target.setYaw(to.getYaw()); - target.setDirection(to.getDirection()); event.setTo(target); - Message.forName("title-pregame-movement-setting").sendTitleInstant(event.getPlayer()); + getChallengeMessageKey("title").sendTitleInstantly(event.getPlayer()); + } + + private void findMaxBlockHeightBelow(@NotNull Location location, @NotNull BoundingBox playerBounds) { + Location originalPlayerLocation = location.clone(); + + while (location.getBlockY() > BukkitReflectionUtils.getMinHeight(location.getWorld()) + && (location.getBlock().isPassable() || getTrueStandY(location.getBlock(), originalPlayerLocation, playerBounds) == location.getBlockY())) { + location.subtract(0, 1, 0); + } + + location.setY(getTrueStandY(location.getBlock(), originalPlayerLocation, playerBounds)); } - private void findNearestBlock(@NotNull Location location) { - for (; location.getBlockY() > 0 && location.getBlock().isPassable(); location.subtract(0, 1, 0)) - ; + public double getTrueStandY(@NotNull Block block, @NotNull Location playerLocation, @NotNull BoundingBox playerBounds) { + // getCollisionShape() tracks the actual physical barriers (1.5 for walls/fences) + Collection boxes = block.getCollisionShape().getBoundingBoxes(); + + double playerHalfWidth = playerBounds.getWidthX() / 2.0; + double playerHalfDepth = playerBounds.getWidthZ() / 2.0; + + double maxHeight = 0; + for (BoundingBox box : boxes) { + if (playerLocation.getX() - block.getX() + playerHalfWidth < box.getMinX() + || playerLocation.getX() - block.getX() - playerHalfWidth > box.getMaxX() + || playerLocation.getZ() - block.getZ() + playerHalfDepth < box.getMinZ() + || playerLocation.getZ() - block.getZ() - playerHalfDepth > box.getMaxZ()) { + continue; // collision box not applicable + } + + double currentBoxAbsoluteTopY = box.getMaxY() + block.getY(); + if (currentBoxAbsoluteTopY > maxHeight) { + maxHeight = currentBoxAbsoluteTopY; + } + } + + if (maxHeight == 0) { // passable block + maxHeight = block.getY(); + } + + return maxHeight; } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java index 8f2532f07..08d1d2612 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java @@ -1,10 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.spigot.events.EntityDamageByPlayerEvent; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java index bfd7ef534..587de479f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -48,10 +48,10 @@ public LocalizableMessage getSettingsName() { @Override public void playValueChangeTitle() { if (getValue() == 1) { - ChallengeHelper.playToggleChallengeTitle(this, false); + ChallengeHelper.playChallengeToggleTitle(this, false); return; } - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == 2 ? Message.forName("enabled") : Message.forName("item-regeneration-setting-not_natural")); + ChallengeHelper.playChallengeValueTitle(this, getValue() == 2 ? Message.forName("enabled") : Message.forName("item-regeneration-setting-not_natural")); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java index 3fe66bb7c..624da0342 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java @@ -1,9 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.GameMode; @@ -14,7 +12,6 @@ import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; -import org.jetbrains.annotations.NotNull; public class SoupSetting extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java index 80dde9378..90373de8c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java @@ -3,12 +3,10 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.commons.bukkit.utils.item.ItemUtils; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; @@ -49,7 +47,7 @@ public LocalizableMessage getSettingsName() { @Override public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, getValue() == LOGS_LEAVES ? Message.forName("item-timber-setting-logs-and-leaves") : Message.forName("item-timber-setting-logs")); + ChallengeHelper.playChallengeValueTitle(this, getValue() == LOGS_LEAVES ? Message.forName("item-timber-setting-logs-and-leaves") : Message.forName("item-timber-setting-logs")); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java index 343ab0fb4..938be2a03 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java @@ -9,6 +9,7 @@ import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; +import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeActionBar; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeScoreboard; import net.codingarea.challenges.plugin.utils.item.DefaultItems; @@ -52,6 +53,8 @@ public abstract class AbstractChallenge implements IChallenge, Listener { @Getter protected final ChallengeScoreboard scoreboard = new ChallengeScoreboard(); @Getter + protected final ChallengeActionBar actionbar = new ChallengeActionBar(); + @Getter protected ItemStack displayItemPreset; @Getter @@ -146,8 +149,8 @@ public LocalizableMessage getChallengeDescription() { } @NotNull - protected MessageKey getChallengeMessageKey(@NotNull String messageNameSuffix) { - return MessageKey.of("challenge." + nameMessageKey + "." + messageNameSuffix); + protected MessageKey getChallengeMessageKey(@NotNull String keySuffix) { + return MessageKey.of("challenge." + nameMessageKey + "." + keySuffix); } @NotNull @@ -183,10 +186,12 @@ public ItemStack getSettingsItemPreset() { /** * @implNote Only used if {@link #isEnabled()}, format will be applied dynamically + * @implSpec Should ideally either return a {@link LocalizableMessage}, {@link MessageKey} + * or {@link net.kyori.adventure.text.Component} for dynamic (e.g. translatable) styling */ @NotNull - public LocalizableMessage getSettingsName() { - return MessageKey.of("enabled"); + public Object getSettingsName() { + return MessageKey.of("generic.enabled"); } /** diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java index b94b42682..c7715f1e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java @@ -2,7 +2,7 @@ import lombok.Getter; import net.codingarea.challenges.plugin.ChallengeAPI; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java index ec0dd1da9..ef159023e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java @@ -1,7 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ForceTarget; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; import net.codingarea.commons.common.config.Document; import org.bukkit.World; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java index cd99c3e5d..2aff1f67b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ForceTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.menu.MenuGoal; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java index e4fdead75..41c417acf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java index 85f8cf92a..179ea315f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java @@ -1,11 +1,12 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import net.codingarea.challenges.plugin.ChallengeAPI; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.commons.common.config.Document; +import net.kyori.adventure.bossbar.BossBar; import org.bukkit.boss.BarColor; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; @@ -48,7 +49,7 @@ protected void onEnable() { bossbar.setContent((bar, player) -> { float i = 1 - ((float) getEntitiesLeftToKill().size() / (float) entitiesToKill.size()); bar.setProgress(i); - bar.setColor(BarColor.GREEN); + bar.setColor(BossBar.Color.GREEN); bar.setTitle(getBossbarMessage().asString(getEntitiesKilled().size(), entitiesToKill.size())); }); bossbar.show(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java index 5984aa1dc..bedb375b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java @@ -3,7 +3,6 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -51,7 +50,7 @@ public ItemStack getSettingsItemPreset() { @NotNull @Override - public LocalizableMessage getSettingsName() { + public Object getSettingsName() { return MessageKey.of("challenge.settings-modifier-value").withArgs(value); } @@ -80,6 +79,10 @@ public void setValue(int value) { updateItems(); } + protected void overwriteValue(int value) { + this.value = value; + } + @Override public final int getMaxValue() { return max; @@ -102,7 +105,7 @@ public void handleClick(@NotNull ChallengeMenuClickInfo info) { @Override public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this); + ChallengeHelper.playChallengeValueTitle(this); } protected void onValueChange() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java index 8ff1737b4..24fb41370 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ModifierCollectionGoal.java @@ -86,7 +86,7 @@ public final int getMinValue() { @Override public void playValueChangeTitle() { - ChallengeHelper.playChangeChallengeValueTitle(this, this); + ChallengeHelper.playChallengeValueTitle(this); } protected void onValueChange() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java index ca007c171..4af9c7aea 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/OneEnabledSetting.java @@ -25,8 +25,8 @@ public OneEnabledSetting(@NotNull MenuType menu, @Nullable SettingCategory categ @Override public void setEnabled(boolean enabled) { - super.setEnabled(enabled); if (isEnabled()) disableOthers(); + super.setEnabled(enabled); } protected final void disableOthers() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java index ad87f8228..735238e38 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java @@ -42,7 +42,7 @@ public void restoreDefaults() { } public void playStatusUpdateTitle() { - ChallengeHelper.playToggleChallengeTitle(this); + ChallengeHelper.playChallengeToggleTitle(this); } protected void onEnable() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java index 68f55ac40..79eaee0de 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java @@ -74,7 +74,7 @@ public void setEnabled(boolean enabled) { } public void playStatusUpdateTitle() { - ChallengeHelper.playToggleChallengeTitle(this); + ChallengeHelper.playChallengeToggleTitle(this); } protected void onEnable() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java index 88efe9e42..7c9542ad1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java @@ -95,6 +95,7 @@ public void restoreDefaults() { settings.values().forEach(SubSetting::restoreDefaults); } + // TODO extract duplicate logic with AbstractChallenge public abstract class SubSetting implements Listener { @Setter @@ -143,7 +144,7 @@ public ItemBuilder getSettingsItem(@NotNull Locale locale) { @NotNull protected LocalizableMessage getSettingsName() { - return MessageKey.of("enabled"); + return MessageKey.of("generic.enabled"); } @Nullable @@ -274,11 +275,11 @@ public NumberSubSetting(@NotNull ItemStack displayItemPreset, int min, int max) } public NumberSubSetting(@NotNull ItemStack displayItemPreset, int min, int max, int defaultValue) { + super(displayItemPreset); if (max <= min) throw new IllegalArgumentException("max <= min"); if (min < 0) throw new IllegalArgumentException("min < 0"); if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); if (defaultValue < min) throw new IllegalArgumentException("defaultValue < min"); - super(displayItemPreset); this.value = defaultValue; this.defaultValue = defaultValue; this.max = max; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java index 514dae440..ef1da7dce 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/ChallengeAnnotations.java @@ -45,4 +45,11 @@ private static boolean isVersionNew(@NotNull Version challengeVersion) { return challengeVersion.isNewerOrEqualThan(pluginVersion); } + public static boolean isCanInstaKillOnEnable(@NotNull IChallenge challenge) { + return challenge.getClass().isAnnotationPresent(CanInstaKillOnEnable.class); + } + + public static boolean isExcludedFromRandomChallenges(@NotNull IChallenge challenge) { + return challenge.getClass().isAnnotationPresent(ExcludeFromRandomChallenges.class); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/RequireDepend.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/RequireDepend.java new file mode 100644 index 000000000..9266bb193 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/annotation/RequireDepend.java @@ -0,0 +1,14 @@ +package net.codingarea.challenges.plugin.challenges.type.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface RequireDepend { + + String plugin(); + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index 6b99fd81b..464cd373f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -7,9 +7,7 @@ import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; -import net.codingarea.challenges.plugin.challenges.type.annotation.CanInstaKillOnEnable; -import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengesMenuGenerator; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -25,6 +23,7 @@ import org.bukkit.event.entity.EntityDamageEvent.DamageModifier; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.CheckReturnValue; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -51,6 +50,7 @@ public static void kill(@NotNull Player player, int delay) { Bukkit.getScheduler().runTaskLater(Challenges.getInstance(), () -> kill(player), delay); } + @CheckReturnValue public static boolean runSyncIfConcurrent(Runnable task) { if (Bukkit.isPrimaryThread()) { return false; @@ -59,16 +59,16 @@ public static boolean runSyncIfConcurrent(Runnable task) { return true; } - public static void updateItems(@NotNull IChallenge challenge) { - challenge.getType().executeWithGenerator(ChallengesMenuGenerator.class, gen -> gen.updateElementDisplay(challenge)); - } - - public static boolean canInstaKillOnEnable(@NotNull IChallenge challenge) { - return challenge.getClass().isAnnotationPresent(CanInstaKillOnEnable.class); + public static void runSync(@NotNull Runnable task) { + if (Bukkit.isPrimaryThread()) { + task.run(); + return; + } + Bukkit.getScheduler().runTask(Challenges.getInstance(), task); } - public static boolean isExcludedFromRandomChallenges(@NotNull IChallenge challenge) { - return challenge.getClass().isAnnotationPresent(ExcludeFromRandomChallenges.class); + public static void updateItems(@NotNull IChallenge challenge) { + challenge.getType().executeWithGenerator(ChallengesMenuGenerator.class, gen -> gen.updateElementDisplay(challenge)); } public static void handleModifierClick(@NotNull MenuClickInfo info, @NotNull IModifier modifier) { @@ -155,28 +155,24 @@ public static List getIngamePlayers() { return Bukkit.getOnlinePlayers().stream().filter(player -> !AbstractChallenge.ignorePlayer(player)).collect(Collectors.toList()); } - public static void playToggleChallengeTitle(@NotNull AbstractChallenge challenge) { - playToggleChallengeTitle(challenge, challenge.isEnabled()); - } - - public static void playToggleChallengeTitle(@NotNull AbstractChallenge challenge, boolean enabled) { - Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(enabled ? Message.forName("title-challenge-enabled") : Message.forName("title-challenge-disabled"), getColoredChallengeName(challenge)); + public static void playChallengeToggleTitle(@NotNull AbstractChallenge challenge) { + playChallengeToggleTitle(challenge, challenge.isEnabled()); } - public static void playChangeChallengeValueTitle(@NotNull AbstractChallenge challenge, @NotNull IModifier modifier) { - playChangeChallengeValueTitle(challenge, modifier.getValue()); + public static void playChallengeToggleTitle(@NotNull AbstractChallenge challenge, boolean enabled) { + Challenges.getInstance().getTitleManager().sendChallengeToggleTitle(challenge, enabled); } - public static void playChangeChallengeValueTitle(@NotNull Modifier modifier) { - playChangeChallengeValueTitle(modifier, modifier.getValue()); + public static void playChallengeValueTitle(@NotNull T modifier) { + playChallengeValueTitle(modifier, modifier.getValue()); } - public static void playChangeChallengeValueTitle(@NotNull AbstractChallenge modifier, @Nullable Object value) { - Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(Message.forName("title-challenge-value-changed"), getColoredChallengeName(modifier), value); + public static void playChallengeValueTitle(@NotNull AbstractChallenge challenge, @NotNull Object value) { + Challenges.getInstance().getTitleManager().sendChallengeValueTitle(challenge, value); } public static void playChallengeHeartsValueChangeTitle(@NotNull AbstractChallenge challenge, int health) { - playChangeChallengeValueTitle(challenge, (health / 2f) + " §c❤"); + playChallengeValueTitle(challenge, (health / 2f) + " §c❤"); } public static void playChallengeHeartsValueChangeTitle(@NotNull Modifier modifier) { @@ -184,15 +180,15 @@ public static void playChallengeHeartsValueChangeTitle(@NotNull Modifier modifie } public static void playChallengeSecondsValueChangeTitle(@NotNull AbstractChallenge challenge, int seconds) { - playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds").asString(seconds)); + playChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds").asString(seconds)); } public static void playChallengeSecondsRangeValueChangeTitle(@NotNull AbstractChallenge challenge, int min, int max) { - playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds-range").asString(min, max)); + playChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds-range").asString(min, max)); } public static void playChallengeMinutesValueChangeTitle(@NotNull AbstractChallenge challenge, int seconds) { - playChangeChallengeValueTitle(challenge, Message.forName("subtitle-time-minutes").asString(seconds)); + playChallengeValueTitle(challenge, Message.forName("subtitle-time-minutes").asString(seconds)); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java index 77e52dc2c..65866054e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeScoreboard.ScoreboardInstance; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.common.collection.NumberFormatter; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java index 2f611f2a0..5d2edccd3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.ChooseItemSubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.ChooseMultipleItemSubSettingBuilder; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java new file mode 100644 index 000000000..bd21e6e5d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java @@ -0,0 +1,98 @@ +package net.codingarea.challenges.plugin.content.i18n; + +import lombok.RequiredArgsConstructor; +import net.codingarea.commons.common.collection.NumberFormatter; +import net.codingarea.commons.common.misc.StringUtils; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.projectiles.ProjectileSource; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NonNull; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +public interface ArgumentFormat { + + @NotNull + LocalizableMessage apply(@NotNull T arg); + + boolean isApplicable(@NotNull Object arg); + + ArgumentFormat HEARTS = register(Number.class, "hearts", arg -> { + double hearts = arg.doubleValue() / 2; + return MessageKey.of("arg-format.hearts").withArgs(NumberFormatter.FLOATING_POINT.format(hearts)); + }); + ArgumentFormat HEARTS_LIMITED = register(Number.class, "hearts_limited", arg -> { + if (arg.doubleValue() >= 1000) return MessageKey.of("symbol.infinity"); + return HEARTS.apply(arg); + }); + + ArgumentFormat HP = register(Number.class, "hp", arg -> { + int hp = arg.intValue(); + double hearts = hp / 2d; + return MessageKey.of("arg-format.hp").withArgs(hp, NumberFormatter.FLOATING_POINT.format(hearts)); + }); + + ArgumentFormat DAMAGE_CAUSE = register(EntityDamageEvent.class, "damage_cause", event -> { + if (event.getCause() == EntityDamageEvent.DamageCause.CUSTOM) return MessageKey.of("generic.undefined"); + String cause = StringUtils.getEnumName(event.getCause()); // DamageCause is not a Translatable, impl custom translations? + + if (!(event instanceof EntityDamageByEntityEvent damageEvent)) { + return MessageKey.of("arg-format.damage-cause").withArgs(cause); + } + + if (damageEvent.getDamager() instanceof Player damagerPlayer) { + return MessageKey.of("arg-format.damage-cause-source").withArgs(cause, damagerPlayer); + } else if (damageEvent.getDamager() instanceof Projectile projectile) { + ProjectileSource shooter = projectile.getShooter(); + if (shooter instanceof Player shooterPlayer) { + return MessageKey.of("arg-format.damage-cause-source").withArgs(projectile.getType(), shooterPlayer); + } else if (shooter instanceof Entity shooterEntity) { + return MessageKey.of("arg-format.damage-cause-source").withArgs(projectile.getType(), shooterEntity.getType()); + } else { + return MessageKey.of("arg-format.damage-cause").withArgs(projectile.getType()); + } + } else { + return MessageKey.of("arg-format.damage-cause-source").withArgs(cause, damageEvent.getDamager().getType()); + } + }); + + @NotNull + static ArgumentFormat register(@NotNull Class argClass, @NotNull String key, @NotNull Function formatter) { + ArgumentFormatImpl format = new ArgumentFormatImpl<>(argClass, formatter); + ArgumentFormatImpl.REGISTRY.put(key, format); + return format; + } + + @Nullable + static ArgumentFormat getByName(@NotNull String name) { + return ArgumentFormatImpl.REGISTRY.get(name); + } + + @RequiredArgsConstructor + class ArgumentFormatImpl implements ArgumentFormat { + + private static final Map> REGISTRY = new HashMap<>(); + + private final Class argClass; + private final Function formatter; + + @NotNull + @Override + public LocalizableMessage apply(@NonNull T arg) { + return formatter.apply(arg); + } + + @Override + public boolean isApplicable(@NotNull Object arg) { + return argClass.isAssignableFrom(arg.getClass()); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LanguageProvider.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LanguageProvider.java index ff58704c2..26e790f9b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LanguageProvider.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LanguageProvider.java @@ -8,8 +8,8 @@ public interface LanguageProvider { /** - * Currently only the language tag of the locale is used, country code and variant are ignored. * Default behavior currently implements one global language set in the plugin.yml. + * Locale only contains the language tag, no country code or variant. */ @NotNull Locale getPlayerLanguage(@NotNull Player player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java index 04e2bac62..13d931a39 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java @@ -1,13 +1,19 @@ package net.codingarea.challenges.plugin.content.i18n; -import net.codingarea.challenges.platform.message.MessageHolder; +import net.codingarea.challenges.plugin.content.i18n.impl.DynamicLocalizableMessageImpl; +import net.codingarea.challenges.plugin.content.i18n.impl.JoinedMessageImpl; import org.bukkit.entity.Player; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.CheckReturnValue; import org.jetbrains.annotations.NotNull; +import java.util.List; import java.util.Locale; +import java.util.function.Function; /** - * Represents a {@link MessageKey} with arguments that can be passed as a message argument. + * Represents a {@link MessageKey} with arguments that can be passed as a message argument for dynamic formatting + * or a {@link MessageKey} instance without arguments. * * @see MessageKey#withArgs(Object...) */ @@ -20,9 +26,52 @@ public interface LocalizableMessage { MessageHolder localize(@NotNull Player playerLocale); @NotNull + @ApiStatus.Internal MessageKey getLocalizableKey(); @NotNull Object[] getLocalizableArgs(); + @NotNull + @CheckReturnValue + static LocalizableMessage of(@NotNull String messageKey, @NotNull Object[] args) { + return MessageKey.of(messageKey).withArgs(args); + } + + @NotNull + @CheckReturnValue + static LocalizableMessage join(@NotNull MessageKey delimiter, @NotNull Object... elements) { + return new JoinedMessageImpl(delimiter, elements); + } + + @NotNull + @CheckReturnValue + static LocalizableMessage joinArray(@NotNull Object[] elements) { + return join(MessageKey.of("generic.delimiter"), elements); + } + + @NotNull + @CheckReturnValue + static LocalizableMessage joinList(@NotNull List elements) { + return joinArray(elements.toArray()); + } + + @NotNull + @CheckReturnValue + static LocalizableMessage joinArgs(@NotNull Object... elements) { // prevents ambiguous var-args + return joinArray(elements); + } + + @NotNull + @CheckReturnValue + static LocalizableMessage fromLines(@NotNull Function valueFunction, @NotNull Object... args) { + return new DynamicLocalizableMessageImpl(valueFunction, args); + } + + @NotNull + @CheckReturnValue + static LocalizableMessage from(@NotNull Function valueFunction, @NotNull Object... args) { + return new DynamicLocalizableMessageImpl(valueFunction.andThen((string) -> new String[]{string}), args); + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageHolder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageHolder.java new file mode 100644 index 000000000..ec262844d --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageHolder.java @@ -0,0 +1,15 @@ +package net.codingarea.challenges.plugin.content.i18n; + + +import org.jetbrains.annotations.NotNull; + +/** + * Represents a localized message with arguments. + * + * @see LocalizableMessage#localize(java.util.Locale) + */ +public record MessageHolder(@NotNull String[] rawValue, @NotNull Object[] positionalArgs) { + + public static final Object[] EMPTY_ARGS = new Object[0]; + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java index 60107aea4..f63098469 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java @@ -1,18 +1,18 @@ package net.codingarea.challenges.plugin.content.i18n; import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.i18n.impl.MessageKeyImpl; +import net.codingarea.challenges.plugin.content.i18n.impl.format.MessageFormatter; +import net.kyori.adventure.text.Component; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.meta.ItemMeta; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.CheckReturnValue; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.List; import java.util.Locale; /** @@ -26,7 +26,6 @@ *

  • {@link #sendTitle(Player, Object...)} to send this as a title and subtitle to a player in their language, where the first line in the array in the header, and the second the subtitle
  • *
  • {@link #sendActionBar(Player, Object...)} to send this as an action bar to a player, the translation must be one line
  • *
  • {@link #broadcast(Prefix, Object...)} to send this as a chat message to all players in their language
  • - *
  • {@link #createInventory(Locale, int, Object...)} to create an inventory with translated title
  • * * See {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder#ItemBuilder(Locale, Material, MessageKey, Object...)} * for creating items with translated names and descriptions. @@ -65,9 +64,7 @@ * (for static linking use {@code {\@x}} reference) *
  • {@link LocalizableMessage} will automatically be localized into the target language, * it can be used to reference messages dynamically with additional object arguments using {@link MessageKey#withArgs(Object...)}
  • - *
  • {@link org.bukkit.Material}
  • - *
  • {@link org.bukkit.entity.EntityType}
  • - *
  • {@link org.bukkit.GameMode}
  • + *
  • {@link net.kyori.adventure.translation.Translatable} like {@link org.bukkit.Material}, {@link org.bukkit.entity.EntityType}, {@link org.bukkit.GameMode}
  • *
  • {@link org.bukkit.entity.Player} using their name
  • *
  • Unknown Enums will be formatted as {@code TEST_ENUM -> "Test Enum"}
  • *
  • Unresolvable types will be serialized using {@link Object#toString()}
  • @@ -75,8 +72,7 @@ * * * @see TranslationManager TranslationManager for localization - * @see net.codingarea.challenges.platform.message.MessagePlatform MessagePlatform for implementation - * @see net.codingarea.challenges.plugin.content.i18n.impl.MessageFormatter MessageFormatter for references + * @see MessageFormatter MessageFormatter for references */ public interface MessageKey extends LocalizableMessage { @@ -92,11 +88,23 @@ static MessageKey of(@NotNull String id) { return i18n.getMessageKey(id); } + @NotNull + @CheckReturnValue + @ApiStatus.Internal + static MessageKey empty(@NotNull String id) { + return new MessageKeyImpl(id); + } + @NotNull static String formatMissingTranslation(@NotNull String key, @NotNull Locale locale) { return String.format("%s/%s", key, locale); } + @NotNull + default MessageKey getChildKey(@NotNull String child) { + return of(getKey() + "." + child); + } + @NotNull String getKey(); @@ -159,124 +167,35 @@ static String formatMissingTranslation(@NotNull String key, @NotNull Locale loca void broadcastActionBar(@NotNull Object... args); - /** - * Creates a new {@link Inventory} with the title of this message translated into the given language - * (and replacing the given args) and the given size. It uses {@link net.codingarea.commons.bukkit.utils.menu.MenuPosition#HOLDER} - * as the {@link InventoryHolder}. - * - * @see org.bukkit.Bukkit#createInventory(InventoryHolder, int, String) - */ - @NotNull - @CheckReturnValue - Inventory createInventory(@NotNull Locale locale, int size, @NotNull Object... args); + // Formatting - /** - * Creates a new {@link Inventory} with the title of this message translated into the Player's language - * (and replacing the given args) and the given size. It uses {@link net.codingarea.commons.bukkit.utils.menu.MenuPosition#HOLDER} - * as the {@link InventoryHolder}. - * - * @see org.bukkit.Bukkit#createInventory(InventoryHolder, int, String) - */ @NotNull - @CheckReturnValue - default Inventory createInventory(@NotNull Player playerLocale, int size, @NotNull Object... args) { - return createInventory(findPlayerLocale(playerLocale), size, args); - } + Component asComponent(@NotNull Locale locale, @Nullable Prefix prefix, @NotNull Object... args); - /** - * Creates a new {@link Inventory} with the title of this message translated into the given language - * (and replacing the given args) and the given type. It uses {@link net.codingarea.commons.bukkit.utils.menu.MenuPosition#HOLDER} - * as the {@link InventoryHolder}. - * - * @see org.bukkit.Bukkit#createInventory(InventoryHolder, InventoryType, String) - */ - @NotNull - @CheckReturnValue - Inventory createInventory(@NotNull Locale locale, @NotNull InventoryType type, @NotNull Object... args); - - /** - * Creates a new {@link Inventory} with the title of this message translated into the Player's language - * (and replacing the given args) and the given type.It uses {@link net.codingarea.commons.bukkit.utils.menu.MenuPosition#HOLDER} - * as the {@link InventoryHolder}. - * - * @see org.bukkit.Bukkit#createInventory(InventoryHolder, InventoryType, String) - */ @NotNull - @CheckReturnValue - default Inventory createInventory(@NotNull Player playerLocale, @NotNull InventoryType type, @NotNull Object... args) { - return createInventory(findPlayerLocale(playerLocale), type, args); + default Component asComponent(@NotNull Player playerLocale, @Nullable Prefix prefix, @NotNull Object... args) { + return asComponent(findPlayerLocale(playerLocale), prefix, args); } - /** - * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. - */ - @ApiStatus.Internal - void applyAsItemNameAndLore(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args); - - /** - * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. - */ - @ApiStatus.Internal - default void applyAsItemNameAndLore(@NotNull Player playerLocale, @NotNull ItemMeta item,@NotNull Object... args) { - applyAsItemNameAndLore(findPlayerLocale(playerLocale), item, args); - } - - /** - * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. - */ - @ApiStatus.Internal - void applyAsItemName(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args); - - /** - * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. - */ - @ApiStatus.Internal - default void applyAsItemName(@NotNull Player playerLocale, @NotNull ItemMeta item, @NotNull Object... args) { - applyAsItemName(findPlayerLocale(playerLocale), item, args); + @NotNull + default Component asComponent(@NotNull Locale locale, @NotNull Object... args) { + return asComponent(locale, null, args); } - /** - * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. - */ - @ApiStatus.Internal - void appendToItemName(@NotNull Locale locale, @NotNull ItemMeta item, boolean withSpace, @NotNull Object... args); - - /** - * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. - */ - @ApiStatus.Internal - default void appendToItemName(@NotNull Player playerLocale, @NotNull ItemMeta item, boolean withSpace, - @NotNull Object... args) { - appendToItemName(findPlayerLocale(playerLocale), item, withSpace, args); + @NotNull + default Component asComponent(@NotNull Player playerLocale, @NotNull Object... args) { + return asComponent(findPlayerLocale(playerLocale), args); } - /** - * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. - */ - @ApiStatus.Internal - void applyAsItemLore(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args); + @NotNull + List asComponents(@NotNull Locale locale, @NotNull Object... args); - /** - * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. - */ - @ApiStatus.Internal - default void applyAsItemLore(@NotNull Player playerLocale, @NotNull ItemMeta item, @NotNull Object... args) { - applyAsItemLore(findPlayerLocale(playerLocale), item, args); + @NotNull + default List asComponents(@NotNull Player playerLocale, @NotNull Object... args) { + return asComponents(findPlayerLocale(playerLocale), args); } - /** - * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. - */ - @ApiStatus.Internal - void appendToItemLore(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args); - - /** - * Internal API. Create Items via {@link net.codingarea.challenges.plugin.utils.item.ItemBuilder} instead. - */ - @ApiStatus.Internal - default void appendToItemLore(@NotNull Player player, @NotNull ItemMeta item, @NotNull Object... args) { - appendToItemLore(findPlayerLocale(player), item, args); - } + // Utils @NotNull private Locale findPlayerLocale(@NotNull Player player) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/TranslationManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/TranslationManager.java index 9a4116539..206299628 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/TranslationManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/TranslationManager.java @@ -2,8 +2,8 @@ import com.google.common.base.Preconditions; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.i18n.impl.MessageFormatter; import net.codingarea.challenges.plugin.content.i18n.impl.MessageKeyImpl; +import net.codingarea.challenges.plugin.content.i18n.impl.format.MessageFormatter; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.misc.ReflectionUtils; import org.jetbrains.annotations.CheckReturnValue; @@ -41,6 +41,7 @@ public void setLanguageProvider(@NotNull LanguageProvider languageProvider) { this.languageProvider = languageProvider; } + @NotNull public MessageKey getMessageKey(@NotNull String key) { return cachedMessages.computeIfAbsent(key, forKey -> { Challenges.getInstance().getILogger().warn("Tried accessing unknown message '{}', called by {}", forKey, ReflectionUtils.getCallerName(3)); @@ -97,6 +98,7 @@ public void populateLanguage(@NotNull Locale locale, @NotNull Map"); + + private final Function valueFunction; + private final Object[] args; + + @NotNull + @Override + public MessageHolder localize(@NotNull Locale locale) { + return new MessageHolder(valueFunction.apply(locale), MessageKeyImpl.localizeArgsAsCopy(locale, args)); + } + + @NotNull + @Override + public MessageHolder localize(@NotNull Player playerLocale) { + return localize(MessageKeyImpl.getPlayerLocale(playerLocale)); + } + + @NotNull + @Override + public MessageKey getLocalizableKey() { + return KEY; + } + + @NotNull + @Override + public Object[] getLocalizableArgs() { + return args; + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/JoinedMessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/JoinedMessageImpl.java new file mode 100644 index 000000000..418a7d3d6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/JoinedMessageImpl.java @@ -0,0 +1,50 @@ +package net.codingarea.challenges.plugin.content.i18n.impl; + +import lombok.RequiredArgsConstructor; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageHolder; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.impl.format.MessageFormatter; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; + +@RequiredArgsConstructor +public class JoinedMessageImpl implements LocalizableMessage { + + private final MessageKey delimiter; + private final Object[] elements; + + @NotNull + @Override + public MessageHolder localize(@NotNull Locale locale) { + StringBuilder raw = new StringBuilder(); + String localizedDelimiter = delimiter.localizeRawValueAsSingleLine(locale); + for (int i = 0; i < elements.length; i++) { + raw.append(MessageFormatter.START_ARG_CHAR).append(i).append(MessageFormatter.END_ARG_CHAR); + if (i != elements.length - 1) raw.append(localizedDelimiter); + } + + Object[] args = MessageKeyImpl.localizeArgsAsCopy(locale, elements); + return new MessageHolder(new String[]{raw.toString()}, args); + } + + @NotNull + @Override + public MessageHolder localize(@NotNull Player playerLocale) { + return localize(MessageKeyImpl.getPlayerLocale(playerLocale)); + } + + @NotNull + @Override + public MessageKey getLocalizableKey() { + return delimiter; + } + + @NotNull + @Override + public Object[] getLocalizableArgs() { + return elements; + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java new file mode 100644 index 000000000..465916ef5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java @@ -0,0 +1,41 @@ +package net.codingarea.challenges.plugin.content.i18n.impl; + +import lombok.RequiredArgsConstructor; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageHolder; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; + +@RequiredArgsConstructor +public class LocalizableMessageImpl implements LocalizableMessage { + + private final MessageKeyImpl messageKey; + private final Object[] args; + + @NotNull + @Override + public MessageHolder localize(@NotNull Locale locale) { + return new MessageHolder(messageKey.localizeRawValue(locale), MessageKeyImpl.localizeArgsAsCopy(locale, args)); + } + + @NotNull + @Override + public MessageHolder localize(@NotNull Player playerLocale) { + return localize(MessageKeyImpl.getPlayerLocale(playerLocale)); + } + + @NotNull + @Override + public MessageKey getLocalizableKey() { + return messageKey; + } + + @NotNull + @Override + public Object[] getLocalizableArgs() { + return args; + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java index f071912e4..9b7964aa3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java @@ -1,31 +1,27 @@ package net.codingarea.challenges.plugin.content.i18n.impl; -import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; -import net.codingarea.challenges.platform.message.MessageHolder; -import net.codingarea.challenges.platform.message.MessagePlatform; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.content.i18n.TranslationManager; +import net.codingarea.challenges.plugin.content.i18n.*; +import net.codingarea.challenges.plugin.content.i18n.impl.format.ComponentFormatter; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.management.server.TitleManager; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.commons.common.collection.IRandom; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.title.Title; +import net.kyori.adventure.util.Ticks; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.meta.ItemMeta; import org.jetbrains.annotations.CheckReturnValue; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jspecify.annotations.NonNull; +import java.time.Duration; import java.util.*; +import java.util.function.BiConsumer; +import java.util.function.Function; public class MessageKeyImpl implements MessageKey { @@ -76,13 +72,13 @@ public String localizeRawValueAsSingleLine(@NotNull Locale locale) { @NotNull @Override public LocalizableMessage withArgs(@NotNull Object... args) { - return new LocalizableMessageImpl(args); + return new LocalizableMessageImpl(this, args); } @NotNull @Override public MessageHolder localize(@NotNull Locale locale) { - return new MessageHolderImpl(localizeRawValue(locale), MessageHolderImpl.EMPTY_ARGS); + return new MessageHolder(localizeRawValue(locale), MessageHolder.EMPTY_ARGS); } @NotNull @@ -100,23 +96,7 @@ public MessageKey getLocalizableKey() { @NotNull @Override public Object[] getLocalizableArgs() { - return MessageHolderImpl.EMPTY_ARGS; - } - - protected void localizeArgs(@NotNull Locale locale, @NotNull Object[] args) { - for (int i = 0; i < args.length; i++) { - if (args[i] instanceof LocalizableMessage message) { - args[i] = message.localize(locale); - } - } - } - - @CheckReturnValue - protected Object[] localizeArgsAsCopy(@NotNull Locale locale, @NotNull Object[] args) { - if (args.length == 0) return args; - Object[] localizedArgs = Arrays.copyOf(args, args.length); // avoid mutating original array - localizeArgs(locale, localizedArgs); - return localizedArgs; + return MessageHolder.EMPTY_ARGS; } @Override @@ -136,9 +116,10 @@ public int hashCode() { } @Nullable - protected String stringifyPrefix(@NotNull Locale locale, @Nullable Prefix prefix) { + protected String localizePrefix(@NotNull Locale locale, @Nullable Prefix prefix) { if (prefix == null) return null; MessageKey asKey = prefix.getKey(); + // TODO remove when legacy color impl is removed if (asKey.isCached(locale)) { return asKey.localizeRawValueAsSingleLine(locale); } @@ -146,36 +127,46 @@ protected String stringifyPrefix(@NotNull Locale locale, @Nullable Prefix prefix } @NotNull - protected Locale getPlayerLocale(@NotNull Player player) { + protected static Locale getPlayerLocale(@NotNull Player player) { return Challenges.getInstance().getTranslationManager().getLanguageProvider().getPlayerLanguage(player); } - @NotNull - protected MessagePlatform getMessagePlatform() { - return Challenges.getInstance().getPlatformManager().getMessagePlatform(); + protected static void localizeArgs(@NotNull Locale locale, @NotNull Object[] args) { + for (int i = 0; i < args.length; i++) { + if (args[i] instanceof LocalizableMessage message) { + args[i] = message.localize(locale); + } + } } + @NotNull + @CheckReturnValue + protected static Object[] localizeArgsAsCopy(@NotNull Locale locale, @NotNull Object[] args) { + if (args.length == 0) return args; + // avoid mutating original array & ensure args array is really of type Object, so MessageHolder can be stored + Object[] localizedArgs = new Object[args.length]; + System.arraycopy(args, 0, localizedArgs, 0, args.length); + localizeArgs(locale, localizedArgs); + return localizedArgs; + } // Action Implementations @Override - public void send(@NotNull CommandSender target, @Nullable Prefix prefix, @NonNull @NotNull Object... args) { + public void send(@NotNull CommandSender target, @Nullable Prefix prefix, @NotNull Object... args) { if (target instanceof Player) { send((Player) target, prefix, args); } else { Locale locale = Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class) .map(LanguageLoader::getConfigLanguage) .orElse(TranslationManager.FALLBACK_LOCALE); - localizeArgs(locale, args); - getMessagePlatform().sendSenderMessage(target, stringifyPrefix(locale, prefix), localizeRawValue(locale), args); + target.sendMessage(asComponent(locale, prefix, args)); } } @Override public void send(@NotNull Player target, @Nullable Prefix prefix, @NotNull Object... args) { - Locale locale = getPlayerLocale(target); - localizeArgs(locale, args); - getMessagePlatform().sendChatMessage(target, stringifyPrefix(locale, prefix), localizeRawValue(locale), args); + target.sendMessage(asComponent(getPlayerLocale(target), prefix, args)); } @Override @@ -183,78 +174,89 @@ public void sendRandom(@NotNull Player target, @Nullable Prefix prefix, @NotNull Locale locale = getPlayerLocale(target); localizeArgs(locale, args); String raw = random.choose(localizeRawValue(locale)); - getMessagePlatform().sendChatMessage(target, stringifyPrefix(locale, prefix), new String[]{raw}, args); + target.sendMessage(ComponentFormatter.deserializeLinesWithArgs(localizePrefix(locale, prefix), new String[]{raw}, args)); } @Override public void broadcast(@Nullable Prefix prefix, @NotNull Object... args) { - doBroadcast(prefix, args, getMessagePlatform()::sendChatMessage); + doBroadcast(prefix, args, Player::sendMessage); } @Override public void broadcastRandom(@Nullable Prefix prefix, @NotNull Object... args) { int index = random.nextInt(getMinValueLengthIncludingFallback()); - doBroadcast(prefix, args, (target, localizedPrefix, raw, localizedArgs) -> - getMessagePlatform().sendChatMessage(target, localizedPrefix, new String[]{raw[index]}, localizedArgs)); + doBroadcast0(Player::sendMessage, locale -> + ComponentFormatter.deserializeLinesWithArgs(localizePrefix(locale, prefix), new String[]{localizeRawValue(locale)[index]}, localizeArgsAsCopy(locale, args))); } @Override - public void sendTitle(@NotNull Player target, @NonNull @NotNull Object... args) { - Locale locale = getPlayerLocale(target); - localizeArgs(locale, args); - getMessagePlatform().sendTitle(target, localizeRawValue(locale), args, TitleManager.FADEIN, TitleManager.DURATION, TitleManager.FADEOUT); + public void sendTitle(@NotNull Player target, @NotNull Object... args) { + target.showTitle(createTitleFromComponentList(asComponents(target, args), + Title.Times.times(Ticks.duration(TitleManager.FADEIN), Ticks.duration(TitleManager.DURATION), Ticks.duration(TitleManager.FADEOUT)))); } @Override - public void sendTitleInstantly(@NotNull Player target, @NonNull @NotNull Object... args) { - Locale locale = getPlayerLocale(target); - localizeArgs(locale, args); - getMessagePlatform().sendTitle(target, localizeRawValue(locale), args, 0, TitleManager.DURATION, TitleManager.FADEOUT); + public void sendTitleInstantly(@NotNull Player target, @NotNull Object... args) { + target.showTitle(createTitleFromComponentList(asComponents(target, args), + Title.Times.times(Duration.ZERO, Ticks.duration(TitleManager.DURATION), Ticks.duration(TitleManager.FADEOUT)))); } @Override public void broadcastTitle(@NotNull Object... args) { - doBroadcast(null, args, (target, _, raw, localizedArgs) -> - getMessagePlatform().sendTitle(target, raw, localizedArgs, TitleManager.FADEIN, TitleManager.DURATION, TitleManager.FADEOUT)); + doBroadcastAsList(args, (player, components) -> + player.showTitle(createTitleFromComponentList(components, + Title.Times.times(Ticks.duration(TitleManager.FADEIN), Ticks.duration(TitleManager.DURATION), Ticks.duration(TitleManager.FADEOUT)))) + ); } @Override - public void broadcastTitleInstantly(@NonNull @NotNull Object... args) { - doBroadcast(null, args, (target, _, raw, localizedArgs) -> - getMessagePlatform().sendTitle(target, raw, localizedArgs, 0, TitleManager.DURATION, TitleManager.FADEOUT)); + public void broadcastTitleInstantly(@NotNull Object... args) { + doBroadcastAsList(args, (player, components) -> + player.showTitle(createTitleFromComponentList(components, + Title.Times.times(Duration.ZERO, Ticks.duration(TitleManager.DURATION), Ticks.duration(TitleManager.FADEOUT)))) + ); } @Override public void sendActionBar(@NotNull Player target, @NotNull Object... args) { - Locale locale = getPlayerLocale(target); - localizeArgs(locale, args); - getMessagePlatform().sendActionBar(target, localizeRawValueAsSingleLine(locale), args); + target.sendActionBar(asComponent(getPlayerLocale(target), null, args)); } @Override public void broadcastActionBar(@NotNull Object... args) { - // array will never be empty - doBroadcast(null, args, (target, _, raw, localizedArgs) -> - getMessagePlatform().sendActionBar(target, raw[0], localizedArgs)); + doBroadcast(null, args, Player::sendActionBar); } @NotNull - @Override - public Inventory createInventory(@NotNull Locale locale, int size, @NotNull Object... args) { - localizeArgs(locale, args); - return getMessagePlatform().createInventory(MenuPosition.HOLDER, size, localizeRawValueAsSingleLine(locale), args); + protected Title createTitleFromComponentList(@NotNull List components, @NotNull Title.Times timing) { + return Title.title(!components.isEmpty() ? components.getFirst() : Component.empty(), + components.size() > 1 ? components.get(1) : Component.empty(), timing); } - @Override - public @NotNull Inventory createInventory(@NotNull Locale locale, @NotNull InventoryType type, @NotNull Object... args) { - localizeArgs(locale, args); - return getMessagePlatform().createInventory(MenuPosition.HOLDER, type, localizeRawValueAsSingleLine(locale), args); + protected void doBroadcast(@Nullable Prefix prefix, @NotNull Object[] args, @NotNull BiConsumer messageSender) { + doBroadcast0(messageSender, locale -> + ComponentFormatter.deserializeLinesWithArgs(localizePrefix(locale, prefix), localizeRawValue(locale), localizeArgsAsCopy(locale, args))); + } + + protected void doBroadcastAsList(@NotNull Object[] args, @NotNull BiConsumer> messageSender) { + doBroadcast0(messageSender, locale -> + ComponentFormatter.deserializeLinesAsListWithArgs(localizeRawValue(locale), localizeArgsAsCopy(locale, args))); } - protected void doBroadcast(@Nullable Prefix prefix, @NotNull Object[] args, @NotNull SendMessageConsumer messageSender) { - for (Player player : Bukkit.getOnlinePlayers()) { - Locale locale = getPlayerLocale(player); - messageSender.accept(player, stringifyPrefix(locale, prefix), localizeRawValue(locale), localizeArgsAsCopy(locale, args)); + protected void doBroadcast0(@NotNull BiConsumer messageSender, @NotNull Function compute) { + Collection targets = Bukkit.getOnlinePlayers(); + if (targets.isEmpty()) return; + if (targets.size() == 1) { // skip overhead + Player player = targets.iterator().next(); + messageSender.accept(player, compute.apply(getPlayerLocale(player))); + return; + } + + Map localizedCache = new HashMap<>(); + for (Player target : targets) { + Locale locale = getPlayerLocale(target); + T formatted = localizedCache.computeIfAbsent(locale, compute); + messageSender.accept(target, formatted); } } @@ -270,87 +272,18 @@ protected int getMinValueLengthIncludingFallback() { return min; // > 1 } - - // Item Implementations - - @Override - public void applyAsItemNameAndLore(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args) { - localizeArgs(locale, args); - - String[] rawValue = localizeRawValue(locale); // length >= 1 - if (rawValue.length == 1) { - applyAsItemName(locale, item, args); - return; - } - - String nameLine = rawValue[0]; - getMessagePlatform().applyItemName(item, nameLine, args); - - String[] loreLines = Arrays.copyOfRange(rawValue, 1, rawValue.length); - getMessagePlatform().applyItemLore(item, loreLines, args); - } - - @Override - public void applyAsItemName(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args) { - localizeArgs(locale, args); - getMessagePlatform().applyItemName(item, localizeRawValueAsSingleLine(locale), args); - } - - @Override - public void appendToItemName(@NotNull Locale locale, @NotNull ItemMeta item, boolean withSpace, @NotNull Object... args) { - String rawValue = localizeRawValueAsSingleLine(locale); - if (withSpace) rawValue = " " + rawValue; - getMessagePlatform().appendItemName(item, rawValue, args); - } - + @NotNull @Override - public void applyAsItemLore(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args) { + public Component asComponent(@NotNull Locale locale, @Nullable Prefix prefix, @NotNull Object... args) { localizeArgs(locale, args); - getMessagePlatform().applyItemLore(item, localizeRawValue(locale), args); + return ComponentFormatter.deserializeLinesWithArgs(localizePrefix(locale, prefix), localizeRawValue(locale), args); } + @NotNull @Override - public void appendToItemLore(@NotNull Locale locale, @NotNull ItemMeta item, @NotNull Object... args) { + public List asComponents(@NotNull Locale locale, @NotNull Object... args) { localizeArgs(locale, args); - getMessagePlatform().appendItemLore(item, localizeRawValue(locale), args); - } - - @FunctionalInterface - public interface SendMessageConsumer { - void accept(@NotNull Player target, @Nullable String localizedPrefix, @NotNull String[] raw, @NotNull Object[] localizedArgs); - } - - @AllArgsConstructor - public class LocalizableMessageImpl implements LocalizableMessage { - - private final Object[] args; - - @NotNull - @Override - public MessageHolder localize(@NotNull Locale locale) { - return new MessageHolderImpl(localizeRawValue(locale), localizeArgsAsCopy(locale, args)); - } - - @NotNull - @Override - public MessageHolder localize(@NotNull Player playerLocale) { - return localize(getPlayerLocale(playerLocale)); - } - - @Override - public @NotNull MessageKey getLocalizableKey() { - return MessageKeyImpl.this; - } - - @NotNull - @Override - public Object[] getLocalizableArgs() { - return args; - } - } - - public record MessageHolderImpl(String[] miniMessageRaw, Object[] positionalArgs) implements MessageHolder { - public static final Object[] EMPTY_ARGS = new Object[0]; + return ComponentFormatter.deserializeLinesAsListWithArgs(localizeRawValue(locale), args); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java new file mode 100644 index 000000000..a408d13b2 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java @@ -0,0 +1,116 @@ +package net.codingarea.challenges.plugin.content.i18n.impl.format; + +import net.codingarea.challenges.plugin.content.i18n.MessageHolder; +import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentLike; +import net.kyori.adventure.translation.Translatable; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public final class ComponentArguments { + + private ComponentArguments() { + } + + @NotNull + public static Component convertToComponent(@Nullable Object obj) { + return switch (obj) { + case null -> Component.empty(); + case Component component -> component; + case ComponentLike like -> like.asComponent(); + case MessageHolder holder -> convertMessageHolderToComponent(holder); + case Material material -> getDetailedMaterialTranslatable(material); + case Translatable translatable -> // net.kyori.adventure.translation.Translatable + Component.translatable(translatable); + case Player player -> player.displayName(); + case String string -> // ! user input must be escaped via Component.text(...) + ComponentFormatter.deserializeText(string); + case Enum enumObj -> Component.text(stringifyEnumName(enumObj.name())); + default -> Component.text(obj.toString()); + }; + } + + @NotNull + public static Component convertMessageHolderToComponent(@NotNull MessageHolder holder) { + return ComponentFormatter.deserializeLinesWithArgs(null, holder.rawValue(), holder.positionalArgs()); + } + + @NotNull + public static Component getDetailedMaterialTranslatable(@NotNull Material material) { + String key = material.translationKey(); // e.g., "item.minecraft.music_disc_strad" + Component baseComponent = Component.translatable(key); + String name = material.name(); + + if (name.startsWith("MUSIC_DISC_")) { + // 1.21+ changed music disc details description: *.desc -> jukebox_song.minecraft.* + + String songTranslationKey; + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_21)) { + songTranslationKey = key.replace("item.minecraft.music_disc_", "jukebox_song.minecraft."); + } else { + songTranslationKey = key + ".desc"; + } + + return appendDetailsTranslatable(baseComponent, songTranslationKey); + } + + if (name.endsWith("_BANNER_PATTERN")) { + // 1.20.5+ added pattern name into item name; before *.desc + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_20_5)) return baseComponent; + + String patternTranslationKey = key + ".desc"; + return appendDetailsTranslatable(baseComponent, patternTranslationKey); + } + + if (name.endsWith("_SMITHING_TEMPLATE")) { + // 1.20.5+ added smithing template name into item name + if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_20_5)) return baseComponent; + + String descTranslationKey; + if (name.equals("NETHERITE_UPGRADE_SMITHING_TEMPLATE")) { + descTranslationKey = "upgrade.minecraft.netherite_upgrade"; + } else { + // Dynamically extract the trim type (e.g., "ward" from "WARD_ARMOR_TRIM_SMITHING_TEMPLATE") + String trimType = name.replace("_ARMOR_TRIM_SMITHING_TEMPLATE", "").toLowerCase(); + descTranslationKey = "trim_pattern.minecraft." + trimType; + } + + return appendDetailsTranslatable(baseComponent, descTranslationKey); + } + + // Default behavior for all other non-ambiguous items + return baseComponent; + } + + @NotNull + private static Component appendDetailsTranslatable(@NotNull Component baseComponent, @NotNull String translationKey) { + return baseComponent + .append(Component.text(" (")) // Component#appendSpace not available pre 1.19.3 + .append(Component.translatable(translationKey)) + .append(Component.text(")")); + } + + @NotNull + public static String stringifyEnumName(@NotNull String enumName) { + // EXAMPLE_ENUM -> "Example Enum" + int len = enumName.length(); + if (len == 0) return ""; + + char[] result = new char[len]; + boolean nextUpperCase = true; + for (int i = 0; i < len; i++) { + char letter = enumName.charAt(i); + if (letter == '_') { + result[i] = ' '; + nextUpperCase = true; + } else { + result[i] = nextUpperCase ? Character.toUpperCase(letter) : Character.toLowerCase(letter); + nextUpperCase = false; + } + } + return new String(result); + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java new file mode 100644 index 000000000..7b9e7b535 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java @@ -0,0 +1,150 @@ +package net.codingarea.challenges.plugin.content.i18n.impl.format; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.TextReplacementConfig; +import net.kyori.adventure.text.format.TextDecoration; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public final class ComponentFormatter { + + public static final MiniMessage MINI_MESSAGE = MiniMessage.miniMessage(); + public static final LegacyComponentSerializer LEGACY_SECTION = LegacyComponentSerializer.legacySection(); // temp migration impl + + private static final Map prefixCache = new ConcurrentHashMap<>(); + + private ComponentFormatter() { + } + + @NotNull + public static Component deserializeLinesWithArgs(@Nullable String prefix, @NotNull String[] textLines, @NotNull Object[] positionalArgs) { + return replacePositionalArgs(deserializeLines(prefix, textLines), positionalArgs); + } + + @NotNull + public static Component deserializeLineWithArgs(@NotNull String line, @NotNull Object[] positionalArgs) { + return replacePositionalArgs(deserializeText(line), positionalArgs); + } + + @NotNull + public static Component deserializeLines(@Nullable String prefix, @NotNull String[] textLines) { + if (textLines.length == 0) return Component.empty(); + + // Component.text() (Builder) incompatible in version change 26.1.2 -> 26.2 + Component rootComponent = Component.empty(); + + Component prefixComponent = (prefix != null && !prefix.isEmpty()) ? + prefixCache.computeIfAbsent(prefix, ComponentFormatter::deserializeText) : null; + + // DISCUSSION: performance trade off for caching frequently used components vs. parsing on the fly + for (int i = 0; i < textLines.length; i++) { + if (textLines[i].isBlank()) { // no prefix for empty lines + rootComponent = rootComponent.append(Component.newline()); + continue; + } + + Component lineComponent = deserializeText(textLines[i]); + + if (prefixComponent != null) { + rootComponent = rootComponent.append(prefixComponent).append(lineComponent); + } else { + rootComponent = rootComponent.append(lineComponent); + } + + if (i < textLines.length - 1) { + rootComponent = rootComponent.append(Component.newline()); + } + } + + return rootComponent; + } + + @NotNull + public static List deserializeLinesAsListWithArgs(@NotNull String[] textLines, @NotNull Object[] args) { + if (textLines.length == 0) return Collections.emptyList(); + + boolean hasArgs = args.length > 0; // don't waste time on processing otherwise + List components = new ArrayList<>(textLines.length + args.length); // might grow with args; extending is more expensive + for (String textLine : textLines) { + Component line = deserializeText(textLine); + if (hasArgs) { + List replaced = replacePositionalArgsAsList(line, args); + components.addAll(replaced); + } else { + components.add(line); + } + } + return components; + } + + @NotNull + public static Component replacePositionalArgs(@NotNull Component component, @Nullable Object[] positionalArgs) { + if (positionalArgs == null || positionalArgs.length == 0) { + return component; + } + + return component.replaceText(TextReplacementConfig.builder() + .match(MessageFormatter.POS_ARG_PATTERN) + .replacement((matchResult, builder) -> { + int index = Integer.parseInt(matchResult.group(1)); + if (index >= 0 && index < positionalArgs.length) { + return ComponentArguments.convertToComponent(positionalArgs[index]); + } + return builder; // or else leave as is, no runtime exceptions + }).build()); + } + + @NotNull + public static List replacePositionalArgsAsList(@NotNull Component component, @Nullable Object[] positionalArgs) { + if (positionalArgs == null || positionalArgs.length == 0) { + return List.of(component); + } + + Component replaced = replacePositionalArgs(component, positionalArgs); + return ComponentSplitter.split(replaced, ComponentSplitter.NEW_LINE); + } + + @NotNull + static Component deserializeText(@NotNull String textLine) { + return applyDecorationIfAbsent(deserializeText0(textLine), TextDecoration.ITALIC, TextDecoration.State.FALSE); + } + + @NotNull + private static Component applyDecorationIfAbsent(@NotNull Component component, @NotNull TextDecoration decoration, @NotNull TextDecoration.State value) { + // Component#decorationIfAbsent introduced in 1.19.3 + if (component.decoration(decoration) == TextDecoration.State.NOT_SET) { + component = component.decoration(decoration, value); + } + return component; + } + + @NotNull + private static Component deserializeText0(@NotNull String textLine) { + // TODO legacy text should only be supported during migration; impl will be removed in the future + if (isProbablyLegacyText(textLine)) { + return LEGACY_SECTION.deserialize(textLine); + } + try { + return MINI_MESSAGE.deserialize(textLine); + } catch (Exception ex) { // maybe heuristic failed, try legacy again + return LEGACY_SECTION.deserialize(textLine); + } + } + + private static boolean isProbablyLegacyText(@NotNull String text) { + // legacy texts often start/end with a '§' color; heuristic so we don't have to check the full string + if (text.length() < 2) return false; + if (text.charAt(0) == '§') return true; + return text.charAt(text.length() - 2) == '§'; + } + +} diff --git a/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/ComponentSplitter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSplitter.java similarity index 96% rename from platform/common/src/main/java/net/codingarea/challenges/platform/message/common/ComponentSplitter.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSplitter.java index 9511dc7d2..15205f4f2 100644 --- a/platform/common/src/main/java/net/codingarea/challenges/platform/message/common/ComponentSplitter.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSplitter.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.platform.message.common; +package net.codingarea.challenges.plugin.content.i18n.impl.format; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; @@ -12,6 +12,9 @@ public final class ComponentSplitter { + @RegExp + public static final String NEW_LINE = "\\n"; + private ComponentSplitter() { } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageFormatter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/MessageFormatter.java similarity index 86% rename from plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageFormatter.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/MessageFormatter.java index 0715ac5ea..85ec1ce8b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageFormatter.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/MessageFormatter.java @@ -1,20 +1,27 @@ -package net.codingarea.challenges.plugin.content.i18n.impl; +package net.codingarea.challenges.plugin.content.i18n.impl.format; import net.codingarea.commons.common.logging.ILogger; import org.jetbrains.annotations.CheckReturnValue; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.*; - -import static net.codingarea.challenges.platform.message.MessagePlatform.*; +import java.util.regex.Pattern; public final class MessageFormatter { // pre expansion for better server runtime performance + public static final char ESCAPE_CHAR = '\\'; + public static final char START_ARG_CHAR = '{'; + public static final char END_ARG_CHAR = '}'; + public static final char REFERENCE_CHAR = '@'; + public static final char START_REFERENCE_ARGS_CHAR = '('; + public static final char END_REFERENCE_ARGS_CHAR = ')'; + public static final char REFERENCE_ARG_CHAR = '\''; public static final char COLORIZE_CHAR = '*'; - public static final String COLORIZE_KEY = "*colorize"; + public static final String COLORIZE_KEY = "*colorize*"; public static final char SUB_DOCUMENT_DELIMITER = '.'; public static final String SUB_DOCUMENT_PATH_PATTERN = "\\."; + + public static final Pattern POS_ARG_PATTERN = Pattern.compile("\\{(\\d+)\\}"); public static final String[] EMPTY_STRINGS = new String[0]; private static final ILogger logger = ILogger.forThisClass(); // logs illegal argument indices or references @@ -22,11 +29,10 @@ public final class MessageFormatter { // pre expansion for better server runtime private MessageFormatter() { } - @CheckReturnValue public static boolean isMetaTag(@NotNull String keyName) { String[] subPathComponents = keyName.split(SUB_DOCUMENT_PATH_PATTERN); String relativeKeyName = subPathComponents[subPathComponents.length - 1]; - return relativeKeyName.equals(COLORIZE_KEY); // currently only meta implemented + return relativeKeyName.equals(COLORIZE_KEY); // only meta tag currently implemented } @NotNull @@ -43,11 +49,10 @@ private static String[] embedReferences(@NotNull String[] origin, @NotNull Strin @NotNull Map messagesBundle, @NotNull Set visited) { if (origin.length == 0) return origin; if (messagesBundle.isEmpty()) return origin; + // colorization via meta tag will be applied after references are resolved and embedded! String[] originSubDocumentPath = extractSubDocumentPath(originKey); // for relative references resolution - colorize(origin, originSubDocumentPath, messagesBundle); // apply colorization if defined for this sub-document - // if a referenced message is more than one line, the result will grow ArrayList result = new ArrayList<>(origin.length); // will be cleared and reused @@ -100,7 +105,10 @@ private static String[] embedReferences(@NotNull String[] origin, @NotNull Strin if (inReferenceArgument) { String builtReferenceArgument = referenceArgument.toString(); - referenceArguments.add(builtReferenceArgument); + // resolve nested references in argument + String[] embeddedReferenceArgument = embedReferences(new String[]{builtReferenceArgument}, originKey, messagesBundle, visited); + + referenceArguments.add(String.join("", embeddedReferenceArgument)); // TODO newline? referenceArgument.setLength(0); // clear and reuse } inReferenceArgument = !inReferenceArgument; @@ -127,11 +135,11 @@ private static String[] embedReferences(@NotNull String[] origin, @NotNull Strin } // end of processing this line if (!reference.isEmpty()) { // arg was not closed - System.err.println("Unclosed reference in '" + line + "' of " + originKey + ": '" + reference + "'"); + logger.warn("Unclosed reference in '" + line + "' of " + originKey + ": '" + reference + "'"); builder.append(START_ARG_CHAR).append(reference); } if (!referenceArgument.isEmpty()) { // arg was not closed - System.err.println("Unclosed reference argument in '" + line + "' of " + originKey + ": '" + referenceArgument + "'"); + logger.warn("Unclosed reference argument in '" + line + "' of " + originKey + ": '" + referenceArgument + "'"); builder.append(REFERENCE_ARG_CHAR).append(referenceArgument); } @@ -141,7 +149,10 @@ private static String[] embedReferences(@NotNull String[] origin, @NotNull Strin builder.setLength(0); // reset line for next iteration } - return result.toArray(String[]::new); + + String[] embedded = result.toArray(String[]::new); + colorize(embedded, originSubDocumentPath, messagesBundle); // apply colorization if defined for this sub-document + return embedded; } private static void resolveReferenceInto(@NotNull String originKey, @NotNull Map messagesBundle, @@ -171,10 +182,6 @@ private static void resolveReferenceInto(@NotNull String originKey, @NotNull Map String[] embeddedReferenced = referenceArguments.isEmpty() ? referenced : embedPositionalArgs(referenced, referenceArguments.toArray()); referenceArguments.clear(); // clear and reuses - - System.out.println("Resolved reference '" + relativeReferenceName + "' (qualified: " + qualifiedReferenceName + ") in " + originKey + - ": " + Arrays.toString(referenced) + " -> " + Arrays.toString(embeddedReferenced)); - // append reference message if (referenced.length == 1) { builder.append(embeddedReferenced[0]); @@ -198,7 +205,7 @@ private static void resolveReferenceInto(@NotNull String originKey, @NotNull Map @NotNull @CheckReturnValue private static String qualifyRelativeKey(@NotNull String relativeReferenceName, @NotNull String[] originSubDocumentPath, - @NonNull Map messagesBundle) { + @NotNull Map messagesBundle) { String qualifiedReferenceName = relativeReferenceName; for (int path = 0; path < originSubDocumentPath.length && !messagesBundle.containsKey(qualifiedReferenceName); path++) { StringBuilder pathQualifierUntilX = new StringBuilder(originSubDocumentPath.length * 12); @@ -283,18 +290,18 @@ public static String embedPositionalArgs(@NotNull String sequence, @NotNull Obje return builder.toString(); } - private static void colorize(@NotNull String[] rawValue, @NotNull String[] originSubDocumentPath, @NotNull Map messageBundle) { - if (rawValue.length == 0) return; + private static void colorize(@NotNull String[] value, @NotNull String[] originSubDocumentPath, @NotNull Map messageBundle) { + if (value.length == 0) return; String qualifiedColorizeKey = qualifyRelativeKey(COLORIZE_KEY, originSubDocumentPath, messageBundle); String[] colorizeValue = messageBundle.get(qualifiedColorizeKey); if (colorizeValue == null || colorizeValue.length == 0) return; // no colorizer defined - StringBuilder builder = new StringBuilder(rawValue[0].length() + colorizeValue[0].length()); + StringBuilder builder = new StringBuilder(value[0].length() + colorizeValue[0].length()); StringBuilder argument = new StringBuilder(32); boolean colorizing = false; - for (int line = 0; line < rawValue.length; line++) { - String text = rawValue[line]; + for (int line = 0; line < value.length; line++) { + String text = value[line]; int len = text.length(); for (int i = 0; i < len; i++) { char c = text.charAt(i); @@ -332,7 +339,7 @@ private static void colorize(@NotNull String[] rawValue, @NotNull String[] origi if (!argument.isEmpty()) { builder.append(COLORIZE_CHAR).append(argument); } - rawValue[line] = builder.toString(); + value[line] = builder.toString(); builder.setLength(0); // reset line for next iteration } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/ItemDescription.java similarity index 98% rename from plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/ItemDescription.java index 3d6ca244b..04e4e60db 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/ItemDescription.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/ItemDescription.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.content; +package net.codingarea.challenges.plugin.content.legacy; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.utils.misc.ColorConversions; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/Message.java similarity index 95% rename from plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/Message.java index 06dab412d..54813880a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/Message.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/Message.java @@ -1,7 +1,6 @@ -package net.codingarea.challenges.plugin.content; +package net.codingarea.challenges.plugin.content.legacy; import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.content.impl.MessageManager; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.collection.IRandom; import net.md_5.bungee.api.chat.BaseComponent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/MessageImpl.java similarity index 85% rename from plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/MessageImpl.java index 046618080..f23a1d362 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/MessageImpl.java @@ -1,8 +1,6 @@ -package net.codingarea.challenges.plugin.content.impl; +package net.codingarea.challenges.plugin.content.legacy; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.ItemDescription; -import net.codingarea.challenges.plugin.content.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; @@ -141,29 +139,7 @@ private void doSendLines(@NotNull Consumer sender, @NotNu } private void doSendLine(@NotNull Consumer sender, @NotNull Prefix prefix, BaseComponent component) { - LanguageLoader loader = Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class); - boolean capsFont = loader.isSmallCapsFont(); - BaseComponent component1 = component; - if (capsFont) { - if (component1 instanceof TextComponent) { - component1 = new TextComponent(FontUtils.toSmallCaps(((TextComponent) component1).getText())); - } - if (component != null) { - List extra = component.getExtra(); - if (extra != null) { - component.setExtra(new LinkedList<>()); - for (BaseComponent baseComponent : extra) { - if (baseComponent instanceof TextComponent) { - String text = ((TextComponent) baseComponent).getText(); - component1.addExtra(new TextComponent(text)); - } else { - component1.addExtra(baseComponent); - } - } - } - } - } // Weird bugs can cause this to be null if the line is empty and kicks the player in 1.19+ if (component1 != null) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/MessageManager.java similarity index 88% rename from plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/MessageManager.java index 3021dcac6..254b7d5e0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/impl/MessageManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/MessageManager.java @@ -1,13 +1,13 @@ -package net.codingarea.challenges.plugin.content.impl; +package net.codingarea.challenges.plugin.content.legacy; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; import org.jetbrains.annotations.NotNull; import java.util.Locale; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +@Deprecated public final class MessageManager { private static final Map cache = new ConcurrentHashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index 63732f346..c6bcd4a56 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -2,6 +2,7 @@ import lombok.Getter; import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.i18n.LanguageProvider; import net.codingarea.challenges.plugin.content.i18n.TranslationManager; import net.codingarea.challenges.plugin.management.files.ConfigManager; @@ -33,14 +34,11 @@ public final class LanguageLoader extends ContentLoader { @Getter private Locale configLanguage; // default, will be ignored if custom LanguageProvider is set in TranslationManager @Getter - @Deprecated - private final boolean smallCapsFont = false; - @Getter private boolean onlineUpdateEnabled; @Getter private Set availableLanguageTags; - @Getter private boolean skipMigration; + private Set loadedLanguages; @Override protected void load() { @@ -51,6 +49,7 @@ protected void load() { skipMigration = config.getBoolean(ConfigManager.Keys.SKIP_LANGUAGE_MIGRATION, false); configLanguage = Locale.forLanguageTag(configLanguageTag); availableLanguageTags = new HashSet<>(); + loadedLanguages = new HashSet<>(); // extracted the language provider so it can easily be overridden Challenges.getInstance().getTranslationManager().setLanguageProvider(new DefaultLanguageProvider()); @@ -62,7 +61,7 @@ private void loadDefault() { if (!skipMigration) migrateLanguages(); discoverAvailableLanguageTagFiles(); checkLanguageFileExists(); - readSelectedLanguage(); + readSelectedLanguageIfNotPresent(); } public void changeLanguage(@NotNull String language) { @@ -76,12 +75,17 @@ public void changeLanguage(@NotNull String language) { Logger.info("Language changed to '{}'", language); } - private void reloadWithLanguage(String language) { + private void reloadWithLanguage(@NotNull String language) { this.configLanguageTag = language; checkLanguageFileExists(); // do the check first, might change languageTag to fallback this.configLanguage = Locale.forLanguageTag(configLanguageTag); - readSelectedLanguage(); // TODO async - Challenges.getInstance().getScoreboardManager().updateAll(); + readSelectedLanguageIfNotPresent(); + + ChallengeHelper.runSync(() -> { + Challenges.getInstance().getChallengeTimer().updateActionbar(); + Challenges.getInstance().getScoreboardManager().updateAll(); + Challenges.getInstance().getMenuManager().reopenCurrentMenus(); // must be run sync + }); } private void checkLanguageFileExists() { @@ -96,14 +100,15 @@ private void checkLanguageFileExists() { Logger.debug("Language '{}' is currently selected", configLanguageTag); } - private void readSelectedLanguage() { + private void readSelectedLanguageIfNotPresent() { + if (loadedLanguages.contains(configLanguageTag)) return; populateLanguageFromFile(configLanguage); } private void discoverAvailableLanguageTagFiles() { // only .json files supported; global is not a selectable language File[] files = getMessagesFolder() - .listFiles((_, name) -> name.endsWith(".json") && !name.startsWith(GLOBAL_TAG)); + .listFiles((file, name) -> name.endsWith(".json") && !name.startsWith(GLOBAL_TAG)); if (files == null) return; for (File file : files) { if (!file.isFile()) continue; @@ -251,6 +256,8 @@ private void populateLanguageFromFile(@NotNull File languageFile, @NotNull File return; } + loadedLanguages.add(locale.getLanguage()); + Document globalDocument = Document.readJsonFile(globalFile); Document languageDocument = Document.readJsonFile(languageFile); int messageCount = Challenges.getInstance().getTranslationManager().populateLanguageFromDocument(locale, languageDocument, globalDocument); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java index df645f7d1..c02348eba 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LoaderRegistry.java @@ -81,7 +81,7 @@ public void subscribe(@NotNull Class classOfLoader, @No @NotNull public Optional getFirstLoaderByClass(@NotNull Class clazz) { for (ContentLoader loader : loaders) { - if (loader.getClass().equals(clazz)) { + if (clazz.isAssignableFrom(loader.getClass())) { return Optional.of(clazz.cast(loader)); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java index 7af2dde08..07d053bb3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java @@ -20,7 +20,6 @@ import net.codingarea.challenges.plugin.challenges.implementation.setting.*; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder.PotionBuilder; import net.codingarea.challenges.plugin.utils.misc.ArmorUtils; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import org.bukkit.Material; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; @@ -42,7 +41,7 @@ public void enable() { register(RespawnSetting.class); register(SplitHealthSetting.class); register(DamageDisplaySetting.class); - register(LanguageSetting.class); + registerWithCommand(LanguageSetting.class, "setlanguage"); register(PregameMovementSetting.class); register(DeathMessageSetting.class); @@ -76,6 +75,7 @@ public void enable() { register(TotemSaveDeathSetting.class); register(SoupSetting.class); + register(HardcoreHeartsSetting.class); // Challenges @@ -260,10 +260,7 @@ public void enable() { registerDamageRule("drowning", PotionBuilder.createWaterBottle(), DamageCause.DROWNING); registerDamageRule("block", Material.SAND, DamageCause.FALLING_BLOCK, DamageCause.SUFFOCATION, DamageCause.CONTACT); registerDamageRule("magic", Material.BREWING_STAND, DamageCause.MAGIC, DamageCause.POISON, DamageCause.WITHER); - - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_17)) { - registerDamageRule("freeze", Material.POWDER_SNOW_BUCKET, DamageCause.FREEZE); - } + registerDamageRule("freeze", Material.POWDER_SNOW_BUCKET, DamageCause.FREEZE); // 1.17+ // Material Rules registerMaterialRule("§cArmor", "Armor", ArmorUtils.getArmor()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java index d2248ce7f..a649397af 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java @@ -4,6 +4,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.damage.DamageRuleSetting; import net.codingarea.challenges.plugin.challenges.implementation.material.BlockMaterialSetting; import net.codingarea.challenges.plugin.challenges.type.IChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.RequireDepend; import net.codingarea.challenges.plugin.challenges.type.annotation.RequireVersion; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.core.BukkitModule; @@ -62,6 +63,16 @@ public final void registerWithCommand(@NotNull Class class } } + if (classOfChallenge.isAnnotationPresent(RequireDepend.class)) { + RequireDepend annotation = classOfChallenge.getAnnotation(RequireDepend.class); + String depend = annotation.plugin(); + + if (!plugin.getServer().getPluginManager().isPluginEnabled(depend)) { + Logger.debug("Did not register challenge {}, requires plugin {}", classOfChallenge.getSimpleName(), depend); + return; + } + } + Constructor constructor = classOfChallenge.getDeclaredConstructor(parameterClasses); IChallenge challenge = constructor.newInstance(parameters); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java index ca7f16ab0..4addfac95 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/files/ConfigManager.java @@ -116,6 +116,7 @@ public class Keys { // type safety public final String NEW_SUFFIX = "challenge-updates.new.suffix"; public final String NEW_IN_FRONT = "challenge-updates.new.in-front"; public final String UPDATED_SUFFIX = "challenge-updates.updated.suffix"; + public final String UPDATED_IN_FRONT = "challenge-updates.updated.in-front"; } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java index 096758d81..32bbf4948 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java @@ -3,7 +3,7 @@ import lombok.Getter; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java index 1a876b4ef..2882ffe7f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/InventoryTitleManager.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.menu; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import org.jetbrains.annotations.NotNull; @Deprecated diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java index 8c9032ff4..611b5e84e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java @@ -7,11 +7,13 @@ import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; +import net.codingarea.challenges.plugin.management.menu.generator.AbstractMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.MainMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengesMenuGenerator; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -83,6 +85,19 @@ public boolean openMenu(@NotNull Player player, @NotNull MenuType type, int page return true; } + public void reopenCurrentMenus() { + for (Player player : Bukkit.getOnlinePlayers()) { + reopenCurrentMenu(player); + } + } + + public void reopenCurrentMenu(@NotNull Player player) { + // applies language change + MenuPosition position = MenuPosition.get(player); + if (!(position instanceof AbstractMenuGenerator.GeneratorMenuPosition generatorPosition)) return; + generatorPosition.getGenerator().openMenu(player, generatorPosition.getPage()); + } + public void playNoPermissionsEffect(@NotNull Player player) { SoundSample.BASS_OFF.play(player); MessageKey.of("no-permission").send(player, Prefix.CHALLENGES); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java index c12b25cdc..4852ff211 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java @@ -5,6 +5,8 @@ import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import org.bukkit.Bukkit; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; @@ -29,8 +31,8 @@ public void setInventoryDecoration(@NotNull Inventory inventory, int page, @NotN @NotNull protected Inventory createEmptyInventory(@NotNull Locale locale, int page) { - return getMenuTitleKey().createInventory(locale, getInventorySize(), - getMenuName(), getMenuTitlePageArg(page)); + return Bukkit.createInventory(MenuPosition.HOLDER, getInventorySize(), + getMenuTitleKey().asComponent(locale, getMenuName(), getMenuTitlePageArg(page))); } @NotNull @@ -40,8 +42,7 @@ protected Object getMenuTitlePageArg(int page) { @NotNull private MessageKey getMenuTitleKey() { - int pageCount = getPageCount(); - if (pageCount == 1) return MessageKey.of("menu.title-format"); + if (getPageCount() == 1) return MessageKey.of("menu.title-format"); return MessageKey.of("menu.title-format-page"); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java index 404105099..504212b5f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java @@ -1,6 +1,8 @@ package net.codingarea.challenges.plugin.management.menu.generator; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.jetbrains.annotations.CheckReturnValue; @@ -26,8 +28,7 @@ public abstract class SinglePageMenuGenerator extends AbstractMenuGenerator { @NotNull protected Inventory createEmptyInventory(@NotNull Locale locale) { - return MessageKey.of("menu.title-format").createInventory(locale, getInventorySize(), - getMenuName()); + return Bukkit.createInventory(MenuPosition.HOLDER, getInventorySize(), MessageKey.of("menu.title-format").asComponent(locale, getMenuName())); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java index e0b117787..6665bd098 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java @@ -3,8 +3,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.ChallengeAnnotations; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.menu.generator.implementation.SettingsMenuGenerator; @@ -12,7 +11,6 @@ import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import org.bukkit.ChatColor; import org.bukkit.inventory.Inventory; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java index 09abbeaf3..49c036ed6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java @@ -29,7 +29,7 @@ public MenuPosition createMenuPosition() { @NotNull @Override public AnimatedInventory createAnimatedInventory(@NotNull Locale locale) { - AnimatedInventory gui = new AnimatedInventory(SIZE, size -> MessageKey.of("menu-main-title").createInventory(locale, size)); + AnimatedInventory gui = new AnimatedInventory(MessageKey.of("menu-main-title").asComponent(locale), SIZE, MenuPosition.HOLDER); gui.createAndAdd().fill(ItemBuilder.FILL_ITEM); gui.cloneLastAndAdd().setContrast(39, 41); gui.cloneLastAndAdd().setContrast(38, 42); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/TimerMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/TimerMenuGenerator.java index c2ff02ed7..1d5ff7aa7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/TimerMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/TimerMenuGenerator.java @@ -5,6 +5,7 @@ import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.management.menu.generator.MultiPageMenuGenerator; +import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerFormat; @@ -20,7 +21,6 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.List; import java.util.Locale; @@ -28,8 +28,9 @@ public class TimerMenuGenerator extends MultiPageMenuGenerator { public static final int SIZE = 5 * 9; - public static final int START_SLOT = 21; - public static final int MODE_SLOT = 23; + public static final int START_SLOT = 20; + public static final int SHOW_SLOT = 22; + public static final int MODE_SLOT = 24; public static final int[] DAYS_SLOTS = {11, 20, 29}; public static final int[] HOUR_SLOTS = {12, 21, 30}; public static final int[] MINUTE_SLOTS = {14, 23, 32}; @@ -37,7 +38,6 @@ public class TimerMenuGenerator extends MultiPageMenuGenerator { public static final int PAGE_STATE = 0, PAGE_TIME = 1; public static final int SHIFT_CHANGE_TIME_AMOUNT = 10; - private static final Material MID_GOLD_ITEM = MinecraftNameWrapper.getMaterialByNames("RAW_GOLD", "GOLDEN_CARROT"); private static final List> SLOTS_AMOUNT_MAPPING = List.of( Tuple.of(DAYS_SLOTS, 24 * 60 * 60), Tuple.of(HOUR_SLOTS, 60 * 60), @@ -55,7 +55,7 @@ public void updateTimerStateInventory() { updatePage(PAGE_STATE); } - @ScheduledTask(ticks = 20) + @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.STARTED) public void updateTimeInventory() { updatePage(PAGE_TIME); } @@ -99,11 +99,14 @@ public int getPageCount() { public void updateTimerStatePage(@NotNull Inventory inventory, @NotNull Locale locale) { inventory.setItem(START_SLOT, Challenges.getInstance().getChallengeTimer().isStarted() ? - new ItemBuilder(locale, Material.LIME_DYE, MessageKey.of("timer-is-running")).build() : - new ItemBuilder(locale, MinecraftNameWrapper.RED_DYE, MessageKey.of("timer-is-paused")).build()); + new ItemBuilder(locale, Material.LIME_DYE, MessageKey.of("menu.timer.item-started")).build() : + new ItemBuilder(locale, MinecraftNameWrapper.RED_DYE, MessageKey.of("menu.timer.item-paused")).build()); + inventory.setItem(SHOW_SLOT, Challenges.getInstance().getChallengeTimer().isHidden() ? + new ItemBuilder(locale, Material.BARRIER, MessageKey.of("menu.timer.item-hidden")).build() : + new ItemBuilder(locale, Material.ENDER_EYE, MessageKey.of("menu.timer.item-shown")).build()); inventory.setItem(MODE_SLOT, Challenges.getInstance().getChallengeTimer().isCountingUp() ? - new ItemBuilder.SkullBuilder(locale, MessageKey.of("timer-counting-up")).setBase64Texture(DefaultItem.SkullTextures.GREEN_ARROW_UP).build() : - new ItemBuilder.SkullBuilder(locale, MessageKey.of("timer-counting-down")).setBase64Texture(DefaultItem.SkullTextures.RED_ARROW_DOWN).build()); + new ItemBuilder.SkullBuilder(locale, MessageKey.of("menu.timer.item-counting-up")).setBase64Texture(DefaultItem.SkullTextures.GREEN_ARROW_UP).build() : + new ItemBuilder.SkullBuilder(locale, MessageKey.of("menu.timer.item-counting-down")).setBase64Texture(DefaultItem.SkullTextures.RED_ARROW_DOWN).build()); } public void updateTimePage(@NotNull Inventory inventory, @NotNull Locale locale) { @@ -122,7 +125,7 @@ public void updateTimePage(@NotNull Inventory inventory, @NotNull Locale locale) MessageKey.of("menu.timer.item-days"), MessageKey.of("menu.timer.item-days-add"), MessageKey.of("menu.timer.item-days-subtract")); - setTimeItems(inventory, locale, HOUR_SLOTS, hours, format, MID_GOLD_ITEM, + setTimeItems(inventory, locale, HOUR_SLOTS, hours, format, Material.RAW_GOLD, MessageKey.of("menu.timer.item-hours"), MessageKey.of("menu.timer.item-hours-add"), MessageKey.of("menu.timer.item-hours-subtract")); @@ -172,20 +175,28 @@ public boolean handleMenuClick(@NotNull MenuClickInfo info) { }; } - private boolean handleTimerStateMenuClick(@NonNull MenuClickInfo info) { - if (info.getSlot() == START_SLOT) { - if (playNoPermissionsEffect(info.getPlayer())) return true; - Challenges.getInstance().getChallengeTimer().toggle(); - return true; - } else if (info.getSlot() == MODE_SLOT) { - if (playNoPermissionsEffect(info.getPlayer())) return true; - Challenges.getInstance().getChallengeTimer().setCountingUp(!Challenges.getInstance().getChallengeTimer().isCountingUp()); - return true; + private boolean handleTimerStateMenuClick(@NotNull MenuClickInfo info) { + switch (info.getSlot()) { + case START_SLOT -> { + if (playNoPermissionsEffect(info.getPlayer())) return true; + Challenges.getInstance().getChallengeTimer().toggle(); + return true; + } + case MODE_SLOT -> { + if (playNoPermissionsEffect(info.getPlayer())) return true; + Challenges.getInstance().getChallengeTimer().setCountingUp(!Challenges.getInstance().getChallengeTimer().isCountingUp()); + return true; + } + case SHOW_SLOT -> { + if (playNoPermissionsEffect(info.getPlayer())) return true; + Challenges.getInstance().getChallengeTimer().setHidden(!Challenges.getInstance().getChallengeTimer().isHidden()); + return true; + } } return false; } - private boolean handleTimeMenuClick(@NonNull MenuClickInfo info) { + private boolean handleTimeMenuClick(@NotNull MenuClickInfo info) { for (Tuple mapping : SLOTS_AMOUNT_MAPPING) { int[] slots = mapping.getFirst(); for (int i = 0; i < 3; i++) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java index 138cb8e82..af1bdd335 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator.impl.challenge; +import lombok.Getter; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.ChallengeAnnotations; @@ -15,7 +16,6 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.*; @@ -29,30 +29,39 @@ public class ChallengeListMenuGenerator extends ChallengesMenuGenerator { public static final int SLOT_OFFSET_LOWER = 2 * 9; private static final int[] SLOT_OFFSETS = {SLOT_OFFSET_UPPER, SLOT_OFFSET_DISPLAY, SLOT_OFFSET_SETTINGS, SLOT_OFFSET_LOWER}; + public static final ItemStack UPDATED_CHALLENGE_ITEM = new StandardItemBuilder(Material.YELLOW_STAINED_GLASS_PANE, "§0").build(); + public static final ItemStack NEW_CHALLENGE_ITEM = new StandardItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build(); + protected final List assignedChallengesCache = new LinkedList<>(); + @Getter protected final boolean newSuffix; + @Getter protected final boolean updatedSuffix; protected final boolean displayNewInFront; + protected final boolean displayUpdatedInFront; public ChallengeListMenuGenerator() { Document config = Challenges.getInstance().getConfigDocument(); newSuffix = config.getBoolean(ConfigManager.Keys.NEW_SUFFIX); updatedSuffix = config.getBoolean(ConfigManager.Keys.UPDATED_SUFFIX); displayNewInFront = config.getBoolean(ConfigManager.Keys.NEW_IN_FRONT); + displayUpdatedInFront = config.getBoolean(ConfigManager.Keys.UPDATED_IN_FRONT); } @Override public void addToCache(@NotNull IChallenge challenge) { - if (displayNewInFront) { + if (displayNewInFront && ChallengeAnnotations.isNew(challenge)) { assignedChallengesCache.add(countNewChallenges(), challenge); + } else if (displayUpdatedInFront && ChallengeAnnotations.isUpdated(challenge)) { + assignedChallengesCache.add(countNewChallenges() + countUpdatedChallenges(), challenge); } else { assignedChallengesCache.add(challenge); } } @Override - public boolean isCached(@NonNull IChallenge challenge) { + public boolean isCached(@NotNull IChallenge challenge) { return assignedChallengesCache.contains(challenge); } @@ -132,11 +141,11 @@ protected void updateChallengeDisplayAt(@NotNull IChallenge challenge, @NotNull protected void setChallengeUpdateItemsAt(@NotNull IChallenge challenge, @NotNull Inventory inventory, int slotIndex, @NotNull Locale locale) { if (newSuffix && ChallengeAnnotations.isNew(challenge)) { - inventory.setItem(DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_UPPER, new StandardItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); - inventory.setItem(DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_LOWER, new StandardItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); + inventory.setItem(DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_UPPER, NEW_CHALLENGE_ITEM); + inventory.setItem(DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_LOWER, NEW_CHALLENGE_ITEM); } else if (updatedSuffix && ChallengeAnnotations.isUpdated(challenge)) { - inventory.setItem(DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_UPPER, new StandardItemBuilder(Material.YELLOW_STAINED_GLASS_PANE, "§0").build()); - inventory.setItem(DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_LOWER, new StandardItemBuilder(Material.YELLOW_STAINED_GLASS_PANE, "§0").build()); + inventory.setItem(DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_UPPER, UPDATED_CHALLENGE_ITEM); + inventory.setItem(DISPLAY_SLOTS[slotIndex] + SLOT_OFFSET_LOWER, UPDATED_CHALLENGE_ITEM); } } @@ -199,6 +208,18 @@ protected int countNewChallenges() { return count; } + protected int countUpdatedChallenges() { + int count = 0; + for (IChallenge challenge : assignedChallengesCache) { + if (ChallengeAnnotations.isUpdated(challenge)) { + count++; + } else if (displayUpdatedInFront) { + break; + } + } + return count; + } + @Override public boolean hasAnyNewChallenges() { if (assignedChallengesCache.isEmpty()) return false; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java index f8f4c6019..0637ea349 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java @@ -4,6 +4,7 @@ import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; +import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengeListMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengesMenuGenerator; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -12,7 +13,6 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.*; @@ -20,6 +20,7 @@ public class CategorisedMenuGenerator extends ChallengesMenuGenerator { public static final int SIZE = 4 * 9; public static final int[] SLOTS = {10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25}; + public static final int MAX_ITEMS_PER_ROW = 7; protected final Map categoryGenerators = new HashMap<>(); protected final List orderedCategories = new ArrayList<>(); @@ -82,7 +83,7 @@ public Optional getFirstEnabledChallenge() { } @Override - public boolean isCached(@NonNull IChallenge element) { + public boolean isCached(@NotNull IChallenge element) { SettingCategory category = getChallengeCategoryOrMics(element); CategorisedListMenuGenerator generator = categoryGenerators.get(category); return generator != null && generator.isCached(element); @@ -98,8 +99,8 @@ public void updateElementDisplay(@NotNull IChallenge challenge) { int index = orderedCategories.indexOf(category); int[] slots = getSlots(); int page = index / slots.length; - int slot = slots[index % slots.length]; - updatePage(page, (inventory, locale) -> inventory.setItem(slot, createCategoryDisplayItem(locale, category))); + int slotIndex = index % slots.length; + updatePage(page, (inventory, locale) -> setCategoryItemsAt(category, inventory, slots, slotIndex, locale)); } } @@ -110,7 +111,30 @@ public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotN int len = categories.size(); for (int i = 0; i < len; i++) { SettingCategory category = categories.get(i); - inventory.setItem(slots[i], createCategoryDisplayItem(locale, category)); + setCategoryDisplayAt(category, inventory, slots, i, locale); + } + } + + private void setCategoryDisplayAt(@NotNull SettingCategory category, @NotNull Inventory inventory, int[] slots, int slotIndex, @NotNull Locale locale) { + setCategoryItemsAt(category, inventory, slots, slotIndex, locale); + setCategoryUpdateItemsAt(category, inventory, slots, slotIndex, locale); + } + + private void setCategoryItemsAt(@NotNull SettingCategory category, @NotNull Inventory inventory, int[] slots, int slotIndex, @NotNull Locale locale) { + inventory.setItem(slots[slotIndex], createCategoryDisplayItem(locale, category)); + } + + private void setCategoryUpdateItemsAt(@NotNull SettingCategory category, @NotNull Inventory inventory, int[] slots, int slotIndex, @NotNull Locale locale) { + CategorisedListMenuGenerator generator = categoryGenerators.get(category); + if (generator != null) { + // This will break if there are more than 2 rows! + int row = slotIndex / getMaxItemsPerRow(); + int offset = row == 0 ? -9 : +9; + if (generator.isNewSuffix() && generator.hasAnyNewChallenges()) { + inventory.setItem(slots[slotIndex] + offset, ChallengeListMenuGenerator.NEW_CHALLENGE_ITEM); + } else if (generator.isUpdatedSuffix() && generator.hasAnyUpdatedChallenges()) { + inventory.setItem(slots[slotIndex] + offset, ChallengeListMenuGenerator.UPDATED_CHALLENGE_ITEM); + } } } @@ -121,9 +145,9 @@ protected ItemStack createCategoryDisplayItem(@NotNull Locale locale, @NotNull S CategorisedListMenuGenerator generator = categoryGenerators.get(category); if (generator != null) { - if (generator.hasAnyNewChallenges()) { + if (generator.isNewSuffix() && generator.hasAnyNewChallenges()) { item.appendName(MessageKey.of("new-challenge-suffix")); - } else if (generator.hasAnyUpdatedChallenges()) { + } else if (generator.isUpdatedSuffix() && generator.hasAnyUpdatedChallenges()) { item.appendName(MessageKey.of("updated-challenge-suffix")); } @@ -188,6 +212,10 @@ public int[] getSlots() { return SLOTS; } + public int getMaxItemsPerRow() { + return MAX_ITEMS_PER_ROW; + } + @Override public int getInventorySize() { return SIZE; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java index 39cf9f31e..2706bfc8e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java @@ -8,7 +8,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java index 4910edfab..020a2b596 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.type.IChallenge; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChallengeMenuGenerator.java index f13f153fd..966bf9f66 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChallengeMenuGenerator.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.ChallengeAnnotations; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuManager; import net.codingarea.challenges.plugin.management.menu.position.LegacyGeneratorMenuPosition; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseMultipleItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseMultipleItemGenerator.java index 3103bc16f..5ddc5c763 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseMultipleItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseMultipleItemGenerator.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator.legacy; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.MainCustomMenuGenerator; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ValueMenuGenerator.java index a00bf5db9..68fb22c2e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ValueMenuGenerator.java @@ -2,7 +2,7 @@ import lombok.Getter; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.position.LegacyGeneratorMenuPosition; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java index 119b91a2e..c9157345f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java @@ -5,26 +5,35 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.impl.TimerMenuGenerator; +import net.codingarea.challenges.plugin.management.scheduler.policy.ExtraWorldPolicy; import net.codingarea.challenges.plugin.management.scheduler.policy.PlayerCountPolicy; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; +import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeActionBar; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.config.FileDocument; +import net.kyori.adventure.text.Component; import org.bukkit.*; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + public final class ChallengeTimer { - @Getter - private final TimerFormat format; + private final Map compiledFormats = new HashMap<>(); + private final boolean specificStartSounds, defaultStartSound; @Getter private long time = 0; @@ -32,19 +41,22 @@ public final class ChallengeTimer { private boolean countingUp = true; @Getter private boolean paused = true; + @Getter private boolean hidden = false; private boolean sentEmpty; public ChallengeTimer() { - Document pluginConfig = Challenges.getInstance().getConfigDocument(); specificStartSounds = pluginConfig.getBoolean("enable-specific-start-sounds"); defaultStartSound = pluginConfig.getBoolean("enable-default-start-sounds"); - Document formatConfig = pluginConfig.getDocument("timer.format"); - format = new TimerFormat(formatConfig); - Challenges.getInstance().getScheduler().register(this); + Challenges.getInstance().getLoaderRegistry().subscribe(LanguageLoader.class, this::precompileFormat); + } + + private void precompileFormat() { + Locale language = Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class).getConfigLanguage(); + getOrCompileFormat(language); } public void enable() { @@ -58,22 +70,38 @@ private void updateTimeRule() { } } - @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.ALWAYS, playerPolicy = PlayerCountPolicy.ALWAYS) - public void onTimerSecond() { + @NotNull + private TimerFormat getOrCompileFormat(@NotNull Locale locale) { + return compiledFormats.computeIfAbsent(locale, forLocale -> new TimerFormat(MessageKey.empty("timer.bar.format"), forLocale)); + } - if (!paused) { - if (countingUp) time++; - else time--; + @ScheduledTask(ticks = 20, async = false, timerPolicy = TimerPolicy.STARTED, playerPolicy = PlayerCountPolicy.ALWAYS) + public void incrementTimerSecond() { + if (countingUp) time++; + else time--; - if (time <= 0) { - time = 0; - countingUp = true; - handleHitZero(); - } + if (time <= 0) { + time = 0; + countingUp = true; + handleHitZero(); } + } - updateActionbar(); + @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.ALWAYS, playerPolicy = PlayerCountPolicy.ALWAYS, worldPolicy = ExtraWorldPolicy.ALWAYS) + public void updateActionbar() { + if (sentEmpty && hidden) return; + ChallengeActionBar currentActionBar = Challenges.getInstance().getScoreboardManager().getCurrentActionBar(); + if (currentActionBar != null) { + currentActionBar.send(); + } else if (!hidden) { + this.getCurrentActionbarMessage().broadcastActionBar(getFormattedTime()); + } else { + sentEmpty = true; + for (Player player : Bukkit.getOnlinePlayers()) { + player.sendActionBar(Component.empty()); + } + } } @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.PAUSED) @@ -97,7 +125,7 @@ public void resume() { updateActionbar(); updateTimeRule(); - MessageKey.of("timer-was-started").broadcast(Prefix.TIMER); + MessageKey.of("timer.messages.started").broadcast(Prefix.TIMER); Challenges.getInstance().getScheduler().fireTimerStatusChange(); Challenges.getInstance().getTitleManager().sendTimerStatusTitle(MessageKey.of("title-timer-started")); Challenges.getInstance().getServerManager().setNotFresh(); @@ -126,7 +154,7 @@ public void pause(boolean playInGameEffects) { Challenges.getInstance().getScheduler().fireTimerStatusChange(); if (playInGameEffects) { Challenges.getInstance().getTitleManager().sendTimerStatusTitle(MessageKey.of("title-timer-paused")); - MessageKey.of("timer-was-paused").broadcast(Prefix.TIMER); + MessageKey.of("timer.messages.paused").broadcast(Prefix.TIMER); SoundSample.BASS_OFF.broadcast(); } } @@ -146,19 +174,12 @@ public void reset() { updateActionbar(); } - public void updateActionbar() { - if (sentEmpty && hidden) return; - if (hidden) sentEmpty = true; - if (!hidden) { - this.getCurrentActionbarMessage().broadcastActionBar(getFormattedTime()); - } - } - @NotNull private MessageKey getCurrentActionbarMessage() { - if (paused) return MessageKey.of("stopped-message"); - if (countingUp) return MessageKey.of("count-up-message"); - return MessageKey.of("count-down-message"); + // TODO save references? + if (paused) return MessageKey.of("timer.bar.paused"); + if (countingUp) return MessageKey.of("timer.bar.up"); + return MessageKey.of("timer.bar.down"); } public synchronized void loadSession() { @@ -189,14 +210,30 @@ public void setSeconds(long seconds) { } public void setHidden(boolean hide) { + if (this.hidden == hide) return; + this.sentEmpty = false; this.hidden = hide; updateActionbar(); + TimerMenuGenerator menuGenerator = (TimerMenuGenerator) MenuType.TIMER.getMenuGenerator(); + menuGenerator.updatePage(TimerMenuGenerator.PAGE_STATE); + MessageKey.of("timer.messages." + (hide ? "hidden" : "shown")).broadcast(Prefix.TIMER); + SoundSample.BASS_ON.broadcast(); + } + + @NotNull + public String getFormattedTime(@NotNull Locale locale) { + return getOrCompileFormat(locale).format(time); + } + + @NotNull + public LocalizableMessage getFormattedTime() { + return getFormattedTimeFor(time); } @NotNull - public String getFormattedTime() { - return format.format(time); + public LocalizableMessage getFormattedTimeFor(long seconds) { + return LocalizableMessage.from(locale -> getOrCompileFormat(locale).format(seconds)); } @NotNull @@ -215,7 +252,7 @@ public void setCountingUp(boolean countingUp) { updateActionbar(); TimerMenuGenerator menuGenerator = (TimerMenuGenerator) MenuType.TIMER.getMenuGenerator(); menuGenerator.updatePage(TimerMenuGenerator.PAGE_STATE); - MessageKey.of("timer-mode-set-" + (countingUp ? "up" : "down")).broadcast(Prefix.TIMER); + MessageKey.of("timer.messages.counting-" + (countingUp ? "up" : "down")).broadcast(Prefix.TIMER); // TODO SoundSample.BASS_ON.broadcast(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java index a059e9075..470885ede 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java @@ -1,70 +1,172 @@ package net.codingarea.challenges.plugin.management.scheduler.timer; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.commons.common.config.Document; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; public final class TimerFormat { + private interface Token { + void append(@NotNull StringBuilder sb, long d, long h, long m, long s); + } + + private static final Token TOKEN_D = (sb, d, h, m, s) -> sb.append(d); + private static final Token TOKEN_DD = (sb, d, h, m, s) -> { + if (d < 10) sb.append('0'); + sb.append(d); + }; + private static final Token TOKEN_H = (sb, d, h, m, s) -> sb.append(h); + private static final Token TOKEN_HH = (sb, d, h, m, s) -> { + if (h < 10) sb.append('0'); + sb.append(h); + }; + private static final Token TOKEN_M = (sb, d, h, m, s) -> sb.append(m); + private static final Token TOKEN_MM = (sb, d, h, m, s) -> { + if (m < 10) sb.append('0'); + sb.append(m); + }; + private static final Token TOKEN_S = (sb, d, h, m, s) -> sb.append(s); + private static final Token TOKEN_SS = (sb, d, h, m, s) -> { + if (s < 10) sb.append('0'); + sb.append(s); + }; + public static final TimerFormat SIMPLE_FORMAT = new TimerFormat(); - private final String seconds, minutes, hours, day, days; + private record LiteralToken(String text) implements Token { + @Override + public void append(@NotNull StringBuilder sb, long d, long h, long m, long s) { + sb.append(text); + } + } + + private record CompiledFormat(Token[] tokens, int baseLength) { + } + + // pre compiled formatting + private final CompiledFormat secondsFormat, minutesFormat, hoursFormat, dayFormat, daysFormat; public TimerFormat(@NotNull Document document) { - seconds = document.getString("seconds", ""); - minutes = document.getString("minutes", ""); - hours = document.getString("hours", ""); - day = document.getString("day", ""); - days = document.getString("days", ""); + secondsFormat = compile(document.getString("seconds", "")); + minutesFormat = compile(document.getString("minutes", "")); + hoursFormat = compile(document.getString("hours", "")); + dayFormat = compile(document.getString("day", "")); + daysFormat = compile(document.getString("days", "")); + } + + public TimerFormat(@NotNull MessageKey rootKey, @NotNull Locale locale) { + secondsFormat = compile(rootKey.getChildKey("seconds").localizeRawValueAsSingleLine(locale)); + minutesFormat = compile(rootKey.getChildKey("minutes").localizeRawValueAsSingleLine(locale)); + hoursFormat = compile(rootKey.getChildKey("hours").localizeRawValueAsSingleLine(locale)); + dayFormat = compile(rootKey.getChildKey("day").localizeRawValueAsSingleLine(locale)); + daysFormat = compile(rootKey.getChildKey("days").localizeRawValueAsSingleLine(locale)); } - public TimerFormat() { - seconds = "{mm}:{ss}"; - minutes = "{mm}:{ss}"; - hours = "{hh}:{mm}:{ss}"; - day = "{d}:{hh}:{mm}:{ss}"; - days = "{d}:{hh}:{mm}:{ss}"; + private TimerFormat() { + secondsFormat = compile("{mm}:{ss}"); + minutesFormat = compile("{mm}:{ss}"); + hoursFormat = compile("{hh}:{mm}:{ss}"); + dayFormat = compile("{d}:{hh}:{mm}:{ss}"); + daysFormat = compile("{d}:{hh}:{mm}:{ss}"); } @NotNull public String format(long time) { - long seconds = time; - long minutes = seconds / 60; - long hours = minutes / 60; - long days = hours / 24; - - seconds %= 60; - minutes %= 60; - hours %= 24; - - return getFormat(minutes, hours, days) - .replace("{d}", String.valueOf(days)) - .replace("{dd}", digit2(days)) - .replace("{h}", String.valueOf(hours)) - .replace("{hh}", digit2(hours)) - .replace("{m}", String.valueOf(minutes)) - .replace("{mm}", digit2(minutes)) - .replace("{s}", String.valueOf(seconds)) - .replace("{ss}", digit2(seconds)); + long s = time % 60; + long m = (time / 60) % 60; + long h = (time / 3_600) % 24; + long d = time / 86_400; + + CompiledFormat compiled = getCompiledFormat(m, h, d); + + // + 8 padding safely fits any numerical values, preventing internal array resizing + StringBuilder sb = new StringBuilder(compiled.baseLength + 8); + + for (Token token : compiled.tokens) { + token.append(sb, d, h, m, s); + } + + return sb.toString(); } - private String getFormat(long minutes, long hours, long days) { - String format; - if (days > 1) { - format = this.days; - } else if (days == 1) { - format = this.day; - } else if (hours >= 1) { - format = this.hours; - } else if (minutes >= 1) { - format = this.minutes; - } else { - format = this.seconds; + @NotNull + private CompiledFormat getCompiledFormat(long minutes, long hours, long days) { + if (days > 1) return this.daysFormat; + if (days == 1) return this.dayFormat; + if (hours >= 1) return this.hoursFormat; + if (minutes >= 1) return this.minutesFormat; + return this.secondsFormat; + } + + @NotNull + private static CompiledFormat compile(@NotNull String template) { + List tokens = new ArrayList<>(); + int baseLength = 0; + int cursor = 0; + int len = template.length(); + + while (cursor < len) { + int start = template.indexOf('{', cursor); + if (start == -1) { + // no args remaining -> literal + String remainder = template.substring(cursor); + tokens.add(new LiteralToken(remainder)); + baseLength += remainder.length(); + break; + } + + if (start > cursor) { + // text in front of brackets as literal + String literal = template.substring(cursor, start); + tokens.add(new LiteralToken(literal)); + baseLength += literal.length(); + } + + int end = template.indexOf('}', start); + if (end == -1) { + // brackets was never closed + String remainder = template.substring(start); + tokens.add(new LiteralToken(remainder)); + baseLength += remainder.length(); + break; + } + + String tag = template.substring(start, end + 1); + Token token = getTokenByTag(tag); + + if (token != null) { + tokens.add(token); + } else { + // unknown tag + tokens.add(new LiteralToken(tag)); + baseLength += tag.length(); + } + + // set cursor BEHIND closing bracket + cursor = end + 1; } - return format; + + return new CompiledFormat(tokens.toArray(new Token[0]), baseLength); } - private String digit2(long number) { - return number > 9 ? String.valueOf(number) : "0" + number; + @Nullable + private static Token getTokenByTag(@NotNull String tag) { + return switch (tag) { + case "{d}" -> TOKEN_D; + case "{dd}" -> TOKEN_DD; + case "{h}" -> TOKEN_H; + case "{hh}" -> TOKEN_HH; + case "{m}" -> TOKEN_M; + case "{mm}" -> TOKEN_MM; + case "{s}" -> TOKEN_S; + case "{ss}" -> TOKEN_SS; + default -> null; + }; } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java index 927823fbe..fd5d50abe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.management.server; import lombok.Getter; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/PlatformManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/PlatformManager.java deleted file mode 100644 index 896710622..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/PlatformManager.java +++ /dev/null @@ -1,49 +0,0 @@ -package net.codingarea.challenges.plugin.management.server; - -import net.codingarea.challenges.platform.message.MessagePlatform; -import net.codingarea.challenges.platform.message.legacy.LegacyMiniMessagePlatform; -import net.codingarea.challenges.platform.message.paper.NativePaperMessagePlatform; -import net.codingarea.challenges.platform.message.paper.NativePaperMessagePlatformChecker; -import net.codingarea.challenges.plugin.Challenges; -import org.jetbrains.annotations.NotNull; - -import java.util.Objects; - -public final class PlatformManager { - - private MessagePlatform messagePlatform; - - public void createPlatforms() { - messagePlatform = createMessagePlatform(); - } - - public void enablePlatforms() { - messagePlatform.enable(); - } - - public void disablePlatforms() { - if (messagePlatform != null) messagePlatform.disable(); - } - - @NotNull - public MessagePlatform getMessagePlatform() { - if (messagePlatform == null) - throw new IllegalStateException("PlatformManager not loaded yet (MessagePlatform uninitialized)"); - return messagePlatform; - } - - public void setMessagePlatform(@NotNull MessagePlatform messagePlatform) { - Objects.requireNonNull(messagePlatform, "messagePlatform cannot be null"); - this.messagePlatform = messagePlatform; - } - - private static MessagePlatform createMessagePlatform() { - if (NativePaperMessagePlatformChecker.isAvailable()) { - Challenges.getInstance().getILogger().debug("Found and using native Paper message API"); - return new NativePaperMessagePlatform(); - } - Challenges.getInstance().getILogger().debug("Using legacy fallback message API"); - return new LegacyMiniMessagePlatform(Challenges.getInstance()); - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java index 9fe7fd1b0..f1a0bf919 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ScoreboardManager.java @@ -5,6 +5,7 @@ import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; +import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeActionBar; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeScoreboard; import org.bukkit.Bukkit; @@ -19,6 +20,7 @@ public final class ScoreboardManager { private final List bossbars = new ArrayList<>(); private ChallengeScoreboard currentScoreboard; + private ChallengeActionBar currentActionBar; public ScoreboardManager() { ChallengeAPI.subscribeLoader(LanguageLoader.class, this::updateAll); @@ -47,6 +49,14 @@ public void updateAll() { if (currentScoreboard != null) { currentScoreboard.update(); } + if (currentActionBar != null) { + currentActionBar.send(); + } + } + + @NotNull + public List getCurrentBossBars() { + return bossbars; } public void showBossBar(@NotNull ChallengeBossBar bossbar) { @@ -56,8 +66,8 @@ public void showBossBar(@NotNull ChallengeBossBar bossbar) { } public void hideBossBar(@NotNull ChallengeBossBar bossbar) { - if (!bossbars.remove(bossbar)) return; - Bukkit.getOnlinePlayers().forEach(bossbar::applyHide); + bossbar.applyHide(); + bossbars.remove(bossbar); } @Nullable @@ -80,6 +90,18 @@ public void setCurrentScoreboard(@Nullable ChallengeScoreboard scoreboard) { scoreboard.update(); } + @Nullable + public ChallengeActionBar getCurrentActionBar() { + return currentActionBar; + } + + public void setCurrentActionBar(@Nullable ChallengeActionBar actionbar) { + if (currentActionBar == actionbar) return; + + currentActionBar = actionbar; + Challenges.getInstance().getChallengeTimer().updateActionbar(); + } + public void disable() { for (ChallengeBossBar bossbar : bossbars.toArray(new ChallengeBossBar[0])) { hideBossBar(bossbar); @@ -95,4 +117,8 @@ public boolean isShown(@NotNull ChallengeScoreboard scoreboard) { return currentScoreboard == scoreboard; } + public boolean isShown(@NotNull ChallengeActionBar actionbar) { + return currentActionBar == actionbar; + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java index e727f351d..dd55325bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java @@ -3,15 +3,14 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.commons.common.config.Document; import net.codingarea.commons.common.misc.ReflectionUtils; -import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; @@ -22,7 +21,6 @@ import java.util.LinkedList; import java.util.List; -import java.util.concurrent.Callable; import java.util.function.Supplier; public final class ServerManager { @@ -103,11 +101,11 @@ public void endChallenge(@NotNull ChallengeEndCause endCause, Supplier "§e§l" + NameHelper.getName(player)); - String time = Challenges.getInstance().getChallengeTimer().getFormattedTime(); String seed = Bukkit.getWorlds().isEmpty() ? "?" : String.valueOf(ChallengeAPI.getGameWorld(Environment.NORMAL).getSeed()); - endCause.getMessage(!winners.isEmpty()).broadcast(Prefix.CHALLENGES, time, winnerString, seed); + LocalizableMessage winnersFormat = LocalizableMessage.joinList(winners); + LocalizableMessage timeFormat = Challenges.getInstance().getChallengeTimer().getFormattedTime(); + endCause.getMessage(!winners.isEmpty()).broadcast(Prefix.CHALLENGES, timeFormat, winnersFormat, seed); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java index 0d836fceb..944c06a62 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java @@ -2,7 +2,9 @@ import lombok.Getter; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.challenges.type.IChallenge; +import net.codingarea.challenges.plugin.challenges.type.IGoal; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.commons.common.config.Document; import org.bukkit.entity.Player; @@ -27,6 +29,28 @@ public void sendTimerStatusTitle(@NotNull MessageKey message) { message.broadcastTitle(); } + public void sendChallengeStatusTitle(@NotNull MessageKey message, @NotNull Object... args) { + if (!challengeStatusEnabled) return; + message.broadcastTitle(args); + } + + public void sendChallengeToggleTitle(@NotNull IChallenge challenge, boolean enabled) { + MessageKey titleMessage = enabled ? MessageKey.of("title.challenge-enabled") : MessageKey.of("title.challenge-disabled"); + sendChallengeStatusTitle(titleMessage, challenge.getChallengeName()); + } + + public void sendGoalToggleTitle(@NotNull IGoal goal, boolean enabled) { + MessageKey titleMessage = enabled ? MessageKey.of("title.goal-enabled") : MessageKey.of("title.goal-disabled"); + sendChallengeStatusTitle(titleMessage, goal.getChallengeName()); + } + + public void sendChallengeValueTitle(@NotNull IChallenge challenge, @NotNull Object arg) { + MessageKey titleMessage = MessageKey.of("title.challenge-value-changed"); + sendChallengeStatusTitle(titleMessage, challenge.getChallengeName(), arg); + } + + + @Deprecated public void sendChallengeStatusTitle(@NotNull Message message, @NotNull Object... args) { if (!challengeStatusEnabled) return; message.broadcastTitle(args); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java index fae421d1c..11a0423b2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java @@ -4,7 +4,7 @@ import lombok.Setter; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.bukkit.container.PlayerData; import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; @@ -138,7 +138,7 @@ private void teleportPlayersOutOfExtraWorld() { for (Player player : Bukkit.getOnlinePlayers()) { if (player.getWorld() != flatWorld) continue; - Location location = player.getRespawnLocation(); + Location location = getRespawnLocation(player); if (location == null) { World world = Bukkit.getWorld(levelName); if (world == null) { @@ -151,6 +151,16 @@ private void teleportPlayersOutOfExtraWorld() { } } + @Nullable + @SuppressWarnings("deprecation") + private Location getRespawnLocation(@NotNull Player player) { + try { + return player.getRespawnLocation(); // introduced in 1.20.4 + } catch (Error e) { + return player.getBedSpawnLocation(); // deprecated since 1.20.4 + } + } + private void applyGameRuleInFlatWorld(Tuple, Boolean> gameRulePair) { flatWorld.setGameRule(gameRulePair.getFirst(), gameRulePair.getSecond()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/CBossBar.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/CBossBar.java deleted file mode 100644 index 943fb4b11..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/CBossBar.java +++ /dev/null @@ -1,16 +0,0 @@ -package net.codingarea.challenges.plugin.management.server.scoreboard; - -import org.bukkit.entity.Player; - -import java.util.function.BiConsumer; - -public class CBossBar { - - private final BiConsumer content = (bar, player) -> { - }; - - interface BossBarInstance { - - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeActionBar.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeActionBar.java new file mode 100644 index 000000000..1f3b47293 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeActionBar.java @@ -0,0 +1,54 @@ +package net.codingarea.challenges.plugin.management.server.scoreboard; + +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.commons.bukkit.utils.logging.Logger; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.function.Function; + +public final class ChallengeActionBar { + + private Function content = player -> null; + + public void setContent(@NotNull Function content) { + this.content = content; + } + + public void send() { + Bukkit.getOnlinePlayers().forEach(this::send); + } + + public void send(@NotNull Player player) { + if (!isShown()) { + Logger.warn("Tried to update actionbar which is not shown"); + return; + } + + try { + LocalizableMessage actionbar = content.apply(player); + actionbar.getLocalizableKey().sendActionBar(player, actionbar.getLocalizableArgs()); + } catch (Exception ex) { + Logger.error("Unable to update actionbar for player '{}'", player.getName(), ex); + } + } + + public boolean isShown() { + return Challenges.getInstance().getScoreboardManager().isShown(this); + } + + /** + * Displaying a challenge actionbar overwrites the timer actionbar! + */ + public void show() { + Challenges.getInstance().getScoreboardManager().setCurrentActionBar(this); + } + + public void hide() { + if (Challenges.getInstance().getScoreboardManager().getCurrentActionBar() != this) return; + Challenges.getInstance().getScoreboardManager().setCurrentActionBar(null); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java index 4242266d9..62603ecd0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java @@ -1,17 +1,15 @@ package net.codingarea.challenges.plugin.management.server.scoreboard; +import lombok.RequiredArgsConstructor; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; -import net.codingarea.challenges.plugin.utils.bukkit.nms.NMSUtils; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; +import net.kyori.adventure.bossbar.BossBar; +import net.kyori.adventure.text.Component; import net.md_5.bungee.api.chat.BaseComponent; -import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.Bukkit; -import org.bukkit.boss.BarColor; -import org.bukkit.boss.BarStyle; -import org.bukkit.boss.BossBar; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -25,32 +23,36 @@ public final class ChallengeBossBar { private BiConsumer content = (bossbar, player) -> { }; + @NotNull private BossBar createBossbar(@NotNull BossBarInstance instance) { - BossBar bossbar = Bukkit.createBossBar(instance.title.toPlainText(), instance.color, instance.style); - bossbar.setProgress(instance.progress); - return bossbar; + return BossBar.bossBar(instance.title, instance.progress, instance.color, instance.style); } - private void apply(@NotNull BossBar bossbar, @NotNull BossBarInstance instance) { - if (MinecraftVersion.current().isNewerOrEqualThan(MinecraftVersion.V1_20_5)) { - bossbar.setTitle(instance.title.toPlainText()); + private void apply(@NotNull BossBar bossbar, @NotNull BossBarInstance instance, @NotNull Player player) { + bossbar.color(instance.color); + bossbar.overlay(instance.style); + bossbar.progress(instance.progress); + bossbar.name(instance.title); + + if (instance.visible) { + player.showBossBar(bossbar); } else { - NMSUtils.setBossBarTitle(bossbar, instance.title); + player.hideBossBar(bossbar); } - bossbar.setColor(instance.color); - bossbar.setStyle(instance.style); - bossbar.setProgress(instance.progress); - bossbar.setVisible(instance.visible); } public void setContent(@NotNull BiConsumer content) { this.content = content; } + public void applyHide() { + Bukkit.getOnlinePlayers().forEach(this::applyHide); + } + public void applyHide(@NotNull Player player) { BossBar bossbar = bossbars.get(player); if (bossbar == null) return; - bossbar.removePlayer(player); + player.hideBossBar(bossbar); } public void update() { @@ -64,23 +66,17 @@ public void update(@NotNull Player player) { } try { - - BossBarInstance instance = new BossBarInstance(); + BossBarInstance instance = new BossBarInstance(player); if (ChallengeAPI.isPaused()) { - instance.setTitle(Message.forName("bossbar-timer-paused").asString()); - instance.setColor(BarColor.RED); + instance.setTitle(MessageKey.of("bossbar-timer-paused")); + instance.setColor(BossBar.Color.RED); } else { content.accept(instance, player); } - BossBar bossbar = bossbars.computeIfAbsent(player, key -> createBossbar(instance)); - apply(bossbar, instance); - - if (!bossbar.getPlayers().contains(player)) - bossbar.addPlayer(player); - + apply(bossbar, instance, player); } catch (Exception ex) { Logger.error("Unable to update bossbar for player '{}'", player.getName(), ex); } @@ -98,31 +94,49 @@ public boolean isShown() { return Challenges.getInstance().getScoreboardManager().isShown(this); } + @RequiredArgsConstructor public static final class BossBarInstance { - private BaseComponent title = new TextComponent(); - private double progress = 1; - private BarColor color = BarColor.WHITE; - private BarStyle style = BarStyle.SOLID; - private boolean visible = true; + private final Player player; - private BossBarInstance() { - } + private Component title; + private float progress = 1; + private BossBar.Color color = BossBar.Color.WHITE; + private BossBar.Overlay style = BossBar.Overlay.PROGRESS; + private boolean visible = true; @NotNull public BossBarInstance setTitle(@NotNull String title) { - this.title = new TextComponent(title); + this.title = Component.text(title); return this; } @NotNull + @Deprecated public BossBarInstance setTitle(@NotNull BaseComponent title) { + return this; + } + + @NotNull + public BossBarInstance setTitle(@NotNull MessageKey title, @NotNull Object... args) { + this.title = title.asComponent(player, args); + return this; + } + + @NotNull + public BossBarInstance setTitle(@NotNull LocalizableMessage title) { + this.title = title.getLocalizableKey().asComponent(player, title.getLocalizableArgs()); + return this; + } + + @NotNull + public BossBarInstance setTitle(Component title) { this.title = title; return this; } @NotNull - public BossBarInstance setProgress(double progress) { + public BossBarInstance setProgress(float progress) { if (progress < 0 || progress > 1) throw new IllegalArgumentException("Progress must be between 0 and 1; Got " + progress); this.progress = progress; @@ -130,13 +144,13 @@ public BossBarInstance setProgress(double progress) { } @NotNull - public BossBarInstance setColor(@NotNull BarColor color) { + public BossBarInstance setColor(BossBar.Color color) { this.color = color; return this; } @NotNull - public BossBarInstance setStyle(@NotNull BarStyle style) { + public BossBarInstance setStyle(BossBar.Overlay style) { this.style = style; return this; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java index b035ef668..ccfcdf064 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java @@ -3,12 +3,11 @@ import lombok.Getter; import lombok.ToString; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; -import org.bukkit.scoreboard.Criteria; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Scoreboard; @@ -117,12 +116,12 @@ private void unregister(@Nullable Objective objective) { @NotNull @SuppressWarnings("deprecation") private Objective registerDummyObjective(@NotNull Scoreboard scoreboard, @NotNull String name, @NotNull String displayName) { - try { - return scoreboard.registerNewObjective(name, Criteria.DUMMY, displayName); - } catch (Error ignored) { +// try { +// return scoreboard.registerNewObjective(name, Criteria.DUMMY, displayName); +// } catch (Error ignored) { // replacement not yet available in this version, use deprecated method return scoreboard.registerNewObjective(name, "dummy", displayName); - } +// } } @ToString diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java index 5f27c624f..2952841d0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.implementation.setting.PregameMovementSetting; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java index 35411c6f6..7d2610cec 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java @@ -1,12 +1,13 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; @@ -59,7 +60,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc player.openInventory(getInventory(target)); MenuPosition.set(player, new SlottedMenuPosition()); - MessageKey.of("command-invsee-open").send(player, Prefix.CHALLENGES, NameHelper.getName(target)); + MessageKey.of("command-invsee-open").send(player, Prefix.CHALLENGES, target); } public Inventory getInventory(@NotNull Player player) { @@ -78,7 +79,7 @@ public void updateInventoryContents(@NotNull Inventory inventory, @NotNull Playe inventory.clear(); for (int slot = startBottom; slot <= endBottom; slot++) { - inventory.setItem(slot, LegacyItemBuilder.FILL_ITEM); + inventory.setItem(slot, ItemBuilder.FILL_ITEM); } inventory.setItem(helmetSlot, playerInventory.getHelmet()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java deleted file mode 100644 index ad558a6c8..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LanguageCommand.java +++ /dev/null @@ -1,45 +0,0 @@ -package net.codingarea.challenges.plugin.spigot.command; - -import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.content.loader.LanguageLoader; -import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; -import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; -import net.codingarea.challenges.plugin.utils.misc.Utils; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; - -public class LanguageCommand implements SenderCommand, Completer { - - @Override - public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { - if (args.length < 1) { - MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "setlang "); - return; - } - switch (args[0].toLowerCase()) { - case "german": - case "deutsch": - case "de": - Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class).changeLanguage("de"); - break; - case "english": - case "englisch": - case "en": - Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class).changeLanguage("en"); - break; - default: - MessageKey.of("unsuported-language").send(sender, Prefix.CHALLENGES, args[0]); - } - } - - @Override - public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { - return Utils.filterRecommendations(args[0], "german", "english"); - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java index bd2d1178a..14ea42bf4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.cloud.CloudSupportManager; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java index 3eaec7367..26f0785db 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java @@ -3,7 +3,7 @@ import com.google.common.collect.Lists; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java index 875387c43..e49ac35c2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java @@ -3,8 +3,12 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; +import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -16,13 +20,22 @@ public class SkipTimerCommand implements SenderCommand, Completer { @Override public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { - for (IChallenge challenge : Challenges.getInstance().getChallengeManager().getChallenges()) { - if (!challenge.isEnabled()) continue; - if (challenge instanceof TimedChallenge) { - TimedChallenge timedChallenge = (TimedChallenge) challenge; - timedChallenge.setSecondsUntilActivation(0); - } + List challenges = Challenges.getInstance().getChallengeManager().getChallenges().stream() + .filter(IChallenge::isEnabled) + .filter(challenge -> challenge instanceof TimedChallenge) + .map(challenge -> (TimedChallenge) challenge) + .filter(challenge -> challenge.getSecondsLeftUntilNextActivation() > 0) + .peek(challenge -> challenge.setSecondsUntilActivation(0)) + .toList(); + + if (challenges.isEmpty()) { + MessageKey.of("command.skip-timer.none").send(sender, Prefix.CHALLENGES); + } else { + LocalizableMessage[] names = challenges.stream().map(IChallenge::getChallengeName).toArray(LocalizableMessage[]::new); + MessageKey.of("command.skip-timer.done").broadcast(Prefix.CHALLENGES, LocalizableMessage.joinArray(names)); } + + MessageKey.of("test").send(sender, null, Material.MUSIC_DISC_13); } @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java index 136805033..5628e3aa2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.cloud.CloudSupportManager; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java index e0d5b1d03..431907fd8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java index eb0d458fc..894921e87 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.listener; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.logging.Logger; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index fa39ab0ae..13c0e5782 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.loader.UpdateLoader; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java index 96c21e7d5..331cc8841 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.item; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder.SkullBuilder; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index 8a2abec7d..550d69458 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.utils.item; +import com.destroystokyo.paper.profile.PlayerProfile; import com.google.common.base.Preconditions; import lombok.Getter; import net.codingarea.challenges.plugin.Challenges; @@ -7,7 +8,7 @@ import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.commons.bukkit.utils.item.BannerPattern; import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; -import net.codingarea.commons.common.config.Document; +import net.kyori.adventure.text.Component; import org.bukkit.*; import org.bukkit.block.banner.Pattern; import org.bukkit.block.banner.PatternType; @@ -15,21 +16,15 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.BannerMeta; -import org.bukkit.inventory.meta.LeatherArmorMeta; -import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.inventory.meta.SkullMeta; +import org.bukkit.inventory.meta.*; import org.bukkit.potion.PotionEffect; -import org.bukkit.profile.PlayerProfile; -import org.bukkit.profile.PlayerTextures; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jspecify.annotations.NonNull; -import java.net.MalformedURLException; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.*; +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.UUID; public class ItemBuilder extends StandardItemBuilder { @@ -55,7 +50,8 @@ public ItemBuilder(@NotNull Locale locale, @NotNull StandardItemBuilder item, @N } public ItemBuilder(@NotNull Player playerLocale, @NotNull Material material, @NotNull MessageKey nameAndLoreKey, @NotNull Object... args) { - this(Challenges.getInstance().getTranslationManager().getLanguageProvider().getPlayerLanguage(playerLocale), material, nameAndLoreKey, args); + Locale locale = Challenges.getInstance().getTranslationManager().getLanguageProvider().getPlayerLanguage(playerLocale); + this(locale, material, nameAndLoreKey, args); } public ItemBuilder(@NotNull Locale locale, @NotNull ItemStack item) { @@ -65,25 +61,61 @@ public ItemBuilder(@NotNull Locale locale, @NotNull ItemStack item) { } protected void resetToNameAndLore(@NotNull MessageKey nameAndLoreKey, @NotNull Object... args) { - nameAndLoreKey.applyAsItemNameAndLore(locale, getItemMeta(), args); hideAttributes(); + + ItemMeta meta = getItemMeta(); + List components = nameAndLoreKey.asComponents(locale, args); + if (components.isEmpty()) return; + meta.displayName(components.getFirst()); + + if (components.size() == 1) return; + meta.lore(components.subList(1, components.size())); + } + + @NotNull + public ItemBuilder setName(@NotNull MessageKey key, @NotNull Object... args) { + getItemMeta().displayName(key.asComponent(locale, args)); + return this; } @NotNull public ItemBuilder appendNameWithSpace(@NotNull MessageKey key, @NotNull Object... args) { - key.appendToItemName(locale, getItemMeta(), true, args); + ItemMeta meta = getItemMeta(); + Component existingName = meta.displayName(); + if (existingName == null) return setName(key, args); + + meta.displayName(existingName.append(Component.space()).append(key.asComponent(locale, args))); return this; } @NotNull public ItemBuilder appendName(@NotNull MessageKey key, @NotNull Object... args) { - key.appendToItemName(locale, getItemMeta(), false, args); + ItemMeta meta = getItemMeta(); + Component existingName = meta.displayName(); + if (existingName == null) return setName(key, args); + + meta.displayName(existingName.append(key.asComponent(locale, args))); + return this; + } + + @NotNull + public ItemBuilder setLore(@NotNull MessageKey key, @NotNull Object... args) { + getItemMeta().lore(key.asComponents(locale, args)); return this; } @NotNull public ItemBuilder appendLore(@NotNull MessageKey key, @NotNull Object... args) { - key.appendToItemLore(locale, getItemMeta(), args); + ItemMeta meta = getItemMeta(); + List existingLore = meta.lore(); + List loreComponents = key.asComponents(locale, args); + if (existingLore == null) { + meta.lore(loreComponents); + return this; + } + + existingLore.addAll(loreComponents); // modifiable copy + meta.lore(existingLore); return this; } @@ -94,7 +126,14 @@ public ItemBuilder appendLore(@NotNull LocalizableMessage localizable) { @NotNull public ItemBuilder appendLoreWithEmptyLine(@NotNull MessageKey key, @NotNull Object... args) { - super.appendLore(" "); + ItemMeta meta = getItemMeta(); + List lore = meta.lore(); + if (lore != null) { + lore.add(Component.empty()); + } else { + meta.lore(List.of(Component.empty())); + } + return this.appendLore(key, args); } @@ -114,13 +153,13 @@ public ItemBuilder addEnchantment(@NotNull Enchantment enchantment, int level) { @NotNull @Override - public ItemBuilder addFlag(@NonNull @NotNull ItemFlag... flags) { + public ItemBuilder addFlag(@NotNull ItemFlag... flags) { return (ItemBuilder) super.addFlag(flags); } @NotNull @Override - public ItemBuilder removeFlag(@NonNull @NotNull ItemFlag... flags) { + public ItemBuilder removeFlag(@NotNull ItemFlag... flags) { return (ItemBuilder) super.removeFlag(flags); } @@ -173,14 +212,14 @@ public StandardItemBuilder setLore(@NotNull List lore) { @NotNull @Override @Deprecated - public StandardItemBuilder setLore(@NonNull @NotNull String... lore) { + public StandardItemBuilder setLore(@NotNull String... lore) { return super.setLore(lore); } @NotNull @Override @Deprecated - public StandardItemBuilder appendLore(@NonNull @NotNull String... lore) { + public StandardItemBuilder appendLore(@NotNull String... lore) { return super.appendLore(lore); } @@ -208,7 +247,7 @@ public StandardItemBuilder setName(@Nullable Object name) { @NotNull @Override @Deprecated - public StandardItemBuilder setName(@NonNull @NotNull String... content) { + public StandardItemBuilder setName(@NotNull String... content) { return super.setName(content); } @@ -221,7 +260,7 @@ public StandardItemBuilder appendName(@Nullable String sequence) { public static class BannerBuilder extends ItemBuilder { - public BannerBuilder(@NotNull Locale locale, @NotNull Material material, @NotNull MessageKey nameAndLoreKey, @NonNull Object... args) { + public BannerBuilder(@NotNull Locale locale, @NotNull Material material, @NotNull MessageKey nameAndLoreKey, @NotNull Object... args) { super(locale, material, nameAndLoreKey, args); } @@ -246,7 +285,7 @@ public BannerMeta getItemMeta() { public static class SkullBuilder extends ItemBuilder { - public SkullBuilder(@NotNull Locale locale, @NotNull MessageKey nameAndLoreKey, @NonNull Object... args) { + public SkullBuilder(@NotNull Locale locale, @NotNull MessageKey nameAndLoreKey, @NotNull Object... args) { super(locale, Material.PLAYER_HEAD, nameAndLoreKey, args); } @@ -258,35 +297,20 @@ public SkullBuilder setOwner(@NotNull OfflinePlayer owner) { @NotNull public SkullBuilder setOwner(@NotNull UUID uuid, @NotNull String name) { - PlayerProfile profile = Bukkit.createPlayerProfile(uuid, name); // TODO compatibility 1.17 - getItemMeta().setOwnerProfile(profile); + PlayerProfile profile = Bukkit.createProfile(uuid, name); + getItemMeta().setPlayerProfile(profile); return this; } @NotNull public SkullBuilder setTexture(@NotNull String textureUrl) { - UUID uuid = UUID.nameUUIDFromBytes(textureUrl.getBytes()); - - PlayerProfile profile = Bukkit.createPlayerProfile(uuid); // TODO does not exist 1.17.1 - PlayerTextures texture = profile.getTextures(); - - try { - texture.setSkin(new URL(textureUrl)); // URI.create(textureUrl).toURL() - } catch (MalformedURLException e) { - throw new IllegalArgumentException("Invalid texture url", e); - } - - profile.setTextures(texture); - getItemMeta().setOwnerProfile(profile); + StandardItemBuilder.SkullBuilder.setTexture(getItemMeta(), textureUrl); return this; } public SkullBuilder setBase64Texture(@NotNull String base64Texture) { - String textureUrlJson = new String(Base64.getDecoder().decode(base64Texture), StandardCharsets.UTF_8); - String textureUrl = Document.parseJson(textureUrlJson) - .getString("textures.SKIN.url"); - if (textureUrl == null) return this; // TODO - return setTexture(textureUrl); + StandardItemBuilder.SkullBuilder.setBase64Texture(getItemMeta(), base64Texture); + return this; } @NotNull @@ -299,7 +323,7 @@ public SkullMeta getItemMeta() { public static class PotionBuilder extends ItemBuilder { - public PotionBuilder(@NotNull Locale locale, @NotNull Material material, @NotNull MessageKey titleAndLoreKey, @NonNull Object... args) { + public PotionBuilder(@NotNull Locale locale, @NotNull Material material, @NotNull MessageKey titleAndLoreKey, @NotNull Object... args) { super(locale, material, titleAndLoreKey, args); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/LegacyItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/LegacyItemBuilder.java index 32a7a5f22..b056c5866 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/LegacyItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/LegacyItemBuilder.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.utils.item; -import net.codingarea.challenges.plugin.content.ItemDescription; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.ItemDescription; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.commons.bukkit.utils.item.BannerPattern; import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import net.codingarea.commons.common.config.Document; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java index 97dd467bb..f993d627e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.utils.misc; +import io.papermc.paper.world.flag.FeatureDependant; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.Material; import org.bukkit.World; @@ -23,9 +24,11 @@ public static Material[] getMaterials() { private static void loadMaterials() { List materials = new LinkedList<>(); + World world = Challenges.getInstance().getGameWorldStorage().getWorld(World.Environment.NORMAL); for (Material material : Material.values()) { try { - if (!material.isEnabledByFeature(Challenges.getInstance().getGameWorldStorage().getWorld(World.Environment.NORMAL))) { + FeatureDependant feature = material.isItem() ? material.asItemType() : material.asBlockType(); + if (feature != null && !world.isEnabled(feature)) { continue; } } catch (NoSuchMethodError ignored) { @@ -46,9 +49,10 @@ public static EntityType[] getEntityTypes() { private static void loadEntityTypes() { List entityTypes = new LinkedList<>(); + World world = Challenges.getInstance().getGameWorldStorage().getWorld(World.Environment.NORMAL); for (EntityType type : EntityType.values()) { try { - if (!type.isEnabledByFeature(Challenges.getInstance().getGameWorldStorage().getWorld(World.Environment.NORMAL))) { + if (!world.isEnabled(type)) { continue; } } catch (NoSuchMethodError | IllegalArgumentException ignored) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java index a8c0157bf..19822a072 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java @@ -50,8 +50,8 @@ public class MinecraftNameWrapper { public static final GameRule WANDERING_TRADERS = getGameRuleByNames("DO_TRADER_SPAWNING", "SPAWN_WANDERING_TRADERS"); // the game rule for toggling raids has been inverted from "disableRaids" to "raids" in the 1.21->26.1 update - public static final GameRule DISABLE_RAIDS = getFirstConstantByNamesOrNull(GameRule.class, "DISABLE_RAIDS"); - public static final GameRule ENABLE_RAIDS = getFirstConstantByNamesOrNull(GameRule.class, "RAIDS"); + private static final GameRule DISABLE_RAIDS = getFirstConstantByNamesOrNull(GameRule.class, "DISABLE_RAIDS"); + private static final GameRule ENABLE_RAIDS = getFirstConstantByNamesOrNull(GameRule.class, "RAIDS"); @NotNull public static Tuple, Boolean> getDisableRaidsGameRulePair() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java index 5923acc84..8c02405fd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/NameHelper.java @@ -5,12 +5,14 @@ import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.NotNull; +@Deprecated public final class NameHelper { private NameHelper() { } @NotNull + @Deprecated public static String getName(@NotNull OfflinePlayer player) { CloudSupportManager cloudSupport = Challenges.getInstance().getCloudSupportManager(); if (cloudSupport.isNameSupport() && cloudSupport.hasNameFor(player.getUniqueId())) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java index 220ea64cf..309bc1a28 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/StatsHelper.java @@ -1,6 +1,6 @@ package net.codingarea.challenges.plugin.utils.misc; -import net.codingarea.challenges.plugin.content.Message; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.stats.Statistic; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.AnimatedInventory; diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java index 876ab3d32..16859089d 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/AnimatedInventory.java @@ -1,6 +1,7 @@ package net.codingarea.commons.bukkit.utils.animation; import net.codingarea.commons.bukkit.core.BukkitModule; +import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; @@ -22,11 +23,17 @@ public class AnimatedInventory { private SoundSample frameSound = SoundSample.CLICK, endSound = SoundSample.OPEN; private int frameDelay = 1; - public AnimatedInventory(@NotNull String title, int size) { + @Deprecated + public AnimatedInventory(@NotNull String title, int size, @Nullable InventoryHolder holder) { + this.size = size; + this.sizeToNewInventory = forSize -> Bukkit.createInventory(holder, forSize, title); + } + + public AnimatedInventory(@NotNull Component title, int size) { this(title, size, null); } - public AnimatedInventory(@NotNull String title, int size, @Nullable InventoryHolder holder) { + public AnimatedInventory(@NotNull Component title, int size, @Nullable InventoryHolder holder) { this.size = size; this.sizeToNewInventory = forSize -> Bukkit.createInventory(holder, forSize, title); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java index d11e8dc77..34014b61e 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/animation/SoundSample.java @@ -33,15 +33,10 @@ public static void playStatusSound(@NotNull Player player, boolean enabled) { (enabled ? BASS_ON : BASS_OFF).play(player); } - private static final class SoundFrame { - - private final float pitch, volume; - private final Sound sound; + private record SoundFrame(float pitch, float volume, Sound sound) { public SoundFrame(@NotNull Sound sound, float volume, float pitch) { - this.volume = volume; - this.pitch = pitch; - this.sound = sound; + this(pitch, volume, sound); } public SoundFrame(@NotNull Sound sound, float volume) { @@ -52,19 +47,6 @@ public void play(@NotNull Player player, @NotNull Location location) { player.playSound(location, sound, volume, pitch); } - public float getPitch() { - return pitch; - } - - public float getVolume() { - return volume; - } - - @NotNull - public Sound getSound() { - return sound; - } - } private final List frames = new ArrayList<>(); diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java index 18a4811ba..e670f5d8e 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/BannerPattern.java @@ -55,9 +55,4 @@ public PatternType getPatternType() { return patternType; } - @NotNull - public String getIdentifier() { - return patternType.getKeyOrThrow().getKey(); - } - } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java index 5eaec2c7b..dbc743da2 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java @@ -60,6 +60,8 @@ public static boolean isObtainableInSurvival(@NotNull Material material) { case "BUNDLE": case "REINFORCED_DEEPSLATE": case "FROGSPAWN": + case "SUSPICIOUS_GRAVEL": + case "SUSPICIOUS_SAND": return false; } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/StandardItemBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/StandardItemBuilder.java index e8bec5461..9db1d8348 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/StandardItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/StandardItemBuilder.java @@ -1,27 +1,28 @@ package net.codingarea.commons.bukkit.utils.item; +import com.destroystokyo.paper.profile.PlayerProfile; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.core.BukkitModule; -import org.bukkit.Color; -import org.bukkit.DyeColor; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; +import net.codingarea.commons.common.config.Document; +import org.bukkit.*; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeModifier; import org.bukkit.block.banner.Pattern; import org.bukkit.block.banner.PatternType; import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.EquipmentSlotGroup; +import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.*; import org.bukkit.potion.PotionEffect; +import org.bukkit.profile.PlayerTextures; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; +import java.net.MalformedURLException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.*; public class StandardItemBuilder { @@ -149,22 +150,22 @@ public StandardItemBuilder hideAttributes() { @SuppressWarnings({"UnstableApiUsage"}) protected void applyDummyAttributeModifier() { - try { - // hacky fix to make paper hide damage attributes (only works with custom modifiers), "Vanilla behavior since 1.20.5" - // see https://github.com/PaperMC/Paper/issues/11224 - Attribute dummyAttribute = Attribute.LUCK; - Collection modifiers = getItemMeta().getAttributeModifiers(dummyAttribute); - - if (modifiers == null || modifiers.isEmpty()) { - meta.addAttributeModifier(dummyAttribute, new AttributeModifier( - new NamespacedKey(BukkitModule.getFirstInstance(), "dummy"), - 0, - AttributeModifier.Operation.ADD_NUMBER, - EquipmentSlotGroup.ANY - )); - } - } catch (Throwable ignored) { // defend against experimental api changes - } +// try { +// // hacky fix to make paper hide damage attributes (only works with custom modifiers), "Vanilla behavior since 1.20.5" +// // see https://github.com/PaperMC/Paper/issues/11224 +// Attribute dummyAttribute = Attribute.LUCK; +// Collection modifiers = getItemMeta().getAttributeModifiers(dummyAttribute); +// +// if (modifiers == null || modifiers.isEmpty()) { +// meta.addAttributeModifier(dummyAttribute, new AttributeModifier( +// new NamespacedKey(BukkitModule.getFirstInstance(), "dummy"), +// 0, +// AttributeModifier.Operation.ADD_NUMBER, +// EquipmentSlotGroup.ANY +// )); +// } +// } catch (Throwable ignored) { // defend against experimental api changes +// } } @NotNull @@ -280,22 +281,55 @@ public BannerMeta getItemMeta() { public static class SkullBuilder extends StandardItemBuilder { + public static void setBase64Texture(@NotNull SkullMeta item, @NotNull String base64Texture) { + String textureUrlJson = new String(Base64.getDecoder().decode(base64Texture), StandardCharsets.UTF_8); + String textureUrl = Document.parseJson(textureUrlJson) + .getString("textures.SKIN.url"); + if (textureUrl == null) return; // TODO + setTexture(item, textureUrl); + } + + public static void setTexture(@NotNull SkullMeta meta, @NotNull String textureUrl) { + UUID uuid = UUID.nameUUIDFromBytes(textureUrl.getBytes()); + + PlayerProfile profile = Bukkit.createProfile(uuid); + PlayerTextures texture = profile.getTextures(); + + try { + texture.setSkin(URI.create(textureUrl).toURL()); + } catch (MalformedURLException e) { + throw new IllegalArgumentException("Invalid texture url", e); + } + + profile.setTextures(texture); + meta.setPlayerProfile(profile); + } + public SkullBuilder() { super(Material.PLAYER_HEAD); } - public SkullBuilder(@NotNull String owner) { - super(Material.PLAYER_HEAD); - setOwner(owner); + @NotNull + public SkullBuilder setOwner(@NotNull OfflinePlayer owner) { + getItemMeta().setOwningPlayer(owner); + return this; } - public SkullBuilder(@NotNull String owner, @NotNull String name, @NotNull String... lore) { - super(Material.PLAYER_HEAD, name, lore); - setOwner(owner); + @NotNull + public SkullBuilder setOwner(@NotNull UUID uuid, @NotNull String name) { + PlayerProfile profile = Bukkit.createProfile(uuid, name); + getItemMeta().setPlayerProfile(profile); + return this; + } + + @NotNull + public SkullBuilder setTexture(@NotNull String textureUrl) { + setTexture(getItemMeta(), textureUrl); + return this; } - public SkullBuilder setOwner(@NotNull String owner) { - getItemMeta().setOwner(owner); + public SkullBuilder setBase64Texture(@NotNull String base64Texture) { + setBase64Texture(getItemMeta(), base64Texture); return this; } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java index dd55136cf..5aa6eebb1 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/BukkitReflectionUtils.java @@ -27,13 +27,12 @@ private BukkitReflectionUtils() { } public static double getAbsorptionAmount(@NotNull Player player) { - Class classOfPlayer = player.getClass(); - try { return player.getAbsorptionAmount(); } catch (Throwable ignored) { } + Class classOfPlayer = player.getClass(); try { Method getHandleMethod = classOfPlayer.getMethod("getHandle"); getHandleMethod.setAccessible(true); diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java index f63e5093d..289d07d43 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java @@ -50,12 +50,12 @@ public enum MinecraftVersion implements Version { V26_1, // 26.1 V26_1_1, // 26.1.1 V26_1_2, // 26.1.2 + V26_2, // 26.2 ; private final int major, minor, revision; MinecraftVersion() { - String name = this.name().substring(1); String[] version = name.split("_"); @@ -65,7 +65,6 @@ public enum MinecraftVersion implements Version { major = Integer.parseInt(version[0]); minor = Integer.parseInt(version[1]); revision = version.length > 2 ? Integer.parseInt(version[2]) : 0; - } @Override @@ -97,7 +96,12 @@ public static Version parseExact(@NotNull String bukkitVersion) { @NotNull public static MinecraftVersion findNearest(@NotNull Version realVersion) { - return Version.findNearest(realVersion, values()); + MinecraftVersion[] versions = values(); // ascending order + for (int i = versions.length - 1; i >= 0; i--) { + if (versions[i].isNewerThan(realVersion)) continue; + return versions[i]; + } + return V1_0; } private static Version currentExact; diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java b/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java index 1326e79a3..b80664e5e 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/IRandom.java @@ -105,14 +105,17 @@ static IRandom singleton() { float nextFloat(); default T choose(@NotNull T... array) { + if (array.length == 0) throw new IllegalArgumentException("Array is empty"); return array[nextInt(array.length)]; } default T choose(@NotNull List list) { + if (list.isEmpty()) throw new IllegalArgumentException("List is empty"); return list.get(nextInt(list.size())); } default T choose(@NotNull Collection collection) { + if (collection.isEmpty()) throw new IllegalArgumentException("Collection is empty"); return choose(new ArrayList<>(collection)); } diff --git a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java index 52f7fd296..2294a89bb 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/common/misc/ReflectionUtils.java @@ -77,7 +77,7 @@ public static > E getFirstEnumByNames(@NotNull Class classO for (String name : names) { try { return Enum.valueOf(classOfEnum, name); - } catch (IllegalArgumentException | NoSuchFieldError _) { + } catch (IllegalArgumentException | NoSuchFieldError ignored) { } } throw new IllegalArgumentException("No enum found in " + classOfEnum.getName() + " for " + Arrays.toString(names)); diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/Version.java b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java index 14eef7e4e..310b4f6ab 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/Version.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/Version.java @@ -5,7 +5,7 @@ import java.util.*; -public interface Version { +public interface Version { // cannot implement Comparable due to enum MinecraftVersion conflicting Version FALLBACK = new VersionInfo(1, 0, 0); @@ -15,24 +15,35 @@ public interface Version { int getRevision(); + default int compareTo(@NotNull Version other) { + // eliminates Comparator chaining overhead + int cmp = Integer.compare(this.getMajor(), other.getMajor()); + if (cmp != 0) return cmp; + + cmp = Integer.compare(this.getMinor(), other.getMinor()); + if (cmp != 0) return cmp; + + return Integer.compare(this.getRevision(), other.getRevision()); + } + default boolean isNewerThan(@NotNull Version other) { - return this.intValue() > other.intValue(); + return this.compareTo(other) > 0; } default boolean isNewerOrEqualThan(@NotNull Version other) { - return this.intValue() >= other.intValue(); + return this.compareTo(other) >= 0; } default boolean isOlderThan(@NotNull Version other) { - return this.intValue() < other.intValue(); + return this.compareTo(other) < 0; } default boolean isOlderOrEqualThan(@NotNull Version other) { - return this.intValue() <= other.intValue(); + return this.compareTo(other) <= 0; } default boolean equals(@NotNull Version other) { - return this.intValue() == other.intValue(); + return this.compareTo(other) == 0; } @NotNull @@ -42,20 +53,6 @@ default String format() { : String.format("%s.%s", getMajor(), getMinor()); } - default int intValue() { - int major = getMajor(); - int minor = getMinor(); - int revision = getRevision(); - - if (major > 99) throw new IllegalStateException("Malformed version: major is greater than 99"); - if (minor > 99) throw new IllegalStateException("Malformed version: minor is greater than 99"); - if (revision > 99) throw new IllegalStateException("Malformed version: revision is greater than 99"); - - return revision - + minor * 100 - + major * 10000; - } - @NotNull static Version parse(@Nullable String input) { return parse(input, FALLBACK); diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java index 3aad5e285..a6011335a 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionComparator.java @@ -10,7 +10,7 @@ public class VersionComparator implements Comparator { @Override public int compare(@NotNull Version v1, @NotNull Version v2) { - return v1.equals(v2) ? 0 : v1.isNewerThan(v2) ? 1 : -1; + return v1.compareTo(v2); } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java index 053e52c2b..4a2b20135 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java +++ b/plugin/src/main/java/net/codingarea/commons/common/version/VersionInfo.java @@ -1,14 +1,17 @@ package net.codingarea.commons.common.version; +import lombok.Getter; import net.codingarea.commons.common.logging.ILogger; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Objects; -public class VersionInfo implements Version { +public class VersionInfo implements Version, Comparable { protected static final ILogger logger = ILogger.forThisClass(); + @Getter private final int major, minor, revision; public VersionInfo(int major, int minor, int revision) { @@ -17,18 +20,6 @@ public VersionInfo(int major, int minor, int revision) { this.revision = revision; } - public int getMajor() { - return major; - } - - public int getMinor() { - return minor; - } - - public int getRevision() { - return revision; - } - @Override public boolean equals(Object other) { if (this == other) return true; @@ -36,6 +27,11 @@ public boolean equals(Object other) { return this.equals((Version) other); } + @Override + public int compareTo(@NotNull Version other) { + return Version.super.compareTo(other); + } + @Override public int hashCode() { return Objects.hash(major, minor, revision); diff --git a/plugin/src/main/resources/config.yml b/plugin/src/main/resources/config.yml index 6a3b9657d..0fd912529 100644 --- a/plugin/src/main/resources/config.yml +++ b/plugin/src/main/resources/config.yml @@ -34,12 +34,6 @@ language: "de" language-online-update: false timer: - format: - seconds: "{mm}:{ss}" - minutes: "{mm}:{ss}" - hours: "{hh}:{mm}:{ss}" - day: "{d} day {hh}:{mm}:{ss}" - days: "{d} days {hh}:{mm}:{ss}" gradient: enabled: false duration: 20 @@ -89,6 +83,7 @@ challenge-updates: in-front: false suffix: true updated: + in-front: false suffix: true # If activated players need the permission "challenges.manage" to manage settings in the gui diff --git a/plugin/src/main/resources/plugin.yml b/plugin/src/main/resources/plugin.yml index 8274c3831..a46368c72 100644 --- a/plugin/src/main/resources/plugin.yml +++ b/plugin/src/main/resources/plugin.yml @@ -11,6 +11,7 @@ main: net.codingarea.challenges.plugin.Challenges load: POSTWORLD softdepend: - CloudNet-Bridge + - ProtocolLib description: | This plugin provides you with lots of challenges for beating minecraft or competing against your friends. You can find more information on our discord: https://discord.gg/74Ay5zF. diff --git a/settings.gradle.kts b/settings.gradle.kts index 886cc4630..cd5191dda 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -3,7 +3,6 @@ rootProject.name = "Challenges" include("plugin", "mongo-connector") includeSubmodules("cloud-support") -includeSubmodules("platform") fun includeSubmodules(parentDirName: String) { val parentDir = File(settingsDir, parentDirName) From 4582651910c4f2bf989eb4056e2f55e5466e5dae Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Mon, 6 Jul 2026 16:43:42 +0200 Subject: [PATCH 099/119] refactor: settings and localization flow Introduce a shared setting interface, separate goal toggle title handling, and tighten i18n message support. Also updates menu cleanup, scheduler pattern matching, and a few small event and formatting fixes. --- language/files/de.json | 8 +- .../extraworld/JumpAndRunChallenge.java | 2 +- .../inventory/NoDupedItemsChallenge.java | 9 +- .../setting/LanguageSetting.java | 1 + .../plugin/challenges/type/IGoal.java | 3 +- .../plugin/challenges/type/ISetting.java | 11 + .../challenges/type/abstraction/Modifier.java | 2 +- .../challenges/type/abstraction/Setting.java | 5 +- .../type/abstraction/SettingGoal.java | 5 + .../type/abstraction/SettingModifier.java | 4 +- .../type/abstraction/SettingModifierGoal.java | 4 + .../type/abstraction/menu/MenuGoal.java | 6 + .../type/helper/ChallengeHelper.java | 9 + .../challenges/type/helper/GoalHelper.java | 2 + .../plugin/content/i18n/ArgumentFormat.java | 11 + .../content/i18n/LocalizableMessage.java | 3 +- .../impl/DynamicLocalizableMessageImpl.java | 2 +- .../content/i18n/impl/JoinedMessageImpl.java | 4 +- .../categorised/CategorisedMenuGenerator.java | 194 ------------------ .../SmallCategorisedMenuGenerator.java | 19 -- .../management/scheduler/ScheduleManager.java | 7 +- .../events/PlayerInventoryClickEvent.java | 2 +- .../utils/menu/MenuPositionListener.java | 12 +- 23 files changed, 85 insertions(+), 240 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/ISetting.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java diff --git a/language/files/de.json b/language/files/de.json index eeb8f31ea..84ce5ba5f 100644 --- a/language/files/de.json +++ b/language/files/de.json @@ -31,10 +31,10 @@ }, "menu": { "generic": { - "click-prefix": "[Klick] {@symbol.arrow} ", - "shift-click-prefix": "[Shift-Klick] {@symbol.arrow} ", - "right-click-prefix": "[Rechts-Klick] {@symbol.arrow} ", - "left-click-prefix": "[Links-Klick] {@symbol.arrow} " + "click-prefix": "[Klick] {@symbol.chevron} ", + "shift-click-prefix": "[Shift-Klick] {@symbol.chevron} ", + "right-click-prefix": "[Rechts-Klick] {@symbol.chevron} ", + "left-click-prefix": "[Links-Klick] {@symbol.chevron} " }, "timer": { "name": "Timer", diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java index 226169565..70d8f673f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java @@ -105,7 +105,7 @@ protected void startJumpAndRun() { currentPlayer = getNextPlayer().getUniqueId(); lastPlayers.add(currentPlayer); - actionbar.setContent(player -> getChallengeMessageKey("actionbar").withArgs(currentJump, jumps)); + actionbar.setContent(_ -> getChallengeMessageKey("actionbar").withArgs(currentJump, jumps)); actionbar.show(); buildNextJump(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java index b383c9206..bb469bf97 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java @@ -4,13 +4,12 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.CanInstaKillOnEnable; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.common.collection.pair.Triple; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -65,10 +64,10 @@ private void checkInventories() { for (Player player : Bukkit.getOnlinePlayers()) { Triple result = checkInventory(player, blackList); if (result != null) { - Message.forName("no-duped-items-failed").broadcast( + MessageKey.of("no-duped-items-failed").broadcast( Prefix.CHALLENGES, - NameHelper.getName(result.getFirst()), - NameHelper.getName(result.getSecond()), + result.getFirst(), + result.getSecond(), result.getThird() ); ChallengeHelper.kill(result.getFirst()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java index 5bec83fe3..ab9cb79bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java @@ -135,6 +135,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr int value = TAG_TO_VALUE.get(languageTag); setValue(value); // trigger change language logic + playValueChangeTitle(); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java index a023037ed..fcd190798 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/IGoal.java @@ -10,7 +10,7 @@ import java.util.List; -public interface IGoal extends IChallenge { +public interface IGoal extends IChallenge, ISetting { /** * Enabled / disabled this goal. @@ -19,6 +19,7 @@ public interface IGoal extends IChallenge { * This can be checked by comparing {@link ChallengeManager#getCurrentGoal()} to {@code this}. * You may just call {@link GoalHelper#handleSetEnabled(IGoal, boolean)} with {@code this}, {@code enabled} */ + @Override void setEnabled(boolean enabled); /** diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/ISetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/ISetting.java new file mode 100644 index 000000000..1a0236162 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/ISetting.java @@ -0,0 +1,11 @@ +package net.codingarea.challenges.plugin.challenges.type; + +public interface ISetting { + + boolean isEnabled(); + + void setEnabled(boolean enabled); + + void playStatusUpdateTitle(); + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java index bedb375b8..60276e4ea 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java @@ -79,7 +79,7 @@ public void setValue(int value) { updateItems(); } - protected void overwriteValue(int value) { + protected final void overwriteValue(int value) { this.value = value; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java index 735238e38..2dd5fe067 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Setting.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.challenges.type.ISetting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -12,7 +13,7 @@ import org.jetbrains.annotations.Nullable; -public abstract class Setting extends AbstractChallenge { +public abstract class Setting extends AbstractChallenge implements ISetting { private final boolean enabledByDefault; protected boolean enabled; @@ -41,6 +42,7 @@ public void restoreDefaults() { setEnabled(enabledByDefault); } + @Override public void playStatusUpdateTitle() { ChallengeHelper.playChallengeToggleTitle(this); } @@ -64,6 +66,7 @@ public boolean isEnabled() { return enabled; } + @Override public void setEnabled(boolean enabled) { if (this.enabled == enabled) return; this.enabled = enabled; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java index 771eb40fd..ea59a1f7b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingGoal.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import net.codingarea.challenges.plugin.challenges.type.IGoal; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -38,4 +39,8 @@ public void setEnabled(boolean enabled) { super.setEnabled(enabled); } + @Override + public void playStatusUpdateTitle() { + ChallengeHelper.playGoalToggleTitle(this); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java index 79eaee0de..d6cab8510 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; +import net.codingarea.challenges.plugin.challenges.type.ISetting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -11,7 +12,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public abstract class SettingModifier extends Modifier { +public abstract class SettingModifier extends Modifier implements ISetting { private boolean enabled; @@ -73,6 +74,7 @@ public void setEnabled(boolean enabled) { updateItems(); } + @Override public void playStatusUpdateTitle() { ChallengeHelper.playChallengeToggleTitle(this); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java index d1974c9b3..174ae85ce 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierGoal.java @@ -63,4 +63,8 @@ public void handleClick(@NotNull ChallengeMenuClickInfo info) { } } + @Override + public void playStatusUpdateTitle() { + ChallengeHelper.playGoalToggleTitle(this); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuGoal.java index 1907d3d16..68be1755a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuGoal.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction.menu; import net.codingarea.challenges.plugin.challenges.type.IGoal; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -34,4 +35,9 @@ public SoundSample getStartSound() { public SoundSample getWinSound() { return SoundSample.WIN; } + + @Override + public void playStatusUpdateTitle() { + ChallengeHelper.playGoalToggleTitle(this); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index 464cd373f..107057db1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -4,6 +4,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; +import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; @@ -163,6 +164,14 @@ public static void playChallengeToggleTitle(@NotNull AbstractChallenge challenge Challenges.getInstance().getTitleManager().sendChallengeToggleTitle(challenge, enabled); } + public static void playGoalToggleTitle(@NotNull IGoal goal) { + playGoalToggleTitle(goal, goal.isEnabled()); + } + + public static void playGoalToggleTitle(@NotNull IGoal goal, boolean enabled) { + Challenges.getInstance().getTitleManager().sendGoalToggleTitle(goal, enabled); + } + public static void playChallengeValueTitle(@NotNull T modifier) { playChallengeValueTitle(modifier, modifier.getValue()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java index 65866054e..1e646ce97 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java @@ -31,8 +31,10 @@ private GoalHelper() { public static void handleSetEnabled(@NotNull IGoal goal, boolean enabled) { if (Challenges.getInstance().getChallengeManager().getCurrentGoal() != goal && enabled) { Challenges.getInstance().getChallengeManager().setCurrentGoal(goal); + goal.playStatusUpdateTitle(); } else if (Challenges.getInstance().getChallengeManager().getCurrentGoal() == goal && !enabled) { Challenges.getInstance().getChallengeManager().setCurrentGoal(null); + goal.playStatusUpdateTitle(); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java index bd21e6e5d..70e6a14f5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java @@ -6,6 +6,7 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; +import org.bukkit.event.entity.EntityDamageByBlockEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.projectiles.ProjectileSource; @@ -39,10 +40,20 @@ public interface ArgumentFormat { return MessageKey.of("arg-format.hp").withArgs(hp, NumberFormatter.FLOATING_POINT.format(hearts)); }); + ArgumentFormat TIME = register(Integer.class, "seconds", arg -> { + return LocalizableMessage.from(_ -> NumberFormatter.TIME.format(arg)); + }); + ArgumentFormat DAMAGE_CAUSE = register(EntityDamageEvent.class, "damage_cause", event -> { if (event.getCause() == EntityDamageEvent.DamageCause.CUSTOM) return MessageKey.of("generic.undefined"); String cause = StringUtils.getEnumName(event.getCause()); // DamageCause is not a Translatable, impl custom translations? + if (event instanceof EntityDamageByBlockEvent damageEvent) { + if (damageEvent.getDamager() != null) { + return MessageKey.of("arg-format.damage-cause-source").withArgs(cause, damageEvent.getDamager().getType()); + } + } + if (!(event instanceof EntityDamageByEntityEvent damageEvent)) { return MessageKey.of("arg-format.damage-cause").withArgs(cause); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java index 13d931a39..9414f0cd0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java @@ -30,6 +30,7 @@ public interface LocalizableMessage { MessageKey getLocalizableKey(); @NotNull + @ApiStatus.Internal Object[] getLocalizableArgs(); @NotNull @@ -71,7 +72,7 @@ static LocalizableMessage fromLines(@NotNull Function valueFun @NotNull @CheckReturnValue static LocalizableMessage from(@NotNull Function valueFunction, @NotNull Object... args) { - return new DynamicLocalizableMessageImpl(valueFunction.andThen((string) -> new String[]{string}), args); + return fromLines(valueFunction.andThen((string) -> new String[]{string}), args); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/DynamicLocalizableMessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/DynamicLocalizableMessageImpl.java index 0d782f26f..795f866cb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/DynamicLocalizableMessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/DynamicLocalizableMessageImpl.java @@ -13,7 +13,7 @@ @RequiredArgsConstructor public class DynamicLocalizableMessageImpl implements LocalizableMessage { - public static final MessageKey KEY = new MessageKeyImpl(""); + public static final MessageKey KEY = MessageKey.empty(""); private final Function valueFunction; private final Object[] args; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/JoinedMessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/JoinedMessageImpl.java index 418a7d3d6..57b36fa64 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/JoinedMessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/JoinedMessageImpl.java @@ -13,6 +13,8 @@ @RequiredArgsConstructor public class JoinedMessageImpl implements LocalizableMessage { + public static final MessageKey KEY = MessageKey.empty(""); + private final MessageKey delimiter; private final Object[] elements; @@ -39,7 +41,7 @@ public MessageHolder localize(@NotNull Player playerLocale) { @NotNull @Override public MessageKey getLocalizableKey() { - return delimiter; + return KEY; } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java deleted file mode 100644 index 6665bd098..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/CategorisedMenuGenerator.java +++ /dev/null @@ -1,194 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.categorised; - -import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.challenges.type.IChallenge; -import net.codingarea.challenges.plugin.challenges.type.annotation.ChallengeAnnotations; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.SettingCategory; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.SettingsMenuGenerator; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; -import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import org.bukkit.inventory.Inventory; -import org.jetbrains.annotations.NotNull; - -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -public class CategorisedMenuGenerator extends SettingsMenuGenerator { - - private final Map categories = new LinkedHashMap<>(); - - @Override - public void addChallengeToCache(@NotNull IChallenge challenge) { - SettingCategory category = challenge.getCategory() != null ? challenge.getCategory() : getMiscCategory(); - if (!categories.containsKey(challenge.getCategory())) { - categories.computeIfAbsent(category, challengeCategory -> { - CategorisedSettingsMenuGenerator generator = new CategorisedSettingsMenuGenerator(this, category); - generator.setMenuType(getMenuType()); - return generator; - }); - } - categories.get(category).addChallengeToCache(challenge); - } - - @Override - public void resetChallengeCache() { - categories.clear(); - } - - private SettingCategory getMiscCategory() { - if (getMenuType() == MenuType.GOAL) { - return SettingCategory.MISC_GOAL; - } - return SettingCategory.MISC_CHALLENGE; - } - - @Override - public void generatePage(@NotNull Inventory inventory, int page) { - - int i = 0; - for (Map.Entry entry : getCategoriesForPage(page)) { - SettingCategory category = entry.getKey(); - CategorisedSettingsMenuGenerator generator = entry.getValue(); - - LegacyItemBuilder builder = category.getDisplayItem(); - String attachment = getLoreAttachment(generator); - if (!attachment.isEmpty()) { - builder.appendLore("", attachment); - } - - int slot = i + 10; - if (i >= 7) slot += 2; - - for (IChallenge challenge : generator.getChallenges()) { - if (newSuffix && ChallengeAnnotations.isNew(challenge)) { - builder.appendName(" " + Message.forName("new-challenge")); - break; - } else if (updatedSuffix && ChallengeAnnotations.isUpdated(challenge)) { - builder.appendName(" " + Message.forName("updated-challenge")); - break; - } - } - - inventory.setItem(slot, builder.build()); - i++; - } - - } - - private String getLoreAttachment(CategorisedSettingsMenuGenerator generator) { - - if (getMenuType() == MenuType.GOAL) { - for (IChallenge challenge : generator.getChallenges()) { - if (challenge.isEnabled()) { - return Message.forName("lore-category-activated").asString(); - } - } - return Message.forName("lore-category-deactivated").asString(); - } - long activatedCount = generator.getChallenges().stream().filter(IChallenge::isEnabled).count(); - return Message.forName("lore-category-activated-count").asString(activatedCount, generator.getChallenges().size()); - } - - @Override - public void updateItem(IChallenge challenge) { - generateInventories(); - - for (Map.Entry entry : categories.entrySet()) { - if (entry.getValue().getChallenges().contains(challenge)) { - entry.getValue().updateGeneratorItem(challenge); - } - } - - } - - @Override - public int getPagesCount() { - return (int) (Math.ceil((double) categories.size() / getEntriesPerPage())); - } - - public int getEntriesPerPage() { - return 14; - } - - @Override - public MenuPosition createMenuPosition(int page) { - return info -> { - if (InventoryUtils.handleNavigationClicking(this, - getNavigationSlots(page), - page, - info, - () -> Challenges.getInstance().getMenuManager().openMainMenuInstantly(info.getPlayer()))) { - return; - } - - int i = 0; - for (Map.Entry entry : getCategoriesForPage(page)) { - int slot = i + 10; - if (i >= 7) slot += 2; - if (slot == info.getSlot()) { - SettingsMenuGenerator generator = entry.getValue(); - SoundSample.CLICK.play(info.getPlayer()); - generator.open(info.getPlayer(), 0); - return; - } - i++; - } - - SoundSample.CLICK.play(info.getPlayer()); - }; - } - - private List> getCategoriesForPage(int page) { - - List> list = categories.entrySet() - .stream() - // Priority might be removed in a future version - .sorted(Comparator.comparingInt(value -> value.getKey().getPriority())) - .collect(Collectors.toList()); - - int entriesPerPage = getEntriesPerPage(); - int startIndex = page * entriesPerPage; - int endIndex = Math.min(page * entriesPerPage + entriesPerPage, categories.size()); - - return list.subList(startIndex, endIndex); - } - - public static class CategorisedSettingsMenuGenerator extends SettingsMenuGenerator { - - private final CategorisedMenuGenerator generator; - private final SettingCategory category; - - public CategorisedSettingsMenuGenerator(CategorisedMenuGenerator generator, SettingCategory category) { - this.generator = generator; - this.category = category; - this.onLeaveClick = player -> { - SoundSample.CLICK.play(player); - generator.open(player, 0); - }; - } - - @Override - protected String getTitle(int page) { - throw new UnsupportedOperationException("This method should not be called in CategorisedSettingsMenuGenerator"); - } - - @Override - public void updateItem(IChallenge challenge) { - generator.updateItem(challenge); - super.updateItem(challenge); - } - - public void updateGeneratorItem(IChallenge challenge) { - super.updateItem(challenge); - } - - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java deleted file mode 100644 index c84df1f4c..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/categorised/SmallCategorisedMenuGenerator.java +++ /dev/null @@ -1,19 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.categorised; - -public class SmallCategorisedMenuGenerator extends CategorisedMenuGenerator { - - @Override - public int getEntriesPerPage() { - return 7; - } - - @Override - public int getSize() { - return 9 * 3; - } - - @Override - public int[] getNavigationSlots(int page) { - return new int[]{18, 26}; - } -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java index 7a6ab42de..76bf4911b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduleManager.java @@ -57,8 +57,7 @@ public void unregister(@NotNull Object object) { } private void register(@NotNull ScheduledFunction function, @NotNull AbstractTaskConfig config) { - if (config instanceof ScheduledTaskConfig) { - ScheduledTaskConfig taskConfig = (ScheduledTaskConfig) config; + if (config instanceof ScheduledTaskConfig taskConfig) { if (taskConfig.getRate() < 1) { Logger.warn("Schedule rate cannot be less than 1; Could not register {}", function); return; @@ -67,9 +66,7 @@ private void register(@NotNull ScheduledFunction function, @NotNull AbstractTask ScheduledTaskExecutor executor = getOrCreateScheduledTaskExecutor(taskConfig); executor.register(function); } - if (config instanceof TimerTaskConfig) { - TimerTaskConfig taskConfig = (TimerTaskConfig) config; - + if (config instanceof TimerTaskConfig taskConfig) { TimerTaskExecutor executor = getOrCreateTimerTaskExecutor(taskConfig); executor.register(function); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java index 5da2d4185..50f99961e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/events/PlayerInventoryClickEvent.java @@ -15,7 +15,7 @@ public class PlayerInventoryClickEvent extends InventoryClickEventWrapper { public PlayerInventoryClickEvent(@NotNull InventoryClickEvent event) { super(event); - player = ((Player) event.getWhoClicked()); + player = (Player) event.getWhoClicked(); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java index 907d0b2a5..0a670e584 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java @@ -7,6 +7,7 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.inventory.Inventory; import org.jetbrains.annotations.NotNull; @@ -14,7 +15,6 @@ public final class MenuPositionListener implements Listener { @EventHandler(priority = EventPriority.LOW) public void onClick(@NotNull InventoryClickEvent event) { - HumanEntity human = event.getWhoClicked(); if (!(human instanceof Player player)) return; @@ -22,7 +22,6 @@ public void onClick(@NotNull InventoryClickEvent event) { if (inventory == null) return; if (inventory == CompatibilityUtils.getTopInventory(event)) { - if (inventory.getHolder() != MenuPosition.HOLDER) return; // No menu inventory MenuPosition position = MenuPosition.get(player); @@ -32,14 +31,19 @@ public void onClick(@NotNull InventoryClickEvent event) { position.handleClick(new MenuClickInfo(player, inventory, event.isShiftClick(), event.isRightClick(), event.getSlot())); } else if (event.isShiftClick()) { // Player inventory was clicked - Inventory topInventory = event.getInventory(); if (topInventory.getHolder() != MenuPosition.HOLDER) return; // No menu inventory event.setCancelled(true); - } + } + @EventHandler(priority = EventPriority.LOW) + public void onClose(@NotNull InventoryCloseEvent event) { + if (!(event.getPlayer() instanceof Player player)) return; + if (event.getReason() == InventoryCloseEvent.Reason.OPEN_NEW) return; + if (event.getInventory().getHolder() != MenuPosition.HOLDER) return; // No menu inventory + MenuPosition.remove(player); } } From df7003684b77420bcbe955503329f953940ac28a Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Mon, 6 Jul 2026 18:43:15 +0200 Subject: [PATCH 100/119] refactor: migrate translations --- language/files/README.md | 16 + language/files/de.json | 3990 ++++++++--------- language/files/en.json | 3647 ++++++++------- language/files/global.json | 233 - language/locales/de.json | 2468 ++++++++++ language/locales/en.json | 2181 +++++++++ language/locales/global.json | 703 +++ plugin/build.gradle.kts | 2 +- .../challenge/DamageTeleportChallenge.java | 2 +- .../challenge/ZeroHeartsChallenge.java | 4 +- .../damage/AdvancementDamageChallenge.java | 2 +- .../damage/BlockBreakDamageChallenge.java | 2 +- .../damage/BlockPlaceDamageChallenge.java | 2 +- .../damage/DamagePerBlockChallenge.java | 2 +- .../damage/DamagePerItemChallenge.java | 2 +- .../damage/DeathOnFallChallenge.java | 2 +- .../damage/DelayDamageChallenge.java | 5 +- .../challenge/damage/FreezeChallenge.java | 2 +- .../challenge/damage/JumpDamageChallenge.java | 5 +- .../damage/ReversedDamageChallenge.java | 2 +- .../damage/SneakDamageChallenge.java | 4 +- .../damage/WaterAllergyChallenge.java | 2 +- .../effect/BlockEffectChallenge.java | 2 +- .../effect/ChunkRandomEffectChallenge.java | 2 +- .../effect/EntityRandomEffectChallenge.java | 2 +- .../challenge/effect/InfectionChallenge.java | 2 +- .../PermanentEffectOnDamageChallenge.java | 7 +- .../effect/RandomPotionEffectChallenge.java | 2 +- .../entities/AllMobsToDeathPoint.java | 2 +- .../entities/BlockMobsChallenge.java | 2 +- .../entities/DupedSpawningChallenge.java | 2 +- .../entities/HydraNormalChallenge.java | 2 +- .../entities/InvisibleMobsChallenge.java | 2 +- .../entities/MobSightDamageChallenge.java | 2 +- .../entities/MobTransformationChallenge.java | 5 +- .../entities/MobsRespawnInEndChallenge.java | 5 +- .../entities/NewEntityOnJumpChallenge.java | 2 +- .../extraworld/JumpAndRunChallenge.java | 16 +- .../extraworld/WaterMLGChallenge.java | 21 +- .../challenge/force/ForceBiomeChallenge.java | 11 +- .../challenge/force/ForceBlockChallenge.java | 9 +- .../challenge/force/ForceHeightChallenge.java | 11 +- .../challenge/force/ForceItemChallenge.java | 9 +- .../challenge/force/ForceMobChallenge.java | 9 +- .../inventory/MissingItemsChallenge.java | 8 +- .../MovementItemRemovingChallenge.java | 10 +- .../inventory/NoDupedItemsChallenge.java | 5 +- .../inventory/PermanentItemChallenge.java | 2 +- .../inventory/PickupItemLaunchChallenge.java | 2 +- .../inventory/UncraftItemsChallenge.java | 2 +- .../miscellaneous/EnderGamesChallenge.java | 5 +- .../miscellaneous/FoodLaunchChallenge.java | 2 +- .../miscellaneous/FoodOnceChallenge.java | 15 +- .../miscellaneous/InvertHealthChallenge.java | 4 +- .../miscellaneous/LowDropRateChallenge.java | 2 +- .../miscellaneous/NoExpChallenge.java | 2 +- .../miscellaneous/NoTradingChallenge.java | 2 +- .../miscellaneous/OneDurabilityChallenge.java | 2 +- .../movement/AlwaysRunningChallenge.java | 2 +- .../movement/DontStopRunningChallenge.java | 4 +- .../movement/FiveHundredBlocksChallenge.java | 6 +- .../movement/HigherJumpsChallenge.java | 2 +- .../challenge/movement/MoveMouseDamage.java | 2 +- .../challenge/movement/OnlyDirtChallenge.java | 4 +- .../challenge/movement/OnlyDownChallenge.java | 4 +- .../movement/TrafficLightChallenge.java | 4 +- .../challenge/quiz/QuizChallenge.java | 14 +- .../randomizer/BlockRandomizerChallenge.java | 2 +- .../CraftingRandomizerChallenge.java | 2 +- .../EntityLootRandomizerChallenge.java | 8 +- .../randomizer/HotBarRandomizerChallenge.java | 2 +- .../randomizer/RandomEventChallenge.java | 14 +- .../randomizer/RandomItemChallenge.java | 2 +- .../RandomItemDroppingChallenge.java | 2 +- .../RandomItemRemovingChallenge.java | 2 +- .../challenge/time/MaxBiomeTimeChallenge.java | 3 +- .../time/MaxHeightTimeChallenge.java | 5 +- .../challenge/world/AnvilRainChallenge.java | 2 +- .../challenge/world/BedrockPathChallenge.java | 2 +- .../world/BlockFlyInAirChallenge.java | 2 +- .../BlocksDisappearAfterTimeChallenge.java | 2 +- .../world/ChunkDeconstructionChallenge.java | 2 +- .../world/ChunkDeletionChallenge.java | 4 +- .../challenge/world/FloorIsLavaChallenge.java | 2 +- .../challenge/world/IceFloorChallenge.java | 5 +- .../challenge/world/LevelBorderChallenge.java | 4 +- .../challenge/world/LoopChallenge.java | 4 +- .../world/RepeatInChunkChallenge.java | 2 +- .../challenge/world/SnakeChallenge.java | 4 +- .../challenge/world/SurfaceHoleChallenge.java | 2 +- .../challenge/world/TsunamiChallenge.java | 6 +- .../goal/AllAdvancementGoal.java | 7 +- .../goal/CollectAllItemsGoal.java | 2 +- .../goal/CollectHorseAmorGoal.java | 2 +- .../goal/CollectIceBlocksGoal.java | 2 +- .../goal/CollectMostDeathsGoal.java | 2 +- .../goal/CollectMostExpGoal.java | 2 +- .../goal/CollectMostItemsGoal.java | 2 +- .../goal/CollectSwordsGoal.java | 2 +- .../implementation/goal/CollectWoodGoal.java | 2 +- .../goal/CollectWorkstationsGoal.java | 2 +- .../implementation/goal/EatCakeGoal.java | 2 +- .../implementation/goal/EatMostGoal.java | 2 +- .../implementation/goal/FindElytraGoal.java | 2 +- .../implementation/goal/FinishRaidGoal.java | 2 +- .../goal/FirstOneToDieGoal.java | 2 +- .../goal/GetFullHealthGoal.java | 2 +- .../implementation/goal/KillAllMobsGoal.java | 2 +- .../goal/KillAllMonsterGoal.java | 2 +- .../goal/KillIronGolemGoal.java | 2 +- .../goal/KillSnowGolemGoal.java | 2 +- .../goal/LastManStandingGoal.java | 2 +- .../implementation/goal/MaxHeightGoal.java | 2 +- .../implementation/goal/MinHeightGoal.java | 2 +- .../goal/MineMostBlocksGoal.java | 2 +- .../implementation/goal/MostEmeraldsGoal.java | 2 +- .../implementation/goal/MostOresGoal.java | 2 +- .../implementation/goal/RaceGoal.java | 5 +- .../forcebattle/ExtremeForceBattleGoal.java | 22 +- .../ForceAdvancementBattleGoal.java | 2 +- .../forcebattle/ForceBiomeBattleGoal.java | 2 +- .../forcebattle/ForceBlockBattleGoal.java | 2 +- .../forcebattle/ForceDamageBattleGoal.java | 2 +- .../forcebattle/ForceHeightBattleGoal.java | 2 +- .../goal/forcebattle/ForceItemBattleGoal.java | 2 +- .../goal/forcebattle/ForceMobBattleGoal.java | 2 +- .../forcebattle/ForcePositionBattleGoal.java | 2 +- .../targets/AdvancementTarget.java | 14 +- .../goal/forcebattle/targets/BiomeTarget.java | 14 +- .../goal/forcebattle/targets/BlockTarget.java | 14 +- .../forcebattle/targets/DamageTarget.java | 14 +- .../goal/forcebattle/targets/ForceTarget.java | 7 +- .../forcebattle/targets/HeightTarget.java | 14 +- .../goal/forcebattle/targets/ItemTarget.java | 14 +- .../goal/forcebattle/targets/MobTarget.java | 14 +- .../forcebattle/targets/PositionTarget.java | 13 +- .../setting/BackpackSetting.java | 2 +- .../setting/CutCleanSetting.java | 2 +- .../setting/DamageMultiplierModifier.java | 2 +- .../setting/EnderChestCommandSetting.java | 2 +- .../setting/ImmediateRespawnSetting.java | 2 +- .../setting/LanguageSetting.java | 3 + .../setting/MaxHealthSetting.java | 1 - .../setting/NoOffhandSetting.java | 2 +- .../setting/PositionSetting.java | 2 +- .../implementation/setting/PvPSetting.java | 2 +- .../setting/RegenerationSetting.java | 2 +- .../setting/SlotLimitSetting.java | 11 +- .../implementation/setting/SoupSetting.java | 2 +- .../setting/SplitHealthSetting.java | 2 +- .../implementation/setting/TimberSetting.java | 2 +- .../setting/TotemSaveDeathSetting.java | 2 +- .../type/abstraction/AbstractChallenge.java | 2 +- .../abstraction/FirstPlayerAtHeightGoal.java | 5 +- .../type/abstraction/ForceBattleGoal.java | 15 +- .../type/abstraction/ItemCollectionGoal.java | 7 +- .../type/abstraction/KillMobsGoal.java | 3 +- .../challenges/type/helper/GoalHelper.java | 22 +- .../plugin/content/i18n/ArgumentFormat.java | 19 +- .../plugin/content/i18n/MessageKey.java | 12 + .../plugin/content/loader/LanguageLoader.java | 8 +- .../challenges/ModuleChallengeLoader.java | 2 +- .../management/server/ChallengeEndCause.java | 22 +- .../management/server/WorldManager.java | 9 +- .../server/scoreboard/ChallengeBossBar.java | 6 - .../scoreboard/ChallengeScoreboard.java | 107 +- .../plugin/spigot/command/BackCommand.java | 2 +- .../plugin/spigot/command/ResetCommand.java | 4 +- .../spigot/command/SkipTimerCommand.java | 2 - .../plugin/spigot/listener/CheatListener.java | 41 +- .../commons/common/collection/pair/Pair.java | 19 + 171 files changed, 9525 insertions(+), 4636 deletions(-) create mode 100644 language/files/README.md delete mode 100644 language/files/global.json create mode 100644 language/locales/de.json create mode 100644 language/locales/en.json create mode 100644 language/locales/global.json diff --git a/language/files/README.md b/language/files/README.md new file mode 100644 index 000000000..d76c32a2d --- /dev/null +++ b/language/files/README.md @@ -0,0 +1,16 @@ +# Legacy Language Files (Backwards Compatibility) + +⚠️ **DO NOT DELETE OR MOVE THIS FOLDER** ⚠️ + +## Purpose +This folder is strictly maintained for backwards compatibility with older versions of the **Challenges** plugin. + +In versions **prior to v2.4**, the plugin did not bundle localization and translation files directly within the build. Instead, it pulled them dynamically at runtime from this GitHub repository, targeting this specific path (`/language/files/`). + +## Usage & Maintenance +* **Who uses this?** Legacy installations running Challenges v2.3.x and below. +* **Format:** The JSON files in this folder use the legacy formatting required by older versions. +* **Updates:** Unless a critical bug fix is required for legacy users, these files should remain untouched. Modern translation assets should be managed in the updated translations directory. + +--- +*For modern versions (v2.4+), please refer to `/locales` directory.* diff --git a/language/files/de.json b/language/files/de.json index 84ce5ba5f..d92a6884a 100644 --- a/language/files/de.json +++ b/language/files/de.json @@ -1,2148 +1,1846 @@ { - "generic": { - "undefined": "undefiniert", - "unknown": "unbekannt", - "disabled": "Deaktiviert", - "enabled": "Aktiviert", - "customized": "Anpassen" - }, - "language": { - "de": "Deutsch", - "en": "Englisch" - }, - "timer": { - "bar": { - "up": "{@actionbar.format('Zeit: {0}')}", - "down": "{@actionbar.format('Zeit: {0}')}", - "paused": "{@actionbar.format('Timer pausiert')}", - "format": { - "day": "{d} Tag {hh}:{mm}:{ss}", - "days": "{d} Tage {hh}:{mm}:{ss}" - } - }, - "messages": { - "started": "Der Timer wurde gestartet", - "paused": "Der Timer wurde pausiert", - "counting-up": "Der Timer zählt nun hoch", - "counting-down": "Der Timer zählt nun runter", - "hidden": "Der Timer ist nun versteckt", - "shown": "Der Timer ist nun sichtbar" - } - }, - "menu": { - "generic": { - "click-prefix": "[Klick] {@symbol.chevron} ", - "shift-click-prefix": "[Shift-Klick] {@symbol.chevron} ", - "right-click-prefix": "[Rechts-Klick] {@symbol.chevron} ", - "left-click-prefix": "[Links-Klick] {@symbol.chevron} " - }, - "timer": { - "name": "Timer", - "name-state": "Status", - "name-time": "Zeit", - "item-paused": [ - "{@item-format('Timer ist pausiert')}", - " ", - "{@generic.click-prefix}Timer fortsetzen" - ], - "item-started": [ - "{@item-format('Timer ist gestartet')}", - " ", - "{@generic.click-prefix}Timer pausieren" - ], - "item-hidden": [ - "{@item-format('Timer ist versteckt')}", - " ", - "{@generic.click-prefix}Timer anzeigen" - ], - "item-shown": [ - "{@item-format('Timer ist sichtbar')}", - " ", - "{@generic.click-prefix}Timer verstecken" - ], - "item-counting-up": [ - "{@item-format('Timer zählt hoch')}", - " ", - "{@generic.click-prefix}Timer auf runterzählen stellen" - ], - "item-counting-down": [ - "{@item-format('Timer zählt runter')}", - " ", - "{@generic.click-prefix}Timer auf hochzählen stellen" - ], - "item-name-format": "{@item-format('{0}: {1} ({2})')}", - "item-add-format": [ - "{@item-name-format('{4}', '{0}', '{1}')}", - " ", - "{@generic.click-prefix}+1 {3}", - "{@generic.shift-click-prefix}+{2} {4}" - ], - "item-subtract-format": [ - "{@item-name-format('{4}', '{0}', '{1}')}", - " ", - "{@generic.click-prefix}-1 {3}", - "{@generic.shift-click-prefix}-{2} {4}" - ], - "item-state-format": [ - "{@item-name-format('{2}', '{0}', '{1}')}", - " ", - "{@generic.click-prefix}Zeit zurücksetzen" - ], - "item-seconds": "{@item-state-format('{0}', '{1}', 'Sekunden')}", - "item-seconds-add": "{@item-add-format('{0}', '{1}', '{2}', 'Sekunde', 'Sekunden')}", - "item-seconds-subtract": "{@item-subtract-format('{0}', '{1}', '{2}', 'Sekunde', 'Sekunden')}", - "item-minutes": "{@item-state-format('{0}', '{1}', 'Minuten')}", - "item-minutes-add": "{@item-add-format('{0}', '{1}', '{2}', 'Minute', 'Minuten')}", - "item-minutes-subtract": "{@item-subtract-format('{0}', '{1}', '{2}', 'Minute', 'Minuten')}", - "item-hours": "{@item-state-format('{0}', '{1}', 'Stunden')}", - "item-hours-add": "{@item-add-format('{0}', '{1}', '{2}', 'Stunde', 'Stunden')}", - "item-hours-subtract": "{@item-subtract-format('{0}', '{1}', '{2}', 'Stunde', 'Stunden')}", - "item-days": "{@item-state-format('{0}', '{1}', 'Tage')}", - "item-days-add": "{@item-add-format('{0}', '{1}', '{2}', 'Tag', 'Tage')}", - "item-days-subtract": "{@item-subtract-format('{0}', '{1}', '{2}', 'Tag', 'Tage')}" - }, - "damage": { - "name": "Schaden" - }, - "goal": { - "name": "Ziele" - }, - "items-blocks": { - "name": "Items & Blöcke" - }, - "challenges": { - "name": "Challenges" - }, - "settings": { - "name": "Einstellungen" - }, - "custom": { - "name": "Individuelle Challenges" - } - }, - "category": { - "desc-most-points": [ - "Der Spieler mit den *meisten Punkten*", - "*gewinnt*, wenn der Timer *abläuft*" - ], - "misc_challenge": { - "menu": "Sonstige", - "desc": [ - "Challenges, die *keiner Kategorie*", - "zugeordnet werden können" - ], - "info": [ - "{@info-format('Aktiviert', '{0}/{1}')}" - ] - }, - "randomizer": { - "menu": "Randomizer", - "desc": [ - "Erlebe ein komplett", - "*durcheinandergebrachtes* Spiel" - ] - }, - "limited_time": { - "menu": "Limitierte Zeit", - "desc": [ - "Du wirst bei verschiedenen", - "Faktoren *zeitlich eingeschränkt*" - ] - }, - "force": { - "menu": "Zwischenziele", - "name": "*{@menu} (Force)*", - "desc": [ - "Du musst *bestimmte Zwischenziele*", - "erfüllen, sonst stirbst du" - ] - }, - "world": { - "menu": "Welteinfluss", - "desc": [ - "Die Welt wird nicht mehr", - "*wiedererkennbar* sein" - ] - }, - "damage": { - "menu": "Schaden", - "desc": [ - "Du wirst auf *verschiedenste*", - "Arten *Schaden* nehmen" - ] - }, - "effect": { - "menu": "Effekte", - "desc": [ - "Erlebe verrückte *Effekte*" - ] - }, - "inventory": { - "menu": "Inventar", - "desc": [ - "Dein *Inventar* wird *verdreht*" - ] - }, - "movement": { - "menu": "Bewegung", - "desc": [ - "Du wirst in deinen *Bewegungen*", - "*eingeschränkt*" - ] - }, - "entities": { - "menu": "Entities", - "desc": [ - "Entities werden *verändert*" - ] - }, - "extra_world": { - "menu": "Extra Welt", - "desc": [ - "Challenges, die in einer", - "*anderen Welt* spielen" - ] - }, - "misc_goal": { - "menu": "Sonstige Ziele", - "desc": [ - "Ziele, die *keiner Kategorie*", - "zugeordnet werden können" - ], - "info": "{@info-format('Aktuell', '{2}')}" - }, - "kill_entity": { - "menu": "Entity töten", - "desc": [ - "Töte *bestimmte Entities*,", - "um zu gewinnen" - ] - }, - "score_points": { - "menu": "Punkte sammeln", - "desc": [ - "Erziele die *meisten Punkte* in", - "einem *bestimmten Bereich*", - " ", - "{@desc-most-points}" - ] - }, - "fastest_time": { - "menu": "Schnellste Zeit", - "desc": [ - "Der *schnellste Spieler*, der das Ziel", - "erreicht *gewinnt* die Challenge" - ] - }, - "force_battle": { - "menu": "Force Battles", - "desc": [ - "Erfülle die *vorgegebenen Zwischenziele*,", - "um Punkte zu erhalten.", - " ", - "{@desc-most-points}" - ] - } - }, - "challenge": { - "language": { - "name": "*Sprache*", - "desc": [ - "Ändert die *Sprache* des Plugins" - ], - "command-disabled": "Diese Funktion ist derzeit deaktiviert", - "command-unknown": "Diese Sprache ({0}) wird nicht unterstützt", - "command-current": "Die derzeitige Sprache ist {0}", - "command-changing": "Die Sprache wird geändert...", - "command-changed": "Die Sprache wurde auf {0} ({1}) gesetzt" - }, - "pregame-movement": { - "name": "*Pregame Movement*", - "desc": [ - "Du kannst dich *bewegen*,", - "bevor der Timer *gestartet* wurde" - ], - "title": [ - "Warte..", - "{@symbol.arrow} Der Timer ist gestoppt.." - ] - }, - "difficulty": { - "name": "*Schwierigkeit*", - "desc": [ - "Ändert die *Schwierigkeit*", - "(*Difficulty*) des Spiels" - ], - "command-set": "Schwierigkeit auf {0} geändert", - "command-current": "Die derzeitige Schwierigkeit ist {0}" - }, - "hardcore-hearts": { - "name": "*Hardcore Herzen*", - "desc": [ - "Die *Herzen* werden im *Hardcore-Stil* angezeigt", - "Um die Änderung zu sehen, *musst* du *rejoinen*" - ] - }, - "random-challenge": { - "name": "*Random Challenge*", - "desc": [ - "In einem *gesetzten Intervall*", - "wird eine *zufällige Challenge* aktiviert" - ], - "challenge-enabled": [ - "Die Challenge {0} wurde aktiviert", - "{1}" - ], - "bossbar-waiting": "{@bossbar.format('Warten auf neue Challenge..')}", - "bossbar-current": "{@bossbar.format('Challenge {0}')}" - }, - "randomized-hp": { - "name": "*Zufällige HP*", - "desc": [ - "Die *Leben* aller *Mobs*", - "sind *zufällig*" - ] - }, - "jump-and-run": { - "name": "*JumpAndRun*", - "desc": [ - "In einem gesetzten *Intervall* muss ein", - "*zufälliger Spieler* ein *JumpAndRun* absolvieren", - "Schafft er es *nicht*, *stirbt* er" - ], - "actionbar": "{@actionbar.format('*Jump & Run* {@symbol.vertical} {0} / {1}')}" - }, - "goal-ender-dragon": { - "name": "*Enderdrache*", - "desc": [ - "Töte den *Enderdrachen* um zu gewinnen" - ] - }, - "goal-wither": { - "name": "*Wither*", - "desc": [ - "Töte einen *Wither* um zu gewinnen" - ] - }, - "goal-elder-guardian": { - "name": "*Elder Guardian*", - "desc": [ - "Töte einen *Großen Wächter* um zu gewinnen" - ] - }, - "goal-warden": { - "name": "*Warden*", - "desc": [ - "Töte einen *Warden* um zu gewinnen" - ] - }, - "goal-all-bosses": { - "name": "*Alle Bosse*", - "desc": [ - "Es müssen *alle Bosse* einmal", - "*getötet* werden, um zu *gewinnen*", - " ", - "({@goal-ender-dragon.name}, {@goal-wither.name}, {@goal-elder-guardian.name})" - ] - }, - "goal-all-bosses-new": { - "name": "*Alle Bosse (+ Warden)*", - "desc": [ - "Es müssen *alle Bosse* einmal", - "*getötet* werden, um zu *gewinnen*", - " ", - "({@goal-ender-dragon.name}, {@goal-wither.name}, {@goal-elder-guardian.name}, {@goal-warden.name})" - ] - } - }, - "title": { - "timer-started": [ - " ", - "{@symbol.arrow} Timer fortgesetzt" - ], - "timer-paused": [ - " ", - "{@symbol.arrow} Timer pausiert" - ], - "challenge-enabled": [ - "{0}", - "{@symbol.check} {@symbol.vertical} Aktiviert" - ], - "challenge-disabled": [ - "{0}", - "{@symbol.x} Deaktiviert" - ], - "challenge-value-changed": [ - "{0}", - "{@symbol.arrow} {1}" - ], - "goal-enabled": [ - "{0}", - "{@symbol.check} {@symbol.vertical} Ziel gewählt" - ], - "goal-disabled": [ - "{0}", - "{@symbol.x} Ziel deaktiviert" - ] - }, - "command": { - "skip-timer": { - "none": "Es ist keine Challenge aktiviert, dessen Timer übersprungen werden könnte", - "done": "Die Timer folgender Challenges wurden übersprungen: {0}" - } - }, - "syntax": "Bitte nutze §e/{0}", - "reload": "Challenges Plugin wird neu geladen...", - "reload-failed": "Ein §cFehler §7ist während dem Reload aufgetreten", - "reload-success": "Challenges Plugin wurde §aerfolgreich §7neu geladen", - "player-command": "Dazu musst du ein Spieler sein!", - "no-permission": "Dazu hast du §ckeine §7Rechte", - "enabled": "§aAktiviert", - "disabled": "§cDeaktiviert", - "customize": "§6Anpassen", - "navigate-back": "§8« §7Zurück", - "navigate-next": "§8» §7Weiter", - "seconds": "Sekunden", - "second": "Sekunde", - "minutes": "Minuten", - "minute": "Minute", - "hours": "Stunden", - "hour": "Stunde", - "amplifier": "Stärke", - "open": "Öffnen", - "everyone": "§5Alle", - "player": "§6Aktiver Spieler", - "none": "Nichts", - "inventory-color": "§9", - "confirm-reset": "Bestätige den Reset mit §e/{0}", - "no-fresh-reset": [ - "Der Server kann §cnicht resettet §7werden", - "Die Challenge wurde §cnoch nicht §7gestartet" - ], - "new-challenge-suffix": "{@challenge.suffix-format('Neu!')}", - "updated-challenge-suffix": "{@challenge.suffix-format('Update!')}", - "feature-disabled": "Diese Funktion ist derzeit §cdeaktiviert", - "challenge-disabled": "Diese Challenge ist derzeit §cdeaktiviert", - "timer-not-started": "Der Timer wurde noch §cnicht gestartet", - "timer-was-set": "Der Timer wurde auf §e§l{0} §7gesetzt", - "timer-already-started": "Der Timer §cläuft bereits", - "timer-already-paused": "Der Timer ist §cbereits pausiert", - "timer-mode-set-down": "Der Timer zählt nun §crunter", - "timer-mode-set-up": "Der Timer zählt nun §ahoch", - "no-database-connection": "Es gibt §ckeine §7Datenbankverbindung", - "fetching-data": "Daten werden abgerufen..", - "no-such-material": "Dieses Material gibt es nicht", - "not-an-item": "§e{0} §7ist kein Item", - "no-such-entity": "Dieses Entity existiert nicht", - "not-alive": "§e{0} §7ist kein lebendes Entity", - "no-loot": "§e{0} §7hat keine Drops", - "deprecated-plugin-version": [ - " ", - "§7Ein neues Update ist verfügbar!", - "§7Download: §e§l{0}", - " " - ], - "deprecated-config-version": [ - "Deine Plugin Config ist §cveraltet §7(§c{1} §7< §a{0}§7)", - "Du kannst die alte Config löschen oder die fehlenden Einstellungen manuell hinzufügen" - ], - "missing-config-settings": "Folgende Einstellungen fehlen in der Config: §e{0}", - "missing-config-settings-separator": "§7, §e", - "no-missing-config-settings": [ - "§cEs fehlen keine Einstellungen in der Config.", - "§cDu kannst die Version ohne bedenken selbst auf §c§l{0} §cstellen." - ], - "unsuported-language": [ - "§cDiese Sprache §7(§e{0}§7) wird nicht unterstützt" - ], - "not-op": [ - "§7Um dieses Plugin zu nutzen, musst du die Berechtigung haben. Gib dir die Berechtigung in der Serverkonsole mit: /op [name]" - ], - "join-message": "{0} hat den Server betreten", - "quit-message": "{0} hat den Server verlassen", - "timer-paused-message": [ - "Der Timer ist noch §cpausiert", - "Nutze §e/timer resume §7um ihn zu starten" - ], - "cheats-detected": [ - "§e{0} §7hat §cgecheated", - "Es können §ckeine weiteren §7Statistiken gesammelt werden" - ], - "cheats-already-detected": [ - "Auf diesem Server wurde §cgecheated", - "Es können §ckeine weiteren §7Statistiken gesammelt werden" - ], - "custom_challenges-reset": "Die §eLokalen §7Challenges wurden §aerfolgreich zurückgesetzt", - "config-reset": "Die §eLokalen §7Einstellungen wurden §aerfolgreich zurückgesetzt", - "player-config-loaded": "Deine Einstellungen wurden §aerfolgreich geladen", - "player-config-saved": "Deine Einstellungen wurden §aerfolgreich gespeichert", - "player-config-reset": "Deine Einstellungen wurden §aerfolgreich zurückgesetzt", - "player-custom_challenges-loaded": "Deine Challenges wurden §aerfolgreich geladen", - "player-custom_challenges-saved": "Deine Challenges wurden §aerfolgreich gespeichert", - "player-custom_challenges-reset": "Deine Challenges wurden §aerfolgreich zurückgesetzt", - "item-prefix": "§8» ", - "item-setting-info": "§8➟ {0}", - "stat-dragon-killed": "Drachen getötet", - "stat-deaths": "Tode", - "stat-entity-kills": "Kills", - "stat-damage-dealt": "Schaden ausgeteilt", - "stat-damage-taken": "Schaden genommen", - "stat-blocks-mined": "Blöcke abgebaut", - "stat-blocks-placed": "Blöcke platziert", - "stat-blocks-traveled": "Blöcke gereist", - "stat-challenges-played": "Challenges gespielt", - "stat-jumps": "Sprünge", - "stats-of": "§8» §7Stats von §e{0}", - "stats-display": "§8» §7{0} §8(§e{1}. §7Platz§8)", - "stats-leaderboard-display": [ - "§8» §e{0}", - "§8§l┣ §7{1} §7{2}", - "§8§l┗ §e{3}. §7Platz" - ], - "position": "§e{4} §8- §7{0}, {1}, {2} §8(§e{3}§8) §8┃ §e{5}m", - "positions-disabled": "Positionen sind §cdeaktiviert", - "position-other-world": "Diese Position befindet sich in einer anderen Welt §8(§e{0}§8)", - "position-not-exists": "Die Position §e{0} §7existiert §cnicht", - "position-already-exists": "Die Position §e{0} §7existiert §cbereits", - "position-set": "§e{5} §7hat §e{4} §7{0}, {1}, {2} §8(§e{3}§8) §7erstellt", - "position-deleted": "§e{5} §7hat §e{4} §7{0}, {1}, {2} §8(§e{3}§8) §7gelöscht", - "no-positions": [ - "Es sind keine §ePositionen §7in dieser Welt gesetzt", - "Erstelle eine mit §e/{0}" - ], - "no-positions-global": [ - "Es sind keine §ePositionen §7gesetzt", - "Erstelle eine mit §e/{0}" - ], - "command-no-target": "Es wurde §ckein §7Spieler gefunden", - "command-heal-healed": "Du wurdest §ageheilt", - "command-heal-healed-others": "Du hast §e{0} Spieler §ageheilt", - "command-gamemode-gamemode-changed": "Du wurdest in den Gamemode §e{0} §7gesetzt", - "command-gamemode-gamemode-changed-others": "Du hast §e{1} Spieler §7in den Gamemode §e{0} §7gesetzt", - "command-village-search": "Es wird nach einem Dorf gesucht..", - "command-village-teleport": "Du wurdest in ein Dorf §ateleportiert", - "command-village-not-found": "Es wurde §ckein neues §7Dorf gefunden", - "command-weather-set-clear": "Wetter zu §eklar §7geändert", - "command-weather-set-rain": "Wetter zu §eregnerisch §7geändert", - "command-weather-set-thunder": "Wetter zu §estürmisch §7geändert", - "command-invsee-open": "Inventar von §e{0} §7geöffnet", - "command-enderchest-open": "Du hast deine §5Enderchest §7geöffnet", - "command-search-nothing": "§e{0} §7wird durch keinen speziellen Block gedroppt", - "command-search-result": "§e{0} §7droppt aus §e{1}", - "command-searchloot-disabled": "Die Entity Loot Randomizer Challenge ist aktuell §cdeaktiviert", - "command-searchloot-nothing": "Der Loot von §e{0} §7wird durch kein spezielles Entity gedroppt", - "command-searchloot-result": [ - "§e{0} §7droppt den Loot von §e{1}", - "Der Loot von §e{0} §7wird von §e{2} §7gedroppt" - ], - "command-time-set": "Die Zeit wurde auf §e{0} §7Ticks §8(§7ca. §e{1}§8) §7geändert", - "command-time-set-exact": "Die Zeit wurde auf §e{0} §8(§e{1} §7Ticks§8) §7geändert", - "command-time-query": [ - "§8» §7Derzeitige Ingamezeiten", - "Spielzeit §e{0} §7Ticks §8(§7Tag §e{1}§8)", - "Tageszeit §e{2} §7Ticks §8(§7ca. §e{3}§8)" - ], - "command-time-noon": "Mittag", - "command-time-night": "Nacht", - "command-time-midnight": "Mitternacht", - "command-time-day": "Tag", - "command-fly-enabled": "Du kannst §anun fliegen", - "command-fly-disabled": "Du kannst nun §cnicht mehr §7fliegen", - "command-fly-toggled-others": "Du hast §eFly §7für §e{0} §7Spieler verändert", - "command-feed-fed": "Dein Hunger wurde §agestillt", - "command-feed-others": "Du hast den Hunger von §e{0} §7Spieler *gestillt*", - "command-gamestate-reload": "Der Gamestate wurde §aneu geladen", - "command-gamestate-reset": "Der Gamestate wurde §azurückgesetzt", - "command-world-teleport": "Du wirst in die Welt §e{0} §7teleportiert", - "command-back-no-locations": "Du hast dich noch §cnicht §7teleportiert", - "command-back-teleported": "Du wurdest §e{0} §7Position zurück teleportiert", - "command-back-teleported-multiple": "Du wurdest §e{0} §7Positionen zurück teleportiert", - "command-result-no-battle-active": "Es ist aktuell §ckein §7Force-Battle aktiviert", - "command-god-mode-enabled": "Du bist nun im §aGod-Mode", - "command-god-mode-disabled": "Du bist nun §cnicht mehr im God-Mode", - "command-god-mode-toggled-others": "§e{0} §7Spieler sind jetzt im §eGod-Mode", - "traffic-light-challenge-fail": "§e{0} §7ist über §crot §7gegangen", - "player-damage-display": "§e{0} §7nahm §7{1} §7Schaden durch §e{2}", - "death-message": "§e{0} §7ist gestorben", - "death-message-cause": "§e{0} §7ist durch §e{1} §7gestorben", - "health-inverted": "Deine Herzen wurden §cinvertiert", - "exp-picked-up": "§e{0} §7hat §cXP §7aufgesammelt", - "unable-to-find-fortress": "Es konnte §ckeine Festung §7gefunden werden", - "unable-to-find-bastion": "Es konnte §ckeine Bastion §7gefunden werden", - "death-collected": "Todesgrund §e{0} §7wurde registriert", - "item-collected": "Item §e{0} §7wurde registriert", - "items-to-collect": "§7Items zu sammeln §8» §e{0}", - "backpacks-disabled": "Rucksäcke sind derzeit §cdeaktiviert", - "backpack-opened": "Du hast den {0} §7geöffnet", - "top-to-overworld": "Du wurdest zur §eOverworld §7teleportiert", - "top-to-surface": "Du wurdest zur §eOberfläche §7teleportiert", - "jnr-countdown": "Nächstes §6JumpAndRun §7in §e{0} Sekunden", - "jnr-countdown-one": "Nächstes §6JumpAndRun §7in §eeiner Sekunde", - "jnr-finished": "§e{0} §7hat das §6JumpAndRun §ageschafft", - "snake-failed": "§e{0} §7ist über die §9Linie §7getreten", - "only-dirt-failed": "§e{0} §7stand nicht auf Erde", - "no-mouse-move-failed": "§e{0} §7hat seine Maus bewegt", - "no-duped-items-failed": "§e{0} §7und §e{1} §7hatten beide §e{2} §7im Inventar", - "only-down-failed": "§e{0} §7ist einen Block nach oben gegangen", - "food-once-failed": "§e{0} §7ist an §e{1} §7erstickt", - "food-once-new-food-team": "§e{0} §7hat §e{1} §7gegessen", - "food-once-new-food": "§eDu §7hast §e{1} §7gegessen", - "sneak-damage-failed": "§e{0} §7ist geschlichen", - "jump-damage-failed": "§e{0} §7ist gesprungen", - "all-items-skipped": "Item §e{0} §7geskippt", - "all-items-already-finished": "Es wurden bereits alle Items gefunden", - "all-items-found": "Das Item §e{0} §7wurde von §e{1} §7registriert", - "mob-kill": "§e{0} §7wurde besiegt §8(§e{1} §7/ §e{2}§8)", - "endergames-teleport": "Du wurdest mit §e{0} §7getauscht", - "force-height-fail": "§e{0} §7war auf der §cfalschen Höhe §8(§e{1}§8)", - "force-height-success": "Alle Spieler waren auf der §arichtigen Höhe", - "force-block-fail": "§e{0} §7war auf dem §cfalschen Block §8(§e{1}§8)", - "force-block-success": "Alle Spieler waren auf dem §arichtigen Block", - "force-biome-fail": "Das Biom §e{0} §7wurde §cnicht gefunden", - "force-biome-success": "§e{0} §7hat das Biom §e{1} §agefunden", - "force-mob-fail": "Das Mob §e{0} §7wurde §cnicht getötet", - "force-mob-success": "§e{0} §7hat das Mob §e{1} §agetötet", - "force-item-fail": "Das Item §e{0} §7wurde §cnicht gefunden", - "force-item-success": "§e{0} §7hat das Item §e{1} §agefunden", - "new-effect": "Effekt §e{0} §8➔ §e{1}", - "missing-items-inventory": "{0}Welches Item fehlt?", - "missing-items-inventory-open": "§8[§aGUI öffnen§8]", - "loops-cleared": "§e{0} §7Loops abgebrochen", - "stopped-moving": "§e{0} §7hat sich zu lange nicht bewegt", - "all-advancements-goal": "§7Advancements §8» §e{0}", - "height-reached": "§e{0} §7hat Höhe §e{1} §7erreicht!", - "race-goal-reached": "§e{0} §7hat das Ziel erreicht!", - "points-change": "§e{0} §7Punkte", - "force-item-battle-found": "Du hast §e{0} §7gefunden!", - "force-item-battle-new-item": "Item zu suchen: §e{0}", - "force-item-battle-leaderboard": "§8➜ §7Force Item Battle Leaderboard", - "force-mob-battle-killed": "Du hast §e{0} §7gefunden!", - "force-mob-battle-new-mob": "Mob zu suchen: §e{0}", - "force-mob-battle-leaderboard": "§8➜ §7Force Mob Battle Leaderboard", - "force-advancement-battle-completed": "Du hast §e{0} §7erzielt!", - "force-advancement-battle-new-advancement": "Nächstes Advancement: §e{0}", - "force-advancement-battle-leaderboard": "§8➜ §7Force Advancement Battle Leaderboard", - "force-block-battle-found": "Du hast §e{0} §7gefunden!", - "force-block-battle-new-block": "Block zu suchen: §e{0}", - "force-block-battle-leaderboard": "§8➜ §7Force Block Battle Leaderboard", - "force-battle-leaderboard-entry": "{0}#{1} §8» §e{2} §8┃ §e{3}", - "force-battle-block-target-display": "§eBlock: {0}", - "force-battle-item-target-display": "§eItem: {0}", - "force-battle-height-target-display": "§eHöhe: {0}", - "force-battle-mob-target-display": "§eMob: {0}", - "force-battle-biome-target-display": "§eBiom: {0}", - "force-battle-damage-target-display": "§eSchaden: §c{0} ❤", - "force-battle-advancement-target-display": "§eAdvancement: {0}", - "force-battle-position-target-display": "§ePosition: {0}", - "extreme-force-battle-new-height": "Höhe zu erreichen: §e{0}", - "extreme-force-battle-reached-height": "Du hast die Höhe §e{0} §7erreicht!", - "extreme-force-battle-new-biome": "Biom zu finden: §e{0}", - "extreme-force-battle-found-biome": "Du hast das Biom §e{0} §7gefunden!", - "extreme-force-battle-new-damage": "Schaden zu nehmen: §c{0} ❤", - "extreme-force-battle-took-damage": "Du hast §c{0} ❤ §7Schaden genommen!", - "extreme-force-battle-position": "§eX: {0} §8┃ §eZ: {1}", - "extreme-force-battle-new-position": "Position zu erreichen: §e{0}", - "extreme-force-battle-reached-position": "Du hast die Position §e{0} §7erreicht!", - "extreme-force-battle-leaderboard": "§8➜ §7Extreme Force Battle Leaderboard", - "force-biome-battle-leaderboard": "§8➜ §7Force Biome Battle Leaderboard", - "force-damage-battle-leaderboard": "§8➜ §7Force Damage Battle Leaderboard", - "force-height-battle-leaderboard": "§8➜ §7Force Height Battle Leaderboard", - "force-position-battle-leaderboard": "§8➜ §7Force Position Battle Leaderboard", - "random-event-speed": [ - "Sonic? Bist du es?", - "Woahh! Das ist aber schnell" - ], - "random-event-entities": [ - "Ist das hier ein Zoo?", - "Wo kommt ihr denn her?", - "Was macht ihr denn hier?" - ], - "random-event-hole": [ - "Du bist aber ganz schön tief gefallen", - "Von ganz oben nach ganz unten..", - "Wo kommt denn das Loch her?" - ], - "random-event-fly": [ - "Guten Flug :)", - "I believe I can fly..", - "So fühlt sich also fliegen an" - ], - "random-event-webs": [ - "Liegen die schon lange hier?" - ], - "random-event-ores": [ - "Wo sind denn die ganzen Erze hin?", - "Gibt es hier keine Erze?", - "Gab es hier mal Erze?" - ], - "random-event-sickness": [ - "Bist du etwa krank?", - "Was geht denn jetzt ab" - ], - "quiz-how-to": "Schreibe deine Antwort mit §e/guess ", - "quiz-right-answer": "§e{0} §7ist die §arichtige §7Antwort!", - "quiz-right-answer-other": "§e{0} §7hat die Frage §arichtig §7beantwortet", - "quiz-wrong-answer": "§e{0} §7ist eine §cfalsche §7Antwort!", - "quiz-wrong-answer-other": "§e{0} §7hat die Frage §cfalsch beantwortet", - "quiz-time-up": "Die Zeit ist §cabgelaufen§7!", - "quiz-cancel": "Die Frage wurde §cabgebrochen§7!", - "quiz-right-answer-was": "Die richtige Antwort lautete: §e{0}", - "quiz-right-answer-was-multiple": "Die richtigen Antworten lauteten: §e{0}", - "quiz-question-often-have": "Wie oft hast du §e{0}§7{1}?", - "quiz-question-often-be": "Wie oft bist du §e{0}§7{1}?", - "quiz-question-far-be": "Wie weit bist du {0}?", - "quiz-question-most": "Was hast du von diesen {1} am meisten {0}?", - "quiz-question-damage-have": "Wie viel Schaden hast du {0}{1}?", - "quiz-question-damage-taken-have": "Wie viel Schaden hast du durch {0}{1}?", - "quiz-verb-traveled": "gelaufen", - "quiz-verb-jumped": "gesprungen", - "quiz-verb-sneaked": "geschlichen", - "quiz-verb-killed": "getötet", - "quiz-verb-damaged": "zugefügt", - "quiz-verb-broken": "abgebaut", - "quiz-verb-placed": "platziert", - "quiz-verb-dropped": "gedropped", - "quiz-verb-suffered": "erlitten", - "bossbar-timer-paused": "§8» §7Der Timer ist §cpausiert", - "bossbar-mob-transformation": "§8» §7Letzter Mob §8§l┃ §a{0}", - "bossbar-biome-time-left": "§8» §7Zeit übrig in §e{0} §8§l┃ §a{1}s", - "bossbar-height-time-left": "§8» §7Zeit übrig auf §e{0} §8§l┃ §a{1}s", - "bossbar-zero-hearts": "§8» §7Schutzzeit §8§l┃ §a{0}s", - "bossbar-all-items-current-max": "§8» §f{0} §8┃ §7{1} §8/ §7{2}", - "bossbar-all-items-finished": "§8» §7Alle Items gefunden", - "bossbar-force-height-waiting": "§8» §7Warten auf nächste Höhe..", - "bossbar-force-height-instruction": "§8» §7Höhe §e{0} §8┃ §a{1}", - "bossbar-force-block-waiting": "§8» §7Warten auf nächsten Block..", - "bossbar-force-block-instruction": "§8» §7Block §e{0} §8┃ §a{1}", - "bossbar-force-biome-waiting": "§8» §7Warten auf nächstes Biom..", - "bossbar-force-biome-instruction": "§8» §7Biom §e{0} §8┃ §a{1}", - "bossbar-force-mob-waiting": "§8» §7Warten auf nächsten Mob..", - "bossbar-force-mob-instruction": "§8» §7Mob §e{0} §8┃ §a{1}", - "bossbar-force-item-waiting": "§8» §7Warten auf nächstes Item..", - "bossbar-force-item-instruction": "§8» §7Item §e{0} §8┃ §a{1}", - "bossbar-tsunami-water": "§8» §7Wasserhöhe: §9{0}", - "bossbar-tsunami-lava": "§8» §7Lavahöhe: §c{0}", - "bossbar-ice-floor": "§8» §fEisboden §8┃ {0}", - "bossbar-dont-stop-running": "§8» §7Bewege dich in §8┃ §e{0}", - "bossbar-five-hundred-blocks": "§8» §fBlöcke Gelaufen §8┃ §7{0} §8/ §7{1}", - "bossbar-level-border": "§8» §7Border Größe §8┃ §7{0}", - "bossbar-race-goal-info": "§8» §fZiel §8┃ §7X: {0} §8/ §7Z: {1} §8┃ §e{2} Blöcke", - "bossbar-race-goal": "§8» §fZiel §8┃ §7X: {0} §8/ §7Z: {1}", - "bossbar-first-at-height-goal": "§8» §fZiel §8┃ §7Y: {0}", - "bossbar-respawn-end": "§8» §5Respawnte Mobs im End §8┃ §e{0}", - "bossbar-kill-all-bosses": "§8» §cAlle Bosse §8┃ §e{0}/{1}", - "bossbar-kill-all-mobs": "§8» §cAlle Mobs §8┃ §e{0}/{1}", - "bossbar-kill-all-monster": "§8» §cAlle Monster §8┃ §e{0}/{1}", - "bossbar-chunk-deletion": "§8» §7Zeit übrig im Chunk §6{0}s", - "subtitle-time-seconds": "§e{0} §7Sekunden", - "subtitle-time-seconds-range": "§e{0}-{1} §7Sekunden", - "subtitle-time-minutes": "§e{0} §7Minuten", - "subtitle-launcher-description": "§7Stärke §e{0}", - "subtitle-blocks": "§e{0} §7Blöcke", - "subtitle-range-blocks": "§7Reichweite: §e{0} §7Blöcke", - "scoreboard-title": "§7» §f§lChallenge", - "scoreboard-leaderboard": "§e#{0} §8┃ §7{1} §8» §e{2}", - "your-place": "§7Dein Platz §8» §e{0}", - "server-reset-restart": [ - "§8§m §r", - " ", - "§8» §cServerreset", - " ", - "§7Reset durch §4§l{0}", - "§7Der Server startet nun §cneu", - " ", - "§8§m §r" - ], - "server-reset-stop": [ - "§8§m §r", - " ", - "§8» §cServerreset", - " ", - "§7Reset durch §4§l{0}", - "§7Der Server wird nun §cgestoppt", - " ", - "§8§m §r" - ], - "challenge-end-timer-hit-zero": [ - " ", - "§cDie Challenge ist vorbei!", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-timer-hit-zero-winner": [ - " ", - "§cDie Challenge ist vorbei!", - "§7Gewinner: §e§l{1}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-reached": [ - " ", - "§7Die Challenge wurde beendet!", - "§7Zeit benötigt: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-reached-winner": [ - " ", - "§7Die Challenge wurde beendet!", - "§7Gewinner: §e§l{1}", - "§7Zeit benötigt: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-failed": [ - " ", - "§cDie Challenge ist vorbei! §6#FeelsBadMan {@symbol.cross}", - "§7Zeit verschwendet: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "title-timer-started": [ - " ", - "§8» §7Timer §afortgesetzt" - ], - "title-timer-paused": [ - " ", - "§8» §7Timer §cpausiert" - ], - "title-challenge-enabled": [ - "§e{0}", - "§2§l✔ §8┃ §aAktiviert" - ], - "title-challenge-disabled": [ - "§e{0}", - "§4✖ §8┃ §cDeaktiviert" - ], - "title-challenge-value-changed": [ - "§e{0}", - "§8» §e{1}" - ], - "item-menu-start": "§8• §aStart Challenge §8┃ §e/start §8•", - "item-menu-challenges": "§8• §cChallenges §8┃ §e/challenge §8•", - "item-menu-timer": "§8• §5Timer §8┃ §e/timer §8•", - "item-menu-leaderboard": "§8• §6Leaderboard §8┃ §e/leaderboard §8•", - "item-menu-stats": "§8• §2Statistiken §8┃ §e/stats §8•", - "menu-main-title": "{@menu.title-format('Menu')}", - "menu-timer": "§6Timer", - "menu-goal": "§5Ziel", - "menu-damage": "§7Schaden", - "menu-item_blocks": "§4Blöcke & Items", - "menu-challenges": "§cChallenges", - "menu-settings": "§eEinstellungen", - "menu-custom": "§aIndividuelle Challenges", - "lore-category-activated-count": "§7Aktiviert §8» §a{0}§8/§7{1}", - "lore-category-activated": "§7Aktiviert §8» §aJa", - "lore-category-deactivated": "§7Aktiviert §8» §cNein", - "item-time-seconds-description": "§8» §7Zeit: §e{0} §7Sekunden", - "item-time-seconds-range-description": "§8» §7Zeit: §e{0}-{1} §7Sekunden", - "item-time-minutes-description": "§8» §7Zeit: §e{0} §7Minuten", - "item-heart-damage-description": "§8» §7Schaden: §e{0} §c❤", - "item-heart-start-description": "§8» §7Start: §e{0} §c❤", - "item-max-health-description": "§8» §7Maximale Leben: §e{0} §c❤", - "item-chance-description": "§8» §7Chance: §e{0}%", - "item-launcher-description": "§8» §7Stärke: §e{0}", - "item-permanent-effect-target-player-description": "§8» §7Nur der aktive Spieler erhält den Effekt", - "item-permanent-effect-target-everyone-description": "§8» §7Alle erhalten den Effekt", - "item-blocks-description": "§8» §7Blöcke zu laufen: §e{0}", - "item-range-blocks-description": "§8» §7Reichweite: §e{0} §7Blöcke", - "item-force-battle-goal-jokers": [ - "§6Anzahl der Joker", - "Die *Anzahl* der *Joker*,", - "die jeder Spieler hat" - ], - "item-force-battle-show-scoreboard": [ - "§bScoreboard anzeigen" - ], - "item-force-battle-duped-targets": [ - "§cDoppelte Ziele", - "Ziele können *mehrfach* vorkommen" - ], - "item-force-position-battle-radius": [ - "§bRadius", - "Der *maximale Radius*, in dem sich die", - "Positionen befinden können" - ], - "item-language-setting": [ - "§bSprache", - "Setze die *Sprache*" - ], - "item-language-setting-german": "§fDeutsch", - "item-language-setting-english": "§fEnglish", - "item-one-life-setting": [ - "§cEin Teamleben", - "*Jeder* stirbt, wenn *einer stirbt*" - ], - "item-respawn-setting": [ - "§4Respawn", - "Wenn du *stirbst*, wirst du nicht zu einem *Zuschauer*" - ], - "item-death-message-setting": [ - "§6Todesnachrichten", - "Schaltet *Todesnachrichten* ein/aus" - ], - "item-death-message-setting-vanilla": "§6Vanilla", - "item-pvp-setting": [ - "§9PvP" - ], - "item-max-health-setting": [ - "§cMaximale Herzen", - "Stellt ein, wie viele", - "Herzen man hat" - ], - "item-soup-setting": [ - "§cSuppen Heilung", - "Wenn du eine *Pilzsuppe* benutzt,", - "wirst du um *4 Herzen* geheilt" - ], - "item-damage-setting": [ - "§cDamage Multiplier", - "Schaden, den du nimmst, wird *multipliziert*" - ], - "item-damage-display-setting": [ - "§eDamage Display", - "Es wird im Chat angezeigt,", - "wenn jemand *Schaden* bekommt" - ], - "item-health-display-setting": [ - "§cHealth Display", - "Die *Herzen* aller Spieler", - "werden in der *Tablist* angezeigt" - ], - "item-position-setting": [ - "§9Positions", - "Erlaubt es dir *Positionen*", - "mit */pos* zu *markieren*" - ], - "item-backpack-setting": [ - "§6Backpack", - "Erlaubt es dir, *deinen Backpack* oder den", - "*Team Backpack* mit */backpack* zu öffnen" - ], - "item-backpack-setting-team": "§5Team", - "item-backpack-setting-player": "§6Player", - "item-cut-clean-setting": [ - "§9CutClean", - "Verschiedene *Einstellungen*, die", - "das *Farmen* von Items *einfacher* machen" - ], - "menu-cut-clean-setting-settings": "CutClean", - "item-cut-clean-gold-setting": [ - "§6Gold", - "*Golderz* wird direkt zu *Goldbarren*" - ], - "item-cut-clean-iron-setting": [ - "§7Iron", - "*Eisenerz* wird direkt zu *Eisenbarren*" - ], - "item-cut-clean-coal-setting": [ - "§eCoal", - "*Kohleerz* wird direkt zu *Fackeln*" - ], - "item-cut-clean-flint-setting": [ - "§eFlint", - "*Gravel* droppt immer *Flint*" - ], - "item-cut-clean-vein-setting": [ - "§eOre Veins", - "*Erz Venen* werden direkt abgebaut" - ], - "item-cut-clean-inventory-setting": [ - "§6Direkt ins Inventar", - "*Items* werden, *anstatt gedroppt* zu werden,", - "*direkt* ins *Inventar* hinzugefügt" - ], - "item-cut-clean-food-setting": [ - "§cGebratenes Essen", - "*Rohes Fleisch* wird direkt zu *gebratenem Fleisch*" - ], - "item-glow-setting": [ - "§fPlayerglow", - "*Spieler* sind durch die *Wand* sichtbar" - ], - "no-hunger-setting": [ - "§cKein Hunger", - "Du bekommst keinen *Hunger*" - ], - "item-no-hit-delay-setting": [ - "§fNoHitDelay", - "Nachdem du *Schaden* genommen hast,", - "kannst du *sofort* wieder Schaden *bekommen*" - ], - "item-timber-setting": [ - "§bTimber", - "Du kannst einen *Baum* zerstören,", - "indem du *einen Block* des Baumes abbaust" - ], - "item-timber-setting-logs": "§6Baumstämme", - "item-timber-setting-logs-and-leaves": "§6Baumstämme §7und §2Blätter", - "item-keep-inventory-setting": [ - "§5Keep Inventory", - "Du verlierst keine *Items*,", - "wenn du *stirbst*" - ], - "item-mob-griefing-setting": [ - "§5Mob Griefing", - "Monster können *nichts zerstören*" - ], - "item-no-item-damage-setting": [ - "§5Kein Itemschaden", - "*Items* sind *unzerstörbar*" - ], - "top-command-setting": [ - "§dTop Command", - "Mit */top* kannst du dich", - "zur *Oberfläche* oder in", - "die *Overworld* teleportieren" - ], - "item-fortress-spawn-setting": [ - "§cFestungs Spawn", - "Wenn du in den *Nether* gehst,", - "spawnst du immer in einer *Festung*" - ], - "item-bastion-spawn-setting": [ - "§cBastions Spawn", - "Wenn du in den *Nether* gehst,", - "spawnst du immer in einer *Bastion*" - ], - "item-no-offhand-setting": [ - "§6Keine Offhand", - "Die *zweite Hand* wird geblockt" - ], - "item-regeneration-setting": [ - "§cRegeneration", - "Stellt ein, *ob* und", - "*wie* man *regeneriert*" - ], - "item-regeneration-setting-not_natural": "§6Nicht natürlich", - "item-immediate-respawn-setting": [ - "§6Direkter Respawn", - "Wenn du stirbst, *respawnst* du *automatisch,*", - "ohne den *Death Screen* zu sehen" - ], - "item-slot-limit-setting": [ - "§4Inventar Slots", - "Stellt ein, wie viele *Inventar*", - "*Slots* nutzbar sind" - ], - "item-death-position-setting": [ - "§cDeath Position", - "Wenn du stirbst, wird mit */pos* ", - "eine *Position an deinem Todespunkt* erstellt" - ], - "item-enderchest-command-setting": [ - "§5Enderchest Command", - "Wenn du */ec* ausführst, öffnet", - "sich deine *Enderchest*" - ], - "item-split-health-setting": [ - "§cGeteilte Herzen", - "Stellt ein, ob sich *alle*", - "*Spieler* eine *Gesundheit teilen*" - ], - "item-old-pvp-setting": [ - "§b1.8 PvP", - "Das *alte 1.8 PvP System* wird genutzt", - "Es gibt keinen *Attack Cooldown*" - ], - "item-totem-save-setting": [ - "§6Challenge Tod Rettung", - "Wenn du durch eine Challenge *instant*", - "*stirbst*, können *Totems* dich retten" - ], - "item-traffic-light-challenge": [ - "§cAmpelchallenge", - "Die *Ampel* schaltet alle paar Minuten um", - "Wenn du bei *rot* gehst, stirbst du" - ], - "item-block-randomizer-challenge": [ - "§6Block Randomizer", - "Jeder *Block* droppt ein *zufälliges Item*" - ], - "item-crafting-randomizer-challenge": [ - "§6Crafting Randomizer", - "Wenn du *etwas craftest*, bekommst du ein *zufälliges Item*" - ], - "item-mob-randomizer-challenge": [ - "§6Mob Randomizer", - "Wenn ein *Entity* spawnt, spawnt ein *anderes*" - ], - "item-hotbar-randomizer-challenge": [ - "§6HotBar Randomizer", - "Alle *paar Minuten* erhält jeder Spieler *zufällige Items*" - ], - "item-damage-block-challenge": [ - "§4Schaden pro Block", - "Du bekommst *Schaden* durch", - "jeden *Block*, den du gehst" - ], - "item-hunger-block-challenge": [ - "§6Hunger pro Block", - "Du bekommst *Hunger* durch", - "jeden *Block*, den du gehst" - ], - "item-stone-sight-challenge": [ - "§fStein Blick", - "*Mobs*, denen du in die *Augen*", - "*schaust*, werden zu *Stein*" - ], - "item-no-mob-sight-challenge": [ - "§cMob Blick Schaden", - "Wenn du einen *Mob* in die *Augen*", - "*schaust*, erleidest du *Schaden*" - ], - "item-bedrock-path-challenge": [ - "§7Bedrock Path", - "*Unter dir* entsteht die", - "ganze Zeit *Bedrock*" - ], - "item-bedrock-walls-challenge": [ - "§7Bedrock Walls", - "Hinter dir *spawnen* riesige", - "*Wände* aus *Bedrock*" - ], - "item-surface-hole-challenge": [ - "§cSurface Hole", - "§7Hinter dir *verschwindet* der", - "*Boden* bis ins *Void*" - ], - "item-damage-inv-clear-challenge": [ - "§cDamage Inventory Clear", - "Die *Inventare* aller Spieler werden *geleert*,", - "wenn ein *Spieler* Schaden erleidet" - ], - "item-no-trading-challenge": [ - "§2Kein Handeln", - "Du kannst *nicht* mit", - "Villager *handeln*" - ], - "item-block-break-damage-challenge": [ - "§6Block Break Damage", - "Wenn du einen *Block abbaust*,", - "*erleidest* du die gesetze Anzahl *schaden*" - ], - "item-block-place-damage-challenge": [ - "§6Block Place Damage", - "Wenn du einen *Block plazierst*,", - "*erleidest* du die gesetze Anzahl *schaden*" - ], - "item-no-exp-challenge": [ - "§aKeine XP", - "Wenn du *XP* aufsammelst, stirbst du" - ], - "item-invert-health-challenge": [ - "§cInvert Health", - "Alle paar Minuten werden deine *Herzen invertiert*.", - "Wenn du *8 Herzen* hast,", - "hast du danach *2 Herzen* und umgekehrt." - ], - "item-jump-and-run-challenge": [ - "§6Jump and Run", - "Alle *paar Minuten* musst du ein random *Jump and Run* machen,", - "welches jedes Mal *schwieriger* wird" - ], - "item-snake-challenge": [ - "§9Snake", - "*Jeder Spieler* zieht eine", - "tödliche Linie hinter sich her" - ], - "item-reversed-damage-challenge": [ - "§cReversed Damage", - "Wenn du Entities *schlägst* oder *abschießt*,", - "bekommst du den *gleichen Schaden*" - ], - "item-duped-spawning-challenge": [ - "§cDoppeltes Spawning", - "Wenn ein Monster *spawnt*,", - "spawnt es *zweimal*" - ], - "item-hydra-challenge": [ - "§5Hydra", - "Wenn du einen *Mob* tötest,", - "spawnen *zwei* neue" - ], - "item-hydra-plus-challenge": [ - "§cHydra Plus", - "Wenn du einen *Mob* tötest,", - "spawnen *doppelt* so viele", - "wie beim *vorherigen* mal", - " ", - "Maximum beträgt *512* Mobs gleichzeitig" - ], - "item-floor-lava-challenge": [ - "§6Der Boden ist Lava", - "Alle *Blöcke* unter dir verwandeln sich", - "erst zu *Magma* und dann zu *Lava*" - ], - "item-only-dirt-challenge": [ - "§cOnly Dirt", - "Wenn du nicht auf *Erde*", - "stehst, *stirbst* du" - ], - "item-food-once-challenge": [ - "§cFood Once", - "Du kannst jedes *Essen*", - "nur einmal *essen*" - ], - "item-food-once-challenge-player": "§6Spieler", - "item-food-once-challenge-everyone": "§5Jeder", - "item-chunk-deconstruction-challenge": [ - "§bChunk Deconstruction", - "*Chunks*, in denen sich Spieler befinden,", - "*bauen* sich von *oben* aus ab" - ], - "item-one-durability-challenge": [ - "§4Eine Haltbarkeit", - "*Items* gehen nach *einer* Benutzung *kaputt*" - ], - "item-low-drop-rate-challenge": [ - "§6Low Drop Chance", - "Die *Dropchance* jedes *Blockes* wird auf die", - "angegebene *Prozentzahl* gesetzt" - ], - "item-invisible-mobs-challenge": [ - "§fUnsichtbare Mobs", - "Alle *Mobs* haben einen", - "*Unsichtbarkeits* Effekt" - ], - "item-mob-transformation-challenge": [ - "§cMob Verwandlung", - "Wenn du einen Mob schlägst, *verwandelt* sich", - "dieser in den *letzen Mob*, den du *geschlagen* hast" - ], - "item-jump-entity-challenge": [ - "§2Jump Entity", - "Wenn du *springst*, *spawnt* ein", - "zufälliges *Entity*" - ], - "item-no-mouse-move-challenge": [ - "§cMausbewegung Schaden", - "Wenn du deinen *Blick bewegst*,", - "erleidest du den *gesetzen Schaden*" - ], - "item-no-duped-items-challenge": [ - "§6Keine Doppelten Items", - "Wenn *2 Spieler* das gleiche *Item* im", - "Inventar haben, *sterben* beide" - ], - "item-infection-challenge": [ - "§aInfection Challenge", - "Du musst *2 Blöcke* Abstand von allen ", - "*Mobs* halten oder du wirst *krank*" - ], - "item-only-down-challenge": [ - "§cNur nach unten", - "Wenn du *einen Block* nach", - "*oben* gehst, *stirbst* du" - ], - "item-advancement-damage-challenge": [ - "§cAdvancement Schaden", - "Du bekommst für jedes neue *Advancement*", - "die gesetze Anzahl *Schaden*" - ], - "item-all-blocks-disappear-challenge": [ - "§cAlle Blöcke verschwinden", - "Bei verschiedenen *Interaktionen*", - "verschwinden alle *Blöcke* im *Chunk*", - "eines *bestimmten Types*" - ], - "menu-all-blocks-disappear-challenge-settings": "Alle Blöcke verschwinden", - "item-all-blocks-disappear-break-challenge": [ - "§bBeim Abbauen", - "Wenn du einen Block *abbaust*, werden", - "*alle Blöcke* des *selben Types zerstört*" - ], - "item-all-blocks-disappear-place-challenge": [ - "§bBeim Platzieren", - "Wenn du einen Block *platzierst*, werden", - "*alle Blöcke* des *selben Types zerstört*" - ], - "item-water-allergy-challenge": [ - "§9Wasserallergie", - "Wenn du in *Wasser* bist,", - "*erleidest* du den gesetzen Schaden" - ], - "item-max-biome-time-challenge": [ - "§2Maximale Biom Zeit", - "Die *Zeit*, die du in jedem *Biom*", - "sein darfst, ist *begrenzt*" - ], - "item-max-height-time-challenge": [ - "§9Maximale Höhen Zeit", - "Die *Zeit*, die du auf jeder *Höhe*", - "sein darfst, ist *begrenzt*" - ], - "item-permanent-item-challenge": [ - "§cPermanente Items", - "*Items* können nicht gedroppt", - "oder *weggelegt* werden" - ], - "item-sneak-damage-challenge": [ - "§6Schaden pro Schleichen", - "Du *erleidest* den gesetzten", - "*Schaden*, wenn du *schleichst*" - ], - "item-jump-damage-challenge": [ - "§6Schaden pro Sprung", - "Du *erleidest* den gesetzen", - "*Schaden*, wenn du *springst*" - ], - "item-random-dropping-challenge": [ - "§cZufälliges Item Droppen", - "Alle paar Sekunden wird ein *zufälliges*", - "*Item* aus deinem Inventar *gedroppt*" - ], - "item-random-swapping-challenge": [ - "§cZufälliges Item Mischen", - "Alle paar Sekunden wird ein", - "*zufälliges Item* aus deinem Inventar", - "mit einem anderem *getauscht*" - ], - "item-random-removing-challenge": [ - "§cZufälliges Item Löschen", - "Alle paar Sekunden wird ein *zufälliges*", - "*Item* aus deinem Inventar *gelöscht*" - ], - "item-death-on-fall-challenge": [ - "§fTod bei Fallschaden", - "Wenn du *Fallschaden* erleidest,", - "*stirbst* du sofort" - ], - "item-zero-hearts-challenge": [ - "§6Null Herzen", - "Nach einer *Schutzzeit* musst du", - "dauerhaft Absorption bekommen" - ], - "item-random-effect-challenge": [ - "§6Random Effekte", - "Du bekommst in einem gesetzen *Intervall*", - "einen *zufälligen Trank Effekt*" - ], - "menu-random-effect-challenge-settings": "Random Effekte", - "item-random-effect-time-challenge": [ - "§6Intervall", - "Das *Intervall*, in dem man", - "einen *Effekt* erhält" - ], - "item-random-effect-length-challenge": [ - "§6Länge", - "Die *Länge*, die der", - "*Effekt* anhält" - ], - "item-random-effect-amplifier-challenge": [ - "§6Stärke", - "Die *Stärke*, die der", - "*Effekt* hat" - ], - "item-permanent-effect-on-damage-challenge": [ - "§6Permanente Effekte", - "Du bekommst immer, wenn du *Schaden*", - "erleidest, einen *zufälligen Effekt*" - ], - "item-anvil-rain-challenge": [ - "§cAmboss Regen", - "Vom *Himmel* fallen *Ambosse*" - ], - "menu-anvil-rain-challenge-settings": "Amboss Regen", - "item-anvil-rain-time-challenge": [ - "§6Intervall", - "Das *Intervall*, in", - "dem *Ambosse* spawnen" - ], - "item-anvil-rain-range-challenge": [ - "§6Range", - "Die *Reichweite*, in", - "der *Ambosse* spawnen" - ], - "item-anvil-rain-count-challenge": [ - "§6Anzahl", - "Die *Anzahl*, an *Ambossen*,", - "die in einem *Chunk* spawnen" - ], - "item-anvil-rain-damage-challenge": [ - "§6Schaden", - "Der *Schaden*, die", - "die *Ambosse* machen" - ], - "item-water-mlg-challenge": [ - "§bWater MLG", - "Du musst *immer wieder*", - "einen *Water MLG* absolvieren" - ], - "item-ender-games-challenge": [ - "§5Ender Games", - "Alle *paar Minuten* wirst du", - "mit einem *zufälligem Entity* aus", - "einem *200 Block* Radius *getauscht*" - ], - "item-random-event-challenge": [ - "§6Random Events", - "Alle *paar Minuten* wird eines von", - "*{0} random Events* aktiviert" - ], - "item-block-chunk-item-remove-challenge": [ - "§6Movement Item Remove", - "Es wird für jeden *Block* / *Chunk*,", - "den du dich *fortbewegst*, ein Item", - "aus deinem Inventar *gelöscht*" - ], - "item-block-chunk-item-remove-challenge-block": "§6Block", - "item-block-chunk-item-remove-challenge-chunk": "§6Chunk", - "item-higher-jumps-challenge": [ - "§aHigher Jumps", - "*Umso öfter* du springst,", - "*desto höher* springst du" - ], - "item-force-height-challenge": [ - "§eForce Height", - "Alle *paar Minuten* musst du auf", - "eine *bestimmte Höhe* oder du stirbst" - ], - "item-force-block-challenge": [ - "§6Force Block", - "Alle *paar Minuten* musst du auf", - "einen *bestimmten Block* oder du stirbst" - ], - "item-force-biome-challenge": [ - "§aForce Biome", - "Alle *paar Minuten* musst du in", - "ein *bestimmtes Biom* oder du stirbst", - "Je *seltener* das Biom ist, desto *mehr Zeit* hast du" - ], - "item-force-mob-challenge": [ - "§bForce Mob", - "Alle *paar Minuten* musst du", - "ein *bestimmtes Entity* killen oder du stirbst" - ], - "item-force-item-challenge": [ - "§6Force Item", - "Alle *paar Minuten* musst du", - "ein *bestimmtes Item* finden oder du stirbst" - ], - "item-random-item-challenge": [ - "§bRandom Items", - "Ein *zufälliger Spieler* erhält alle paar", - "*Sekunden* ein *zufälliges Item*" - ], - "item-always-running-challenge": [ - "§cAlways Running", - "Du kannst *nicht aufhören*, vorwärts zu laufen" - ], - "item-pickup-launch-challenge": [ - "§cPickup Boost", - "Wenn du ein *Item aufhebst*,", - "wirst du *in die Luft* geschleudert" - ], - "item-tsunami-challenge": [ - "§9Tsunami", - "In einem *gesetztem Intervall*", - "*steigt* das *Wasser* in der *Overworld*", - "und die *Lava* in im *Nether*", - " ", - "Sollte mit wenigen Personen gespielt werden!" - ], - "item-all-mobs-to-death-position-challenge": [ - "§cAlle Monster zum Todespunkt", - "Wenn ein *Mob* von einem Spieler", - "*getötet* wird, werden *alle* anderen", - "Monster vom *selben Typen* zum", - "*Todespunkt* teleportiert" - ], - "item-ice-floor-challenge": [ - "§bEisboden", - "Unter dir wird *Luft* zu einem", - "*3x3* Boden aus *Eis*" - ], - "item-blocks-disappear-time-challenge": [ - "§fBlöcke verschwinden nach Zeit", - "Blöcke, die du *platzierst*, *verschwinden*", - "nach ein *paar Sekunden* wieder" - ], - "item-missing-items-challenge": [ - "§9Items Fehlen", - "Alle paar Minuten *verschwindet* ein *Item* aus", - "deinem *Inventar* und du musst *erraten*, welches" - ], - "item-damage-item-challenge": [ - "§cSchaden pro Item", - "Wenn du ein *Item aufhebst* oder es", - "in deinem Inventar *anklickst* erleidest", - "du *0,5 ❤* multipliziert mit der Anzahl der Items" - ], - "item-damage-teleport-challenge": [ - "§cSchaden Random Teleport", - "Du wirst *zufällig teleportiert*,", - "wenn du *Schaden* erleidest" - ], - "item-loop-challenge": [ - "§6Wiederholungs Challenge", - "Verschiedene Aktionen *wiederholen* sich", - "unendlich oft, bis ein Spieler *schleicht*" - ], - "item-uncraft-challenge": [ - "§6Items craften sich zurück", - "Alle *Items* in deinem Inventar *craften*", - "sich alle paar Sekunden *zurück*" - ], - "item-freeze-challenge": [ - "§bFreeze Challenge", - "Für *jedes Herz*, das du *Schaden* erleidest, kannst", - "du dich für eine bestimmte Zeit *nicht bewegen*" - ], - "item-dont-stop-running-challenge": [ - "§9Nicht stehen bleiben", - "Du darfst nur eine bestimmte Zeit", - "*stehen bleiben* bevor du *stirbst*" - ], - "item-consume-launch-challenge": [ - "§cEssens Boost", - "Wenn du ein *Item isst*,", - "wirst du *in die Luft* geschleudert" - ], - "item-five-hundred-blocks-challenges": [ - "§5500 Blöcke", - "*Alle* 500 Blöcke, die du *läufst*,", - "bekommst du *64* eines *zufälliges Items*.", - "Es droppen *keine Items* von", - "*Blöcken* und *Entities* mehr." - ], - "item-level-border-challenges": [ - "§eLevel = Border", - "Die *Border-Größe* passt sich dem *Spieler*", - "mit den *meisten Leveln* an." - ], - "item-chunk-effect-challenge": [ - "§3Zufällige Chunk Effekte", - "In *jedem Chunk* bekommst du", - "einen *zufälligen Effekt*" - ], - "item-repeat-chunk-challenge": [ - "§2Wiederholende Chunks", - "Blöcke die *platziert oder zerstört* werden,", - "werden in *jedem Chunk* platziert / zerstört" - ], - "item-blocks-fly-challenge": [ - "§fBlöcke fliegen in die Luft", - "*Blöcke*, auf denen du *gelaufen* bist,", - "fliegen nach *einer Sekunde* in die *Luft*" - ], - "item-respawn-end-challenge": [ - "§5Mobs respawnen im End", - "Mobs, die *getötet werden*,", - "respawnen im *End*" - ], - "item-block-effect-challenge": [ - "§3Zufällige Block Effekte", - "Auf *jedem Block* bekommst du", - "einen *zufälligen Effekt*" - ], - "item-entity-effect-challenge": [ - "§5Mobs Haben Random Effekte", - "*Jedes Mob* hat einen zufälligen", - "Effekt auf *höchster Stufe*" - ], - "item-mob-damage-teleport-challenge": [ - "§5Mob Tausch Beim Schlagen", - "Jedes mal, wenn du einen *Mob schlägst*,", - "tauschst du mit einem *zufälligem Mob* die Position" - ], - "item-block-mob-challenge": [ - "§cMob Blöcke", - "Aus jedem abgebautem Block, *spawnt ein Mob*,", - "dass *getötet* werden muss, um den Block *zu erhalten*" - ], - "item-entity-loot-randomizer-challenge": [ - "§6Entity Loot Randomizer", - "Alle Mob Drops sind *zufällig vertauscht*." - ], - "item-no-shared-advancements-challenge": [ - "§2Keine Gleichen Advancements", - "Spieler dürfen *nicht* die *gleichen Advancements*", - "abschließen, sonst *stirbt* der *Spieler*" - ], - "item-chunk-deletion-challenge": [ - "§6Chunk Löschung", - "*Chunks*, in denen sich *Spieler* befinden,", - "werden nach gegebener *Zeit* komplett *gelöscht*" - ], - "item-delay-damage-description": [ - "§4Verzögerter Schaden", - "Der *schaden* von allen *Spielern* ist", - "zusammenaddiert und wird nach einer bestimmten *Zeit* hinzugefügt." - ], - "item-iron-golem-goal": [ - "§bEisengolem", - "Töte einen *Eisengolem* um zu gewinnen" - ], - "item-snow-golem-goal": [ - "§bSchneemann", - "Töte einen *Schneemann* um zu gewinnen" - ], - "item-most-deaths-goal": [ - "§6Meiste Tode", - "Wer die meisten *verschiedenen Tode*", - "sammelt, *gewinnt*" - ], - "item-most-items-goal": [ - "§cMeisten Items", - "Wer die meisten *verschiedenen Items*", - "findet, *gewinnt*" - ], - "item-last-man-standing-goal": [ - "§cLast Man Standing", - "Wer *am Ende* noch *lebt*, gewinnt" - ], - "item-mine-most-blocks-goal": [ - "§eMeisten Blöcke", - "Wer die *meisten Blöcke* abbaut, gewinnt" - ], - "item-most-xp-goal": [ - "§aMeiste XP", - "Wer die meiste *XP sammelt*, gewinnt" - ], - "item-first-one-to-die-goal": [ - "§cErster Tod", - "Wer als *erstes stirbt*, gewinnt" - ], - "item-collect-wood-goal": [ - "§6Holzarten Sammeln", - "Wer als *erstes* alle *Holzarten*, die", - "*eingestellt* sind, gesammelt hat, gewinnt" - ], - "item-collect-wood-goal-overworld": "§aOverworld", - "item-collect-wood-goal-nether": "§cNether", - "item-collect-wood-goal-both": "§9Beide", - "item-all-mobs-goal": [ - "§bAlle Mobs", - "Es müssen *alle Mobs* einmal", - "*getötet* werden, um zu *gewinnen*" - ], - "item-all-monster-goal": [ - "§bAlle Monster", - "Es müssen *alle Monster* einmal", - "*getötet* werden, um zu *gewinnen*" - ], - "item-all-items-goal": [ - "§2Alle Items", - "Finde *alle Items*, die es *in Minecraft gibt*" - ], - "item-finish-raid-goal": [ - "§6Raid Gewinnen", - "Der erste Spieler, der einen *Raid*", - "*abschließt*, gewinnt" - ], - "item-most-emeralds-goal": [ - "§2Meisten Emeralds", - "Der Spieler mit den *meisten*", - "*Emeralds* gewinnt" - ], - "item-all-advancements-goal": [ - "§6Alle Advancements", - "Der Spieler, der als erstes *alle*", - "Errungenschaften *erhalten hat*, gewinnt" - ], - "item-max-height-goal": [ - "§fMaximale Höhe", - "Der Spieler, der als *erstes* die", - "Höhe *{0}* erreicht hat, gewinnt" - ], - "item-min-height-goal": [ - "§fMinimale Höhe", - "Der Spieler, der als *erstes* die", - "Höhe *{0}* erreicht hat, gewinnt" - ], - "item-race-goal": [ - "§5Wettrennen", - "Der Spieler, der als *erstes* an", - "einer *zufälligen* Position ist, gewinnt" - ], - "item-most-ores-goal": [ - "§9Meiste Erze", - "Der Spieler, der am *meisten Erze*", - "*abgebaut* hat, gewinnt" - ], - "item-find-elytra-goal": [ - "§fElytra Finden", - "Der Spieler, der als *erstes*", - "eine *Elytra findet*, gewinnt" - ], - "item-eat-cake-goal": [ - "§fKuchen Essen", - "Der Spieler, der als *erstes*", - "einen *Kuchen isst*, gewinnt" - ], - "item-collect-horse-armor-goal": [ - "§bSammle Pferderüstungen", - "Der Spieler, der als *erstes*", - "*alle Pferderüstungen* hat, gewinnt" - ], - "item-collect-ice-goal": [ - "§bSammle Eisblöcke", - "Der Spieler, der als *erstes*", - "*alle Eisblöcke* und Schnee hat, gewinnt" - ], - "item-collect-swords-goal": [ - "§9Sammle Schwerter", - "Der Spieler, der als *erstes*", - "*alle Schwerter* hat, gewinnt" - ], - "item-collect-workstations-item": [ - "§6Sammle Arbeitsblöcke", - "Der Spieler, der als *erstes*", - "*alle Villager Arbeitsblöcke* hat, gewinnt" - ], - "item-eat-most-goal": [ - "§6Am Meisten Essen", - "Der Spieler, der am *meisten isst*, gewinnt" - ], - "item-force-item-battle-goal": [ - "§5Force Item Battle", - "Jeder Spieler bekommt ein *zufälliges Item*,", - "das er finden muss.", - "Wer am Ende die *meisten Items* hat, gewinnt" - ], - "menu-force-item-battle-goal-settings": "Force Item Battle", - "item-force-item-battle-goal-give-item": [ - "§bItem bei Skippen geben", - "Wenn ein Spieler ein Item *skippt*,", - "wird dieses in sein *Inventar hinzugefügt*" - ], - "item-force-mob-battle-goal": [ - "§bForce Mob Battle", - "Jeder Spieler bekommt ein *zufälliges Mob*,", - "das er töten muss." - ], - "menu-force-mob-battle-goal-settings": "Force Mob Battle", - "item-force-advancement-battle-goal": [ - "§6Force Advancement Battle", - "Jeder Spieler bekommt ein *zufälliges*", - "*Advancement*, welches er erreichen muss." - ], - "menu-force-advancement-battle-goal-settings": "Force Advancement Battle", - "item-force-block-battle-goal": [ - "§aForce Block Battle", - "Jeder Spieler bekommt einen *zufälligen*", - "*Block*, auf welchem er stehen muss" - ], - "menu-force-block-battle-goal-settings": "Force Block Battle", - "item-force-block-battle-goal-give-block": [ - "§bBlock bei Skippen geben", - "Wenn ein Spieler einen Block *skippt*,", - "wird dieser in sein *Inventar hinzugefügt*" - ], - "item-force-biome-battle-goal": [ - "§2Force Biome Battle", - "Jeder Spieler bekommt ein *zufälliges Biom*,", - "das er betreten muss" - ], - "menu-force-biome-battle-goal-settings": "Force Biome Battle", - "item-force-damage-battle-goal": [ - "§3Force Damage Battle", - "Jeder Spieler bekommt eine *zufällige Anzahl Schaden*,", - "die er *erhalten* muss" - ], - "menu-force-damage-battle-goal-settings": "Force Damage Battle", - "item-force-height-battle-goal": [ - "§6Force Height Battle", - "Jeder Spieler bekommt eine *zufällige Höhe*,", - "auf der er sich befinden muss." - ], - "menu-force-height-battle-goal-settings": "Force Height Battle", - "item-force-position-battle-goal": [ - "§aForce Position Battle", - "Jeder Spieler bekommt eine *zufällige Position*,", - "die er erreichen muss." - ], - "menu-force-position-battle-goal-settings": "Force Position Battle", - "item-extreme-force-battle-goal": [ - "§cExtreme Force Battle", - "Jeder Spieler bekommt ein *zufälliges Ziel*,", - "welches er erreichen muss" - ], - "menu-extreme-force-battle-goal-settings": "Extreme Force Battle", - "item-get-full-health-goal": [ - "§aRegeneriere Volle Leben", - "The first player to gain full health wins." - ], - "item-damage-rule-none": [ - "§6Genereller Schaden", - "Stellt ein, ob du Schaden bekommen kannst" - ], - "item-damage-rule-fire": [ - "§6Feuer Schaden", - "Stellt ein, ob du Schaden durch", - "*Lava* und *Feuer* bekommen kannst" - ], - "item-damage-rule-attack": [ - "§3Angriff Schaden", - "Stellt ein, ob du Schaden durch", - "*Nahkampfangriffe von Entities* bekommen kannst" - ], - "item-damage-rule-projectile": [ - "§6Projektil Schaden", - "Stellt ein, ob du Schaden durch", - "*Projektile* bekommen kannst" - ], - "item-damage-rule-fall": [ - "§fFallschaden", - "Stellt ein, ob du *Fallschaden* bekommen kannst" - ], - "item-damage-rule-explosion": [ - "§cExplosions Schaden", - "Stellt ein, ob du *Explosions Schaden* bekommen kannst" - ], - "item-damage-rule-drowning": [ - "§9Ertrink Schaden", - "Stellt ein, ob du Schaden durch", - "*Ertrinken* bekommen kannst" - ], - "item-damage-rule-block": [ - "§eBlock Schaden", - "Stellt ein, ob du Schaden durch", - "*Fallende Blöcke* bekommen kannst" - ], - "item-damage-rule-magic": [ - "§5Magie Schaden", - "Stellt ein, ob du Schaden durch", - "*Gift*, *Wither* und andere *Tränke* bekommen kannst" - ], - "item-damage-rule-freeze": [ - "§fFrost Schaden", - "Stellt ein, ob du Schaden durch", - "*Frost* bekommen kannst" - ], - "item-block-material": [ - "{0}", - "Stellt ein, ob *{1}*", - "genutzt werden *kann*" - ], - "custom-limit": "Du hast das Limit von §e{0} Challenges §7erreicht", - "custom-not-deleted": "Diese Challenge existiert noch nicht!", - "custom-saved": "§7Challenge wurde lokal §agespeichert", - "custom-saved-db": [ - "Um in §eDatenbank §7zu Speichern benutze §e/db save customs", - "§cAchtung: §7Alte Einstellungen werden dabei überschrieben!" - ], - "custom-no-changes": "Du hast an der Challenge §ckeine §7Änderungen gemacht", - "custom-name-info": "Schreibe den Namen der Challenge in den Chat", - "custom-command-info": [ - "Schreibe den Command den der Spieler ausführen soll §eohne / §7in den Chat", - "Erlaubte Commands: §e{0}", - "§cWeitere Commands können in der Config erlaubt werden" - ], - "custom-command-not-allowed": "Der Command §e{0} §7ist in der Config nicht als erlaubter Command angegeben", - "custom-chars-max_length": "Du hast die Maximale Anzahl von §e{0} Zeichen §7überschritten", - "custom-not-loaded": [ - " ", - "Es sind derzeit keine Custom Challenges geladen.", - "Du vermisst deine Challenges? §e/db load customs", - "Du hast Probleme beim Speichern?", - "Speichere vorm verlassen manuell §e/db save customs", - " " - ], - "custom-main-view-challenges": "§6Challenges Ansehen", - "custom-main-create-challenge": "§aChallenge Erstellen", - "custom-title-trigger": "Auslöser", - "custom-title-action": "Aktion", - "custom-title-view": "Gespeichert", - "custom-sub-finish": "§aFertig", - "item-custom-info-delete": [ - "§cLöschen", - "*Achtung* diese Aktion kann *nicht*", - "rückgängig gemacht werden" - ], - "item-custom-info-save": "§aSpeichern", - "item-custom-info-trigger": [ - "§cAuslöser", - "*Klicke* um einzustellen, was passieren", - "muss, damit die *Aktion* ausgeführt wird" - ], - "item-custom-info-action": [ - "§bAktion", - "*Klicke* um einzustellen, was passieren", - "soll, wenn der *Auslöser* erfüllt ist" - ], - "item-custom-info-material": [ - "§6Anzeige Item", - "*Klicke* um das Anzeigeitem zu ändern" - ], - "item-custom-info-name": [ - "§6Name", - "*Klicke* um den Namen über den Chat zu ändern", - "Maximale Zeichenanzahl: 50" - ], - "custom-info-currently": "§7Eingestellt §8» §e", - "custom-info-trigger": "§7Auslöser", - "custom-info-action": "§7Aktion", - "item-custom-trigger-jump": [ - "§aSpieler Springt" - ], - "item-custom-trigger-sneak": [ - "§aSpieler Schleicht" - ], - "item-custom-trigger-move_block": [ - "§6Spieler Läuft Einen Block" - ], - "item-custom-trigger-death": [ - "§cEntity Stirbt" - ], - "item-custom-trigger-damage": [ - "§cEntity Erleidet Schaden" - ], - "item-custom-trigger-damage-any": [ - "§aJeglicher Grund" - ], - "item-custom-trigger-damage_by_player": [ - "§cEntity Bekommt Schaden Von Spieler" - ], - "item-custom-trigger-intervall": [ - "§6Intervall" - ], - "item-custom-trigger-intervall-second": [ - "§6Jede Sekunde" - ], - "item-custom-trigger-intervall-seconds": [ - "§6Alle {0} Sekunden" - ], - "item-custom-trigger-intervall-minutes": [ - "§6Alle {0} Minuten" - ], - "item-custom-trigger-block_place": [ - "§aBlock Platziert" - ], - "item-custom-trigger-block_break": [ - "§cBlock Zerstört" - ], - "item-custom-trigger-consume_item": [ - "§2Item Konsumieren" - ], - "item-custom-trigger-pickup_item": [ - "§bItem Aufheben" - ], - "item-custom-trigger-drop_item": [ - "§9Spieler Droppt Item" - ], - "item-custom-trigger-advancement": [ - "§cSpieler Erhält Errungenschaft" - ], - "item-custom-trigger-hunger": [ - "§2Spieler Verliert Hunger" - ], - "item-custom-trigger-move_down": [ - "§6Block Nach Unten Bewegen" - ], - "item-custom-trigger-move_up": [ - "§6Block Nach Oben Bewegen" - ], - "item-custom-trigger-move_camera": [ - "§6Kamera Bewegen" - ], - "item-custom-trigger-stands_on_specific_block": [ - "§6Spieler Ist Auf Bestimmten Block" - ], - "item-custom-trigger-stands_not_on_specific_block": [ - "§6Spieler Ist Nicht Auf Bestimmten Block" - ], - "item-custom-trigger-gain_xp": [ - "§5Spieler Bekommt XP" - ], - "item-custom-trigger-level_up": [ - "§5Spieler Levelt Auf" - ], - "item-custom-trigger-item_craft": [ - "§6Spieler Craftet Item" - ], - "item-custom-trigger-in_liquid": [ - "§9Spieler In Flüssigkeit" - ], - "item-custom-trigger-get_item": [ - "§aItem bekommen", - "Aktion wird für *jedes* anklicken oder aufheben ausgeführt" - ], - "item-custom-action-cancel": [ - "§4Auslöser Abbrechen", - "Verhindert, dass der Auslöser ausgeführt wird.", - "Nicht abrechenbare Auslöser: *Springen*, *Sneaken*, *Töten*", - "*Advancement*, *Auf Leveln*, *In Flüssigkeit*" - ], - "item-custom-action-command": [ - "§4Command Ausführen", - "Lasse Spieler einen Command ausführen lassen", - "Die Commands werden für Spieler mit */execute as* von", - "der Konsole ausgeführt.", - "Erlaubte Commands werden in der Config eingestellt.", - "Der Spieler braucht *keine Rechte* auf den Command haben.", - "Spieler können *keine Plugin Commands* ausführen." - ], - "item-custom-action-kill": [ - "§4Töten", - "Töte Entities" - ], - "item-custom-action-damage": [ - "§cSchaden", - "Füge Entities Schaden zu" - ], - "item-custom-action-heal": [ - "§aHeilen", - "Heile Entities" - ], - "item-custom-action-hunger": [ - "§6Hunger", - "Füge Spielern Hunger hinzu" - ], - "item-custom-action-max_health": [ - "§cMaximale Leben Verändern", - "Verändere die Maximalen Leben von Spielern", - "Wird mit einem */gamestate reset* zurückgesetzt" - ], - "item-custom-action-max_health-offset": [ - "§cVeränderung", - "Wähle aus wie viele Leben verändert werden sollen" - ], - "item-custom-action-spawn_entity": [ - "§3Entity Spawnen", - "Spawne ein Entity bestimmten Types" - ], - "item-custom-action-random_mob": [ - "§6Zufälliges Entity", - "Spawne ein zufälliges Entity" - ], - "item-custom-action-random_item": [ - "§bZufälliges Item", - "Gebe Spielern zufällige Items" - ], - "item-custom-action-uncraft_inventory": [ - "§eInventar Zurück-Craften", - "Lasse das Inventar von Spielern Zurück-Craften" - ], - "item-custom-action-boost_in_air": [ - "§fIn Luft Schleudern", - "Schleudere Entities in die Luft" - ], - "item-custom-action-boost_in_air-strength": [ - "§fStärke" - ], - "item-custom-action-potion_effect": [ - "§dTrank Effekt", - "Gebe Entities einen bestimmten Trank Effekt" - ], - "item-custom-action-permanent_effect": [ - "§6Permanenten Trank Effekt", - "Füge Spieler einen Permanenten Effekt hinzu.", - "Die Aktion nutzt die Einstellungen", - "von der Permanenten Effekt Challenge." - ], - "item-custom-action-random_effect": [ - "§dZufälliger Trank Effekt", - "Gebe Entities einen zufälligen Trank Effekt" - ], - "item-custom-action-clear_inventory": [ - "§cInventar Leeren", - "Leere das Inventar von Spielern komplett" - ], - "item-custom-action-drop_random_item": [ - "§aItem Aus Inventar Droppen", - "Droppe ein Item aus dem Inventar auf den Boden" - ], - "item-custom-action-remove_random_item": [ - "§cItem Aus Inventar Entfernen", - "Entferne ein Item aus dem Inventar" - ], - "item-custom-action-swap_random_item": [ - "§6Items Im Inventar Tauschen", - "Tausche zwei Item im Inventar" - ], - "item-custom-action-freeze": [ - "§bFreeze", - "Friere Mobs Zeitweise ein.", - "Die Aktion nutzt die Einstellungen", - "von der Freeze On Damage Challenge." - ], - "item-custom-action-invert_health": [ - "§cInvert Health", - "Invertiere die Herzen eines Spielers.", - "Wenn du *8 Herzen* hast,", - "hast du danach *2 Herzen* und umgekehrt." - ], - "item-custom-action-water_mlg": [ - "§9Water MLG", - "Alle Spieler müssen einen Water MLG machen" - ], - "item-custom-action-win": [ - "§6Gewinnen", - "Die Challenge wird von *bestimmten Spielern* gewonnen" - ], - "item-custom-action-random_hotbar": [ - "§eZufällige Hotbar", - "Das Inventar wird geleert und der Spieler", - "bekommt zufällige Items in die HotBar" - ], - "item-custom-action-modify_border": [ - "§bWorld Border Verändern", - "Mache die Worldborder *größer* §7oder *kleiner*" - ], - "item-custom-action-modify_border-change": [ - "§dVeränderung" - ], - "item-custom-action-swap_mobs": [ - "§5Mobs tauschen", - "Tausche ein Mob mit einem zufälligen", - "anderem Mob aus der gleichen Welt" - ], - "item-custom-action-place_structure": [ - "§aStruktur Platzieren", - "Platziert eine Struktur" - ], - "item-custom-action-place_structure-random": "§bZufällige Struktur", - "item-custom-setting-target-current": [ - "§6Aktives Entity", - "Die Aktion wird für das *aktive Entity* ausgeführt" - ], - "item-custom-setting-target-every_mob": [ - "§4Alle Mobs", - "Die Aktion wird für *alle Mobs* ausgeführt" - ], - "item-custom-setting-target-every_mob_except_current": [ - "§4Alle Mobs Außer Aktives", - "Die Aktion wird für *alle Mobs*", - "*außer* das Aktive ausgeführt ausgeführt" - ], - "item-custom-setting-target-every_mob_except_players": [ - "§4Alle Mobs Außer Spieler", - "Die Aktion wird für *alle Mobs*", - "*außer* Spieler ausgeführt" - ], - "item-custom-setting-target-random_player": [ - "§5Zufälliger Spieler", - "Die Aktion wird für einen *zufälligen Spieler* ausgeführt" - ], - "item-custom-setting-target-every_player": [ - "§cAlle Spieler", - "Die Aktion wird für *jeden Spieler* ausgeführt" - ], - "item-custom-setting-target-current_player": [ - "§aAktiver Spieler", - "Die Aktion wird für den *aktiven Spieler* ausgeführt", - "§7§oWenn das Entity kein Spieler ist, wird nichts passieren" - ], - "item-custom-setting-target-console": [ - "§4Konsole", - "Die Aktion wird für die *Konsole* ausgeführt" - ], - "item-custom-setting-entity_type-any": "§cJegliches Entity", - "item-custom-setting-entity_type-player": "§aSpieler", - "item-custom-setting-block-any": "§2Jeglicher Block", - "item-custom-setting-item-any": "§2Jegliches Item", - "custom-subsetting-target_entity": "Ziel Entity", - "custom-subsetting-entity_type": "Entity Typ", - "custom-subsetting-liquid": "Flüssigkeit", - "custom-subsetting-time": "Zeit", - "custom-subsetting-damage_cause": "Schadens Art", - "custom-subsetting-amount": "Anzahl", - "custom-subsetting-value": "Werte Editor", - "custom-subsetting-health_offset": "Veränderung", - "custom-subsetting-length": "Länge", - "custom-subsetting-amplifier": "Stärke", - "custom-subsetting-change": "Veränderung", - "custom-subsetting-swap_targets": "Tausch Ziele" + "syntax": "Bitte nutze §e/{0}", + "reload": "Challenges Plugin wird neu geladen...", + "reload-failed": "Ein §cFehler §7ist während dem Reload aufgetreten", + "reload-success": "Challenges Plugin wurde §aerfolgreich §7neu geladen", + "player-command": "Dazu musst du ein Spieler sein!", + "no-permission": "Dazu hast du §ckeine §7Rechte", + "enabled": "§aAktiviert", + "disabled": "§cDeaktiviert", + "customize": "§6Anpassen", + "navigate-back": "§8« §7Zurück", + "navigate-next": "§8» §7Weiter", + "seconds": "Sekunden", + "second": "Sekunde", + "minutes": "Minuten", + "minute": "Minute", + "hours": "Stunden", + "hour": "Stunde", + "amplifier": "Stärke", + "open": "Öffnen", + "everyone": "§5Alle", + "player": "§6Aktiver Spieler", + "none": "Nichts", + "inventory-color": "§9", + "timer-counting-up": "§8» §7Timer zählt §ahoch", + "timer-counting-down": "§8» §7Timer zählt §crunter", + "timer-is-paused": "§8» §7Timer ist §cpausiert", + "timer-is-running": "§8» §7Timer ist §agestartet", + "confirm-reset": "Bestätige den Reset mit §e/{0}", + "no-fresh-reset": [ + "Der Server kann §cnicht resettet §7werden", + "Die Challenge wurde §cnoch nicht §7gestartet" + ], + "new-challenge": "§a§lNeu!", + "feature-disabled": "Diese Funktion ist derzeit §cdeaktiviert", + "challenge-disabled": "Diese Challenge ist derzeit §cdeaktiviert", + "timer-not-started": "Der Timer wurde noch §cnicht gestartet", + "timer-was-started": "Der Timer wurde §agestartet", + "timer-was-paused": "Der Timer wurde §cpausiert", + "timer-was-set": "Der Timer wurde auf §e§l{0} §7gesetzt", + "timer-already-started": "Der Timer §cläuft bereits", + "timer-already-paused": "Der Timer ist §cbereits pausiert", + "timer-mode-set-down": "Der Timer zählt nun §crunter", + "timer-mode-set-up": "Der Timer zählt nun §ahoch", + "no-database-connection": "Es gibt §ckeine §7Datenbankverbindung", + "fetching-data": "Daten werden abgerufen..", + "undefined": "undefiniert", + "no-such-material": "Dieses Material gibt es nicht", + "not-an-item": "§e{0} §7ist kein Item", + "no-such-entity": "Dieses Entity existiert nicht", + "not-alive": "§e{0} §7ist kein lebendes Entity", + "no-loot": "§e{0} §7hat keine Drops", + "deprecated-plugin-version": [ + " ", + "§7Ein neues Update ist verfügbar!", + "§7Download: §e§l{0}", + " " + ], + "deprecated-config-version": [ + "Deine Plugin Config ist §cveraltet §7(§c{1} §7< §a{0}§7)", + "Du kannst die alte Config löschen oder die fehlenden Einstellungen manuell hinzufügen" + ], + "missing-config-settings": "Folgende Einstellungen fehlen in der Config: §e{0}", + "missing-config-settings-separator": "§7, §e", + "no-missing-config-settings": [ + "§cEs fehlen keine Einstellungen in der Config.", + "§cDu kannst die Version ohne bedenken selbst auf §c§l{0} §cstellen." + ], + "join-message": "§e{0} §7hat den Server §abetreten", + "quit-message": "§e{0} §7hat den Server §cverlassen", + "timer-paused-message": [ + "Der Timer ist noch §cpausiert", + "Nutze §e/timer resume §7um ihn zu starten" + ], + "cheats-detected": [ + "§e{0} §7hat §cgecheated", + "Es können §ckeine weiteren §7Statistiken gesammelt werden" + ], + "cheats-already-detected": [ + "Auf diesem Server wurde §cgecheated", + "Es können §ckeine weiteren §7Statistiken gesammelt werden" + ], + "custom_challenges-reset": "Die §eLokalen §7Challenges wurden §aerfolgreich zurückgesetzt", + "config-reset": "Die §eLokalen §7Einstellungen wurden §aerfolgreich zurückgesetzt", + "player-config-loaded": "Deine Einstellungen wurden §aerfolgreich geladen", + "player-config-saved": "Deine Einstellungen wurden §aerfolgreich gespeichert", + "player-config-reset": "Deine Einstellungen wurden §aerfolgreich zurückgesetzt", + "player-custom_challenges-loaded": "Deine Challenges wurden §aerfolgreich geladen", + "player-custom_challenges-saved": "Deine Challenges wurden §aerfolgreich gespeichert", + "player-custom_challenges-reset": "Deine Challenges wurden §aerfolgreich zurückgesetzt", + "item-prefix": "§8» ", + "item-setting-info": "§8➟ {0}", + "stat-dragon-killed": "Drachen getötet", + "stat-deaths": "Tode", + "stat-entity-kills": "Kills", + "stat-damage-dealt": "Schaden ausgeteilt", + "stat-damage-taken": "Schaden genommen", + "stat-blocks-mined": "Blöcke abgebaut", + "stat-blocks-placed": "Blöcke platziert", + "stat-blocks-traveled": "Blöcke gereist", + "stat-challenges-played": "Challenges gespielt", + "stat-jumps": "Sprünge", + "stats-of": "§8» §7Stats von §e{0}", + "stats-display": "§8» §7{0} §8(§e{1}. §7Platz§8)", + "stats-leaderboard-display": [ + "§8» §e{0}", + "§8§l┣ §7{1} §7{2}", + "§8§l┗ §e{3}. §7Platz" + ], + "position": "§e{4} §8- §7{0}, {1}, {2} §8(§e{3}§8) §8┃ §e{5}m", + "positions-disabled": "Positionen sind §cdeaktiviert", + "position-other-world": "Diese Position befindet sich in einer anderen Welt §8(§e{0}§8)", + "position-not-exists": "Die Position §e{0} §7existiert §cnicht", + "position-already-exists": "Die Position §e{0} §7existiert §cbereits", + "position-set": "§e{5} §7hat §e{4} §7{0}, {1}, {2} §8(§e{3}§8) §7erstellt", + "position-deleted": "§e{5} §7hat §e{4} §7{0}, {1}, {2} §8(§e{3}§8) §7gelöscht", + "no-positions": [ + "Es sind keine §ePositionen §7in dieser Welt gesetzt", + "Erstelle eine mit §e/{0}" + ], + "no-positions-global": [ + "Es sind keine §ePositionen §7gesetzt", + "Erstelle eine mit §e/{0}" + ], + "command-no-target": "Es wurde §ckein §7Spieler gefunden", + "command-heal-healed": "Du wurdest §ageheilt", + "command-heal-healed-others": "Du hast §e{0} Spieler §ageheilt", + "command-gamemode-gamemode-changed": "Du wurdest in den Gamemode §e{0} §7gesetzt", + "command-gamemode-gamemode-changed-others": "Du hast §e{1} Spieler §7in den Gamemode §e{0} §7gesetzt", + "command-village-search": "Es wird nach einem Dorf gesucht..", + "command-village-teleport": "Du wurdest in ein Dorf §ateleportiert", + "command-village-not-found": "Es wurde §ckein neues §7Dorf gefunden", + "command-weather-set-clear": "Wetter zu §eklar §7geändert", + "command-weather-set-rain": "Wetter zu §eregnerisch §7geändert", + "command-weather-set-thunder": "Wetter zu §estürmisch §7geändert", + "command-invsee-open": "Inventar von §e{0} §7geöffnet", + "command-enderchest-open": "Du hast deine §5Enderchest §7geöffnet", + "command-difficulty-change": "Schwierigkeit auf {0} §7geändert", + "command-difficulty-current": "Die derzeitige Schwierigkeit ist {0}", + "command-search-nothing": "§e{0} §7wird durch keinen speziellen Block gedroppt", + "command-search-result": "§e{0} §7droppt aus §e{1}", + "command-searchloot-disabled": "Die Entity Loot Randomizer Challenge ist aktuell §cdeaktiviert", + "command-searchloot-nothing": "Der Loot von §e{0} §7wird durch kein spezielles Entity gedroppt", + "command-searchloot-result": [ + "§e{0} §7droppt den Loot von §e{1}", + "Der Loot von §e{0} §7wird von §e{2} §7gedroppt" + ], + "command-time-set": "Die Zeit wurde auf §e{0} §7Ticks §8(§7ca. §e{1}§8) §7geändert", + "command-time-set-exact": "Die Zeit wurde auf §e{0} §8(§e{1} §7Ticks§8) §7geändert", + "command-time-query": [ + "§8» §7Derzeitige Ingamezeiten", + "Spielzeit §e{0} §7Ticks §8(§7Tag §e{1}§8)", + "Tageszeit §e{2} §7Ticks §8(§7ca. §e{3}§8)" + ], + "command-time-noon": "Mittag", + "command-time-night": "Nacht", + "command-time-midnight": "Mitternacht", + "command-time-day": "Tag", + "command-fly-enabled": "Du kannst §anun fliegen", + "command-fly-disabled": "Du kannst nun §cnicht mehr §7fliegen", + "command-fly-toggled-others": "Du hast §eFly §7für §e{0} §7Spieler verändert", + "command-feed-fed": "Dein Hunger wurde §agestillt", + "command-feed-others": "Du hast den Hunger von §e{0} §7Spieler *gestillt*", + "command-gamestate-reload": "Der Gamestate wurde §aneu geladen", + "command-gamestate-reset": "Der Gamestate wurde §azurückgesetzt", + "command-world-teleport": "Du wirst in die Welt §e{0} §7teleportiert", + "command-back-no-locations": "Du hast dich noch §cnicht §7teleportiert", + "command-back-teleported": "Du wurdest §e{0} §7Position zurück teleportiert", + "command-back-teleported-multiple": "Du wurdest §e{0} §7Positionen zurück teleportiert", + "command-result-no-battle-active": "Es ist aktuell §ckein §7Force-Battle aktiviert", + "command-god-mode-enabled": "Du bist nun im §aGod-Mode", + "command-god-mode-disabled": "Du bist nun §cnicht mehr im God-Mode", + "command-god-mode-toggled-others": "§e{0} §7Spieler sind jetzt im §eGod-Mode", + "traffic-light-challenge-fail": "§e{0} §7ist über §crot §7gegangen", + "player-damage-display": "§e{0} §7nahm §7{1} §7Schaden durch §e{2}", + "death-message": "§e{0} §7ist gestorben", + "death-message-cause": "§e{0} §7ist durch §e{1} §7gestorben", + "health-inverted": "Deine Herzen wurden §cinvertiert", + "exp-picked-up": "§e{0} §7hat §cXP §7aufgesammelt", + "unable-to-find-fortress": "Es konnte §ckeine Festung §7gefunden werden", + "unable-to-find-bastion": "Es konnte §ckeine Bastion §7gefunden werden", + "death-collected": "Todesgrund §e{0} §7wurde registriert", + "item-collected": "Item §e{0} §7wurde registriert", + "items-to-collect": "§7Items zu sammeln §8» §e{0}", + "backpacks-disabled": "Rucksäcke sind derzeit §cdeaktiviert", + "backpack-opened": "Du hast den {0} §7geöffnet", + "top-to-overworld": "Du wurdest zur §eOverworld §7teleportiert", + "top-to-surface": "Du wurdest zur §eOberfläche §7teleportiert", + "jnr-countdown": "Nächstes §6JumpAndRun §7in §e{0} Sekunden", + "jnr-countdown-one": "Nächstes §6JumpAndRun §7in §eeiner Sekunde", + "jnr-finished": "§e{0} §7hat das §6JumpAndRun §ageschafft", + "snake-failed": "§e{0} §7ist über die §9Linie §7getreten", + "only-dirt-failed": "§e{0} §7stand nicht auf Erde", + "no-mouse-move-failed": "§e{0} §7hat seine Maus bewegt", + "no-duped-items-failed": "§e{0} §7und §e{1} §7hatten beide §e{2} §7im Inventar", + "only-down-failed": "§e{0} §7ist einen Block nach oben gegangen", + "food-once-failed": "§e{0} §7ist an §e{1} §7erstickt", + "food-once-new-food-team": "§e{0} §7hat §e{1} §7gegessen", + "food-once-new-food": "§eDu §7hast §e{1} §7gegessen", + "sneak-damage-failed": "§e{0} §7ist geschlichen", + "jump-damage-failed": "§e{0} §7ist gesprungen", + "random-challenge-enabled": "Die Challenge §e{0} §7wurde §aaktiviert", + "all-items-skipped": "Item §e{0} §7geskippt", + "all-items-already-finished": "Es wurden bereits alle Items gefunden", + "all-items-found": "Das Item §e{0} §7wurde von §e{1} §7registriert", + "mob-kill": "§e{0} §7wurde besiegt §8(§e{1} §7/ §e{2}§8)", + "endergames-teleport": "Du wurdest mit §e{0} §7getauscht", + "force-height-fail": "§e{0} §7war auf der §cfalschen Höhe §8(§e{1}§8)", + "force-height-success": "Alle Spieler waren auf der §arichtigen Höhe", + "force-block-fail": "§e{0} §7war auf dem §cfalschen Block §8(§e{1}§8)", + "force-block-success": "Alle Spieler waren auf dem §arichtigen Block", + "force-biome-fail": "Das Biom §e{0} §7wurde §cnicht gefunden", + "force-biome-success": "§e{0} §7hat das Biom §e{1} §agefunden", + "force-mob-fail": "Das Mob §e{0} §7wurde §cnicht getötet", + "force-mob-success": "§e{0} §7hat das Mob §e{1} §agetötet", + "force-item-fail": "Das Item §e{0} §7wurde §cnicht gefunden", + "force-item-success": "§e{0} §7hat das Item §e{1} §agefunden", + "new-effect": "Effekt §e{0} §8➔ §e{1}", + "missing-items-inventory": "{0}Welches Item fehlt?", + "missing-items-inventory-open": "§8[§aGUI öffnen§8]", + "loops-cleared": "§e{0} §7Loops abgebrochen", + "stopped-moving": "§e{0} §7hat sich zu lange nicht bewegt", + "all-advancements-goal": "§7Advancements §8» §e{0}", + "Chalheight-reached": "§e{0} §7hat Höhe §e{1} §7erreicht!", + "race-goal-reached": "§e{0} §7hat das Ziel erreicht!", + "points-change": "§e{0} §7Punkte", + "force-item-battle-found": "Du hast §e{0} §7gefunden!", + "force-item-battle-new-item": "Item zu suchen: §e{0}", + "force-item-battle-leaderboard": "§8➜ §7Force Item Battle Leaderboard", + "force-mob-battle-killed": "Du hast §e{0} §7gefunden!", + "force-mob-battle-new-mob": "Mob zu suchen: §e{0}", + "force-mob-battle-leaderboard": "§8➜ §7Force Mob Battle Leaderboard", + "force-advancement-battle-completed": "Du hast §e{0} §7erzielt!", + "force-advancement-battle-new-advancement": "Nächstes Advancement: §e{0}", + "force-advancement-battle-leaderboard": "§8➜ §7Force Advancement Battle Leaderboard", + "force-block-battle-found": "Du hast §e{0} §7gefunden!", + "force-block-battle-new-block": "Block zu suchen: §e{0}", + "force-block-battle-leaderboard": "§8➜ §7Force Block Battle Leaderboard", + "force-battle-leaderboard-entry": "{0}#{1} §8» §e{2} §8┃ §e{3}", + "force-battle-block-target-display": "§eBlock: {0}", + "force-battle-item-target-display":"§eItem: {0}", + "force-battle-height-target-display": "§eHöhe: {0}", + "force-battle-mob-target-display": "§eMob: {0}", + "force-battle-biome-target-display": "§eBiom: {0}", + "force-battle-damage-target-display": "§eSchaden: §c{0} ❤", + "force-battle-advancement-target-display": "§eAdvancement: {0}", + "force-battle-position-target-display": "§ePosition: {0}", + "extreme-force-battle-new-height": "Höhe zu erreichen: §e{0}", + "extreme-force-battle-reached-height": "Du hast die Höhe §e{0} §7erreicht!", + "extreme-force-battle-new-biome": "Biom zu finden: §e{0}", + "extreme-force-battle-found-biome": "Du hast das Biom §e{0} §7gefunden!", + "extreme-force-battle-new-damage": "Schaden zu nehmen: §c{0} ❤", + "extreme-force-battle-took-damage": "Du hast §c{0} ❤ §7Schaden genommen!", + "extreme-force-battle-position": "§eX: {0} §8┃ §eZ: {1}", + "extreme-force-battle-new-position": "Position zu erreichen: §e{0}", + "extreme-force-battle-reached-position": "Du hast die Position §e{0} §7erreicht!", + "extreme-force-battle-leaderboard": "§8➜ §7Extreme Force Battle Leaderboard", + "force-biome-battle-leaderboard": "§8➜ §7Force Biome Battle Leaderboard", + "force-damage-battle-leaderboard": "§8➜ §7Force Damage Battle Leaderboard", + "force-height-battle-leaderboard": "§8➜ §7Force Height Battle Leaderboard", + "force-position-battle-leaderboard": "§8➜ §7Force Position Battle Leaderboard", + "random-event-speed": [ + "Sonic? Bist du es?", + "Woahh! Das ist aber schnell" + ], + "random-event-entities": [ + "Ist das hier ein Zoo?", + "Wo kommt ihr denn her?", + "Was macht ihr denn hier?" + ], + "random-event-hole": [ + "Du bist aber ganz schön tief gefallen", + "Von ganz oben nach ganz unten..", + "Wo kommt denn das Loch her?" + ], + "random-event-fly": [ + "Guten Flug :)", + "I believe I can fly..", + "So fühlt sich also fliegen an" + ], + "random-event-webs": [ + "Liegen die schon lange hier?" + ], + "random-event-ores": [ + "Wo sind denn die ganzen Erze hin?", + "Gibt es hier keine Erze?", + "Gab es hier mal Erze?" + ], + "random-event-sickness": [ + "Bist du etwa krank?", + "Was geht denn jetzt ab" + ], + "bossbar-timer-paused": "§8» §7Der Timer ist §cpausiert", + "bossbar-mob-transformation": "§8» §7Letzter Mob §8§l┃ §a{0}", + "bossbar-biome-time-left": "§8» §7Zeit übrig in §e{0} §8§l┃ §a{1}s", + "bossbar-height-time-left": "§8» §7Zeit übrig auf §e{0} §8§l┃ §a{1}s", + "bossbar-zero-hearts": "§8» §7Schutzzeit §8§l┃ §a{0}s", + "bossbar-random-challenge-waiting": "§8» §7Warten auf neue Challenge..", + "bossbar-random-challenge-current": "§8» §7Challenge §e{0}", + "bossbar-all-items-current-max": "§8» §f{0} §8┃ §7{1} §8/ §7{2}", + "bossbar-all-items-finished": "§8» §7Alle Items gefunden", + "bossbar-force-height-waiting": "§8» §7Warten auf nächste Höhe..", + "bossbar-force-height-instruction": "§8» §7Höhe §e{0} §8┃ §a{1}", + "bossbar-force-block-waiting": "§8» §7Warten auf nächsten Block..", + "bossbar-force-block-instruction": "§8» §7Block §e{0} §8┃ §a{1}", + "bossbar-force-biome-waiting": "§8» §7Warten auf nächstes Biom..", + "bossbar-force-biome-instruction": "§8» §7Biom §e{0} §8┃ §a{1}", + "bossbar-force-mob-waiting": "§8» §7Warten auf nächsten Mob..", + "bossbar-force-mob-instruction": "§8» §7Mob §e{0} §8┃ §a{1}", + "bossbar-force-item-waiting": "§8» §7Warten auf nächstes Item..", + "bossbar-force-item-instruction": "§8» §7Item §e{0} §8┃ §a{1}", + "bossbar-tsunami-water": "§8» §7Wasserhöhe: §9{0}", + "bossbar-tsunami-lava": "§8» §7Lavahöhe: §c{0}", + "bossbar-ice-floor": "§8» §fEisboden §8┃ {0}", + "bossbar-dont-stop-running": "§8» §7Bewege dich in §8┃ §e{0}", + "bossbar-five-hundred-blocks": "§8» §fBlöcke Gelaufen §8┃ §7{0} §8/ §7{1}", + "bossbar-level-border": "§8» §7Border Größe §8┃ §7{0}", + "bossbar-race-goal-info": "§8» §fZiel §8┃ §7X: {0} §8/ §7Z: {1} §8┃ §e{2} Blöcke", + "bossbar-race-goal": "§8» §fZiel §8┃ §7X: {0} §8/ §7Z: {1}", + "bossbar-first-at-height-goal": "§8» §fZiel §8┃ §7Y: {0}", + "bossbar-respawn-end": "§8» §5Respawnte Mobs im End §8┃ §e{0}", + "bossbar-kill-all-bosses": "§8» §cAlle Bosse §8┃ §e{0}/{1}", + "bossbar-kill-all-mobs": "§8» §cAlle Mobs §8┃ §e{0}/{1}", + "bossbar-kill-all-monster": "§8» §cAlle Monster §8┃ §e{0}/{1}", + "bossbar-chunk-deletion": "§8» §7Zeit übrig im Chunk §6{0}s", + "subtitle-time-seconds": "§e{0} §7Sekunden", + "subtitle-time-seconds-range": "§e{0}-{1} §7Sekunden", + "subtitle-time-minutes": "§e{0} §7Minuten", + "subtitle-launcher-description": "§7Stärke §e{0}", + "subtitle-blocks": "§e{0} §7Blöcke", + "subtitle-range-blocks": "§7Reichweite: §e{0} §7Blöcke", + "scoreboard-title": "§7» §f§lChallenge", + "scoreboard-leaderboard": "§e#{0} §8┃ §7{1} §8» §e{2}", + "your-place": "§7Dein Platz §8» §e{0}", + "server-reset": [ + "§8————————————————————", + " ", + "§8» §cServerreset", + " ", + "§7Reset durch §4§l{0}", + "§7Der Server startet nun §cneu", + " ", + "§8————————————————————" + ], + "challenge-end-timer-hit-zero": [ + " ", + "§cDie Challenge ist vorbei!", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-timer-hit-zero-winner": [ + " ", + "§cDie Challenge ist vorbei!", + "§7Gewinner: §e§l{1}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-reached": [ + " ", + "§7Die Challenge wurde beendet!", + "§7Zeit benötigt: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-reached-winner": [ + " ", + "§7Die Challenge wurde beendet!", + "§7Gewinner: §e§l{1}", + "§7Zeit benötigt: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-failed": [ + " ", + "§cDie Challenge ist vorbei! §6#FeelsBadMan ✞", + "§7Zeit verschwendet: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "title-timer-started": [ + " ", + "§8» §7Timer §afortgesetzt" + ], + "title-timer-paused": [ + " ", + "§8» §7Timer §cpausiert" + ], + "title-challenge-enabled": [ + "§e{0}", + "§2§l✔ §8┃ §aAktiviert" + ], + "title-challenge-disabled": [ + "§e{0}", + "§4✖ §8┃ §cDeaktiviert" + ], + "title-challenge-value-changed": [ + "§e{0}", + "§8» §e{1}" + ], + "title-pregame-movement-setting": [ + "§cWarte..", + "§8» §7Der Timer ist gestoppt.." + ], + "item-menu-start": "§8• §aStart Challenge §8┃ §e/start §8•", + "item-menu-challenges": "§8• §cChallenges §8┃ §e/challenge §8•", + "item-menu-timer": "§8• §5Timer §8┃ §e/timer §8•", + "item-menu-leaderboard": "§8• §6Leaderboard §8┃ §e/leaderboard §8•", + "item-menu-stats": "§8• §2Statistiken §8┃ §e/stats §8•", + "menu-title": "Menu", + "menu-timer": "§6Timer", + "menu-goal": "§5Ziel", + "menu-damage": "§7Schaden", + "menu-item_blocks": "§4Blöcke & Items", + "menu-challenges": "§cChallenges", + "menu-settings": "§eEinstellungen", + "menu-custom": "§aIndividuelle Challenges", + "lore-category-activated-count": "§7Aktiviert §8» §a{0}§8/§7{1}", + "lore-category-activated": "§7Aktiviert §8» §aJa", + "lore-category-deactivated": "§7Aktiviert §8» §cNein", + "category-misc_challenge": [ + "§9Miscellaneous", + "Challenges, die *keiner Kategorie*", + "zugeordnet werden können" + ], + "category-randomizer": [ + "§6Randomizer", + "Erlebe ein komplett", + "*durcheinandergebrachtes* Spiel" + ], + "category-limited_time": [ + "§aLimitierte Zeit", + "Du wirst bei verschiedenen", + "Faktoren *zeitlich eingeschränkt*" + ], + "category-force": [ + "§3Zwischenziele (Force)", + "Du musst *bestimmte Zwischenziele*", + "erfüllen, sonst stirbst du" + ], + "category-world": [ + "§4Weltveränderung", + "Die Welt wird nicht mehr", + "*wiedererkennbar* sein" + ], + "category-damage": [ + "§cSchaden", + "Neue *Schadens Regeln*" + ], + "category-effect": [ + "§5Effekte", + "Erlebe verrückte *Effekte*" + ], + "category-inventory": [ + "§6Inventory", + "Dein Inventar wird *verdreht*" + ], + "category-movement": [ + "§aBewegung", + "Du wirst in deinen Bewegungen *eingeschränkt*" + ], + "category-entities": [ + "§bEntities", + "Entities werden *verändert*" + ], + "category-extra_world": [ + "§aExtra Welt", + "Challenges, die in einer", + "*anderen Welt* spielen" + ], + "category-misc_goal": [ + "§9Miscellaneous", + "Ziele, die *keiner Kategorie*", + "zugeordnet werden können" + ], + "category-kill_entity": [ + "§cEntity töten", + "Töte *bestimmte Entities*,", + "um zu gewinnen" + ], + "category-score_points": [ + "§eMeiste Punkte", + "Erziele die *meisten Punkte* in", + "einem *bestimmten Bereich*." + ], + "category-fastest_time": [ + "§6Schnellste Zeit", + "Sei der *schnellste Spieler*, der", + "das Ziel erfüllt" + ], + "category-force_battle": [ + "§bForce Battles", + "Erfülle die *vorgegebenen Zwischenziele*,", + "um Punkte zu erhalten.", + " ", + "Der Spieler mit den *meisten Punkten* gewinnt." + ], + "item-time-seconds-description": "§8» §7Zeit: §e{0} §7Sekunden", + "item-time-seconds-range-description": "§8» §7Zeit: §e{0}-{1} §7Sekunden", + "item-time-minutes-description": "§8» §7Zeit: §e{0} §7Minuten", + "item-heart-damage-description": "§8» §7Schaden: §e{0} §c❤", + "item-heart-start-description": "§8» §7Start: §e{0} §c❤", + "item-max-health-description": "§8» §7Maximale Leben: §e{0} §c❤", + "item-chance-description": "§8» §7Chance: §e{0}%", + "item-launcher-description": "§8» §7Stärke: §e{0}", + "item-permanent-effect-target-player-description": "§8» §7Nur der aktive Spieler erhält den Effekt", + "item-permanent-effect-target-everyone-description": "§8» §7Alle erhalten den Effekt", + "item-blocks-description": "§8» §7Blöcke zu laufen: §e{0}", + "item-range-blocks-description": "§8» §7Reichweite: §e{0} §7Blöcke", + "item-force-battle-goal-jokers": [ + "§6Anzahl der Joker", + "Die *Anzahl* der *Joker*,", + "die jeder Spieler hat" + ], + "item-force-battle-show-scoreboard": [ + "§bScoreboard anzeigen" + ], + "item-force-battle-duped-targets": [ + "§cDoppelte Ziele", + "Ziele können *mehrfach* vorkommen" + ], + "item-force-position-battle-radius": [ + "§bRadius", + "Der *maximale Radius*, in dem sich die", + "Positionen befinden können" + ], + "item-difficulty-setting": [ + "§aSchwierigkeit", + "Stellt die *Schwierigkeitsstufe* ein" + ], + "item-one-life-setting": [ + "§cEin Teamleben", + "*Jeder* stirbt, wenn *einer stirbt*" + ], + "item-respawn-setting": [ + "§4Respawn", + "Wenn du *stirbst*, wirst du nicht zu einem *Zuschauer*" + ], + "item-death-message-setting": [ + "§6Todesnachrichten", + "Schaltet *Todesnachrichten* ein/aus" + ], + "item-death-message-setting-vanilla": "§6Vanilla", + "item-pvp-setting": [ + "§9PvP" + ], + "item-max-health-setting": [ + "§cMaximale Herzen", + "Stellt ein, wie viele", + "Herzen man hat" + ], + "item-soup-setting": [ + "§cSuppen Heilung", + "Wenn du eine *Pilzsuppe* benutzt,", + "wirst du um *4 Herzen* geheilt" + ], + "item-damage-setting": [ + "§cDamage Multiplier", + "Schaden, den du nimmst, wird *multipliziert*" + ], + "item-damage-display-setting": [ + "§eDamage Display", + "Es wird im Chat angezeigt,", + "wenn jemand *Schaden* bekommt" + ], + "item-health-display-setting": [ + "§cHealth Display", + "Die *Herzen* aller Spieler", + "werden in der *Tablist* angezeigt" + ], + "item-position-setting": [ + "§9Positions", + "Erlaubt es dir *Positionen*", + "mit */pos* zu *markieren*" + ], + "item-backpack-setting": [ + "§6Backpack", + "Erlaubt es dir, *deinen Backpack* oder den", + "*Team Backpack* mit */backpack* zu öffnen" + ], + "item-backpack-setting-team": "§5Team", + "item-backpack-setting-player": "§6Player", + "item-cut-clean-setting": [ + "§9CutClean", + "Verschiedene *Einstellungen*, die", + "das *Farmen* von Items *einfacher* machen" + ], + "menu-cut-clean-setting-settings": "CutClean", + "item-cut-clean-gold-setting": [ + "§6Gold", + "*Golderz* wird direkt zu *Goldbarren*" + ], + "item-cut-clean-iron-setting": [ + "§7Iron", + "*Eisenerz* wird direkt zu *Eisenbarren*" + ], + "item-cut-clean-coal-setting": [ + "§eCoal", + "*Kohleerz* wird direkt zu *Fackeln*" + ], + "item-cut-clean-flint-setting": [ + "§eFlint", + "*Gravel* droppt immer *Flint*" + ], + "item-cut-clean-vein-setting": [ + "§eOre Veins", + "*Erz Venen* werden direkt abgebaut" + ], + "item-cut-clean-inventory-setting": [ + "§6Direkt ins Inventar", + "*Items* werden, *anstatt gedroppt* zu werden,", + "*direkt* ins *Inventar* hinzugefügt" + ], + "item-cut-clean-food-setting": [ + "§cGebratenes Essen", + "*Rohes Fleisch* wird direkt zu *gebratenem Fleisch*" + ], + "item-glow-setting": [ + "§fPlayerglow", + "*Spieler* sind durch die *Wand* sichtbar" + ], + "no-hunger-setting": [ + "§cKein Hunger", + "Du bekommst keinen *Hunger*" + ], + "pregame-movement-setting": [ + "§6Pregame Movement", + "Du kannst dich *bewegen*, bevor", + "das Spiel *gestartet* hat" + ], + "item-no-hit-delay-setting": [ + "§fNoHitDelay", + "Nachdem du *Schaden* genommen hast,", + "kannst du *sofort* wieder Schaden *bekommen*" + ], + "item-timber-setting": [ + "§bTimber", + "Du kannst einen *Baum* zerstören,", + "indem du *einen Block* des Baumes abbaust" + ], + "item-timber-setting-logs": "§6Baumstämme", + "item-timber-setting-logs-and-leaves": "§6Baumstämme §7und §2Blätter", + "item-keep-inventory-setting": [ + "§5Keep Inventory", + "Du verlierst keine *Items*,", + "wenn du *stirbst*" + ], + "item-mob-griefing-setting": [ + "§5Mob Griefing", + "Monster können *nichts zerstören*" + ], + "item-no-item-damage-setting": [ + "§5Kein Itemschaden", + "*Items* sind *unzerstörbar*" + ], + "top-command-setting": [ + "§dTop Command", + "Mit */top* kannst du dich", + "zur *Oberfläche* oder in", + "die *Overworld* teleportieren" + ], + "item-fortress-spawn-setting": [ + "§cFestungs Spawn", + "Wenn du in den *Nether* gehst,", + "spawnst du immer in einer *Festung*" + ], + "item-bastion-spawn-setting": [ + "§cBastions Spawn", + "Wenn du in den *Nether* gehst,", + "spawnst du immer in einer *Bastion*" + ], + "item-no-offhand-setting": [ + "§6Keine Offhand", + "Die *zweite Hand* wird geblockt" + ], + "item-regeneration-setting": [ + "§cRegeneration", + "Stellt ein, *ob* und", + "*wie* man *regeneriert*" + ], + "item-regeneration-setting-not_natural": "§6Nicht natürlich", + "item-immediate-respawn-setting": [ + "§6Direkter Respawn", + "Wenn du stirbst, *respawnst* du *automatisch,*", + "ohne den *Death Screen* zu sehen" + ], + "item-slot-limit-setting": [ + "§4Inventar Slots", + "Stellt ein, wie viele *Inventar*", + "*Slots* nutzbar sind" + ], + "item-death-position-setting": [ + "§cDeath Position", + "Wenn du stirbst, wird mit */pos* ", + "eine *Position an deinem Todespunkt* erstellt" + ], + "item-enderchest-command-setting": [ + "§5Enderchest Command", + "Wenn du */ec* ausführst, öffnet", + "sich deine *Enderchest*" + ], + "item-split-health-setting": [ + "§cGeteilte Herzen", + "Stellt ein, ob sich *alle*", + "*Spieler* eine *Gesundheit teilen*" + ], + "item-old-pvp-setting": [ + "§b1.8 PvP", + "Das *alte 1.8 PvP System* wird genutzt", + "Es gibt keinen *Attack Cooldown*" + ], + "item-totem-save-setting": [ + "§6Challenge Tod Rettung", + "Wenn du durch eine Challenge *instant*", + "*stirbst*, können *Totems* dich retten" + ], + "item-traffic-light-challenge": [ + "§cAmpelchallenge", + "Die *Ampel* schaltet alle paar Minuten um", + "Wenn du bei *rot* gehst, stirbst du" + ], + "item-block-randomizer-challenge": [ + "§6Block Randomizer", + "Jeder *Block* droppt ein *zufälliges Item*" + ], + "item-crafting-randomizer-challenge": [ + "§6Crafting Randomizer", + "Wenn du *etwas craftest*, bekommst du ein *zufälliges Item*" + ], + "item-mob-randomizer-challenge": [ + "§6Mob Randomizer", + "Wenn ein *Entity* spawnt, spawnt ein *anderes*" + ], + "item-hotbar-randomizer-challenge": [ + "§6HotBar Randomizer", + "Alle *paar Minuten* erhält jeder Spieler *zufällige Items*" + ], + "item-damage-block-challenge": [ + "§4Schaden pro Block", + "Du bekommst *Schaden* durch", + "jeden *Block*, den du gehst" + ], + "item-hunger-block-challenge": [ + "§6Hunger pro Block", + "Du bekommst *Hunger* durch", + "jeden *Block*, den du gehst" + ], + "item-stone-sight-challenge": [ + "§fStein Blick", + "*Mobs*, denen du in die *Augen*", + "*schaust*, werden zu *Stein*" + ], + "item-no-mob-sight-challenge": [ + "§cMob Blick Schaden", + "Wenn du einen *Mob* in die *Augen*", + "*schaust*, erleidest du *Schaden*" + ], + "item-bedrock-path-challenge": [ + "§7Bedrock Path", + "*Unter dir* entsteht die", + "ganze Zeit *Bedrock*" + ], + "item-bedrock-walls-challenge": [ + "§7Bedrock Walls", + "Hinter dir *spawnen* riesige", + "*Wände* aus *Bedrock*" + ], + "item-surface-hole-challenge": [ + "§cSurface Hole", + "§7Hinter dir *verschwindet* der", + "*Boden* bis ins *Void*" + ], + "item-damage-inv-clear-challenge": [ + "§cDamage Inventory Clear", + "Die *Inventare* aller Spieler werden *geleert*,", + "wenn ein *Spieler* Schaden erleidet" + ], + "item-no-trading-challenge": [ + "§2Kein Handeln", + "Du kannst *nicht* mit", + "Villager *handeln*" + ], + "item-block-break-damage-challenge": [ + "§6Block Break Damage", + "Wenn du einen *Block abbaust*,", + "*erleidest* du die gesetze Anzahl *schaden*" + ], + "item-block-place-damage-challenge": [ + "§6Block Place Damage", + "Wenn du einen *Block plazierst*,", + "*erleidest* du die gesetze Anzahl *schaden*" + ], + "item-no-exp-challenge": [ + "§aKeine XP", + "Wenn du *XP* aufsammelst, stirbst du" + ], + "item-invert-health-challenge": [ + "§cInvert Health", + "Alle paar Minuten werden deine *Herzen invertiert*.", + "Wenn du *8 Herzen* hast,", + "hast du danach *2 Herzen* und umgekehrt." + ], + "item-jump-and-run-challenge": [ + "§6Jump and Run", + "Alle *paar Minuten* musst du ein random *Jump and Run* machen,", + "welches jedes Mal *schwieriger* wird" + ], + "item-randomized-hp-challenge": [ + "§4Randomized HP", + "Die *Leben* aller *Mobs*", + "sind *random*" + ], + "item-snake-challenge": [ + "§9Snake", + "*Jeder Spieler* zieht eine", + "tödliche Linie hinter sich her" + ], + "item-reversed-damage-challenge": [ + "§cReversed Damage", + "Wenn du Entities *schlägst* oder *abschießt*,", + "bekommst du den *gleichen Schaden*" + ], + "item-duped-spawning-challenge": [ + "§cDoppeltes Spawning", + "Wenn ein Monster *spawnt*,", + "spawnt es *zweimal*" + ], + "item-hydra-challenge": [ + "§5Hydra", + "Wenn du einen *Mob* tötest,", + "spawnen *zwei* neue" + ], + "item-hydra-plus-challenge": [ + "§cHydra Plus", + "Wenn du einen *Mob* tötest,", + "spawnen *doppelt* so viele", + "wie beim *vorherigen* mal", + " ", + "Maximum beträgt *512* Mobs gleichzeitig" + ], + "item-floor-lava-challenge": [ + "§6Der Boden ist Lava", + "Alle *Blöcke* unter dir verwandeln sich", + "erst zu *Magma* und dann zu *Lava*" + ], + "item-only-dirt-challenge": [ + "§cOnly Dirt", + "Wenn du nicht auf *Erde*", + "stehst, *stirbst* du" + ], + "item-food-once-challenge": [ + "§cFood Once", + "Du kannst jedes *Essen*", + "nur einmal *essen*" + ], + "item-food-once-challenge-player": "§6Spieler", + "item-food-once-challenge-everyone": "§5Jeder", + "item-chunk-deconstruction-challenge": [ + "§bChunk Deconstruction", + "*Chunks*, in denen sich Spieler befinden,", + "*bauen* sich von *oben* aus ab" + ], + "item-one-durability-challenge": [ + "§4Eine Haltbarkeit", + "*Items* gehen nach *einer* Benutzung *kaputt*" + ], + "item-low-drop-rate-challenge": [ + "§6Low Drop Chance", + "Die *Dropchance* jedes *Blockes* wird auf die", + "angegebene *Prozentzahl* gesetzt" + ], + "item-invisible-mobs-challenge": [ + "§fUnsichtbare Mobs", + "Alle *Mobs* haben einen", + "*Unsichtbarkeits* Effekt" + ], + "item-mob-transformation-challenge": [ + "§cMob Verwandlung", + "Wenn du einen Mob schlägst, *verwandelt* sich", + "dieser in den *letzen Mob*, den du *geschlagen* hast" + ], + "item-jump-entity-challenge": [ + "§2Jump Entity", + "Wenn du *springst*, *spawnt* ein", + "zufälliges *Entity*" + ], + "item-no-mouse-move-challenge": [ + "§cMausbewegung Schaden", + "Wenn du deinen *Blick bewegst*,", + "erleidest du den *gesetzen Schaden*" + ], + "item-no-duped-items-challenge": [ + "§6Keine Doppelten Items", + "Wenn *2 Spieler* das gleiche *Item* im", + "Inventar haben, *sterben* beide" + ], + "item-infection-challenge": [ + "§aInfection Challenge", + "Du musst *2 Blöcke* Abstand von allen ", + "*Mobs* halten oder du wirst *krank*" + ], + "item-only-down-challenge": [ + "§cNur nach unten", + "Wenn du *einen Block* nach", + "*oben* gehst, *stirbst* du" + ], + "item-advancement-damage-challenge": [ + "§cAdvancement Schaden", + "Du bekommst für jedes neue *Advancement*", + "die gesetze Anzahl *Schaden*" + ], + "item-all-blocks-disappear-challenge": [ + "§cAlle Blöcke verschwinden", + "Bei verschiedenen *Interaktionen*", + "verschwinden alle *Blöcke* im *Chunk*", + "eines *bestimmten Types*" + ], + "menu-all-blocks-disappear-challenge-settings": "Alle Blöcke verschwinden", + "item-all-blocks-disappear-break-challenge": [ + "§bBeim Abbauen", + "Wenn du einen Block *abbaust*, werden", + "*alle Blöcke* des *selben Types zerstört*" + ], + "item-all-blocks-disappear-place-challenge": [ + "§bBeim Platzieren", + "Wenn du einen Block *platzierst*, werden", + "*alle Blöcke* des *selben Types zerstört*" + ], + "item-water-allergy-challenge": [ + "§9Wasserallergie", + "Wenn du in *Wasser* bist,", + "*erleidest* du den gesetzen Schaden" + ], + "item-max-biome-time-challenge": [ + "§2Maximale Biom Zeit", + "Die *Zeit*, die du in jedem *Biom*", + "sein darfst, ist *begrenzt*" + ], + "item-max-height-time-challenge": [ + "§9Maximale Höhen Zeit", + "Die *Zeit*, die du auf jeder *Höhe*", + "sein darfst, ist *begrenzt*" + ], + "item-permanent-item-challenge": [ + "§cPermanente Items", + "*Items* können nicht gedroppt", + "oder *weggelegt* werden" + ], + "item-sneak-damage-challenge": [ + "§6Schaden pro Schleichen", + "Du *erleidest* den gesetzten", + "*Schaden*, wenn du *schleichst*" + ], + "item-jump-damage-challenge": [ + "§6Schaden pro Sprung", + "Du *erleidest* den gesetzen", + "*Schaden*, wenn du *springst*" + ], + "item-random-dropping-challenge": [ + "§cZufälliges Item Droppen", + "Alle paar Sekunden wird ein *zufälliges*", + "*Item* aus deinem Inventar *gedroppt*" + ], + "item-random-swapping-challenge": [ + "§cZufälliges Item Mischen", + "Alle paar Sekunden wird ein", + "*zufälliges Item* aus deinem Inventar", + "mit einem anderem *getauscht*" + ], + "item-random-removing-challenge": [ + "§cZufälliges Item Löschen", + "Alle paar Sekunden wird ein *zufälliges*", + "*Item* aus deinem Inventar *gelöscht*" + ], + "item-death-on-fall-challenge": [ + "§fTod bei Fallschaden", + "Wenn du *Fallschaden* erleidest,", + "*stirbst* du sofort" + ], + "item-zero-hearts-challenge": [ + "§6Null Herzen", + "Nach einer *Schutzzeit* musst du", + "dauerhaft Absorption bekommen" + ], + "item-random-effect-challenge": [ + "§6Random Effekte", + "Du bekommst in einem gesetzen *Intervall*", + "einen *zufälligen Trank Effekt*" + ], + "menu-random-effect-challenge-settings": "Random Effekte", + "item-random-effect-time-challenge": [ + "§6Intervall", + "Das *Intervall*, in dem man", + "einen *Effekt* erhält" + ], + "item-random-effect-length-challenge": [ + "§6Länge", + "Die *Länge*, die der", + "*Effekt* anhält" + ], + "item-random-effect-amplifier-challenge": [ + "§6Stärke", + "Die *Stärke*, die der", + "*Effekt* hat" + ], + "item-permanent-effect-on-damage-challenge": [ + "§6Permanente Effekte", + "Du bekommst immer, wenn du *Schaden*", + "erleidest, einen *zufälligen Effekt*" + ], + "item-random-challenge-challenge": [ + "§cRandom Challenge", + "In einem *gesetzten Intervall*", + "wird eine *Random Challenge* aktiviert" + ], + "item-anvil-rain-challenge": [ + "§cAmboss Regen", + "Vom *Himmel* fallen *Ambosse*" + ], + "menu-anvil-rain-challenge-settings": "Amboss Regen", + "item-anvil-rain-time-challenge": [ + "§6Intervall", + "Das *Intervall*, in", + "dem *Ambosse* spawnen" + ], + "item-anvil-rain-range-challenge": [ + "§6Range", + "Die *Reichweite*, in", + "der *Ambosse* spawnen" + ], + "item-anvil-rain-count-challenge": [ + "§6Anzahl", + "Die *Anzahl*, an *Ambossen*,", + "die in einem *Chunk* spawnen" + ], + "item-anvil-rain-damage-challenge": [ + "§6Schaden", + "Der *Schaden*, die", + "die *Ambosse* machen" + ], + "item-water-mlg-challenge": [ + "§bWater MLG", + "Du musst *immer wieder*", + "einen *Water MLG* absolvieren" + ], + "item-ender-games-challenge": [ + "§5Ender Games", + "Alle *paar Minuten* wirst du", + "mit einem *zufälligem Entity* aus", + "einem *200 Block* Radius *getauscht*" + ], + "item-random-event-challenge": [ + "§6Random Events", + "Alle *paar Minuten* wird eines von", + "*{0} random Events* aktiviert" + ], + "item-block-chunk-item-remove-challenge": [ + "§6Movement Item Remove", + "Es wird für jeden *Block* / *Chunk*,", + "den du dich *fortbewegst*, ein Item", + "aus deinem Inventar *gelöscht*" + ], + "item-block-chunk-item-remove-challenge-block": "§6Block", + "item-block-chunk-item-remove-challenge-chunk": "§6Chunk", + "item-higher-jumps-challenge": [ + "§aHigher Jumps", + "*Umso öfter* du springst,", + "*desto höher* springst du" + ], + "item-force-height-challenge": [ + "§eForce Height", + "Alle *paar Minuten* musst du auf", + "eine *bestimmte Höhe* oder du stirbst" + ], + "item-force-block-challenge": [ + "§6Force Block", + "Alle *paar Minuten* musst du auf", + "einen *bestimmten Block* oder du stirbst" + ], + "item-force-biome-challenge": [ + "§aForce Biome", + "Alle *paar Minuten* musst du in", + "ein *bestimmtes Biom* oder du stirbst", + "Je *seltener* das Biom ist, desto *mehr Zeit* hast du" + ], + "item-force-mob-challenge": [ + "§bForce Mob", + "Alle *paar Minuten* musst du", + "ein *bestimmtes Entity* killen oder du stirbst" + ], + "item-force-item-challenge": [ + "§6Force Item", + "Alle *paar Minuten* musst du", + "ein *bestimmtes Item* finden oder du stirbst" + ], + "item-random-item-challenge": [ + "§bRandom Items", + "Ein *zufälliger Spieler* erhält alle paar", + "*Sekunden* ein *zufälliges Item*" + ], + "item-always-running-challenge": [ + "§cAlways Running", + "Du kannst *nicht aufhören*, vorwärts zu laufen" + ], + "item-pickup-launch-challenge": [ + "§cPickup Boost", + "Wenn du ein *Item aufhebst*,", + "wirst du *in die Luft* geschleudert" + ], + "item-tsunami-challenge": [ + "§9Tsunami", + "In einem *gesetztem Intervall*", + "*steigt* das *Wasser* in der *Overworld*", + "und die *Lava* in im *Nether*", + " ", + "Sollte mit wenigen Personen gespielt werden!" + ], + "item-all-mobs-to-death-position-challenge": [ + "§cAlle Monster zum Todespunkt", + "Wenn ein *Mob* von einem Spieler", + "*getötet* wird, werden *alle* anderen", + "Monster vom *selben Typen* zum", + "*Todespunkt* teleportiert" + ], + "item-ice-floor-challenge": [ + "§bEisboden", + "Unter dir wird *Luft* zu einem", + "*3x3* Boden aus *Eis*" + ], + "item-blocks-disappear-time-challenge": [ + "§fBlöcke verschwinden nach Zeit", + "Blöcke, die du *platzierst*, *verschwinden*", + "nach ein *paar Sekunden* wieder" + ], + "item-missing-items-challenge": [ + "§9Items Fehlen", + "Alle paar Minuten *verschwindet* ein *Item* aus", + "deinem *Inventar* und du musst *erraten*, welches" + ], + "item-damage-item-challenge": [ + "§cSchaden pro Item", + "Wenn du ein *Item aufhebst* oder es", + "in deinem Inventar *anklickst* erleidest", + "du *0,5 ❤* multipliziert mit der Anzahl der Items" + ], + "item-damage-teleport-challenge": [ + "§cSchaden Random Teleport", + "Du wirst *zufällig teleportiert*,", + "wenn du *Schaden* erleidest" + ], + "item-loop-challenge": [ + "§6Wiederholungs Challenge", + "Verschiedene Aktionen *wiederholen* sich", + "unendlich oft, bis ein Spieler *schleicht*" + ], + "item-uncraft-challenge": [ + "§6Items craften sich zurück", + "Alle *Items* in deinem Inventar *craften*", + "sich alle paar Sekunden *zurück*" + ], + "item-freeze-challenge": [ + "§bFreeze Challenge", + "Für *jedes Herz*, das du *Schaden* erleidest, kannst", + "du dich für eine bestimmte Zeit *nicht bewegen*" + ], + "item-dont-stop-running-challenge": [ + "§9Nicht stehen bleiben", + "Du darfst nur eine bestimmte Zeit", + "*stehen bleiben* bevor du *stirbst*" + ], + "item-consume-launch-challenge": [ + "§cEssens Boost", + "Wenn du ein *Item isst*,", + "wirst du *in die Luft* geschleudert" + ], + "item-five-hundred-blocks-challenges": [ + "§5500 Blöcke", + "*Alle* 500 Blöcke, die du *läufst*,", + "bekommst du *64* eines *zufälliges Items*.", + "Es droppen *keine Items* von", + "*Blöcken* und *Entities* mehr." + ], + "item-level-border-challenges": [ + "§eLevel = Border", + "Die *Border-Größe* passt sich dem *Spieler*", + "mit den *meisten Leveln* an." + ], + "item-chunk-effect-challenge": [ + "§3Zufällige Chunk Effekte", + "In *jedem Chunk* bekommst du", + "einen *zufälligen Effekt*" + ], + "item-repeat-chunk-challenge": [ + "§2Wiederholende Chunks", + "Blöcke die *platziert oder zerstört* werden,", + "werden in *jedem Chunk* platziert / zerstört" + ], + "item-blocks-fly-challenge": [ + "§fBlöcke fliegen in die Luft", + "*Blöcke*, auf denen du *gelaufen* bist,", + "fliegen nach *einer Sekunde* in die *Luft*" + ], + "item-respawn-end-challenge": [ + "§5Mobs respawnen im End", + "Mobs, die *getötet werden*,", + "respawnen im *End*" + ], + "item-block-effect-challenge": [ + "§3Zufällige Block Effekte", + "Auf *jedem Block* bekommst du", + "einen *zufälligen Effekt*" + ], + "item-entity-effect-challenge": [ + "§5Mobs Haben Random Effekte", + "*Jedes Mob* hat einen zufälligen", + "Effekt auf *höchster Stufe*" + ], + "item-mob-damage-teleport-challenge": [ + "§5Mob Tausch Beim Schlagen", + "Jedes mal, wenn du einen *Mob schlägst*,", + "tauschst du mit einem *zufälligem Mob* die Position" + ], + "item-block-mob-challenge": [ + "§cMob Blöcke", + "Aus jedem abgebautem Block, *spawnt ein Mob*,", + "dass *getötet* werden muss, um den Block *zu erhalten*" + ], + "item-entity-loot-randomizer-challenge": [ + "§6Entity Loot Randomizer", + "Alle Mob Drops sind *zufällig vertauscht*." + ], + "item-no-shared-advancements-challenge": [ + "§2Keine Gleichen Advancements", + "Spieler dürfen *nicht* die *gleichen Advancements*", + "abschließen, sonst *stirbt* der *Spieler*" + ], + "item-chunk-deletion-challenge": [ + "§6Chunk Löschung", + "*Chunks*, in denen sich *Spieler* befinden,", + "werden nach gegebener *Zeit* komplett *gelöscht*" + ], + "item-dragon-goal": [ + "§5Enderdrache", + "Töte den *Enderdrachen* um zu gewinnen" + ], + "item-wither-goal": [ + "§dWither", + "Töte einen *Wither* um zu gewinnen" + ], + "item-elder-guardian-goal": [ + "§bElder Guardian", + "Töte einen *Elder Guardian* um zu gewinnen" + ], + "item-warden-goal": [ + "§5Warden", + "Töte einen *Warden* um zu gewinnen" + ], + "item-iron-golem-goal": [ + "§bEisengolem", + "Töte einen *Eisengolem* um zu gewinnen" + ], + "item-snow-golem-goal": [ + "§bSchneemann", + "Töte einen *Schneemann* um zu gewinnen" + ], + "item-most-deaths-goal": [ + "§6Meiste Tode", + "Wer die meisten *verschiedenen Tode*", + "sammelt, *gewinnt*" + ], + "item-most-items-goal": [ + "§cMeisten Items", + "Wer die meisten *verschiedenen Items*", + "findet, *gewinnt*" + ], + "item-last-man-standing-goal": [ + "§cLast Man Standing", + "Wer *am Ende* noch *lebt*, gewinnt" + ], + "item-mine-most-blocks-goal": [ + "§eMeisten Blöcke", + "Wer die *meisten Blöcke* abbaut, gewinnt" + ], + "item-most-xp-goal": [ + "§aMeiste XP", + "Wer die meiste *XP sammelt*, gewinnt" + ], + "item-first-one-to-die-goal": [ + "§cErster Tod", + "Wer als *erstes stirbt*, gewinnt" + ], + "item-collect-wood-goal": [ + "§6Holzarten Sammeln", + "Wer als *erstes* alle *Holzarten*, die", + "*eingestellt* sind, gesammelt hat, gewinnt" + ], + "item-collect-wood-goal-overworld": "§aOverworld", + "item-collect-wood-goal-nether": "§cNether", + "item-collect-wood-goal-both": "§9Beide", + "item-all-bosses-goal": [ + "§bAlle Bosse", + "Es müssen *alle Bosse* einmal", + "*getötet* werden, um zu *gewinnen*" + ], + "item-all-bosses-new-goal": [ + "§5Alle Bosse (+ Warden)", + "Es müssen *alle Bosse* einmal", + "*getötet* werden, um zu *gewinnen*" + ], + "item-all-mobs-goal": [ + "§bAlle Mobs", + "Es müssen *alle Mobs* einmal", + "*getötet* werden, um zu *gewinnen*" + ], + "item-all-monster-goal": [ + "§bAlle Monster", + "Es müssen *alle Monster* einmal", + "*getötet* werden, um zu *gewinnen*" + ], + "item-all-items-goal": [ + "§2Alle Items", + "Finde *alle Items*, die es *in Minecraft gibt*" + ], + "item-finish-raid-goal": [ + "§6Raid Gewinnen", + "Der erste Spieler, der einen *Raid*", + "*abschließt*, gewinnt" + ], + "item-most-emeralds-goal": [ + "§2Meisten Emeralds", + "Der Spieler mit den *meisten*", + "*Emeralds* gewinnt" + ], + "item-all-advancements-goal": [ + "§6Alle Advancements", + "Der Spieler, der als erstes *alle*", + "Errungenschaften *erhalten hat*, gewinnt" + ], + "item-max-height-goal": [ + "§fMaximale Höhe", + "Der Spieler, der als *erstes* die", + "Höhe *{0}* erreicht hat, gewinnt" + ], + "item-min-height-goal": [ + "§fMinimale Höhe", + "Der Spieler, der als *erstes* die", + "Höhe *{0}* erreicht hat, gewinnt" + ], + "item-race-goal": [ + "§5Wettrennen", + "Der Spieler, der als *erstes* an", + "einer *zufälligen* Position ist, gewinnt" + ], + "item-most-ores-goal": [ + "§9Meiste Erze", + "Der Spieler, der am *meisten Erze*", + "*abgebaut* hat, gewinnt" + ], + "item-find-elytra-goal": [ + "§fElytra Finden", + "Der Spieler, der als *erstes*", + "eine *Elytra findet*, gewinnt" + ], + "item-eat-cake-goal": [ + "§fKuchen Essen", + "Der Spieler, der als *erstes*", + "einen *Kuchen isst*, gewinnt" + ], + "item-collect-horse-armor-goal": [ + "§bSammle Pferderüstungen", + "Der Spieler, der als *erstes*", + "*alle Pferderüstungen* hat, gewinnt" + ], + "item-collect-ice-goal": [ + "§bSammle Eisblöcke", + "Der Spieler, der als *erstes*", + "*alle Eisblöcke* und Schnee hat, gewinnt" + ], + "item-collect-swords-goal": [ + "§9Sammle Schwerter", + "Der Spieler, der als *erstes*", + "*alle Schwerter* hat, gewinnt" + ], + "item-collect-workstations-item": [ + "§6Sammle Arbeitsblöcke", + "Der Spieler, der als *erstes*", + "*alle Villager Arbeitsblöcke* hat, gewinnt" + ], + "item-eat-most-goal": [ + "§6Am Meisten Essen", + "Der Spieler, der am *meisten isst*, gewinnt" + ], + "item-force-item-battle-goal": [ + "§5Force Item Battle", + "Jeder Spieler bekommt ein *zufälliges Item*,", + "das er finden muss.", + "Wer am Ende die *meisten Items* hat, gewinnt" + ], + "menu-force-item-battle-goal-settings": "Force Item Battle", + "item-force-item-battle-goal-give-item": [ + "§bItem bei Skippen geben", + "Wenn ein Spieler ein Item *skippt*,", + "wird dieses in sein *Inventar hinzugefügt*" + ], + "item-force-mob-battle-goal": [ + "§bForce Mob Battle", + "Jeder Spieler bekommt ein *zufälliges Mob*,", + "das er töten muss." + ], + "menu-force-mob-battle-goal-settings": "Force Mob Battle", + "item-force-advancement-battle-goal": [ + "§6Force Advancement Battle", + "Jeder Spieler bekommt ein *zufälliges*", + "*Advancement*, welches er erreichen muss." + ], + "menu-force-advancement-battle-goal-settings": "Force Advancement Battle", + "item-force-block-battle-goal": [ + "§aForce Block Battle", + "Jeder Spieler bekommt einen *zufälligen*", + "*Block*, auf welchem er stehen muss" + ], + "menu-force-block-battle-goal-settings": "Force Block Battle", + "item-force-block-battle-goal-give-block": [ + "§bBlock bei Skippen geben", + "Wenn ein Spieler einen Block *skippt*,", + "wird dieser in sein *Inventar hinzugefügt*" + ], + "item-force-biome-battle-goal": [ + "§2Force Biome Battle", + "Jeder Spieler bekommt ein *zufälliges Biom*,", + "das er betreten muss" + ], + "menu-force-biome-battle-goal-settings": "Force Biome Battle", + "item-force-damage-battle-goal": [ + "§3Force Damage Battle", + "Jeder Spieler bekommt eine *zufällige Anzahl Schaden*,", + "die er *erhalten* muss" + ], + "menu-force-damage-battle-goal-settings": "Force Damage Battle", + "item-force-height-battle-goal": [ + "§6Force Height Battle", + "Jeder Spieler bekommt eine *zufällige Höhe*,", + "auf der er sich befinden muss." + ], + "menu-force-height-battle-goal-settings": "Force Height Battle", + "item-force-position-battle-goal": [ + "§aForce Position Battle", + "Jeder Spieler bekommt eine *zufällige Position*,", + "die er erreichen muss." + ], + "menu-force-position-battle-goal-settings": "Force Position Battle", + "item-extreme-force-battle-goal": [ + "§cExtreme Force Battle", + "Jeder Spieler bekommt ein *zufälliges Ziel*,", + "welches er erreichen muss" + ], + "menu-extreme-force-battle-goal-settings": "Extreme Force Battle", + "item-get-full-health-goal": [ + "§aRegeneriere Volle Leben", + "The first player to gain full health wins." + ], + "item-damage-rule-none": [ + "§6Genereller Schaden", + "Stellt ein, ob du Schaden bekommen kannst" + ], + "item-damage-rule-fire": [ + "§6Feuer Schaden", + "Stellt ein, ob du Schaden durch", + "*Lava* und *Feuer* bekommen kannst" + ], + "item-damage-rule-attack": [ + "§3Angriff Schaden", + "Stellt ein, ob du Schaden durch", + "*Nahkampfangriffe von Entities* bekommen kannst" + ], + "item-damage-rule-projectile": [ + "§6Projektil Schaden", + "Stellt ein, ob du Schaden durch", + "*Projektile* bekommen kannst" + ], + "item-damage-rule-fall": [ + "§fFallschaden", + "Stellt ein, ob du *Fallschaden* bekommen kannst" + ], + "item-damage-rule-explosion": [ + "§cExplosions Schaden", + "Stellt ein, ob du *Explosions Schaden* bekommen kannst" + ], + "item-damage-rule-drowning": [ + "§9Ertrink Schaden", + "Stellt ein, ob du Schaden durch", + "*Ertrinken* bekommen kannst" + ], + "item-damage-rule-block": [ + "§eBlock Schaden", + "Stellt ein, ob du Schaden durch", + "*Fallende Blöcke* bekommen kannst" + ], + "item-damage-rule-magic": [ + "§5Magie Schaden", + "Stellt ein, ob du Schaden durch", + "*Gift*, *Wither* und andere *Tränke* bekommen kannst" + ], + "item-damage-rule-freeze": [ + "§fFrost Schaden", + "Stellt ein, ob du Schaden durch", + "*Frost* bekommen kannst" + ], + "item-block-material": [ + "{0}", + "Stellt ein, ob *{1}*", + "genutzt werden *kann*" + ], + "custom-limit": "Du hast das Limit von §e{0} Challenges §7erreicht", + "custom-not-deleted": "Diese Challenge existiert noch nicht!", + "custom-saved": "§7Challenge wurde lokal §agespeichert", + "custom-saved-db": [ + "Um in §eDatenbank §7zu Speichern benutze §e/db save customs", + "§cAchtung: §7Alte Einstellungen werden dabei überschrieben!" + ], + "custom-no-changes": "Du hast an der Challenge §ckeine §7Änderungen gemacht", + "custom-name-info": "Schreibe den Namen der Challenge in den Chat", + "custom-command-info": [ + "Schreibe den Command den der Spieler ausführen soll §eohne / §7in den Chat", + "Erlaubte Commands: §e{0}", + "§cWeitere Commands können in der Config erlaubt werden" + ], + "custom-command-not-allowed": "Der Command §e{0} §7ist in der Config nicht als erlaubter Command angegeben", + "custom-chars-max_length": "Du hast die Maximale Anzahl von §e{0} Zeichen §7überschritten", + "custom-not-loaded": [ + " ", + "Es sind derzeit keine Custom Challenges geladen.", + "Du vermisst deine Challenges? §e/db load customs", + "Du hast Probleme beim Speichern?", + "Speichere vorm verlassen manuell §e/db save customs", + " " + ], + "custom-main-view-challenges": "§6Challenges Ansehen", + "custom-main-create-challenge": "§aChallenge Erstellen", + "custom-title-trigger": "Auslöser", + "custom-title-action": "Aktion", + "custom-title-view": "Gespeichert", + "custom-sub-finish": "§aFertig", + "item-custom-info-delete": [ + "§cLöschen", + "*Achtung* diese Aktion kann *nicht*", + "rückgängig gemacht werden" + ], + "item-custom-info-save": "§aSpeichern", + "item-custom-info-trigger": [ + "§cAuslöser", + "*Klicke* um einzustellen, was passieren", + "muss, damit die *Aktion* ausgeführt wird" + ], + "item-custom-info-action": [ + "§bAktion", + "*Klicke* um einzustellen, was passieren", + "soll, wenn der *Auslöser* erfüllt ist" + ], + "item-custom-info-material": [ + "§6Anzeige Item", + "*Klicke* um das Anzeigeitem zu ändern" + ], + "item-custom-info-name": [ + "§6Name", + "*Klicke* um den Namen über den Chat zu ändern", + "Maximale Zeichenanzahl: 50" + ], + "custom-info-currently": "§7Eingestellt §8» §e", + "custom-info-trigger": "§7Auslöser", + "custom-info-action": "§7Aktion", + "item-custom-trigger-jump": [ + "§aSpieler Springt" + ], + "item-custom-trigger-sneak": [ + "§aSpieler Schleicht" + ], + "item-custom-trigger-move_block": [ + "§6Spieler Läuft Einen Block" + ], + "item-custom-trigger-death": [ + "§cEntity Stirbt" + ], + "item-custom-trigger-damage": [ + "§cEntity Erleidet Schaden" + ], + "item-custom-trigger-damage-any": [ + "§aJeglicher Grund" + ], + "item-custom-trigger-damage_by_player": [ + "§cEntity Bekommt Schaden Von Spieler" + ], + "item-custom-trigger-intervall": [ + "§6Intervall" + ], + "item-custom-trigger-intervall-second": [ + "§6Jede Sekunde" + ], + "item-custom-trigger-intervall-seconds": [ + "§6Alle {0} Sekunden" + ], + "item-custom-trigger-intervall-minutes": [ + "§6Alle {0} Minuten" + ], + "item-custom-trigger-block_place": [ + "§aBlock Platziert" + ], + "item-custom-trigger-block_break": [ + "§cBlock Zerstört" + ], + "item-custom-trigger-consume_item": [ + "§2Item Konsumieren" + ], + "item-custom-trigger-pickup_item": [ + "§bItem Aufheben" + ], + "item-custom-trigger-drop_item": [ + "§9Spieler Droppt Item" + ], + "item-custom-trigger-advancement": [ + "§cSpieler Erhält Errungenschaft" + ], + "item-custom-trigger-hunger": [ + "§2Spieler Verliert Hunger" + ], + "item-custom-trigger-move_down": [ + "§6Block Nach Unten Bewegen" + ], + "item-custom-trigger-move_up": [ + "§6Block Nach Oben Bewegen" + ], + "item-custom-trigger-move_camera": [ + "§6Kamera Bewegen" + ], + "item-custom-trigger-stands_on_specific_block": [ + "§6Spieler Ist Auf Bestimmten Block" + ], + "item-custom-trigger-stands_not_on_specific_block": [ + "§6Spieler Ist Nicht Auf Bestimmten Block" + ], + "item-custom-trigger-gain_xp": [ + "§5Spieler Bekommt XP" + ], + "item-custom-trigger-level_up": [ + "§5Spieler Levelt Auf" + ], + "item-custom-trigger-item_craft": [ + "§6Spieler Craftet Item" + ], + "item-custom-trigger-in_liquid": [ + "§9Spieler In Flüssigkeit" + ], + "item-custom-trigger-get_item": [ + "§aItem bekommen", + "Aktion wird für *jedes* anklicken oder aufheben ausgeführt" + ], + "item-custom-action-cancel": [ + "§4Auslöser Abbrechen", + "Verhindert, dass der Auslöser ausgeführt wird.", + "Nicht abrechenbare Auslöser: *Springen*, *Sneaken*, *Töten*", + "*Advancement*, *Auf Leveln*, *In Flüssigkeit*" + ], + "item-custom-action-command": [ + "§4Command Ausführen", + "Lasse Spieler einen Command ausführen lassen", + "Die Commands werden für Spieler mit */execute as* von", + "der Konsole ausgeführt.", + "Erlaubte Commands werden in der Config eingestellt.", + "Der Spieler braucht *keine Rechte* auf den Command haben.", + "Spieler können *keine Plugin Commands* ausführen." + ], + "item-custom-action-kill": [ + "§4Töten", + "Töte Entities" + ], + "item-custom-action-damage": [ + "§cSchaden", + "Füge Entities Schaden zu" + ], + "item-custom-action-heal": [ + "§aHeilen", + "Heile Entities" + ], + "item-custom-action-hunger": [ + "§6Hunger", + "Füge Spielern Hunger hinzu" + ], + "item-custom-action-max_health": [ + "§cMaximale Leben Verändern", + "Verändere die Maximalen Leben von Spielern", + "Wird mit einem */gamestate reset* zurückgesetzt" + ], + "item-custom-action-max_health-offset": [ + "§cVeränderung", + "Wähle aus wie viele Leben verändert werden sollen" + ], + "item-custom-action-spawn_entity": [ + "§3Entity Spawnen", + "Spawne ein Entity bestimmten Types" + ], + "item-custom-action-random_mob": [ + "§6Zufälliges Entity", + "Spawne ein zufälliges Entity" + ], + "item-custom-action-random_item": [ + "§bZufälliges Item", + "Gebe Spielern zufällige Items" + ], + "item-custom-action-uncraft_inventory": [ + "§eInventar Zurück-Craften", + "Lasse das Inventar von Spielern Zurück-Craften" + ], + "item-custom-action-boost_in_air": [ + "§fIn Luft Schleudern", + "Schleudere Entities in die Luft" + ], + "item-custom-action-boost_in_air-strength": [ + "§fStärke" + ], + "item-custom-action-potion_effect": [ + "§dTrank Effekt", + "Gebe Entities einen bestimmten Trank Effekt" + ], + "item-custom-action-permanent_effect": [ + "§6Permanenten Trank Effekt", + "Füge Spieler einen Permanenten Effekt hinzu.", + "Die Aktion nutzt die Einstellungen", + "von der Permanenten Effekt Challenge." + ], + "item-custom-action-random_effect": [ + "§dZufälliger Trank Effekt", + "Gebe Entities einen zufälligen Trank Effekt" + ], + "item-custom-action-clear_inventory": [ + "§cInventar Leeren", + "Leere das Inventar von Spielern komplett" + ], + "item-custom-action-drop_random_item": [ + "§aItem Aus Inventar Droppen", + "Droppe ein Item aus dem Inventar auf den Boden" + ], + "item-custom-action-remove_random_item": [ + "§cItem Aus Inventar Entfernen", + "Entferne ein Item aus dem Inventar" + ], + "item-custom-action-swap_random_item": [ + "§6Items Im Inventar Tauschen", + "Tausche zwei Item im Inventar" + ], + "item-custom-action-freeze": [ + "§bFreeze", + "Friere Mobs Zeitweise ein.", + "Die Aktion nutzt die Einstellungen", + "von der Freeze On Damage Challenge." + ], + "item-custom-action-invert_health": [ + "§cInvert Health", + "Invertiere die Herzen eines Spielers.", + "Wenn du *8 Herzen* hast,", + "hast du danach *2 Herzen* und umgekehrt." + ], + "item-custom-action-water_mlg": [ + "§9Water MLG", + "Alle Spieler müssen einen Water MLG machen" + ], + "item-custom-action-jnr": [ + "§6Jump And Run", + "Ein zufälliger Spieler muss ein Jump And Run machen" + ], + "item-custom-action-win": [ + "§6Gewinnen", + "Die Challenge wird von *bestimmten Spielern* gewonnen" + ], + "item-custom-action-random_hotbar": [ + "§eZufällige Hotbar", + "Das Inventar wird geleert und der Spieler", + "bekommt zufällige Items in die HotBar" + ], + "item-custom-action-modify_border": [ + "§bWorld Border Verändern", + "Mache die Worldborder *größer* §7oder *kleiner*" + ], + "item-custom-action-modify_border-change": [ + "§dVeränderung" + ], + "item-custom-action-swap_mobs": [ + "§5Mobs tauschen", + "Tausche ein Mob mit einem zufälligen", + "anderem Mob aus der gleichen Welt" + ], + "item-custom-action-place_structure": [ + "§aStruktur Platzieren", + "Platziert eine Struktur" + ], + "item-custom-action-place_structure-random": "§bZufällige Struktur", + "item-custom-setting-target-current": [ + "§6Aktives Entity", + "Die Aktion wird für das *aktive Entity* ausgeführt" + ], + "item-custom-setting-target-every_mob": [ + "§4Alle Mobs", + "Die Aktion wird für *alle Mobs* ausgeführt" + ], + "item-custom-setting-target-every_mob_except_current": [ + "§4Alle Mobs Außer Aktives", + "Die Aktion wird für *alle Mobs*", + "*außer* das Aktive ausgeführt ausgeführt" + ], + "item-custom-setting-target-every_mob_except_players": [ + "§4Alle Mobs Außer Spieler", + "Die Aktion wird für *alle Mobs*", + "*außer* Spieler ausgeführt" + ], + "item-custom-setting-target-random_player": [ + "§5Zufälliger Spieler", + "Die Aktion wird für einen *zufälligen Spieler* ausgeführt" + ], + "item-custom-setting-target-every_player": [ + "§cAlle Spieler", + "Die Aktion wird für *jeden Spieler* ausgeführt" + ], + "item-custom-setting-target-current_player": [ + "§aAktiver Spieler", + "Die Aktion wird für den *aktiven Spieler* ausgeführt", + "§7§oWenn das Entity kein Spieler ist, wird nichts passieren" + ], + "item-custom-setting-target-console": [ + "§4Konsole", + "Die Aktion wird für die *Konsole* ausgeführt" + ], + "item-custom-setting-entity_type-any": "§cJegliches Entity", + "item-custom-setting-entity_type-player": "§aSpieler", + "item-custom-setting-block-any": "§2Jeglicher Block", + "item-custom-setting-item-any": "§2Jegliches Item", + "custom-subsetting-target_entity": "Ziel Entity", + "custom-subsetting-entity_type": "Entity Typ", + "custom-subsetting-liquid": "Flüssigkeit", + "custom-subsetting-time": "Zeit", + "custom-subsetting-damage_cause": "Schadens Art", + "custom-subsetting-amount": "Anzahl", + "custom-subsetting-value": "Werte Editor", + "custom-subsetting-health_offset": "Veränderung", + "custom-subsetting-length": "Länge", + "custom-subsetting-amplifier": "Stärke", + "custom-subsetting-change": "Veränderung", + "custom-subsetting-swap_targets": "Tausch Ziele" } diff --git a/language/files/en.json b/language/files/en.json index 6cd0b8c6c..351203878 100644 --- a/language/files/en.json +++ b/language/files/en.json @@ -1,1849 +1,1802 @@ { - "syntax": "Please use §e/{0}", - "reload": "Challenges Plugin is reloading...", - "reload-failed": "An §cerror &7occurred while reloading the plugin", - "reload-success": "Challenges Plugin §asuccessfully §7reloaded", - "player-command": "You must be a player!", - "no-permission": "You §cdon't §7have permissions to do this", - "enabled": "§aActivated", - "disabled": "§cDeactivated", - "customize": "§6Customize", - "navigate-back": "§8« §7Back", - "navigate-next": "§8» §7Next", - "seconds": "seconds", - "second": "second", - "minutes": "minutes", - "minute": "minute", - "hours": "hours", - "hour": "hour", - "amplifier": "amplifier", - "open": "Open", - "everyone": "§5Everyone", - "player": "§6Active player", - "none": "None", - "inventory-color": "§9", - "timer-counting-up": "§8» §7Timer counting §aup", - "timer-counting-down": "§8» §7Timer counting §cdown", - "timer-is-paused": "§8» §7Timer §cpaused", - "timer-is-running": "§8» §7Timer §astarted", - "confirm-reset": "Confirm reset with §e/{0}", - "no-fresh-reset": [ - "The Server §ccan't §7be reset yet", - "The Challenge §chasn't been §7started" - ], - "new-challenge": "§a§lNew!", - "updated-challenge": "§e§lUpdated!", - "feature-disabled": "This function is currently §cdeactivated", - "challenge-disabled": "This challenge is currently §cdeactivated", - "stopped-message": "§8• §7Timer §c§lpaused §8•", - "count-up-message": "§8• §7Time: §a§l{0} §8•", - "count-down-message": "§8• §7Time: §c§l{0} §8•", - "timer-not-started": "The timer §chasn't been started", - "timer-was-started": "The timer has been §astarted", - "timer-was-paused": "The timer has been §cpaused", - "timer-was-set": "The timer has ben set on §e§l{0}", - "timer-already-started": "The timer is §calready running", - "timer-already-paused": "The timer is §calready paused", - "timer-mode-set-down": "The timer is counting §cdown", - "timer-mode-set-up": "The timer is counting §aup", - "no-database-connection": "There is §cno §7database connection", - "fetching-data": "Data is being retrieved..", - "undefined": "undefined", - "no-such-material": "This material doesn't exist", - "not-an-item": "§e{0} §7is not an item", - "no-such-entity": "This entity doesn't exist", - "not-alive": "§e{0} §7is not a living entity", - "no-loot": "§e{0} §7doesn't have any drops", - "deprecated-plugin-version": [ - " ", - "An update for the plugin is available", - "Download: §e{0}", - " " - ], - "deprecated-config-version": [ - "The plugin config version is §coutdated §7(§c{1} §7< §a{0}§7)", - "You can either manually add all missing settings or delete the old one" - ], - "missing-config-settings": "There are missing config settings: §e{0}", - "missing-config-settings-separator": "§7, §e", - "no-missing-config-settings": [ - "§cThere are no missing config settings.", - "§cYou can manually update it to §c§l{0}" - ], - "unsuported-language": [ - "§cThe language §7(§e{0}§7) is not supported" - ], - "not-op": [ - "§7To use this plugin you need to have permissions. Give yourself permissions in the Server Console with: /op [name]" - ], - "join-message": "§e{0} §7has §ajoined §7the server", - "quit-message": "§e{0} §7has §cleft §7the server", - "timer-paused-message": [ - "The timer is §cpaused", - "Use §e/timer resume §7to start it" - ], - "cheats-detected": [ - "§e{0} §7has §ccheated", - "§cNo §7further statistics can be collected" - ], - "cheats-already-detected": [ - "On this server has been §ccheated", - "§cNo §7further statistics can be collected" - ], - "custom_challenges-reset": "The §elokal §7settings were reset §asuccessfully", - "config-reset": "The §elocal §7settings were reset §asuccessfully", - "player-config-loaded": "Your settings have been loaded §asuccessfully", - "player-config-saved": "Your settings have been saved §asuccessfully", - "player-config-reset": "Your settings were reset §asuccessfully", - "player-custom_challenges-loaded": "Your challenges have been loaded §asuccessfully", - "player-custom_challenges-saved": "Your challenges have been saved §asuccessfully", - "player-custom_challenges-reset": "Your challenges were §asuccessfully §7reset", - "item-prefix": "§8» ", - "item-setting-info": "§8➟ {0}", - "stat-dragon-killed": "Dragons killed", - "stat-deaths": "Deaths", - "stat-entity-kills": "Kills", - "stat-damage-dealt": "Damage dealt", - "stat-damage-taken": "Damage taken", - "stat-blocks-mined": "Blocks destroyed", - "stat-blocks-placed": "Blocks placed", - "stat-blocks-traveled": "Blocks travelled", - "stat-challenges-played": "Challenges played", - "stat-jumps": "Jumps", - "stats-of": "§8» §7Stats of §e{0}", - "stats-display": "§8» §7{0} §8(§e{1}. §7Platz§8)", - "stats-leaderboard-display": [ - "§8» §e{0}", - "§8§l┣ §7{1} §7{2}", - "§8§l┗ §e{3}. §7Place" - ], - "position": "§e{4} §8- §7{0}, {1}, {2} §8(§e{3}§8) §8┃ §e{5}m", - "positions-disabled": "Positions are §cdeactivated", - "position-other-world": "This position is in another world §8(§e{0}§8)", - "position-not-exists": "The position §e{0} §cdoesn't §7exist", - "position-already-exists": "The position {0} §calready §7exist", - "position-set": "§e{5} §7created position §e{4} §7{0}, {1}, {2} §8(§e{3}§8)", - "position-deleted": "§e{5} §7deleted §e{4} §7{0}, {1}, {2} §8(§e{3}§8)", - "no-positions": [ - "There are no §epositions §7set in this world", - "Create on with §e/{0}" - ], - "no-positions-global": [ - "There are no §epositions §7set", - "Create on with §e/{0}" - ], - "command-no-target": "§cNo §7players has been found", - "command-heal-healed": "You have been §ahealed", - "command-heal-healed-others": "You healed §e{0} player/s", - "command-gamemode-gamemode-changed": "Your gamemode has been changed to §e{0}", - "command-gamemode-gamemode-changed-others": "The gamemode of §e{1} §7player/s has been changed to §e{0}", - "command-village-search": "A village is being searched..", - "command-village-teleport": "You have been §ateleported to a village", - "command-village-not-found": "§cNo §7new village was found", - "command-weather-set-clear": "Weather was changed to §eclear", - "command-weather-set-rain": "Weather was changed to §erainy", - "command-weather-set-thunder": "Weather was changed to §ethundery", - "command-invsee-open": "Inventory of §e{0} §7opened", - "command-enderchest-open": "You opened your §5Enderchest", - "command-difficulty-change": "Difficulty changed to {0}", - "command-difficulty-current": "Current difficulty is {0}", - "command-search-nothing": "§e{0} §7is not dropped by any special block", - "command-search-result": "§e{0} §7drops from §e{1}", - "command-searchloot-disabled": "The entity loot randomizer challenge is currently §cdeactivated", - "command-searchloot-nothing": "The loot of §e{0} §7isn't dropped by any specific entity", - "command-searchloot-result": [ - "§e{0} §7drops the loot of §e{1}", - "The loot of §e{0} §7is dropped by §e{2}" - ], - "command-time-set": "Time was changed to §e{0} §7Ticks §8(§7ca. §e{1}§8)", - "command-time-set-exact": "Time was changed to §e{0} §8(§e{1} §7Ticks§8)", - "command-time-query": [ - "§8» §7Current ingame times", - "Playtime §e{0} §7Ticks §8(§7Tag §e{1}§8)", - "Time of day §e{2} §7Ticks §8(§7ca. §e{3}§8)" - ], - "command-time-noon": "Noon", - "command-time-night": "Night", - "command-time-midnight": "Midnight", - "command-time-day": "Day", - "command-fly-enabled": "You can fly §anow", - "command-fly-disabled": "You can §cno longer §7fly", - "command-fly-toggled-others": "You toggled §efly §7for §e{0} §7player/s", - "command-feed-fed": "Your appetite was §esated", - "command-feed-others": "You satiated the appetite of §e{0} §7player/s", - "command-gamestate-reload": "The gamestate was §areloaded", - "command-gamestate-reset": "The gamestate was §areset", - "command-world-teleport": "You'll be teleported into the §e{0}", - "command-back-no-locations": "You §cweren't §7teleported yet", - "command-back-teleported": "You were teleported §e{0} §7location back", - "command-back-teleported-multiple": "You were teleported §e{0} §7locations back", - "command-result-no-battle-active": "There is currently §cno §7Force Battle enabled", - "command-god-mode-enabled": "You are now in §aGod mode", - "command-god-mode-disabled": "You are §cno longer in God mode", - "command-god-mode-toggled-others": "§e{0} §7players are now in §eGod mode", - "traffic-light-challenge-fail": "§e{0} §7went over §cred", - "player-damage-display": "§e{0} §7took §7{1} §7damage by §e{2}", - "death-message": "§e{0} §7died", - "death-message-cause": "§e{0} §7died by §e{1}", - "health-inverted": "Your hearts have been §cinverted", - "exp-picked-up": "§e{0} §7collected §cEXP", - "unable-to-find-fortress": "§cNo fortress §7could be found", - "unable-to-find-bastion": "§cNo bastion §7could be found", - "death-collected": "Death reason §e{0} §7registered", - "item-collected": "Item §e{0} §7registered", - "items-to-collect": "§7Items to collect §8» §e{0}", - "backpacks-disabled": "Backpacks are currently §cdeactivated", - "backpack-opened": "You opened the {0}", - "top-to-overworld": "You have been teleported to the §eoverworld", - "top-to-surface": "You have been teleported to the §etop", - "jnr-countdown": "Next §6JumpAndRun §7in §e{0} seconds", - "jnr-countdown-one": "Next §6JumpAndRun §7in §eone second", - "jnr-finished": "§e{0} §afinished §7the §6JumpAndRun", - "snake-failed": "§e{0} §7stepped over the §9line", - "only-dirt-failed": "§e{0} §7did not stand on dirt", - "no-mouse-move-failed": "§e{0} §7moved his mouse", - "no-duped-items-failed": "§e{0} §7and §e{1} §7both had §e{2} §7in their inventory", - "only-down-failed": "§e{0} §7went up one block", - "food-once-failed": "§e{0} §7suffocated by §e{1}", - "food-once-new-food-team": "§e{0} §7ate §e{1}", - "food-once-new-food": "§eYou §7ate §e{1}", - "sneak-damage-failed": "§e{0} §7sneaked", - "jump-damage-failed": "§e{0} §7jumped", - "random-challenge-enabled": "The challenge §e{0} §7has been §aactivated", - "all-items-skipped": "Item §e{0} §7skipped", - "all-items-already-finished": "All items has been already found", - "all-items-found": "Item §e{0} §7registered by §e{1}", - "mob-kill": "§e{0} §ehas been killed §8(§e{1} §7/ §e{2}§8)", - "endergames-teleport": "Swapped with §e{0}", - "force-height-fail": "§e{0} §7was on the §cwrong §7height §8(§e{1}§8)", - "force-height-success": "All players were on the §aright §7height", - "force-block-fail": "§e{0} §7was on the §cwrong §7block §8(§e{1}§8)", - "force-block-success": "All players were on the §aright §7block", - "force-biome-fail": "The biome §e{0} §chasn't been found", - "force-biome-success": "§e{0} §7found the biome §e{1}", - "force-mob-fail": "The mob §e{0} §chasn't been killed", - "force-mob-success": "§e{0} §7killed the mob §e{1}", - "force-item-fail": "Item §e{0} §chasn't been found", - "force-item-success": "§e{0} §afound §7the item §e{1}", - "new-effect": "Effect §e{0} §8➔ §e{1}", - "missing-items-inventory": "{0}Which item is missing?", - "missing-items-inventory-open": "§8[§aOpen GUI§8]", - "loops-cleared": "§e{0} §7Loops cancelled", - "stopped-moving": "§e{0} §7hasn't moved for too long", - "all-advancements-goal": "§7Advancements §8» §e{0}", - "height-reached": "§e{0} §7reached §eY = {1} §7first!", - "race-goal-reached": "§e{0} §7reached the goal!", - "points-change": "§e{0} §7Points", - "force-item-battle-found": "You've found §e{0}!", - "force-item-battle-new-item": "Item to find: §e{0}", - "force-item-battle-leaderboard": "§8➜ §7Force Item Battle Leaderboard", - "force-mob-battle-killed": "You've killed §e{0}!", - "force-mob-battle-new-mob": "Mob to kill: §e{0}", - "force-mob-battle-leaderboard": "§8➜ §7Force Mob Battle Leaderboard", - "force-advancement-battle-completed": "You've completed §e{0}!", - "force-advancement-battle-new-advancement": "Nächstes Advancement: §e{0}", - "force-advancement-battle-leaderboard": "§8➜ §7Force Advancement Battle Leaderboard", - "force-block-battle-found": "You've found §e{0}!", - "force-block-battle-new-block": "Block to find: §e{0}", - "force-block-battle-leaderboard": "§8➜ §7Force Block Battle Leaderboard", - "force-battle-leaderboard-entry": "{0}#{1} §8» §e{2} §8┃ §e{3}", - "force-battle-block-target-display": "§eBlock: {0}", - "force-battle-item-target-display": "§eItem: {0}", - "force-battle-height-target-display": "§eHeight: {0}", - "force-battle-mob-target-display": "§eMob: {0}", - "force-battle-biome-target-display": "§eBiome: {0}", - "force-battle-damage-target-display": "§eDamage: §c{0} ❤", - "force-battle-advancement-target-display": "§eAdvancement: {0}", - "force-battle-position-target-display": "§ePosition: {0}", - "extreme-force-battle-new-height": "Height to reach: §e{0}", - "extreme-force-battle-reached-height": "You've reached height §e{0}!", - "extreme-force-battle-new-biome": "Biome to find: §e{0}", - "extreme-force-battle-found-biome": "You've found the biome §e{0}!", - "extreme-force-battle-new-damage": "Damage to take: §c{0} ❤", - "extreme-force-battle-took-damage": "You took §c{0} ❤ §7damage!", - "extreme-force-battle-position": "§eX: {0} §8┃ §eZ: {1}", - "extreme-force-battle-new-position": "Position to reach: §e{0}", - "extreme-force-battle-reached-position": "You've reached the position §e{0}!", - "extreme-force-battle-leaderboard": "§8➜ §7Extreme Force Battle Leaderboard", - "force-biome-battle-leaderboard": "§8➜ §7Force Biome Battle Leaderboard", - "force-damage-battle-leaderboard": "§8➜ §7Force Damage Battle Leaderboard", - "force-height-battle-leaderboard": "§8➜ §7Force Height Battle Leaderboard", - "force-position-battle-leaderboard": "§8➜ §7Force Position Battle Leaderboard", - "random-event-speed": [ - "Sonic? Is it you?", - "Woahh! That's fast" - ], - "random-event-entities": [ - "Is this a zoo?", - "Where did this come from?", - "What are you doing here?" - ], - "random-event-hole": [ - "But you fell pretty deep", - "From the very top to the very bottom..", - "Where did this hole come from?" - ], - "random-event-fly": [ - "Good flight :)", - "I believe I can fly..", - "So this is what flying feels like" - ], - "random-event-webs": [ - "Have they been here for a long time?" - ], - "random-event-ores": [ - "Where did all the ores go?", - "Aren't there any ores here?", - "Was there any ore here??" - ], - "random-event-sickness": [ - "Are you sick??", - "What's going on now?!" - ], - - "quiz-how-to": "Write your answer with §e/guess ", - - "quiz-right-answer": "§e{0} §7is the §aright §7answer!", - "quiz-right-answer-other": "§e{0} §7answered the question §acorrectly§7!", - - "quiz-wrong-answer": "§e{0} §7is a §cwrong §7answer!", - "quiz-wrong-answer-other": "§e{0} §7answered the question §cincorrectly§7!", - "quiz-time-up": "The time is §cup§7!", - "quiz-cancel": "The question was §ccancelled§7!", - - "quiz-right-answer-was": "The right answer was: §e{0}", - "quiz-right-answer-was-multiple": "the right answers were: §e{0}", - - "quiz-question-often-have": "How often have you{1} §e{0}?", - "quiz-question-often-be": "How often did you{1} §e{0}?", - "quiz-question-far-be": "How far did you {0}?", - "quiz-question-most": "What do you have the most of these {1} {0}?", - "quiz-question-damage-have": "How much damage have you {0}", - "quiz-question-damage-taken-have": "How much damage have you taken from {0}", - - "quiz-verb-traveled": "walk", - "quiz-verb-jumped": "jump", - "quiz-verb-sneaked": "sneak", - "quiz-verb-killed": "killed", - "quiz-verb-damaged": "hurt", - "quiz-verb-broken": "broken", - "quiz-verb-placed": "placed", - "quiz-verb-dropped": "dropped", - "quiz-verb-suffered": "suffered", - - "bossbar-timer-paused": "§8» §7The timer is §cpaused", - "bossbar-mob-transformation": "§8» §7Last mob §8§l┃ §a{0}", - "bossbar-biome-time-left": "§8» §7Time left in §e{0} §8§l┃ §a{1}s", - "bossbar-height-time-left": "§8» §7Time left on §e{0} §8§l┃ §a{1}s", - "bossbar-zero-hearts": "§8» §7Protection time §8§l┃ §a{0}s", - "bossbar-random-challenge-waiting": "§8» §7Waiting for new challenge..", - "bossbar-random-challenge-current": "§8» §7Challenge §e{0}", - "bossbar-all-items-current-max": "§8» §f{0} §8┃ §7{1} §8/ §7{2}", - "bossbar-all-items-finished": "§8» §7All items found", - "bossbar-force-height-waiting": "§8» §7Waiting for next height..", - "bossbar-force-height-instruction": "§8» §7Height §e{0} §8┃ §a{1}", - "bossbar-force-block-waiting": "§8» §7Waiting for next block..", - "bossbar-force-block-instruction": "§8» §7Block §e{0} §8┃ §a{1}", - "bossbar-force-biome-waiting": "§8» §7Waiting for next biome..", - "bossbar-force-biome-instruction": "§8» §7Biome §e{0} §8┃ §a{1}", - "bossbar-force-mob-waiting": "§8» §7Waiting for next mob..", - "bossbar-force-mob-instruction": "§8» §7Mob §e{0} §8┃ §a{1}", - "bossbar-force-item-waiting": "§8» §7Waiting for next item..", - "bossbar-force-item-instruction": "§8» §7Item §e{0} §8┃ §a{1}", - "bossbar-tsunami-water": "§8» §7Waterheight: §9{0}", - "bossbar-tsunami-lava": "§8» §7Lavaheight: §c{0}", - "bossbar-ice-floor": "§8» §bIce floor §8┃ {0}", - "bossbar-dont-stop-running": "§8» §7Move in §8┃ §e{0}", - "bossbar-five-hundred-blocks": "§8» §fBlocks Walked §8┃ §7{0} §8/ §7{1}", - "bossbar-level-border": "§8» §7Border size §8┃ §7{0}", - "bossbar-race-goal-info": "§8» §fGoal §8┃ §7X: {0} §8/ §7Z: {1} §8┃ §e{2} Blocks", - "bossbar-race-goal": "§8» §fGoal §8┃ §7X: {0} §8/ §7Z: {1}", - "bossbar-first-at-height-goal": "§8» §fGoal §8┃ §7Y: {0}", - "bossbar-respawn-end": "§8» §5Respawned Mobs in End §8┃ §e{0}", - "bossbar-kill-all-bosses": "§8» §cAll Bosses §8┃ §e{0}/{1}", - "bossbar-kill-all-mobs": "§8» §cAll Mobs §8┃ §e{0}/{1}", - "bossbar-kill-all-monster": "§8» §cAll Monsters §8┃ §e{0}/{1}", - "bossbar-chunk-deletion": "§8» §7Time left in chunk §6{0}s", - "subtitle-time-seconds": "§e{0} §7seconds", - "subtitle-time-seconds-range": "§e{0}-{1} §7seconds", - "subtitle-time-minutes": "§e{0} §7minutes", - "subtitle-launcher-description": "§7Power §e{0}", - "subtitle-blocks": "§e{0} §7Blocks", - "subtitle-range-blocks": "§eRange: §e{0} §7Blöcke", - "scoreboard-title": "§7» §f§lChallenge", - "scoreboard-leaderboard": "§e#{0} §8┃ §7{1} §8» §e{2}", - "your-place": "§7Your place §8» §e{0}", - "server-reset": [ - "§8————————————————————", - " ", - "§8» §cServer reset", - " ", - "§7Reset by §4§l{0}", - "§7The server is §crestarting", - " ", - "§8————————————————————" - ], - "challenge-end-timer-hit-zero": [ - " ", - "§cThe challenge is over!", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-timer-hit-zero-winner": [ - " ", - "§cThe challenge is over!", - "§7Gewinner: §e§l{1}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-reached": [ - " ", - "§7The challenge was ended!", - "§7Time needed: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-reached-winner": [ - " ", - "§7The challenge was ended!", - "§7Winner: §e§l{1}", - "§7Time needed: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "challenge-end-goal-failed": [ - " ", - "§cThe challenge is over! §6#FeelsBadMan ✞", - "§7Time wasted: §a§l{0}", - "§7Seed: §e§l{2}", - " " - ], - "title-timer-started": [ - " ", - "§8» §7Timer §acontinued" - ], - "title-timer-paused": [ - " ", - "§8» §7Timer §cpaused" - ], - "title-challenge-enabled": [ - "§e{0}", - "§2§l✔ §8┃ §aActivated" - ], - "title-challenge-disabled": [ - "§e{0}", - "§4✖ §8┃ §cDeactivated" - ], - "title-challenge-value-changed": [ - "§e{0}", - "§8» §e{1}" - ], - "item-menu-start": "§8• §aStart Challenge §8┃ §e/start §8•", - "item-menu-challenges": "§8• §cChallenges §8┃ §e/challenge §8•", - "item-menu-timer": "§8• §5Timer §8┃ §e/timer §8•", - "item-menu-leaderboard": "§8• §6Leaderboard §8┃ §e/leaderboard §8•", - "item-menu-stats": "§8• §2Statistics §8┃ §e/stats §8•", - "menu-title": "Menu", - "menu-timer": "§6Timer", - "menu-goal": "§5Goal", - "menu-damage": "§7Schaden", - "menu-item_blocks": "§4Blocks & Items", - "menu-challenges": "§cChallenges", - "menu-settings": "§eSettings", - "menu-custom": "§aCustom Challenges", - "lore-category-activated-count": "§7Activated §8» §a{0}§8/§7{1}", - "lore-category-activated": "§7Activated §8» §aYes", - "lore-category-deactivated": "§7Activated §8» §cNo", - "category-misc_challenge": [ - "§9Miscellaneous", - "Challenges that *couldn't be*", - "*assigned* with a category" - ], - "category-randomizer": [ - "§6Randomizer", - "Experience a *randomized gameplay*" - ], - "category-limited_time": [ - "§aLimited Time", - "Some things are timely restricted" - ], - "category-force": [ - "§3Force", - "You have to fulfill specific", - "*intermediate goals* to survive" - ], - "category-world": [ - "§4World Change", - "The world will be *modified* significant" - ], - "category-damage": [ - "§cSchaden", - "New *damage rules*" - ], - "category-effect": [ - "§5Effekte", - "Have fun with *lots of effects*" - ], - "category-inventory": [ - "§6Inventory", - "You'll have problems managing *your inventory*" - ], - "category-movement": [ - "§aBewegung", - "You're *restricted in your movements*" - ], - "category-entities": [ - "§bEntities", - "Entities will be *modified*" - ], - "category-extra_world": [ - "§aExtra Welt", - "Challenges that will *send*", - "you to *another world*" - ], - "category-misc_goal": [ - "§9Miscellaneous", - "Goals that *couldn't be*", - "*assigned* with a category" - ], - "category-kill_entity": [ - "§cEntities töten", - "Kill *specific entities* to win" - ], - "category-score_points": [ - "§eBest Score", - "Get the best score *to win*" - ], - "category-fastest_time": [ - "§6Fastest Time", - "Be the fastest *to win*" - ], - "category-force_battle": [ - "§bForce Battles", - "Fulfill the given *intermediate goals*", - "to earn points.", - " ", - "The player with the *most points* wins." - ], - "item-time-seconds-description": "§8» §7Time: §e{0} §7seconds", - "item-time-seconds-range-description": "§8» §7Time: §e{0}-{1} §7Sekunden", - "item-time-minutes-description": "§8» §7Time: §e{0} §7minutes", - "item-heart-damage-description": "§8» §7Damage: §e{0} §c❤", - "item-heart-start-description": "§8» §7Start: §e{0} §c❤", - "item-max-health-description": "§8» §7Max health: §e{0} §c❤", - "item-chance-description": "§8» §7Chance: §e{0}%", - "item-launcher-description": "§8» §7Strength: §e{0}", - "item-permanent-effect-target-player-description": "§8» §7Only the active players gets the effect", - "item-permanent-effect-target-everyone-description": "§8» §7All players are getting the effect", - "item-blocks-description": "§8» Blocks to walk: §e{0}", - "item-range-blocks-description": "§8» §7Range: §e{0} §7Block", - "item-force-battle-goal-jokers": [ - "§6Number of jokers", - "The *amount* of *jokers*", - "hat every player has" - ], - "item-force-battle-show-scoreboard": [ - "§bShow Scoreboard" - ], - "item-force-battle-duped-targets": [ - "§cDuped Targets", - "Targets can occur *multiple times*" - ], - "item-force-position-battle-radius": [ - "§bRadius", - "The *maximum radius*, in which the", - "positions will be located" - ], - "item-difficulty-setting": [ - "§aDifficulty", - "Sets the *Difficulty*" - ], - "item-language-setting": [ - "§bLanguage", - "Sets the *Language*" - ], - "item-language-setting-german": "§fDeutsch", - "item-language-setting-english": "§fEnglish", - "item-one-life-setting": [ - "§cOne Teamlife", - "*Everyone* dies when *one player dies*" - ], - "item-respawn-setting": [ - "§4Respawn", - "When you *die*, you won't be a *spectator*" - ], - "item-death-message-setting": [ - "§6Death messages", - "Toggles *death messages*" - ], - "item-death-message-setting-vanilla": "§6Vanilla", - "item-pvp-setting": [ - "§9PvP" - ], - "item-max-health-setting": [ - "§cMax health", - "Sets the *max health*", - "for *all players*" - ], - "item-soup-setting": [ - "§cSoup healing", - "When you use a *mushroom soup*", - "you will be healed for *4 hearts*" - ], - "item-damage-setting": [ - "§cDamage Multiplier", - "Damage you take will be *multiplied*" - ], - "item-damage-display-setting": [ - "§eDamage Display", - "It will be displayed in the *chat*", - "when anybody takes *damage*" - ], - "item-health-display-setting": [ - "§cHealth Display", - "The *hearts* of all players", - "will be showed in the *tablist*" - ], - "item-position-setting": [ - "§9Positions", - "Allows you to mark *positions*", - "with */pos*" - ], - "item-backpack-setting": [ - "§6Backpack", - "Allows you to open *your backpack* or", - "the *team backpack* with */backpack*" - ], - "item-backpack-setting-team": "§5Team", - "item-backpack-setting-player": "§6Player", - "item-cut-clean-setting": [ - "§9CutClean", - "Different *settings* to simplify", - "the *farming* of items" - ], - "menu-cut-clean-setting-settings": "CutClean", - "item-cut-clean-gold-setting": [ - "§6Gold", - "*Gold ore* will be directly dropped as *Gold ingot*" - ], - "item-cut-clean-iron-setting": [ - "§7Iron", - "*Iron ore* will be directly dropped as *Iron ingot*" - ], - "item-cut-clean-coal-setting": [ - "§eCoal", - "*Coal* will be directly dropped as *torches*" - ], - "item-cut-clean-flint-setting": [ - "§eFlint", - "*Gravel* will always drop *flint*" - ], - "item-cut-clean-vein-setting": [ - "§eOre Veins", - "*Ore veins* will be directly destroyed" - ], - "item-cut-clean-inventory-setting": [ - "§6Direct Into Inventory", - "*Items* will be put *directly* into your", - "*inventory* instead of dropping" - ], - "item-cut-clean-food-setting": [ - "§cCooked Food", - "*Raw meat* will be directly dropped as *cooked meat*" - ], - "item-glow-setting": [ - "§fPlayer Glow", - "*Players* are visible through *walls*" - ], - "no-hunger-setting": [ - "§cNo Hunger", - "You don't get *hungry*" - ], - "pregame-movement-setting": [ - "§6Pregame Movement", - "You can *move* before", - "the game has been *started*" - ], - "item-no-hit-delay-setting": [ - "§fNoHitDelay", - "After you've *taken* damage", - "you can *get* damage *immediately* again" - ], - "item-timber-setting": [ - "§bTimber", - "You can destroy a *tree*", - "by breaking down *a single block* of the tree" - ], - "item-timber-setting-logs": "§6Logs", - "item-timber-setting-logs-and-leaves": "§6Logs §7and §2Leaves", - "item-keep-inventory-setting": [ - "§5Keep Inventory", - "You don't lose any *items*", - "when you die" - ], - "item-mob-griefing-setting": [ - "§5Mob Griefing", - "Monsters *can't destroy* anything" - ], - "item-no-item-damage-setting": [ - "§5No Item Damage", - "*Items* are *unbreakable*" - ], - "top-command-setting": [ - "§dTop Command", - "You can *teleport* to the *top*", - "of the world or to the *overworld*", - "with /top" - ], - "item-fortress-spawn-setting": [ - "§cFortress Spawn", - "When you go into the *nether*", - "you will always spawn in a *fortress*" - ], - "item-bastion-spawn-setting": [ - "§cBastion Spawn", - "When you go into the *nether*", - "you will always spawn in a *bastion*" - ], - "item-no-offhand-setting": [ - "§6No Offhand", - "The *second hand* will be blocked" - ], - "item-regeneration-setting": [ - "§cRegeneration", - "Sets *whether* and", - "*how* to *regenerate*" - ], - "item-regeneration-setting-not_natural": "§6Not Natural", - "item-immediate-respawn-setting": [ - "§6Direct Respawn", - "When you *die* you *respawn* automatically", - "*without* seeing the *death screen*" - ], - "item-slot-limit-setting": [ - "§4Inventory Slots", - "Sets how many *inventory*", - "*slots* are useable" - ], - "item-death-position-setting": [ - "§cDeath Position", - "When you die, */pos* creates", - "a position at your death point" - ], - "item-enderchest-command-setting": [ - "§5Enderchest Command", - "When you execute */ec*,", - "your *Enderchest* opens" - ], - "item-split-health-setting": [ - "§cSplit Health", - "Sets whether *all players*", - "share the same *health*" - ], - "item-old-pvp-setting": [ - "§b1.8 PvP", - "The *old 1.8 PvP System* will be used", - "There will be no *attack damage cooldown*" - ], - "item-totem-save-setting": [ - "§6Challenge Death Rescue", - "If you *instant die* from a *challenge*", - "*totems* can *rescue* you" - ], - "item-traffic-light-challenge": [ - "§cTraffic Light Challenge", - "The *traffic light* switches every few minutes.", - "If you go on *red*, you die" - ], - "item-block-randomizer-challenge": [ - "§6Block Randomizer", - "Each *block* drops a *random item*" - ], - "item-crafting-randomizer-challenge": [ - "§6Crafting Randomizer", - "If you *craft* something you will get another *random item*" - ], - "item-mob-randomizer-challenge": [ - "§6Mob Randomizer", - "When an *Entity* spawns, it spawns *twice*" - ], - "item-hotbar-randomizer-challenge": [ - "§6HotBar Randomizer", - "Every *few minutes* every player gets *random items*" - ], - "item-damage-block-challenge": [ - "§4Damage per Block", - "You take *damage* for", - "every *block* you walk" - ], - "item-hunger-block-challenge": [ - "§6Hunger per Block", - "You lose *food* for", - "every *block* you walk" - ], - "item-stone-sight-challenge": [ - "§fStone Sight", - "*Mobs* that you look in the", - "*eyes* turn to stone" - ], - "item-no-mob-sight-challenge": [ - "§cMob Sight Damage", - "When you look into the *eyes* of an", - "*entity*, you get *damage*" - ], - "item-bedrock-path-challenge": [ - "§7Bedrock Path", - "*Bedrock *generates* under you*", - "the whole time" - ], - "item-bedrock-walls-challenge": [ - "§7Bedrock Walls", - "Huge *walls of bedrock*", - "are *generating* behind you" - ], - "item-surface-hole-challenge": [ - "§cSurface Hole", - "The *floor* is disappearing", - "to *void* behind you" - ], - "item-damage-inv-clear-challenge": [ - "§cDamage Inventory Clear", - "Player *inventories* are *cleared*", - "when a *player* takes damage" - ], - "item-no-trading-challenge": [ - "§2No Trading", - "You *cannot* trade", - "with villagers" - ], - "item-block-break-damage-challenge": [ - "§6Block Break Damage", - "If you *break* a *block*, you", - "will *take* the set amount of *damage*" - ], - "item-block-place-damage-challenge": [ - "§6Block Place Damage", - "If you *place* a *block*, you", - "will *take* the set amount of *damage*" - ], - "item-no-exp-challenge": [ - "§aNo EXP", - "If you pickup *EXP* you die" - ], - "item-invert-health-challenge": [ - "§cInvert Health", - "Every few minutes the *hearts are inverted*.", - "If you have *8 hearts*, you will have *2 hearts*", - "and the other way around" - ], - "item-jump-and-run-challenge": [ - "§6Jump and Run", - "Every *few minutes* you have to do a random", - "*jump and run* which gets *harder* every time" - ], - "item-randomized-hp-challenge": [ - "§4Randomized HP", - "The *health* of all mobs", - "is randomized" - ], - "item-snake-challenge": [ - "§9Snake", - "Each player draws a *deadly line*", - "behind them" - ], - "item-reversed-damage-challenge": [ - "§cReversed Damage", - "If you deal damage to entites", - "you take the same damage" - ], - "item-duped-spawning-challenge": [ - "§cDuped Spawning", - "If a mob *spawns*", - "it spawns *two times*" - ], - "item-hydra-challenge": [ - "§5Hydra", - "If you *kill* a mob", - "*two new* are spawning" - ], - "item-hydra-plus-challenge": [ - "§cHydra Plus", - "If you kill a *mob* it", - "spawns *twice* as many", - "times as the *previous* time", - " ", - "Maximum are *512* Mobs each time" - ], - "item-floor-lava-challenge": [ - "§6The Floor Is Lava", - "*Blocks* below you transform first", - "to *magma* and then to *lava*" - ], - "item-only-dirt-challenge": [ - "§cOnly Dirt", - "You must stay on *dirt*", - "otherwise you will *die*" - ], - "item-food-once-challenge": [ - "§cFood Once", - "Each *food* can be*", - "*eaten* only once" - ], - "item-food-once-challenge-player": "§6Player", - "item-food-once-challenge-everyone": "§5Everyone", - "item-chunk-deconstruction-challenge": [ - "§bChunk Deconstruction", - "*Chunks* that players are in", - "*break* down from *above*" - ], - "item-one-durability-challenge": [ - "§4One Durability", - "Items are *destroyed* after one *use*" - ], - "item-low-drop-rate-challenge": [ - "§6Low Drop Chance", - "The *drop chance* of each *block*", - "will be set to the defined *percentage*" - ], - "item-invisible-mobs-challenge": [ - "§fInvisible Mobs", - "All *Mobs* have an", - "*invisibility* effect" - ], - "item-mob-transformation-challenge": [ - "§cMob Transformation", - "When you hit a mob, it *turns*", - "into the last mob *you* hit" - ], - "item-jump-entity-challenge": [ - "§2Jump Entity", - "A *random entity* spawns", - "everytime you *jump*" - ], - "item-no-mouse-move-challenge": [ - "§cMouse Movement Damage", - "You take *damage* everytime", - "you *move* your *view*" - ], - "item-no-duped-items-challenge": [ - "§6No Duped Items", - "Players are *not allowed* to have", - "the *same item* in their *inventories*", - "at the same time" - ], - "item-infection-challenge": [ - "§aInfection Challenge", - "You have to keep *2 blocks* away", - "from all *mobs* or you will *get* sick" - ], - "item-only-down-challenge": [ - "§cOnly Down", - "If you go *up* by *a block*, you *die*" - ], - "item-advancement-damage-challenge": [ - "§cAdvancement Damage", - "You *take* the set amount of *damage*", - "for every new *advancement*" - ], - "item-all-blocks-disappear-challenge": [ - "§cAll Blocks Disappear", - "With different *interactions* all", - "*blocks* of a certain type", - "disappear in the same chunk" - ], - "menu-all-blocks-disappear-challenge-settings": "All blocks disappear", - "item-all-blocks-disappear-break-challenge": [ - "§bBy breaking", - "If you *break* a *block* all blocks", - "of the same types disappear" - ], - "item-all-blocks-disappear-place-challenge": [ - "§bBy Placing", - "If you *place* a *block* all blocks", - "of the same types disappear" - ], - "item-water-allergy-challenge": [ - "§9Water Allergy", - "You *take* the set amount of *damage*", - "while you are in *water*" - ], - "item-max-biome-time-challenge": [ - "§2Max Biome Time", - "The *time* that you may spend", - "in every *biome* is limited" - ], - "item-max-height-time-challenge": [ - "§9Max Height Time", - "The *time* that you may spend", - "on every *height* is limited" - ], - "item-permanent-item-challenge": [ - "§cPermanent Items", - "*Items* cannot be dropped", - "or put *away*" - ], - "item-sneak-damage-challenge": [ - "§6Damage per Sneak", - "You *take* the set amount", - "of *damage* if you *sneak*" - ], - "item-jump-damage-challenge": [ - "§6Damage per Jump", - "You *take* the set amount", - "of *damage* if you *jump*" - ], - "item-random-dropping-challenge": [ - "§cRandom Item Dropping", - "Every few seconds a *random item*", - "will be *dropped* from your *inventory*" - ], - "item-random-swapping-challenge": [ - "§cRandom Item Swapping", - "Every few seconds a *random item*", - "will be *swapped* with *another item*", - "in your *inventory*" - ], - "item-random-removing-challenge": [ - "§cRandom Item Removing", - "Every few seconds a *random item*", - "will be *removed* from your *inventory*" - ], - "item-death-on-fall-challenge": [ - "§fDeath On Fall Damage", - "You *die instantly*, when", - "you take *fall damage*" - ], - "item-zero-hearts-challenge": [ - "§6Zero Hearts", - "After a *protection time* you have to", - "get *absorption permanently* else you will die" - ], - "item-random-effect-challenge": [ - "§6Random Effects", - "You get a *random potion effect*", - "in a set *interval*" - ], - "menu-random-effect-challenge-settings": "Random Effects", - "item-random-effect-time-challenge": [ - "§6Interval", - "The *interval* you get the *effect* in" - ], - "item-random-effect-length-challenge": [ - "§6Length", - "The *length* you have the *effect*" - ], - "item-random-effect-amplifier-challenge": [ - "§6Amplifier", - "The *amplifier* the effect has" - ], - "item-permanent-effect-on-damage-challenge": [ - "§6Permanent Effects", - "Everytime you *take damage* you get", - "a random *permanent potion effect*" - ], - "item-random-challenge-challenge": [ - "§cRandom Challenge", - "In a set *interval* a random", - "*challenge* will be *activated*" - ], - "item-anvil-rain-challenge": [ - "§cAnvil Rain", - "*Anvils* are falling from the *sky*" - ], - "menu-anvil-rain-challenge-settings": "Anvil Rain", - "item-anvil-rain-time-challenge": [ - "§6Interval", - "The *interval*, the *anvils* are spawning in" - ], - "item-anvil-rain-range-challenge": [ - "§6Range", - "The *range* of chunks, the *anvils* are spawning in" - ], - "item-anvil-rain-count-challenge": [ - "§6Amount", - "The *amount* of anvils that", - "are spawning in one chunk" - ], - "item-anvil-rain-damage-challenge": [ - "§6Damage", - "The *damage* you take from an *anvil*" - ], - "item-water-mlg-challenge": [ - "§bWater MLG", - "You have to do a *Water MLG*", - "over and over again" - ], - "item-ender-games-challenge": [ - "§5Ender Games", - "Every *few minutes* you will be", - "*swapped* with a *random entity*", - "in a *200 blocks* range" - ], - "item-random-event-challenge": [ - "§6Random Events", - "Every *few minutes* one of", - "*{0} random Events* will be activated" - ], - "item-block-chunk-item-remove-challenge": [ - "§6Movement Item Remove", - "A random item will be removed from", - "your inventory for every", - "*block* / *chunk* you walk" - ], - "item-block-chunk-item-remove-challenge-block": "§6Block", - "item-block-chunk-item-remove-challenge-chunk": "§6Chunk", - "item-higher-jumps-challenge": [ - "§aHigher Jumps", - "The more *you jump*, the *higher* you jump" - ], - "item-force-height-challenge": [ - "§eForce Height", - "Every *few minutes* you have to be", - "on a *certain height*, else you die" - ], - "item-force-block-challenge": [ - "§6Force Block", - "Every *few minutes* you have to be", - "on a *certain block*, else you die" - ], - "item-force-biome-challenge": [ - "§aForce Biome", - "Every *few minutes* you have to be", - "in a *certain biome*, else you die", - "The *rarer* the biome, the *more time* you have" - ], - "item-force-mob-challenge": [ - "§bForce Mob", - "Every *few minutes* you have to", - "*kill* a *certain mob*, else you die" - ], - "item-force-item-challenge": [ - "§6Force Item", - "Every *few minutes* you have to get", - "a *certain item*, else you die" - ], - "item-random-item-challenge": [ - "§bRandom Items", - "A *random player* gets a *random item*", - "every *few seconds*" - ], - "item-always-running-challenge": [ - "§cAlways Running", - "You *cannot stop* to *walk forwards*" - ], - "item-pickup-launch-challenge": [ - "§cPickup Boost", - "When you *pick up* an *item*", - "you will be *launched* into the air" - ], - "item-tsunami-challenge": [ - "§9Tsunami", - "In a *set interval* ", - "the water rises in the *Overworld*", - "and the *lava* in the nether", - " ", - "Should be played with a *few people*!" - ], - "item-all-mobs-to-death-position-challenge": [ - "§cAll Mobs To Death Point", - "If a *Mob* gets *killed* by a player", - "all mobs of the *same type* will be", - "*teleported* to its *death point*" - ], - "item-ice-floor-challenge": [ - "§bIce Floor", - "*Air* will be replaced in a", - "*3x3* area with *packed ice*" - ], - "item-blocks-disappear-time-challenge": [ - "§fBlocks Disappear After Time", - "Placed *blocks*, will *disappear*", - "after a *few seconds*" - ], - "item-missing-items-challenge": [ - "§9Items Missing", - "Every few minutes a *random item disappears* from", - "your *inventory* and you have to *guess* which it was" - ], - "item-damage-item-challenge": [ - "§cDamage Per Item", - "When you *pickup* or *click* an item", - "in your *inventory* you take the", - "*amount* of the items as *damage*" - ], - "item-damage-teleport-challenge": [ - "§cRandom Teleport On Damage", - "You'll be teleported randomly", - "when you take damage" - ], - "item-loop-challenge": [ - "§6Loop Challenge", - "Certain actions are *looped*", - "until a player *sneaks*" - ], - "item-uncraft-challenge": [ - "§6Items Crafting Back", - "*Items* in your inventory are", - "*crafting* back all few seconds" - ], - "item-freeze-challenge": [ - "§bFreeze Challenge", - "For each heart of *damage*, you'll be", - "*frozen* for a certain time" - ], - "item-dont-stop-running-challenge": [ - "§9Dont stop running", - "You are only allowed to stand *still*", - "a certain *time* before you *die*" - ], - "item-consume-launch-challenge": [ - "§cConsume Boost", - "When you *eat* an *item*", - "you will be *launched* into the air" - ], - "item-five-hundred-blocks-challenges": [ - "§5500 Blocks", - "*Every 500 Blocks walked* players", - "will get a *64 stack* of a random item.", - "*Blocks* and *Entities* won't *drop* any items." - ], - "item-level-border-challenges": [ - "§eLevel = Border", - "The *border size* adjusts to *the player*", - "with the *most levels*." - ], - "item-chunk-effect-challenge": [ - "§3Random Chunk Effects", - "In *each chunk* you'll get", - "a random *potion effect*" - ], - "item-repeat-chunk-challenge": [ - "§2Repeated Chunk", - "Blocks that are *placed or destroyed*", - "will be placed / destroyed in *every chunk*" - ], - "item-blocks-fly-challenge": [ - "§fBlocks Fly in Air", - "*Blocks* you've *walked* on fly", - "into the air after *one second*" - ], - "item-respawn-end-challenge": [ - "§5Mobs Respawn In End", - "*Killed mobs* respawn in *end dimension*" - ], - "item-block-effect-challenge": [ - "§3Random Block Effects", - "On *each block* you'll get", - "a random *potion effect*" - ], - "item-entity-effect-challenge": [ - "§5Mobs Got Random Effects", - "*Every Mob* has a random", - "potion effect with *max amplifier*" - ], - "item-block-mob-challenge": [ - "§cMob Blocks", - "A *random mob* spawns out of *every broken block*", - "and to *get the block* you have to *kill it*" - ], - "item-entity-loot-randomizer-challenge": [ - "§6Entity Loot Randomizer", - "All mob drops are *randomly swapped*." - ], - "item-no-shared-advancements-challenge": [ - "§2No Shared Advancements", - "You're *not allowed* to get *advancements* someone else", - "*already did*. Else *you'll die*." - ], - "item-chunk-deletion-challenge": [ - "§6Chunk Deletion", - "*Chunks* that players are in *delete*", - "completely after the given *time*" - ], - "item-delay-damage-description": [ - "§4Damage delay", - "All *damage* from all *players* is", - "added up and dealt after *5 minutes*." - ], - "item-dragon-goal": [ - "§5Ender Dragon", - "Kill the *Ender Dragon* to win" - ], - "item-wither-goal": [ - "§dWither", - "Kill a *Wither* to win" - ], - "item-iron-golem-goal": [ - "§bIron Golem", - "Kill an *Iron Golem* to win" - ], - "item-snow-golem-goal": [ - "§bSnowman", - "Kill a *Snowman* to win" - ], - "item-elder-guardian-goal": [ - "§bElder Guardian", - "Kill an *Elder Guardian* to win" - ], - "item-warden-goal": [ - "§5Warden", - "Kill an *Warden* to win" - ], - "item-most-deaths-goal": [ - "§6Most Deaths", - "Who *collects* the most *different deaths* wins" - ], - "item-most-items-goal": [ - "§cMost Items", - "Who *collects* the most *different items* wins" - ], - "item-last-man-standing-goal": [ - "§cLast Man Standing", - "Who survived until the end wins" - ], - "item-mine-most-blocks-goal": [ - "§eMost Blocks", - "Who *breaks* the most *blocks* wins" - ], - "item-most-xp-goal": [ - "§aMost XP", - "Who *collects* the most *EXP* wins" - ], - "item-first-one-to-die-goal": [ - "§cFirst Death", - "Who *dies* first wins" - ], - "item-collect-wood-goal": [ - "§6Collect Wood", - "Who first collected all types of wood set wins" - ], - "item-collect-wood-goal-overworld": "§aOverworld", - "item-collect-wood-goal-nether": "§cNether", - "item-collect-wood-goal-both": "§9Both", - "item-all-bosses-goal": [ - "§bAll Bosses", - "Each boss must has to be killed once to win" - ], - "item-all-bosses-new-goal": [ - "§5All Bosses (+ Warden)", - "Each boss must has to be killed once to win" - ], - "item-all-mobs-goal": [ - "§bAll Mobs", - "Each mob has to be killed once to win" - ], - "item-all-monster-goal": [ - "§bAll Monsters", - "Each monster has to be killed once to win" - ], - "item-all-items-goal": [ - "§2All Items", - "Find *all items* that are in *Minecraft*" - ], - "item-finish-raid-goal": [ - "§6Finish Raid", - "The first player that *finishes* a *raid* wins" - ], - "item-most-emeralds-goal": [ - "§2Most Emeralds", - "The player with the *most*", - "*emeralds* wins" - ], - "item-all-advancements-goal": [ - "§6All Advancements", - "The first player that *gets* all *advancements* wins" - ], - "item-max-height-goal": [ - "§fMaximum Height", - "The *first* player to reach", - "*Y = {0}* wins" - ], - "item-min-height-goal": [ - "§fMinimum Height", - "The *first* player to reach", - "*Y = {0}* wins" - ], - "item-race-goal": [ - "§5Race", - "The *first* player to *reach* a", - "*random* location in the overworld wins" - ], - "item-most-ores-goal": [ - "§9Most Ores", - "The player that mines the most ores wins" - ], - "item-find-elytra-goal": [ - "§fFind Elytra", - "The *player* that finds an elytra *wins*" - ], - "item-eat-cake-goal": [ - "§fEat Cake", - "The player that *eats a cake* first *wins*" - ], - "item-collect-horse-armor-goal": [ - "§bCollect Horse Armor", - "The player that *collects* every", - "horse armor first *wins*" - ], - "item-collect-ice-goal": [ - "§bCollect Ice Blocks", - "The player that *collects* every", - "ice blocks and snow first *wins*" - ], - "item-collect-swords-goal": [ - "§9Collect Swords", - "The player that *collects* every", - "sword first *wins*" - ], - "item-collect-workstations-item": [ - "§6Collect Workstations", - "The player that *collects* every", - "villager workstation first *wins*" - ], - "item-eat-most-goal": [ - "§6Eat most", - "The player that fills the mods hunger bars *wins*" - ], - "item-force-item-battle-goal": [ - "§5Force Item Battle", - "Each player gets *a random item* that", - "he has *to find*.", - "The player that *found* the *most items*, wins." - ], - "menu-force-item-battle-goal-settings": "Force Item Battle", - "item-force-item-battle-goal-give-item": [ - "§bGive Item On Skip", - "If a player *skips* an item,", - "they will *receive* it" - ], - "item-force-mob-battle-goal": [ - "§bForce Mob Battle", - "Each player gets *a random mob* that", - "he has to *kill*.", - "The player that *killed* the *most mobs*, wins." - ], - "item-force-advancement-battle-goal": [ - "§6Force Advancement Battle", - "Each player gets a *random advancement*,", - "that he has to complete." - ], - "menu-force-mob-battle-goal-settings": "Force Mob Battle", - "item-get-full-health-goal": [ - "§aGet Full Health", - "The first player to gain full health wins." - ], - "menu-force-advancement-battle-goal-settings": "Force Advancement Battle", - "item-force-block-battle-goal": [ - "§aForce Block Battle", - "Every player gets a *random*", - "*block*, on which he has to stand" - ], - "menu-force-block-battle-goal-settings": "Force Block Battle", - "item-force-block-battle-goal-give-block": [ - "§bGive Block On Skip", - "If a player *skips* a block,", - "they will *receive* it" - ], - "item-force-biome-battle-goal": [ - "§2Force Biome Battle", - "Each player gets a *random biome*,", - "that he has to *enter*." - ], - "menu-force-biome-battle-goal-settings": "Force Biome Battle", - "item-force-damage-battle-goal": [ - "§3Force Damage Battle", - "Each player gets a *random damage amount*,", - "that he has to *take*." - ], - "menu-force-damage-battle-goal-settings": "Force Damage Battle", - "item-force-height-battle-goal": [ - "§6Force Height Battle", - "Each player gets a *random height*,", - "that he has to *reach*." - ], - "menu-force-height-battle-goal-settings": "Force Height Battle", - "item-force-position-battle-goal": [ - "§aForce Position Battle", - "Each player gets a *random position*,", - "that he has to *reach*." - ], - "menu-force-position-battle-goal-settings": "Force Position Battle", - "item-extreme-force-battle-goal": [ - "§cExtreme Force Battle", - "Each player gets a *random target*,", - "that he has to reach." - ], - "menu-extreme-force-battle-goal-settings": "Extreme Force Battle", - "item-damage-rule-none": [ - "§6General Damage", - "Sets whether you can get damage or not" - ], - "item-damage-rule-fire": [ - "§6Fire Damage", - "Sets whether you get *damage* from *Fire* and *Lava*" - ], - "item-damage-rule-attack": [ - "§3Attack Damage", - "Sets whether you get *damage* from *Melee Attacks* of entites" - ], - "item-damage-rule-projectile": [ - "§6Projectile Damage", - "Sets whether you get *damage* from *Projectiles*" - ], - "item-damage-rule-fall": [ - "§fFall Damage", - "Sets whether you get *damage* from *Fall Damage" - ], - "item-damage-rule-explosion": [ - "§cExplosion Damage", - "Sets whether you get *damage* from *Explosions" - ], - "item-damage-rule-drowning": [ - "§9Drowning Damage", - "Sets whether you get *damage* from *Drowning" - ], - "item-damage-rule-block": [ - "§eBlock Damage", - "Sets whether you get *damage* from *Falling Blocks" - ], - "item-damage-rule-magic": [ - "§5Magic Damage", - "Sets whether you get *damage* from", - "*Poison, Wither or other Potions" - ], - "item-damage-rule-freeze": [ - "§cFreeze Damage", - "Sets whether you get *damage* from *Freezing*" - ], - "item-block-material": [ - "{0}", - "Sets whether *{1}* can be used" - ], - "custom-limit": "You've reached the limit of §e{0} challenges", - "custom-not-deleted": "Challenge doesn't exist yet!", - "custom-saved": "§7Challenge §asaved §7locally", - "custom-saved-db": [ - "To save it in your database use §e/db save customs", - "§cWarning: §7Old challenges will be overwritten!" - ], - "custom-no-changes": "You haven't made any changes", - "custom-name-info": "Type the new name into the chat", - "custom-command-info": [ - "Type the command §ewithout / §7in chat", - "Allowed commands: §e{0}", - "§cOther commands can be allowed in the config" - ], - "custom-command-not-allowed": "Command §e{0} §7is not set as allowed command in config", - "custom-chars-max_length": "You've reached the limit of {0} characters", - "custom-not-loaded": [ - " ", - "There are no currently loaded challenges.", - "You're missing your challenges? §e/db load customs", - "You've got problems with saving them?", - "Save your challenges before leaving with §e/db save customs", - " " - ], - "custom-main-view-challenges": "§6View Challenges", - "custom-main-create-challenge": "§aCreate Challenge", - "custom-title-trigger": "Trigger", - "custom-title-action": "Action", - "custom-title-view": "View", - "custom-sub-finish": "§aFinished", - "item-custom-info-delete": [ - "§cDelete", - "*Warning* This Action cannot be made *undone*" - ], - "item-custom-info-save": "§aSave", - "item-custom-info-trigger": [ - "§cTrigger", - "*Click here* to set what has to be happening", - "for the *action* to execute" - ], - "item-custom-info-action": [ - "§bAction", - "*Click here* to set what should happen", - "once the *trigger* is met" - ], - "item-custom-info-material": [ - "§6Display Item", - "*Click here* to change the display item" - ], - "item-custom-info-name": [ - "§6Name", - "*Click here* to change the name via chat", - "Max Characters: 50" - ], - "custom-info-currently": "§7Set §8» §e", - "custom-info-trigger": "§7Trigger", - "custom-info-action": "§7Action", - "item-custom-trigger-jump": [ - "§aPlayer Jumps" - ], - "item-custom-trigger-sneak": [ - "§aPlayer Sneaks" - ], - "item-custom-trigger-move_block": [ - "§6Player Walks A Block" - ], - "item-custom-trigger-death": [ - "§cEntity Dies" - ], - "item-custom-trigger-damage": [ - "§cEntity Takes Damage" - ], - "item-custom-trigger-damage-any": [ - "§aAny Cause" - ], - "item-custom-trigger-damage_by_player": [ - "§cEntity Takes Damage By Player" - ], - "item-custom-trigger-intervall": [ - "§6Interval" - ], - "item-custom-trigger-intervall-second": [ - "§6Each Second" - ], - "item-custom-trigger-intervall-seconds": [ - "§6Every {0} Seconds" - ], - "item-custom-trigger-intervall-minutes": [ - "§6Every {0} Minutes" - ], - "item-custom-trigger-block_place": [ - "§aBlock Placed" - ], - "item-custom-trigger-block_break": [ - "§cBlock Destroyed" - ], - "item-custom-trigger-consume_item": [ - "§2Consume Item" - ], - "item-custom-trigger-pickup_item": [ - "§bPickup Item" - ], - "item-custom-trigger-drop_item": [ - "§9Player Dropped Item" - ], - "item-custom-trigger-advancement": [ - "§cPlayer Gets Advancement" - ], - "item-custom-trigger-hunger": [ - "§2Player Looses Hunger" - ], - "item-custom-trigger-move_down": [ - "§6Player Moves Block Down" - ], - "item-custom-trigger-move_up": [ - "§6Player Moves Block Up" - ], - "item-custom-trigger-move_camera": [ - "§6Moves Camera" - ], - "item-custom-trigger-stands_on_specific_block": [ - "§6Player Is On Specific Block" - ], - "item-custom-trigger-stands_not_on_specific_block": [ - "§6Player Is Not On Specific Block" - ], - "item-custom-trigger-gain_xp": [ - "§5Player Gets XP" - ], - "item-custom-trigger-level_up": [ - "§5Player Gets Level" - ], - "item-custom-trigger-item_craft": [ - "§6Player Crafts Item" - ], - "item-custom-trigger-in_liquid": [ - "§9Player Is In Liquid" - ], - "item-custom-trigger-get_item": [ - "§aGet Item", - "Action will be executed *every time*", - "item is clicked or picked up" - ], - "item-custom-action-cancel": [ - "§4Cancel Trigger", - "Prevent that the trigger will be executed", - "Non preventable Trigger: *Jump*, *Sneak*, *Death*", - "*Advancement*, *Level Up*, *In Liquid*" - ], - "item-custom-action-command": [ - "§4Execute Command", - "Make players execute commands.", - "Commands are executed for players via */execute as*.", - "Allowed commands can be set in plugin config.", - "The player doesn't need the *permission* to the commands.", - "Player aren't able to execute *plugin commands*." - ], - "item-custom-action-kill": [ - "§4Kill", - "Kill entities" - ], - "item-custom-action-damage": [ - "§cDamage", - "Hurt entities" - ], - "item-custom-action-heal": [ - "§aHeal", - "Restore entity health" - ], - "item-custom-action-hunger": [ - "§6Hunger", - "Make Entities get hunger" - ], - "item-custom-action-max_health": [ - "§cChange Max Health", - "Modify the max health of players.", - "Will be reset with */gamestate reset*" - ], - "item-custom-action-max_health-offset": [ - "§cHealth Change", - "Choose how the max health should be changed" - ], - "item-custom-action-spawn_entity": [ - "§3Spawn Entity", - "Spawn an entity with a specific type" - ], - "item-custom-action-random_mob": [ - "§6Random Entity", - "Spawn a random entity" - ], - "item-custom-action-random_item": [ - "§bRandom Item", - "Give random items to players" - ], - "item-custom-action-uncraft_inventory": [ - "§eUncraft Inventory", - "Make players inventories uncraft" - ], - "item-custom-action-boost_in_air": [ - "§fBoost In Air", - "Boost entities into the air" - ], - "item-custom-action-boost_in_air-strength": [ - "§fAmplifier" - ], - "item-custom-action-potion_effect": [ - "§dPotion Effect", - "Add a potion effect to entities" - ], - "item-custom-action-permanent_effect": [ - "§6Permanent Potion Effect", - "Add a permanent potion effect to players.", - "Uses the settings of the permanent effect challenge." - ], - "item-custom-action-random_effect": [ - "§dRandom Potion Effect", - "Add a random potion effect to entities" - ], - "item-custom-action-clear_inventory": [ - "§cClear Inventory", - "Clear the inventory of players" - ], - "item-custom-action-drop_random_item": [ - "§aDrop Item From Inventory", - "Drop a random item from the inventory onto the floor" - ], - "item-custom-action-remove_random_item": [ - "§cRemove Item From Inventory", - "Remove a random item from the inventory" - ], - "item-custom-action-swap_random_item": [ - "§6Swap Items In Inventory", - "Swap two items in the inventory" - ], - "item-custom-action-freeze": [ - "§bFreeze", - "Temporarily freeze mobs", - "Uses the settings of the freeze challenge" - ], - "item-custom-action-invert_health": [ - "§cInvert Health", - "Invert the current health of players" - ], - "item-custom-action-water_mlg": [ - "§9Water MLG", - "All players have to do a water mlg to survive" - ], - "item-custom-action-jnr": [ - "§6Jump And Run", - "A random player has to a a jump and run", - "that gets longer everytime" - ], - "item-custom-action-win": [ - "§6Win", - "The challenge will be won *by specific players*" - ], - "item-custom-action-random_hotbar": [ - "§eRandom Hotbar", - "The inventory is emptied and the player", - "gets a full hotbar of random items" - ], - "item-custom-action-modify_border": [ - "§bModify World Border", - "Make the world border *bigger* or *tinier*" - ], - "item-custom-action-modify_border-change": [ - "§dChange" - ], - "item-custom-action-swap_mobs": [ - "§5Swap mobs", - "Swap a mob with another of the same world" - ], - "item-custom-action-place_structure": [ - "§aPlace Structure", - "Places a structure" - ], - "item-custom-action-place_structure-random": "§bRandom structure", - "item-custom-setting-target-current": [ - "§6Current Entity", - "The action will be executed for the *current entity*" - ], - "item-custom-setting-target-every_mob": [ - "§4Every Mob", - "The action will be executed for *every mob*" - ], - "item-custom-setting-target-every_mob_except_current": [ - "§4Every Mob Except Current", - "The action will be executed for *every mob*", - "*except* the current one" - ], - "item-custom-setting-target-every_mob_except_players": [ - "§4Every Mob Except Players", - "The action will be executed for *every mob except players*" - ], - "item-custom-setting-target-random_player": [ - "§5Random Player", - "The action will be executed for a *random player*" - ], - "item-custom-setting-target-every_player": [ - "§cEvery Player", - "The action will be executed for *every player*" - ], - "item-custom-setting-target-current_player": [ - "§aCurrent Player", - "The action will be executed for the *active player*.", - "§7§oIf the current entity is not a player nothing will be happen" - ], - "item-custom-setting-target-console": [ - "§4Console", - "The action will be executed for the *console*" - ], - "item-custom-setting-entity_type-any": "§cAny Entity", - "item-custom-setting-entity_type-player": "§aPlayer", - "item-custom-setting-block-any": "§2Any Block", - "item-custom-setting-item-any": "§2Any Item", - "custom-subsetting-target_entity": "Target Entity", - "custom-subsetting-entity_type": "Entity Type", - "custom-subsetting-liquid": "Liquid", - "custom-subsetting-time": "Time", - "custom-subsetting-damage_cause": "Damage Cause", - "custom-subsetting-amount": "Amount", - "custom-subsetting-value": "Value Editor", - "custom-subsetting-health_offset": "Change", - "custom-subsetting-length": "Length", - "custom-subsetting-amplifier": "Amplifier", - "custom-subsetting-change": "Change", - "custom-subsetting-swap_targets": "Swap Targets" + "syntax": "Please use §e/{0}", + "reload": "Challenges Plugin is reloading...", + "reload-failed": "An §cerror &7occurred while reloading the plugin", + "reload-success": "Challenges Plugin §asuccessfully §7reloaded", + "player-command": "You must be a player!", + "no-permission": "You §cdon't §7have permissions to do this", + "enabled": "§aActivated", + "disabled": "§cDeactivated", + "customize": "§6Customize", + "navigate-back": "§8« §7Back", + "navigate-next": "§8» §7Next", + "seconds": "seconds", + "second": "second", + "minutes": "minutes", + "minute": "minute", + "hours": "hours", + "hour": "hour", + "amplifier": "amplifier", + "open": "Open", + "everyone": "§5Everyone", + "player": "§6Active player", + "none": "None", + "inventory-color": "§9", + "timer-counting-up": "§8» §7Timer counting §aup", + "timer-counting-down": "§8» §7Timer counting §cdown", + "timer-is-paused": "§8» §7Timer §cpaused", + "timer-is-running": "§8» §7Timer §astarted", + "confirm-reset": "Confirm reset with §e/{0}", + "no-fresh-reset": [ + "The Server §ccan't §7be reset yet", + "The Challenge §chasn't been §7started" + ], + "new-challenge": "§a§lNew!", + "feature-disabled": "This function is currently §cdeactivated", + "challenge-disabled": "This challenge is currently §cdeactivated", + "timer-not-started": "The timer §chasn't been started", + "timer-was-started": "The timer has been §astarted", + "timer-was-paused": "The timer has been §cpaused", + "timer-was-set": "The timer has ben set on §e§l{0}", + "timer-already-started": "The timer is §calready running", + "timer-already-paused": "The timer is §calready paused", + "timer-mode-set-down": "The timer is counting §cdown", + "timer-mode-set-up": "The timer is counting §aup", + "no-database-connection": "There is §cno §7database connection", + "fetching-data": "Data is being retrieved..", + "undefined": "undefined", + "no-such-material": "This material doesn't exist", + "not-an-item": "§e{0} §7is not an item", + "no-such-entity": "This entity doesn't exist", + "not-alive": "§e{0} §7is not a living entity", + "no-loot": "§e{0} §7doesn't have any drops", + "deprecated-plugin-version": [ + " ", + "An update for the plugin is available", + "Download: §e{0}", + " " + ], + "deprecated-config-version": [ + "The plugin config version is §coutdated §7(§c{1} §7< §a{0}§7)", + "You can either manually add all missing settings or delete the old one" + ], + "missing-config-settings": "There are missing config settings: §e{0}", + "missing-config-settings-separator": "§7, §e", + "no-missing-config-settings": [ + "§cThere are no missing config settings.", + "§cYou can manually update it to §c§l{0}" + ], + "join-message": "§e{0} §7has §ajoined §7the server", + "quit-message": "§e{0} §7has §cleft §7the server", + "timer-paused-message": [ + "The timer is §cpaused", + "Use §e/timer resume §7to start it" + ], + "cheats-detected": [ + "§e{0} §7has §ccheated", + "§cNo §7further statistics can be collected" + ], + "cheats-already-detected": [ + "On this server has been §ccheated", + "§cNo §7further statistics can be collected" + ], + "custom_challenges-reset": "The §elokal §7settings were reset §asuccessfully", + "config-reset": "The §elocal §7settings were reset §asuccessfully", + "player-config-loaded": "Your settings have been loaded §asuccessfully", + "player-config-saved": "Your settings have been saved §asuccessfully", + "player-config-reset": "Your settings were reset §asuccessfully", + "player-custom_challenges-loaded": "Your challenges have been loaded §asuccessfully", + "player-custom_challenges-saved": "Your challenges have been saved §asuccessfully", + "player-custom_challenges-reset": "Your challenges were §asuccessfully §7reset", + "item-prefix": "§8» ", + "item-setting-info": "§8➟ {0}", + "stat-dragon-killed": "Dragons killed", + "stat-deaths": "Deaths", + "stat-entity-kills": "Kills", + "stat-damage-dealt": "Damage dealt", + "stat-damage-taken": "Damage taken", + "stat-blocks-mined": "Blocks destroyed", + "stat-blocks-placed": "Blocks placed", + "stat-blocks-traveled": "Blocks travelled", + "stat-challenges-played": "Challenges played", + "stat-jumps": "Jumps", + "stats-of": "§8» §7Stats of §e{0}", + "stats-display": "§8» §7{0} §8(§e{1}. §7Platz§8)", + "stats-leaderboard-display": [ + "§8» §e{0}", + "§8§l┣ §7{1} §7{2}", + "§8§l┗ §e{3}. §7Place" + ], + "position": "§e{4} §8- §7{0}, {1}, {2} §8(§e{3}§8) §8┃ §e{5}m", + "positions-disabled": "Positions are §cdeactivated", + "position-other-world": "This position is in another world §8(§e{0}§8)", + "position-not-exists": "The position §e{0} §cdoesn't §7exist", + "position-already-exists": "The position {0} §calready §7exist", + "position-set": "§e{5} §7created position §e{4} §7{0}, {1}, {2} §8(§e{3}§8)", + "position-deleted": "§e{5} §7deleted §e{4} §7{0}, {1}, {2} §8(§e{3}§8)", + "no-positions": [ + "There are no §epositions §7set in this world", + "Create on with §e/{0}" + ], + "no-positions-global": [ + "There are no §epositions §7set", + "Create on with §e/{0}" + ], + "command-no-target": "§cNo §7players has been found", + "command-heal-healed": "You have been §ahealed", + "command-heal-healed-others": "You healed §e{0} player/s", + "command-gamemode-gamemode-changed": "Your gamemode has been changed to §e{0}", + "command-gamemode-gamemode-changed-others": "The gamemode of §e{1} §7player/s has been changed to §e{0}", + "command-village-search": "A village is being searched..", + "command-village-teleport": "You have been §ateleported to a village", + "command-village-not-found": "§cNo §7new village was found", + "command-weather-set-clear": "Weather was changed to §eclear", + "command-weather-set-rain": "Weather was changed to §erainy", + "command-weather-set-thunder": "Weather was changed to §ethundery", + "command-invsee-open": "Inventory of §e{0} §7opened", + "command-enderchest-open": "You opened your §5Enderchest", + "command-difficulty-change": "Difficulty changed to {0}", + "command-difficulty-current": "Current difficulty is {0}", + "command-search-nothing": "§e{0} §7is not dropped by any special block", + "command-search-result": "§e{0} §7drops from §e{1}", + "command-searchloot-disabled": "The entity loot randomizer challenge is currently §cdeactivated", + "command-searchloot-nothing": "The loot of §e{0} §7isn't dropped by any specific entity", + "command-searchloot-result": [ + "§e{0} §7drops the loot of §e{1}", + "The loot of §e{0} §7is dropped by §e{2}" + ], + "command-time-set": "Time was changed to §e{0} §7Ticks §8(§7ca. §e{1}§8)", + "command-time-set-exact": "Time was changed to §e{0} §8(§e{1} §7Ticks§8)", + "command-time-query": [ + "§8» §7Current ingame times", + "Playtime §e{0} §7Ticks §8(§7Tag §e{1}§8)", + "Time of day §e{2} §7Ticks §8(§7ca. §e{3}§8)" + ], + "command-time-noon": "Noon", + "command-time-night": "Night", + "command-time-midnight": "Midnight", + "command-time-day": "Day", + "command-fly-enabled": "You can fly §anow", + "command-fly-disabled": "You can §cno longer §7fly", + "command-fly-toggled-others": "You toggled §efly §7for §e{0} §7player/s", + "command-feed-fed": "Your appetite was §esated", + "command-feed-others": "You satiated the appetite of §e{0} §7player/s", + "command-gamestate-reload": "The gamestate was §areloaded", + "command-gamestate-reset": "The gamestate was §areset", + "command-world-teleport": "You'll be teleported into the §e{0}", + "command-back-no-locations": "You §cweren't §7teleported yet", + "command-back-teleported": "You were teleported §e{0} §7location back", + "command-back-teleported-multiple": "You were teleported §e{0} §7locations back", + "command-result-no-battle-active": "There is currently §cno §7Force Battle enabled", + "command-god-mode-enabled": "You are now in §aGod mode", + "command-god-mode-disabled": "You are §cno longer in God mode", + "command-god-mode-toggled-others": "§e{0} §7players are now in §eGod mode", + "traffic-light-challenge-fail": "§e{0} §7went over §cred", + "player-damage-display": "§e{0} §7took §7{1} §7damage by §e{2}", + "death-message": "§e{0} §7died", + "death-message-cause": "§e{0} §7died by §e{1}", + "health-inverted": "Your hearts have been §cinverted", + "exp-picked-up": "§e{0} §7collected §cEXP", + "unable-to-find-fortress": "§cNo fortress §7could be found", + "unable-to-find-bastion": "§cNo bastion §7could be found", + "death-collected": "Death reason §e{0} §7registered", + "item-collected": "Item §e{0} §7registered", + "items-to-collect": "§7Items to collect §8» §e{0}", + "backpacks-disabled": "Backpacks are currently §cdeactivated", + "backpack-opened": "You opened the {0}", + "top-to-overworld": "You have been teleported to the §eoverworld", + "top-to-surface": "You have been teleported to the §etop", + "jnr-countdown": "Next §6JumpAndRun §7in §e{0} seconds", + "jnr-countdown-one": "Next §6JumpAndRun §7in §eone second", + "jnr-finished": "§e{0} §afinished §7the §6JumpAndRun", + "snake-failed": "§e{0} §7stepped over the §9line", + "only-dirt-failed": "§e{0} §7did not stand on dirt", + "no-mouse-move-failed": "§e{0} §7moved his mouse", + "no-duped-items-failed": "§e{0} §7and §e{1} §7both had §e{2} §7in their inventory", + "only-down-failed": "§e{0} §7went up one block", + "food-once-failed": "§e{0} §7suffocated by §e{1}", + "food-once-new-food-team": "§e{0} §7ate §e{1}", + "food-once-new-food": "§eYou §7ate §e{1}", + "sneak-damage-failed": "§e{0} §7sneaked", + "jump-damage-failed": "§e{0} §7jumped", + "random-challenge-enabled": "The challenge §e{0} §7has been §aactivated", + "all-items-skipped": "Item §e{0} §7skipped", + "all-items-already-finished": "All items has been already found", + "all-items-found": "Item §e{0} §7registered by §e{1}", + "mob-kill": "§e{0} §ehas been killed §8(§e{1} §7/ §e{2}§8)", + "endergames-teleport": "Swapped with §e{0}", + "force-height-fail": "§e{0} §7was on the §cwrong §7height §8(§e{1}§8)", + "force-height-success": "All players were on the §aright §7height", + "force-block-fail": "§e{0} §7was on the §cwrong §7block §8(§e{1}§8)", + "force-block-success": "All players were on the §aright §7block", + "force-biome-fail": "The biome §e{0} §chasn't been found", + "force-biome-success": "§e{0} §7found the biome §e{1}", + "force-mob-fail": "The mob §e{0} §chasn't been killed", + "force-mob-success": "§e{0} §7killed the mob §e{1}", + "force-item-fail": "Item §e{0} §chasn't been found", + "force-item-success": "§e{0} §afound §7the item §e{1}", + "new-effect": "Effect §e{0} §8➔ §e{1}", + "missing-items-inventory": "{0}Which item is missing?", + "missing-items-inventory-open": "§8[§aOpen GUI§8]", + "loops-cleared": "§e{0} §7Loops cancelled", + "stopped-moving": "§e{0} §7hasn't moved for too long", + "all-advancements-goal": "§7Advancements §8» §e{0}", + "height-reached": "§e{0} §7reached §eY = {1} §7first!", + "race-goal-reached": "§e{0} §7reached the goal!", + "points-change": "§e{0} §7Points", + "force-item-battle-found": "You've found §e{0}!", + "force-item-battle-new-item": "Item to find: §e{0}", + "force-item-battle-leaderboard": "§8➜ §7Force Item Battle Leaderboard", + "force-mob-battle-killed": "You've killed §e{0}!", + "force-mob-battle-new-mob": "Mob to kill: §e{0}", + "force-mob-battle-leaderboard": "§8➜ §7Force Mob Battle Leaderboard", + "force-advancement-battle-completed": "You've completed §e{0}!", + "force-advancement-battle-new-advancement": "Nächstes Advancement: §e{0}", + "force-advancement-battle-leaderboard": "§8➜ §7Force Advancement Battle Leaderboard", + "force-block-battle-found": "You've found §e{0}!", + "force-block-battle-new-block": "Block to find: §e{0}", + "force-block-battle-leaderboard": "§8➜ §7Force Block Battle Leaderboard", + "force-battle-leaderboard-entry": "{0}#{1} §8» §e{2} §8┃ §e{3}", + "force-battle-block-target-display": "§eBlock: {0}", + "force-battle-item-target-display":"§eItem: {0}", + "force-battle-height-target-display": "§eHeight: {0}", + "force-battle-mob-target-display": "§eMob: {0}", + "force-battle-biome-target-display": "§eBiome: {0}", + "force-battle-damage-target-display": "§eDamage: §c{0} ❤", + "force-battle-advancement-target-display": "§eAdvancement: {0}", + "force-battle-position-target-display": "§ePosition: {0}", + "extreme-force-battle-new-height": "Height to reach: §e{0}", + "extreme-force-battle-reached-height": "You've reached height §e{0}!", + "extreme-force-battle-new-biome": "Biome to find: §e{0}", + "extreme-force-battle-found-biome": "You've found the biome §e{0}!", + "extreme-force-battle-new-damage": "Damage to take: §c{0} ❤", + "extreme-force-battle-took-damage": "You took §c{0} ❤ §7damage!", + "extreme-force-battle-position": "§eX: {0} §8┃ §eZ: {1}", + "extreme-force-battle-new-position": "Position to reach: §e{0}", + "extreme-force-battle-reached-position": "You've reached the position §e{0}!", + "extreme-force-battle-leaderboard": "§8➜ §7Extreme Force Battle Leaderboard", + "force-biome-battle-leaderboard": "§8➜ §7Force Biome Battle Leaderboard", + "force-damage-battle-leaderboard": "§8➜ §7Force Damage Battle Leaderboard", + "force-height-battle-leaderboard": "§8➜ §7Force Height Battle Leaderboard", + "force-position-battle-leaderboard": "§8➜ §7Force Position Battle Leaderboard", + "random-event-speed": [ + "Sonic? Is it you?", + "Woahh! That's fast" + ], + "random-event-entities": [ + "Is this a zoo?", + "Where did this come from?", + "What are you doing here?" + ], + "random-event-hole": [ + "But you fell pretty deep", + "From the very top to the very bottom..", + "Where did this hole come from?" + ], + "random-event-fly": [ + "Good flight :)", + "I believe I can fly..", + "So this is what flying feels like" + ], + "random-event-webs": [ + "Have they been here for a long time?" + ], + "random-event-ores": [ + "Where did all the ores go?", + "Aren't there any ores here?", + "Was there any ore here??" + ], + "random-event-sickness": [ + "Are you sick??", + "What's going on now?!" + ], + "bossbar-timer-paused": "§8» §7The timer is §cpaused", + "bossbar-mob-transformation": "§8» §7Last mob §8§l┃ §a{0}", + "bossbar-biome-time-left": "§8» §7Time left in §e{0} §8§l┃ §a{1}s", + "bossbar-height-time-left": "§8» §7Time left on §e{0} §8§l┃ §a{1}s", + "bossbar-zero-hearts": "§8» §7Protection time §8§l┃ §a{0}s", + "bossbar-random-challenge-waiting": "§8» §7Waiting for new challenge..", + "bossbar-random-challenge-current": "§8» §7Challenge §e{0}", + "bossbar-all-items-current-max": "§8» §f{0} §8┃ §7{1} §8/ §7{2}", + "bossbar-all-items-finished": "§8» §7All items found", + "bossbar-force-height-waiting": "§8» §7Waiting for next height..", + "bossbar-force-height-instruction": "§8» §7Height §e{0} §8┃ §a{1}", + "bossbar-force-block-waiting": "§8» §7Waiting for next block..", + "bossbar-force-block-instruction": "§8» §7Block §e{0} §8┃ §a{1}", + "bossbar-force-biome-waiting": "§8» §7Waiting for next biome..", + "bossbar-force-biome-instruction": "§8» §7Biome §e{0} §8┃ §a{1}", + "bossbar-force-mob-waiting": "§8» §7Waiting for next mob..", + "bossbar-force-mob-instruction": "§8» §7Mob §e{0} §8┃ §a{1}", + "bossbar-force-item-waiting": "§8» §7Waiting for next item..", + "bossbar-force-item-instruction": "§8» §7Item §e{0} §8┃ §a{1}", + "bossbar-tsunami-water": "§8» §7Waterheight: §9{0}", + "bossbar-tsunami-lava": "§8» §7Lavaheight: §c{0}", + "bossbar-ice-floor": "§8» §bIce floor §8┃ {0}", + "bossbar-dont-stop-running": "§8» §7Move in §8┃ §e{0}", + "bossbar-five-hundred-blocks": "§8» §fBlocks Walked §8┃ §7{0} §8/ §7{1}", + "bossbar-level-border": "§8» §7Border size §8┃ §7{0}", + "bossbar-level-border": "§8» §7Border size §8┃ §7{0}", + "bossbar-race-goal-info": "§8» §fGoal §8┃ §7X: {0} §8/ §7Z: {1} §8┃ §e{2} Blocks", + "bossbar-race-goal": "§8» §fGoal §8┃ §7X: {0} §8/ §7Z: {1}", + "bossbar-first-at-height-goal": "§8» §fGoal §8┃ §7Y: {0}", + "bossbar-respawn-end": "§8» §5Respawned Mobs in End §8┃ §e{0}", + "bossbar-kill-all-bosses": "§8» §cAll Bosses §8┃ §e{0}/{1}", + "bossbar-kill-all-mobs": "§8» §cAll Mobs §8┃ §e{0}/{1}", + "bossbar-kill-all-monster": "§8» §cAll Monsters §8┃ §e{0}/{1}", + "bossbar-chunk-deletion": "§8» §7Time left in chunk §6{0}s", + "subtitle-time-seconds": "§e{0} §7seconds", + "subtitle-time-seconds-range": "§e{0}-{1} §7seconds", + "subtitle-time-minutes": "§e{0} §7minutes", + "subtitle-launcher-description": "§7Power §e{0}", + "subtitle-blocks": "§e{0} §7Blocks", + "subtitle-range-blocks": "§eRange: §e{0} §7Blöcke", + "scoreboard-title": "§7» §f§lChallenge", + "scoreboard-leaderboard": "§e#{0} §8┃ §7{1} §8» §e{2}", + "your-place": "§7Your place §8» §e{0}", + "server-reset": [ + "§8————————————————————", + " ", + "§8» §cServer reset", + " ", + "§7Reset by §4§l{0}", + "§7The server is §crestarting", + " ", + "§8————————————————————" + ], + "challenge-end-timer-hit-zero": [ + " ", + "§cThe challenge is over!", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-timer-hit-zero-winner": [ + " ", + "§cThe challenge is over!", + "§7Gewinner: §e§l{1}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-reached": [ + " ", + "§7The challenge was ended!", + "§7Time needed: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-reached-winner": [ + " ", + "§7The challenge was ended!", + "§7Winner: §e§l{1}", + "§7Time needed: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "challenge-end-goal-failed": [ + " ", + "§cThe challenge is over! §6#FeelsBadMan ✞", + "§7Time wasted: §a§l{0}", + "§7Seed: §e§l{2}", + " " + ], + "title-timer-started": [ + " ", + "§8» §7Timer §acontinued" + ], + "title-timer-paused": [ + " ", + "§8» §7Timer §cpaused" + ], + "title-challenge-enabled": [ + "§e{0}", + "§2§l✔ §8┃ §aActivated" + ], + "title-challenge-disabled": [ + "§e{0}", + "§4✖ §8┃ §cDeactivated" + ], + "title-challenge-value-changed": [ + "§e{0}", + "§8» §e{1}" + ], + "title-pregame-movement-setting": [ + "§cWarte..", + "§8» §7Timer is stopped.." + ], + "item-menu-start": "§8• §aStart Challenge §8┃ §e/start §8•", + "item-menu-challenges": "§8• §cChallenges §8┃ §e/challenge §8•", + "item-menu-timer": "§8• §5Timer §8┃ §e/timer §8•", + "item-menu-leaderboard": "§8• §6Leaderboard §8┃ §e/leaderboard §8•", + "item-menu-stats": "§8• §2Statistics §8┃ §e/stats §8•", + "menu-title": "Menu", + "menu-timer": "§6Timer", + "menu-goal": "§5Goal", + "menu-damage": "§7Schaden", + "menu-item_blocks": "§4Blocks & Items", + "menu-challenges": "§cChallenges", + "menu-settings": "§eSettings", + "menu-custom": "§aCustom Challenges", + "lore-category-activated-count": "§7Activated §8» §a{0}§8/§7{1}", + "lore-category-activated": "§7Activated §8» §aYes", + "lore-category-deactivated": "§7Activated §8» §cNo", + "category-misc_challenge": [ + "§9Miscellaneous", + "Challenges that *couldn't be*", + "*assigned* with a category" + ], + "category-randomizer": [ + "§6Randomizer", + "Experience a *randomized gameplay*" + ], + "category-limited_time": [ + "§aLimited Time", + "Some things are timely restricted" + ], + "category-force": [ + "§3Force", + "You have to fulfill specific", + "*intermediate goals* to survive" + ], + "category-world": [ + "§4World Change", + "The world will be *modified* significant" + ], + "category-damage": [ + "§cSchaden", + "New *damage rules*" + ], + "category-effect": [ + "§5Effekte", + "Have fun with *lots of effects*" + ], + "category-inventory": [ + "§6Inventory", + "You'll have problems managing *your inventory*" + ], + "category-movement": [ + "§aBewegung", + "You're *restricted in your movements*" + ], + "category-entities": [ + "§bEntities", + "Entities will be *modified*" + ], + "category-extra_world": [ + "§aExtra Welt", + "Challenges that will *send*", + "you to *another world*" + ], + "category-misc_goal": [ + "§9Miscellaneous", + "Goals that *couldn't be*", + "*assigned* with a category" + ], + "category-kill_entity": [ + "§cEntities töten", + "Kill *specific entities* to win" + ], + "category-score_points": [ + "§eBest Score", + "Get the best score *to win*" + ], + "category-fastest_time": [ + "§6Fastest Time", + "Be the fastest *to win*" + ], + "category-force_battle": [ + "§bForce Battles", + "Fulfill the given *intermediate goals*", + "to earn points.", + " ", + "The player with the *most points* wins." + ], + "item-time-seconds-description": "§8» §7Time: §e{0} §7seconds", + "item-time-seconds-range-description": "§8» §7Time: §e{0}-{1} §7Sekunden", + "item-time-minutes-description": "§8» §7Time: §e{0} §7minutes", + "item-heart-damage-description": "§8» §7Damage: §e{0} §c❤", + "item-heart-start-description": "§8» §7Start: §e{0} §c❤", + "item-max-health-description": "§8» §7Max health: §e{0} §c❤", + "item-chance-description": "§8» §7Chance: §e{0}%", + "item-launcher-description": "§8» §7Strength: §e{0}", + "item-permanent-effect-target-player-description": "§8» §7Only the active players gets the effect", + "item-permanent-effect-target-everyone-description": "§8» §7All players are getting the effect", + "item-blocks-description": "§8» Blocks to walk: §e{0}", + "item-range-blocks-description": "§8» §7Range: §e{0} §7Block", + "item-force-battle-goal-jokers": [ + "§6Number of jokers", + "The *amount* of *jokers*", + "hat every player has" + ], + "item-force-battle-show-scoreboard": [ + "§bShow Scoreboard" + ], + "item-force-battle-duped-targets": [ + "§cDuped Targets", + "Targets can occur *multiple times*" + ], + "item-force-position-battle-radius": [ + "§bRadius", + "The *maximum radius*, in which the", + "positions will be located" + ], + "item-difficulty-setting": [ + "§aDifficulty", + "Sets the *Difficulty*" + ], + "item-one-life-setting": [ + "§cOne Teamlife", + "*Everyone* dies when *one player dies*" + ], + "item-respawn-setting": [ + "§4Respawn", + "When you *die*, you won't be a *spectator*" + ], + "item-death-message-setting": [ + "§6Death messages", + "Toggles *death messages*" + ], + "item-death-message-setting-vanilla": "§6Vanilla", + "item-pvp-setting": [ + "§9PvP" + ], + "item-max-health-setting": [ + "§cMax health", + "Sets the *max health*", + "for *all players*" + ], + "item-soup-setting": [ + "§cSoup healing", + "When you use a *mushroom soup*", + "you will be healed for *4 hearts*" + ], + "item-damage-setting": [ + "§cDamage Multiplier", + "Damage you take will be *multiplied*" + ], + "item-damage-display-setting": [ + "§eDamage Display", + "It will be displayed in the *chat*", + "when anybody takes *damage*" + ], + "item-health-display-setting": [ + "§cHealth Display", + "The *hearts* of all players", + "will be showed in the *tablist*" + ], + "item-position-setting": [ + "§9Positions", + "Allows you to mark *positions*", + "with */pos*" + ], + "item-backpack-setting": [ + "§6Backpack", + "Allows you to open *your backpack* or", + "the *team backpack* with */backpack*" + ], + "item-backpack-setting-team": "§5Team", + "item-backpack-setting-player": "§6Player", + "item-cut-clean-setting": [ + "§9CutClean", + "Different *settings* to simplify", + "the *farming* of items" + ], + "menu-cut-clean-setting-settings": "CutClean", + "item-cut-clean-gold-setting": [ + "§6Gold", + "*Gold ore* will be directly dropped as *Gold ingot*" + ], + "item-cut-clean-iron-setting": [ + "§7Iron", + "*Iron ore* will be directly dropped as *Iron ingot*" + ], + "item-cut-clean-coal-setting": [ + "§eCoal", + "*Coal* will be directly dropped as *torches*" + ], + "item-cut-clean-flint-setting": [ + "§eFlint", + "*Gravel* will always drop *flint*" + ], + "item-cut-clean-vein-setting": [ + "§eOre Veins", + "*Ore veins* will be directly destroyed" + ], + "item-cut-clean-inventory-setting": [ + "§6Direct Into Inventory", + "*Items* will be put *directly* into your", + "*inventory* instead of dropping" + ], + "item-cut-clean-food-setting": [ + "§cCooked Food", + "*Raw meat* will be directly dropped as *cooked meat*" + ], + "item-glow-setting": [ + "§fPlayer Glow", + "*Players* are visible through *walls*" + ], + "no-hunger-setting": [ + "§cNo Hunger", + "You don't get *hungry*" + ], + "pregame-movement-setting": [ + "§6Pregame Movement", + "You can *move* before", + "the game has been *started*" + ], + "item-no-hit-delay-setting": [ + "§fNoHitDelay", + "After you've *taken* damage", + "you can *get* damage *immediately* again" + ], + "item-timber-setting": [ + "§bTimber", + "You can destroy a *tree*", + "by breaking down *a single block* of the tree" + ], + "item-timber-setting-logs": "§6Logs", + "item-timber-setting-logs-and-leaves": "§6Logs §7and §2Leaves", + "item-keep-inventory-setting": [ + "§5Keep Inventory", + "You don't lose any *items*", + "when you die" + ], + "item-mob-griefing-setting": [ + "§5Mob Griefing", + "Monsters *can't destroy* anything" + ], + "item-no-item-damage-setting": [ + "§5No Item Damage", + "*Items* are *unbreakable*" + ], + "top-command-setting": [ + "§dTop Command", + "You can *teleport* to the *top*", + "of the world or to the *overworld*", + "with /top" + ], + "item-fortress-spawn-setting": [ + "§cFortress Spawn", + "When you go into the *nether*", + "you will always spawn in a *fortress*" + ], + "item-bastion-spawn-setting": [ + "§cBastion Spawn", + "When you go into the *nether*", + "you will always spawn in a *bastion*" + ], + "item-no-offhand-setting": [ + "§6No Offhand", + "The *second hand* will be blocked" + ], + "item-regeneration-setting": [ + "§cRegeneration", + "Sets *whether* and", + "*how* to *regenerate*" + ], + "item-regeneration-setting-not_natural": "§6Not Natural", + "item-immediate-respawn-setting": [ + "§6Direct Respawn", + "When you *die* you *respawn* automatically", + "*without* seeing the *death screen*" + ], + "item-slot-limit-setting": [ + "§4Inventory Slots", + "Sets how many *inventory*", + "*slots* are useable" + ], + "item-death-position-setting": [ + "§cDeath Position", + "When you die, */pos* creates", + "a position at your death point" + ], + "item-enderchest-command-setting": [ + "§5Enderchest Command", + "When you execute */ec*,", + "your *Enderchest* opens" + ], + "item-split-health-setting": [ + "§cSplit Health", + "Sets whether *all players*", + "share the same *health*" + ], + "item-old-pvp-setting": [ + "§b1.8 PvP", + "The *old 1.8 PvP System* will be used", + "There will be no *attack damage cooldown*" + ], + "item-totem-save-setting": [ + "§6Challenge Death Rescue", + "If you *instant die* from a *challenge*", + "*totems* can *rescue* you" + ], + "item-traffic-light-challenge": [ + "§cTraffic Light Challenge", + "The *traffic light* switches every few minutes.", + "If you go on *red*, you die" + ], + "item-block-randomizer-challenge": [ + "§6Block Randomizer", + "Each *block* drops a *random item*" + ], + "item-crafting-randomizer-challenge": [ + "§6Crafting Randomizer", + "If you *craft* something you will get another *random item*" + ], + "item-mob-randomizer-challenge": [ + "§6Mob Randomizer", + "When an *Entity* spawns, it spawns *twice*" + ], + "item-hotbar-randomizer-challenge": [ + "§6HotBar Randomizer", + "Every *few minutes* every player gets *random items*" + ], + "item-damage-block-challenge": [ + "§4Damage per Block", + "You take *damage* for", + "every *block* you walk" + ], + "item-hunger-block-challenge": [ + "§6Hunger per Block", + "You lose *food* for", + "every *block* you walk" + ], + "item-stone-sight-challenge": [ + "§fStone Sight", + "*Mobs* that you look in the", + "*eyes* turn to stone" + ], + "item-no-mob-sight-challenge": [ + "§cMob Sight Damage", + "When you look into the *eyes* of an", + "*entity*, you get *damage*" + ], + "item-bedrock-path-challenge": [ + "§7Bedrock Path", + "*Bedrock *generates* under you*", + "the whole time" + ], + "item-bedrock-walls-challenge": [ + "§7Bedrock Walls", + "Huge *walls of bedrock*", + "are *generating* behind you" + ], + "item-surface-hole-challenge": [ + "§cSurface Hole", + "The *floor* is disappearing", + "to *void* behind you" + ], + "item-damage-inv-clear-challenge": [ + "§cDamage Inventory Clear", + "Player *inventories* are *cleared*", + "when a *player* takes damage" + ], + "item-no-trading-challenge": [ + "§2No Trading", + "You *cannot* trade", + "with villagers" + ], + "item-block-break-damage-challenge": [ + "§6Block Break Damage", + "If you *break* a *block*, you", + "will *take* the set amount of *damage*" + ], + "item-block-place-damage-challenge": [ + "§6Block Place Damage", + "If you *place* a *block*, you", + "will *take* the set amount of *damage*" + ], + "item-no-exp-challenge": [ + "§aNo EXP", + "If you pickup *EXP* you die" + ], + "item-invert-health-challenge": [ + "§cInvert Health", + "Every few minutes the *hearts are inverted*.", + "If you have *8 hearts*, you will have *2 hearts*", + "and the other way around" + ], + "item-jump-and-run-challenge": [ + "§6Jump and Run", + "Every *few minutes* you have to do a random", + "*jump and run* which gets *harder* every time" + ], + "item-randomized-hp-challenge": [ + "§4Randomized HP", + "The *health* of all mobs", + "is randomized" + ], + "item-snake-challenge": [ + "§9Snake", + "Each player draws a *deadly line*", + "behind them" + ], + "item-reversed-damage-challenge": [ + "§cReversed Damage", + "If you deal damage to entites", + "you take the same damage" + ], + "item-duped-spawning-challenge": [ + "§cDuped Spawning", + "If a mob *spawns*", + "it spawns *two times*" + ], + "item-hydra-challenge": [ + "§5Hydra", + "If you *kill* a mob", + "*two new* are spawning" + ], + "item-hydra-plus-challenge": [ + "§cHydra Plus", + "If you kill a *mob* it", + "spawns *twice* as many", + "times as the *previous* time", + " ", + "Maximum are *512* Mobs each time" + ], + "item-floor-lava-challenge": [ + "§6The Floor Is Lava", + "*Blocks* below you transform first", + "to *magma* and then to *lava*" + ], + "item-only-dirt-challenge": [ + "§cOnly Dirt", + "You must stay on *dirt*", + "otherwise you will *die*" + ], + "item-food-once-challenge": [ + "§cFood Once", + "Each *food* can be*", + "*eaten* only once" + ], + "item-food-once-challenge-player": "§6Player", + "item-food-once-challenge-everyone": "§5Everyone", + "item-chunk-deconstruction-challenge": [ + "§bChunk Deconstruction", + "*Chunks* that players are in", + "*break* down from *above*" + ], + "item-one-durability-challenge": [ + "§4One Durability", + "Items are *destroyed* after one *use*" + ], + "item-low-drop-rate-challenge": [ + "§6Low Drop Chance", + "The *drop chance* of each *block*", + "will be set to the defined *percentage*" + ], + "item-invisible-mobs-challenge": [ + "§fInvisible Mobs", + "All *Mobs* have an", + "*invisibility* effect" + ], + "item-mob-transformation-challenge": [ + "§cMob Transformation", + "When you hit a mob, it *turns*", + "into the last mob *you* hit" + ], + "item-jump-entity-challenge": [ + "§2Jump Entity", + "A *random entity* spawns", + "everytime you *jump*" + ], + "item-no-mouse-move-challenge": [ + "§cMouse Movement Damage", + "You take *damage* everytime", + "you *move* your *view*" + ], + "item-no-duped-items-challenge": [ + "§6No Duped Items", + "Players are *not allowed* to have", + "the *same item* in their *inventories*", + "at the same time" + ], + "item-infection-challenge": [ + "§aInfection Challenge", + "You have to keep *2 blocks* away", + "from all *mobs* or you will *get* sick" + ], + "item-only-down-challenge": [ + "§cOnly Down", + "If you go *up* by *a block*, you *die*" + ], + "item-advancement-damage-challenge": [ + "§cAdvancement Damage", + "You *take* the set amount of *damage*", + "for every new *advancement*" + ], + "item-all-blocks-disappear-challenge": [ + "§cAll Blocks Disappear", + "With different *interactions* all", + "*blocks* of a certain type", + "disappear in the same chunk" + ], + "menu-all-blocks-disappear-challenge-settings": "All blocks disappear", + "item-all-blocks-disappear-break-challenge": [ + "§bBy breaking", + "If you *break* a *block* all blocks", + "of the same types disappear" + ], + "item-all-blocks-disappear-place-challenge": [ + "§bBy Placing", + "If you *place* a *block* all blocks", + "of the same types disappear" + ], + "item-water-allergy-challenge": [ + "§9Water Allergy", + "You *take* the set amount of *damage*", + "while you are in *water*" + ], + "item-max-biome-time-challenge": [ + "§2Max Biome Time", + "The *time* that you may spend", + "in every *biome* is limited" + ], + "item-max-height-time-challenge": [ + "§9Max Biome Time", + "The *time* that you may spend", + "on every *height* is limited" + ], + "item-permanent-item-challenge": [ + "§cPermanent Items", + "*Items* cannot be dropped", + "or put *away*" + ], + "item-sneak-damage-challenge": [ + "§6Damage per Sneak", + "You *take* the set amount", + "of *damage* if you *sneak*" + ], + "item-jump-damage-challenge": [ + "§6Damage per Jump", + "You *take* the set amount", + "of *damage* if you *jump*" + ], + "item-random-dropping-challenge": [ + "§cRandom Item Dropping", + "Every few seconds a *random item*", + "will be *dropped* from your *inventory*" + ], + "item-random-swapping-challenge": [ + "§cRandom Item Swapping", + "Every few seconds a *random item*", + "will be *swapped* with *another item*", + "in your *inventory*" + ], + "item-random-removing-challenge": [ + "§cRandom Item Removing", + "Every few seconds a *random item*", + "will be *removed* from your *inventory*" + ], + "item-death-on-fall-challenge": [ + "§fDeath On Fall Damage", + "You *die instantly*, when", + "you take *fall damage*" + ], + "item-zero-hearts-challenge": [ + "§6Zero Hearts", + "After a *protection time* you have to", + "get *absorption permanently* else you will die" + ], + "item-random-effect-challenge": [ + "§6Random Effects", + "You get a *random potion effect*", + "in a set *interval*" + ], + "menu-random-effect-challenge-settings": "Random Effects", + "item-random-effect-time-challenge": [ + "§6Interval", + "The *interval* you get the *effect* in" + ], + "item-random-effect-length-challenge": [ + "§6Length", + "The *length* you have the *effect*" + ], + "item-random-effect-amplifier-challenge": [ + "§6Amplifier", + "The *amplifier* the effect has" + ], + "item-permanent-effect-on-damage-challenge": [ + "§6Permanent Effects", + "Everytime you *take damage* you get", + "a random *permanent potion effect*" + ], + "item-random-challenge-challenge": [ + "§cRandom Challenge", + "In a set *interval* a random", + "*challenge* will be *activated*" + ], + "item-anvil-rain-challenge": [ + "§cAnvil Rain", + "*Anvils* are falling from the *sky*" + ], + "menu-anvil-rain-challenge-settings": "Anvil Rain", + "item-anvil-rain-time-challenge": [ + "§6Interval", + "The *interval*, the *anvils* are spawning in" + ], + "item-anvil-rain-range-challenge": [ + "§6Range", + "The *range* of chunks, the *anvils* are spawning in" + ], + "item-anvil-rain-count-challenge": [ + "§6Amount", + "The *amount* of anvils that", + "are spawning in one chunk" + ], + "item-anvil-rain-damage-challenge": [ + "§6Damage", + "The *damage* you take from an *anvil*" + ], + "item-water-mlg-challenge": [ + "§bWater MLG", + "You have to do a *Water MLG*", + "over and over again" + ], + "item-ender-games-challenge": [ + "§5Ender Games", + "Every *few minutes* you will be", + "*swapped* with a *random entity*", + "in a *200 blocks* range" + ], + "item-random-event-challenge": [ + "§6Random Events", + "Every *few minutes* one of", + "*{0} random Events* will be activated" + ], + "item-block-chunk-item-remove-challenge": [ + "§6Movement Item Remove", + "A random item will be removed from", + "your inventory for every", + "*block* / *chunk* you walk" + ], + "item-block-chunk-item-remove-challenge-block": "§6Block", + "item-block-chunk-item-remove-challenge-chunk": "§6Chunk", + "item-higher-jumps-challenge": [ + "§aHigher Jumps", + "The more *you jump*, the *higher* you jump" + ], + "item-force-height-challenge": [ + "§eForce Height", + "Every *few minutes* you have to be", + "on a *certain height*, else you die" + ], + "item-force-block-challenge": [ + "§6Force Block", + "Every *few minutes* you have to be", + "on a *certain block*, else you die" + ], + "item-force-biome-challenge": [ + "§aForce Biome", + "Every *few minutes* you have to be", + "in a *certain biome*, else you die", + "The *rarer* the biome, the *more time* you have" + ], + "item-force-mob-challenge": [ + "§bForce Mob", + "Every *few minutes* you have to", + "*kill* a *certain mob*, else you die" + ], + "item-force-item-challenge": [ + "§6Force Item", + "Every *few minutes* you have to get", + "a *certain item*, else you die" + ], + "item-random-item-challenge": [ + "§bRandom Items", + "A *random player* gets a *random item*", + "every *few seconds*" + ], + "item-always-running-challenge": [ + "§cAlways Running", + "You *cannot stop* to *walk forwards*" + ], + "item-pickup-launch-challenge": [ + "§cPickup Boost", + "When you *pick up* an *item*", + "you will be *launched* into the air" + ], + "item-tsunami-challenge": [ + "§9Tsunami", + "In a *set interval* ", + "the water rises in the *Overworld*", + "and the *lava* in the nether", + " ", + "Should be played with a *few people*!" + ], + "item-all-mobs-to-death-position-challenge": [ + "§cAll Mobs To Death Point", + "If a *Mob* gets *killed* by a player", + "all mobs of the *same type* will be", + "*teleported* to its *death point*" + ], + "item-ice-floor-challenge": [ + "§bIce Floor", + "*Air* will be replaced in a", + "*3x3* area with *packed ice*" + ], + "item-blocks-disappear-time-challenge": [ + "§fBlocks Disappear After Time", + "Placed *blocks*, will *disappear*", + "after a *few seconds*" + ], + "item-missing-items-challenge": [ + "§9Items Missing", + "Every few minutes a *random item disappears* from", + "your *inventory* and you have to *guess* which it was" + ], + "item-damage-item-challenge": [ + "§cDamage Per Item", + "When you *pickup* or *click* an item", + "in your *inventory* you take the", + "*amount* of the items as *damage*" + ], + "item-damage-teleport-challenge": [ + "§cRandom Teleport On Damage", + "You'll be teleported randomly", + "when you take damage" + ], + "item-loop-challenge": [ + "§6Loop Challenge", + "Certain actions are *looped*", + "until a player *sneaks*" + ], + "item-uncraft-challenge": [ + "§6Items Crafting Back", + "*Items* in your inventory are", + "*crafting* back all few seconds" + ], + "item-freeze-challenge": [ + "§bFreeze Challenge", + "For each heart of *damage*, you'll be", + "*frozen* for a certain time" + ], + "item-dont-stop-running-challenge": [ + "§9Dont stop running", + "You are only allowed to stand *still*", + "a certain *time* before you *die*" + ], + "item-consume-launch-challenge": [ + "§cConsume Boost", + "When you *eat* an *item*", + "you will be *launched* into the air" + ], + "item-five-hundred-blocks-challenges": [ + "§5500 Blocks", + "*Every 500 Blocks walked* players", + "will get a *64 stack* of a random item.", + "*Blocks* and *Entities* won't *drop* any items." + ], + "item-level-border-challenges": [ + "§eLevel = Border", + "The *border size* adjusts to *the player*", + "with the *most levels*." + ], + "item-chunk-effect-challenge": [ + "§3Random Chunk Effects", + "In *each chunk* you'll get", + "a random *potion effect*" + ], + "item-repeat-chunk-challenge": [ + "§2Repeated Chunk", + "Blocks that are *placed or destroyed*", + "will be placed / destroyed in *every chunk*" + ], + "item-blocks-fly-challenge": [ + "§fBlocks Fly in Air", + "*Blocks* you've *walked* on fly", + "into the air after *one second*" + ], + "item-respawn-end-challenge": [ + "§5Mobs Respawn In End", + "*Killed mobs* respawn in *end dimension*" + ], + "item-block-effect-challenge": [ + "§3Random Block Effects", + "On *each block* you'll get", + "a random *potion effect*" + ], + "item-entity-effect-challenge": [ + "§5Mobs Got Random Effects", + "*Every Mob* has a random", + "potion effect with *max amplifier*" + ], + "item-block-mob-challenge": [ + "§cMob Blocks", + "A *random mob* spawns out of *every broken block*", + "and to *get the block* you have to *kill it*" + ], + "item-entity-loot-randomizer-challenge": [ + "§6Entity Loot Randomizer", + "All mob drops are *randomly swapped*." + ], + "item-no-shared-advancements-challenge": [ + "§2No Shared Advancements", + "You're *not allowed* to get *advancements* someone else", + "*already did*. Else *you'll die*." + ], + "item-chunk-deletion-challenge": [ + "§6Chunk Deletion", + "*Chunks* that players are in *delete*", + "completely after the given *time*" + ], + "item-dragon-goal": [ + "§5Ender Dragon", + "Kill the *Ender Dragon* to win" + ], + "item-wither-goal": [ + "§dWither", + "Kill a *Wither* to win" + ], + "item-iron-golem-goal": [ + "§bIron Golem", + "Kill an *Iron Golem* to win" + ], + "item-snow-golem-goal": [ + "§bSnowman", + "Kill a *Snowman* to win" + ], + "item-elder-guardian-goal": [ + "§bElder Guardian", + "Kill an *Elder Guardian* to win" + ], + "item-warden-goal": [ + "§5Warden", + "Kill an *Warden* to win" + ], + "item-most-deaths-goal": [ + "§6Most Deaths", + "Who *collects* the most *different deaths* wins" + ], + "item-most-items-goal": [ + "§cMost Items", + "Who *collects* the most *different items* wins" + ], + "item-last-man-standing-goal": [ + "§cLast Man Standing", + "Who survived until the end wins" + ], + "item-mine-most-blocks-goal": [ + "§eMost Blocks", + "Who *breaks* the most *blocks* wins" + ], + "item-most-xp-goal": [ + "§aMost XP", + "Who *collects* the most *EXP* wins" + ], + "item-first-one-to-die-goal": [ + "§cFirst Death", + "Who *dies* first wins" + ], + "item-collect-wood-goal": [ + "§6Collect Wood", + "Who first collected all types of wood set wins" + ], + "item-collect-wood-goal-overworld": "§aOverworld", + "item-collect-wood-goal-nether": "§cNether", + "item-collect-wood-goal-both": "§9Both", + "item-all-bosses-goal": [ + "§bAll Bosses", + "Each boss must has to be killed once to win" + ], + "item-all-bosses-new-goal": [ + "§5All Bosses (+ Warden)", + "Each boss must has to be killed once to win" + ], + "item-all-mobs-goal": [ + "§bAll Mobs", + "Each mob has to be killed once to win" + ], + "item-all-monster-goal": [ + "§bAll Monsters", + "Each monster has to be killed once to win" + ], + "item-all-items-goal": [ + "§2All Items", + "Find *all items* that are in *Minecraft*" + ], + "item-finish-raid-goal": [ + "§6Finish Raid", + "The first player that *finishes* a *raid* wins" + ], + "item-most-emeralds-goal": [ + "§2Most Emeralds", + "The player with the *most*", + "*emeralds* wins" + ], + "item-all-advancements-goal": [ + "§6All Advancements", + "The first player that *gets* all *advancements* wins" + ], + "item-max-height-goal": [ + "§fMaximum Height", + "The *first* player to reach", + "*Y = {0}* wins" + ], + "item-min-height-goal": [ + "§fMinimum Height", + "The *first* player to reach", + "*Y = {0}* wins" + ], + "item-race-goal": [ + "§5Race", + "The *first* player to *reach* a", + "*random* location in the overworld wins" + ], + "item-most-ores-goal": [ + "§9Most Ores", + "The player that mines the most ores wins" + ], + "item-find-elytra-goal": [ + "§fFind Elytra", + "The *player* that finds an elytra *wins*" + ], + "item-eat-cake-goal": [ + "§fEat Cake", + "The player that *eats a cake* first *wins*" + ], + "item-collect-horse-armor-goal": [ + "§bCollect Horse Armor", + "The player that *collects* every", + "horse armor first *wins*" + ], + "item-collect-ice-goal": [ + "§bCollect Ice Blocks", + "The player that *collects* every", + "ice blocks and snow first *wins*" + ], + "item-collect-swords-goal": [ + "§9Collect Swords", + "The player that *collects* every", + "sword first *wins*" + ], + "item-collect-workstations-item": [ + "§6Collect Workstations", + "The player that *collects* every", + "villager workstation first *wins*" + ], + "item-eat-most-goal": [ + "§6Eat most", + "The player that fills the mods hunger bars *wins*" + ], + "item-force-item-battle-goal": [ + "§5Force Item Battle", + "Each player gets *a random item* that", + "he has *to find*.", + "The player that *found* the *most items*, wins." + ], + "menu-force-item-battle-goal-settings": "Force Item Battle", + "item-force-item-battle-goal-give-item": [ + "§bGive Item On Skip", + "If a player *skips* an item,", + "they will *receive* it" + ], + "item-force-mob-battle-goal": [ + "§bForce Mob Battle", + "Each player gets *a random mob* that", + "he has to *kill*.", + "The player that *killed* the *most mobs*, wins." + ], + "item-force-advancement-battle-goal": [ + "§6Force Advancement Battle", + "Each player gets a *random advancement*,", + "that he has to complete." + ], + "menu-force-mob-battle-goal-settings": "Force Mob Battle", + "item-get-full-health-goal": [ + "§aGet Full Health", + "The first player to gain full health wins." + ], + "menu-force-advancement-battle-goal-settings": "Force Advancement Battle", + "item-force-block-battle-goal": [ + "§aForce Block Battle", + "Every player gets a *random*", + "*block*, on which he has to stand" + ], + "menu-force-block-battle-goal-settings": "Force Block Battle", + "item-force-block-battle-goal-give-block": [ + "§bGive Block On Skip", + "If a player *skips* a block,", + "they will *receive* it" + ], + "item-force-biome-battle-goal": [ + "§2Force Biome Battle", + "Each player gets a *random biome*,", + "that he has to *enter*." + ], + "menu-force-biome-battle-goal-settings": "Force Biome Battle", + "item-force-damage-battle-goal": [ + "§3Force Damage Battle", + "Each player gets a *random damage amount*,", + "that he has to *take*." + ], + "menu-force-damage-battle-goal-settings": "Force Damage Battle", + "item-force-height-battle-goal": [ + "§6Force Height Battle", + "Each player gets a *random height*,", + "that he has to *reach*." + ], + "menu-force-height-battle-goal-settings": "Force Height Battle", + "item-force-position-battle-goal": [ + "§aForce Position Battle", + "Each player gets a *random position*,", + "that he has to *reach*." + ], + "menu-force-position-battle-goal-settings": "Force Position Battle", + "item-extreme-force-battle-goal": [ + "§cExtreme Force Battle", + "Each player gets a *random target*,", + "that he has to reach." + ], + "menu-extreme-force-battle-goal-settings": "Extreme Force Battle", + "item-damage-rule-none": [ + "§6General Damage", + "Sets whether you can get damage or not" + ], + "item-damage-rule-fire": [ + "§6Fire Damage", + "Sets whether you get *damage* from *Fire* and *Lava*" + ], + "item-damage-rule-attack": [ + "§3Attack Damage", + "Sets whether you get *damage* from *Melee Attacks* of entites" + ], + "item-damage-rule-projectile": [ + "§6Projectile Damage", + "Sets whether you get *damage* from *Projectiles*" + ], + "item-damage-rule-fall": [ + "§fFall Damage", + "Sets whether you get *damage* from *Fall Damage" + ], + "item-damage-rule-explosion": [ + "§cExplosion Damage", + "Sets whether you get *damage* from *Explosions" + ], + "item-damage-rule-drowning": [ + "§9Drowning Damage", + "Sets whether you get *damage* from *Drowning" + ], + "item-damage-rule-block": [ + "§eBlock Damage", + "Sets whether you get *damage* from *Falling Blocks" + ], + "item-damage-rule-magic": [ + "§5Magic Damage", + "Sets whether you get *damage* from", + "*Poison, Wither or other Potions" + ], + "item-damage-rule-freeze": [ + "§cFreeze Damage", + "Sets whether you get *damage* from *Freezing*" + ], + "item-block-material": [ + "{0}", + "Sets whether *{1}* can be used" + ], + "custom-limit": "You've reached the limit of §e{0} challenges", + "custom-not-deleted": "Challenge doesn't exist yet!", + "custom-saved": "§7Challenge §asaved §7locally", + "custom-saved-db": [ + "To save it in your database use §e/db save customs", + "§cWarning: §7Old challenges will be overwritten!" + ], + "custom-no-changes": "You haven't made any changes", + "custom-name-info": "Type the new name into the chat", + "custom-command-info": [ + "Type the command §ewithout / §7in chat", + "Allowed commands: §e{0}", + "§cOther commands can be allowed in the config" + ], + "custom-command-not-allowed": "Command §e{0} §7is not set as allowed command in config", + "custom-chars-max_length": "You've reached the limit of {0} characters", + "custom-not-loaded": [ + " ", + "There are no currently loaded challenges.", + "You're missing your challenges? §e/db load customs", + "You've got problems with saving them?", + "Save your challenges before leaving with §e/db save customs", + " " + ], + "custom-main-view-challenges": "§6View Challenges", + "custom-main-create-challenge": "§aCreate Challenge", + "custom-title-trigger": "Trigger", + "custom-title-action": "Action", + "custom-title-view": "View", + "custom-sub-finish": "§aFinished", + "item-custom-info-delete": [ + "§cDelete", + "*Warning* This Action cannot be made *undone*" + ], + "item-custom-info-save": "§aSave", + "item-custom-info-trigger": [ + "§cTrigger", + "*Click here* to set what has to be happening", + "for the *action* to execute" + ], + "item-custom-info-action": [ + "§bAction", + "*Click here* to set what should happen", + "once the *trigger* is met" + ], + "item-custom-info-material": [ + "§6Display Item", + "*Click here* to change the display item" + ], + "item-custom-info-name": [ + "§6Name", + "*Click here* to change the name via chat", + "Max Characters: 50" + ], + "custom-info-currently": "§7Set §8» §e", + "custom-info-trigger": "§7Trigger", + "custom-info-action": "§7Action", + "item-custom-trigger-jump": [ + "§aPlayer Jumps" + ], + "item-custom-trigger-sneak": [ + "§aPlayer Sneaks" + ], + "item-custom-trigger-move_block": [ + "§6Player Walks A Block" + ], + "item-custom-trigger-death": [ + "§cEntity Dies" + ], + "item-custom-trigger-damage": [ + "§cEntity Takes Damage" + ], + "item-custom-trigger-damage-any": [ + "§aAny Cause" + ], + "item-custom-trigger-damage_by_player": [ + "§cEntity Takes Damage By Player" + ], + "item-custom-trigger-intervall": [ + "§6Interval" + ], + "item-custom-trigger-intervall-second": [ + "§6Each Second" + ], + "item-custom-trigger-intervall-seconds": [ + "§6Every {0} Seconds" + ], + "item-custom-trigger-intervall-minutes": [ + "§6Every {0} Minutes" + ], + "item-custom-trigger-block_place": [ + "§aBlock Placed" + ], + "item-custom-trigger-block_break": [ + "§cBlock Destroyed" + ], + "item-custom-trigger-consume_item": [ + "§2Consume Item" + ], + "item-custom-trigger-pickup_item": [ + "§bPickup Item" + ], + "item-custom-trigger-drop_item": [ + "§9Player Dropped Item" + ], + "item-custom-trigger-advancement": [ + "§cPlayer Gets Advancement" + ], + "item-custom-trigger-hunger": [ + "§2Player Looses Hunger" + ], + "item-custom-trigger-move_down": [ + "§6Player Moves Block Down" + ], + "item-custom-trigger-move_up": [ + "§6Player Moves Block Up" + ], + "item-custom-trigger-move_camera": [ + "§6Moves Camera" + ], + "item-custom-trigger-stands_on_specific_block": [ + "§6Player Is On Specific Block" + ], + "item-custom-trigger-stands_not_on_specific_block": [ + "§6Player Is Not On Specific Block" + ], + "item-custom-trigger-gain_xp": [ + "§5Player Gets XP" + ], + "item-custom-trigger-level_up": [ + "§5Player Gets Level" + ], + "item-custom-trigger-item_craft": [ + "§6Player Crafts Item" + ], + "item-custom-trigger-in_liquid": [ + "§9Player Is In Liquid" + ], + "item-custom-trigger-get_item": [ + "§aGet Item", + "Action will be executed *every time*", + "item is clicked or picked up" + ], + "item-custom-action-cancel": [ + "§4Cancel Trigger", + "Prevent that the trigger will be executed", + "Non preventable Trigger: *Jump*, *Sneak*, *Death*", + "*Advancement*, *Level Up*, *In Liquid*" + ], + "item-custom-action-command": [ + "§4Execute Command", + "Make players execute commands.", + "Commands are executed for players via */execute as*.", + "Allowed commands can be set in plugin config.", + "The player doesn't need the *permission* to the commands.", + "Player aren't able to execute *plugin commands*." + ], + "item-custom-action-kill": [ + "§4Kill", + "Kill entities" + ], + "item-custom-action-damage": [ + "§cDamage", + "Hurt entities" + ], + "item-custom-action-heal": [ + "§aHeal", + "Restore entity health" + ], + "item-custom-action-hunger": [ + "§6Hunger", + "Make Entities get hunger" + ], + "item-custom-action-max_health": [ + "§cChange Max Health", + "Modify the max health of players.", + "Will be reset with */gamestate reset*" + ], + "item-custom-action-max_health-offset": [ + "§cHealth Change", + "Choose how the max health should be changed" + ], + "item-custom-action-spawn_entity": [ + "§3Spawn Entity", + "Spawn an entity with a specific type" + ], + "item-custom-action-random_mob": [ + "§6Random Entity", + "Spawn a random entity" + ], + "item-custom-action-random_item": [ + "§bRandom Item", + "Give random items to players" + ], + "item-custom-action-uncraft_inventory": [ + "§eUncraft Inventory", + "Make players inventories uncraft" + ], + "item-custom-action-boost_in_air": [ + "§fBoost In Air", + "Boost entities into the air" + ], + "item-custom-action-boost_in_air-strength": [ + "§fAmplifier" + ], + "item-custom-action-potion_effect": [ + "§dPotion Effect", + "Add a potion effect to entities" + ], + "item-custom-action-permanent_effect": [ + "§6Permanent Potion Effect", + "Add a permanent potion effect to players.", + "Uses the settings of the permanent effect challenge." + ], + "item-custom-action-random_effect": [ + "§dRandom Potion Effect", + "Add a random potion effect to entities" + ], + "item-custom-action-clear_inventory": [ + "§cClear Inventory", + "Clear the inventory of players" + ], + "item-custom-action-drop_random_item": [ + "§aDrop Item From Inventory", + "Drop a random item from the inventory onto the floor" + ], + "item-custom-action-remove_random_item": [ + "§cRemove Item From Inventory", + "Remove a random item from the inventory" + ], + "item-custom-action-swap_random_item": [ + "§6Swap Items In Inventory", + "Swap two items in the inventory" + ], + "item-custom-action-freeze": [ + "§bFreeze", + "Temporarily freeze mobs", + "Uses the settings of the freeze challenge" + ], + "item-custom-action-invert_health": [ + "§cInvert Health", + "Invert the current health of players" + ], + "item-custom-action-water_mlg": [ + "§9Water MLG", + "All players have to do a water mlg to survive" + ], + "item-custom-action-jnr": [ + "§6Jump And Run", + "A random player has to a a jump and run", + "that gets longer everytime" + ], + "item-custom-action-win": [ + "§6Win", + "The challenge will be won *by specific players*" + ], + "item-custom-action-random_hotbar": [ + "§eRandom Hotbar", + "The inventory is emptied and the player", + "gets a full hotbar of random items" + ], + "item-custom-action-modify_border": [ + "§bModify World Border", + "Make the world border *bigger* or *tinier*" + ], + "item-custom-action-modify_border-change": [ + "§dChange" + ], + "item-custom-action-swap_mobs": [ + "§5Swap mobs", + "Swap a mob with another of the same world" + ], + "item-custom-action-place_structure": [ + "§aPlace Structure", + "Places a structure" + ], + "item-custom-action-place_structure-random": "§bRandom structure", + "item-custom-setting-target-current": [ + "§6Current Entity", + "The action will be executed for the *current entity*" + ], + "item-custom-setting-target-every_mob": [ + "§4Every Mob", + "The action will be executed for *every mob*" + ], + "item-custom-setting-target-every_mob_except_current": [ + "§4Every Mob Except Current", + "The action will be executed for *every mob*", + "*except* the current one" + ], + "item-custom-setting-target-every_mob_except_players": [ + "§4Every Mob Except Players", + "The action will be executed for *every mob except players*" + ], + "item-custom-setting-target-random_player": [ + "§5Random Player", + "The action will be executed for a *random player*" + ], + "item-custom-setting-target-every_player": [ + "§cEvery Player", + "The action will be executed for *every player*" + ], + "item-custom-setting-target-current_player": [ + "§aCurrent Player", + "The action will be executed for the *active player*.", + "§7§oIf the current entity is not a player nothing will be happen" + ], + "item-custom-setting-target-console": [ + "§4Console", + "The action will be executed for the *console*" + ], + "item-custom-setting-entity_type-any": "§cAny Entity", + "item-custom-setting-entity_type-player": "§aPlayer", + "item-custom-setting-block-any": "§2Any Block", + "item-custom-setting-item-any": "§2Any Item", + "custom-subsetting-target_entity": "Target Entity", + "custom-subsetting-entity_type": "Entity Type", + "custom-subsetting-liquid": "Liquid", + "custom-subsetting-time": "Time", + "custom-subsetting-damage_cause": "Damage Cause", + "custom-subsetting-amount": "Amount", + "custom-subsetting-value": "Value Editor", + "custom-subsetting-health_offset": "Change", + "custom-subsetting-length": "Length", + "custom-subsetting-amplifier": "Amplifier", + "custom-subsetting-change": "Change", + "custom-subsetting-swap_targets": "Swap Targets" } diff --git a/language/files/global.json b/language/files/global.json deleted file mode 100644 index e47971c7b..000000000 --- a/language/files/global.json +++ /dev/null @@ -1,233 +0,0 @@ -{ - "symbol": { - "arrow-back": "«", - "arrow": "»", - "chevron": "›", - "chevron-back": "‹", - "dart": "→", - "vertical": "┃", - "cross": "✞", - "check": "✔", - "x": "✘", - "heart": "❤", - "dot": "•", - "circle": "●", - "altert": "⚠", - "flag": "⚐", - "infinity": "∞", - "lock": "\uD83D\uDD12" - }, - "generic": { - "delimiter": ", " - }, - "arg-format": { - "hp": "{0} HP ({1} {@symbol.heart})", - "hearts": "{0} {@symbol.heart}", - "damage-cause": "{0}", - "damage-cause-source": "{0} ({1})" - }, - "prefix": { - "format": "{@symbol.vertical} {0} {@symbol.vertical} ", - "challenges": "{@format('Challenges')}", - "timer": "{@format('Timer')}", - "backpack": "{@format('Backpack')}", - "position": "{@format('Position')}", - "damage": "{@format('Damage')}", - "custom": "{@format('Custom')}" - }, - "item": { - "format": "{@symbol.dot} {0} {@symbol.dot}", - "format-with-command": "{@format('{0} {@symbol.vertical} {1}')}" - }, - "actionbar": { - "format": "{@symbol.dot} {0} {@symbol.dot}" - }, - "bossbar": { - "format": "{@symbol.arrow} {0}" - }, - "timer": { - "bar": { - "format": { - "seconds": "{mm}:{ss}", - "minutes": "{mm}:{ss}", - "hours": "{hh}:{mm}:{ss}", - "day": "{d}:{hh}:{mm}:{ss}", - "days": "{d}:{hh}:{mm}:{ss}" - } - } - }, - "menu": { - "title-prefix": "{@symbol.arrow} ", - "title-delimiter": " {@symbol.vertical} ", - "title-colored": "{0}", - "title-format": "{@title-prefix}{@title-colored('{0}')}", - "title-format-page": "{@title-format('{0}')}{@title-delimiter}{@title-colored('{1}')}", - "title-name-format-sub": "{@title-colored('{0}')}{@title-delimiter}{@title-colored('{1}')}", - "item-format": "{@symbol.arrow} {0}", - "goal": { - "display": "{@name}" - }, - "timer": { - "display": "{@name}" - }, - "damage": { - "display": "{@name}" - }, - "items-blocks": { - "display": "{@name}" - }, - "challenges": { - "display": "{@name}" - }, - "settings": { - "display": "{@name}" - }, - "custom": { - "display": "{@name}" - } - }, - "category": { - "info-format": [ - " ", - "{0} {@symbol.circle} {1}" - ], - "misc_challenge": { - "*colorize*": "{0}", - "name": "*{@menu}*" - }, - "randomizer": { - "*colorize*": "{0}", - "name": "*{@menu}*", - "info": "{@misc_challenge.info}" - }, - "limited_time": { - "*colorize*": "{0}", - "name": "*{@menu}*", - "info": "{@misc_challenge.info}" - }, - "force": { - "*colorize*": "{0}", - "name": "*{@menu}*", - "info": "{@misc_challenge.info}" - }, - "world": { - "*colorize*": "{0}", - "name": "*{@menu}*", - "info": "{@misc_challenge.info}" - }, - "damage": { - "*colorize*": "{0}", - "name": "*{@menu}*", - "info": "{@misc_challenge.info}" - }, - "effect": { - "*colorize*": "{0}", - "name": "*{@menu}*", - "info": "{@misc_challenge.info}" - }, - "inventory": { - "*colorize*": "{0}", - "name": "*{@menu}*", - "info": "{@misc_challenge.info}" - }, - "movement": { - "*colorize*": "{0}", - "name": "*{@menu}*", - "info": "{@misc_challenge.info}" - }, - "entities": { - "*colorize*": "{0}", - "name": "*{@menu}*", - "info": "{@misc_challenge.info}" - }, - "extra_world": { - "*colorize*": "{0}", - "name": "*{@menu}*", - "info": "{@misc_challenge.info}" - }, - "misc_goal": { - "*colorize*": "{0}", - "name": "*{@menu}*" - }, - "kill_entity": { - "*colorize*": "{0}", - "name": "*{@menu}*", - "info": "{@misc_goal.info}" - }, - "score_points": { - "*colorize*": "{0}", - "name": "*{@menu}*", - "info": "{@misc_goal.info}" - }, - "fastest_time": { - "*colorize*": "{0}", - "name": "*{@menu}*", - "info": "{@misc_goal.info}" - }, - "force_battle": { - "*colorize*": "{0}", - "name": "*{@menu}*", - "info": "{@misc_goal.info}" - } - }, - "challenge": { - "display-format": [ - "{@symbol.arrow} {0}", - " ", - "{1}" - ], - "suffix-format": " {@symbol.vertical} {0}", - "settings-format": "{@symbol.dart} {0}", - "settings-format-lore": [ - " ", - "{0}" - ], - "subsettings-format": "{@settings-format}", - "subsettings-format-lore": "{@settings-format-lore}", - "settings-modifier-value": "{0}", - "settings-modifier-multiplier": "{0}x", - "settings-modifier-health": "{0} HP ({1} {@symbol.heart})", - "language": { - "*colorize*": "{0}" - }, - "damage-display": { - "*colorize*": "{0}" - }, - "pregame-movement": { - "*colorize*": "{0}" - }, - "difficulty": { - "*colorize*": "{0}" - }, - "hardcore-hearts": { - "*colorize*": "{0}" - }, - "random-challenge": { - "*colorize*": "{0}" - }, - "randomized-hp": { - "*colorize*": "{0}" - }, - "jump-and-run": { - "*colorize*": "{0}" - }, - "goal-ender-dragon": { - "*colorize*": "{0}" - }, - "goal-wither": { - "*colorize*": "{0}" - }, - "goal-elder-guardian": { - "*colorize*": "{0}" - }, - "goal-warden": { - "*colorize*": "{0}" - }, - "goal-all-bosses": { - "*colorize*": "{0}" - }, - "goal-all-bosses-new": { - "*colorize*": "{0}" - } - } -} diff --git a/language/locales/de.json b/language/locales/de.json new file mode 100644 index 000000000..b5b577e9b --- /dev/null +++ b/language/locales/de.json @@ -0,0 +1,2468 @@ +{ + "generic": { + "undefined": "undefiniert", + "unknown": "unbekannt", + "second": "Sekunde", + "seconds": "Sekunden", + "minute": "Minute", + "minutes": "Minuten", + "hour": "Stunde", + "hours": "Stunden", + "day": "Tag", + "days": "Tage", + "time": "Zeit", + "disabled": "Deaktiviert", + "enabled": "Aktiviert", + "customized": "Anpassen", + "console": "Konsole" + }, + "language": { + "de": "Deutsch", + "en": "Englisch" + }, + "timer": { + "bar": { + "up": "{@actionbar.format('Zeit: {0}')}", + "down": "{@actionbar.format('Zeit: {0}')}", + "paused": "{@actionbar.format('Timer pausiert')}" + }, + "messages": { + "started": "Der Timer wurde gestartet", + "paused": "Der Timer wurde pausiert", + "counting-up": "Der Timer zählt nun hoch", + "counting-down": "Der Timer zählt nun runter", + "hidden": "Der Timer ist nun versteckt", + "shown": "Der Timer ist nun sichtbar" + } + }, + "menu": { + "generic": { + "click-prefix": "[Klick] {@symbol.chevron} ", + "shift-click-prefix": "[Shift-Klick] {@symbol.chevron} ", + "right-click-prefix": "[Rechts-Klick] {@symbol.chevron} ", + "left-click-prefix": "[Links-Klick] {@symbol.chevron} " + }, + "timer": { + "name": "Timer", + "name-state": "Status", + "name-time": "Zeit", + "item-paused": [ + "{@item-format('Timer ist pausiert')}", + " ", + "{@generic.click-prefix}Timer fortsetzen" + ], + "item-started": [ + "{@item-format('Timer ist gestartet')}", + " ", + "{@generic.click-prefix}Timer pausieren" + ], + "item-hidden": [ + "{@item-format('Timer ist versteckt')}", + " ", + "{@generic.click-prefix}Timer anzeigen" + ], + "item-shown": [ + "{@item-format('Timer ist sichtbar')}", + " ", + "{@generic.click-prefix}Timer verstecken" + ], + "item-counting-up": [ + "{@item-format('Timer zählt hoch')}", + " ", + "{@generic.click-prefix}Timer auf runterzählen stellen" + ], + "item-counting-down": [ + "{@item-format('Timer zählt runter')}", + " ", + "{@generic.click-prefix}Timer auf hochzählen stellen" + ], + "item-name-format": "{@item-format('{0}: {1} ({2})')}", + "item-add-format": [ + "{@item-name-format('{4}', '{0}', '{1}')}", + " ", + "{@generic.click-prefix}+1 {3}", + "{@generic.shift-click-prefix}+{2} {4}" + ], + "item-subtract-format": [ + "{@item-name-format('{4}', '{0}', '{1}')}", + " ", + "{@generic.click-prefix}-1 {3}", + "{@generic.shift-click-prefix}-{2} {4}" + ], + "item-state-format": [ + "{@item-name-format('{2}', '{0}', '{1}')}", + " ", + "{@generic.click-prefix}Zeit zurücksetzen" + ], + "item-seconds": "{@item-state-format('{0}', '{1}', 'Sekunden')}", + "item-seconds-add": "{@item-add-format('{0}', '{1}', '{2}', 'Sekunde', 'Sekunden')}", + "item-seconds-subtract": "{@item-subtract-format('{0}', '{1}', '{2}', 'Sekunde', 'Sekunden')}", + "item-minutes": "{@item-state-format('{0}', '{1}', 'Minuten')}", + "item-minutes-add": "{@item-add-format('{0}', '{1}', '{2}', 'Minute', 'Minuten')}", + "item-minutes-subtract": "{@item-subtract-format('{0}', '{1}', '{2}', 'Minute', 'Minuten')}", + "item-hours": "{@item-state-format('{0}', '{1}', 'Stunden')}", + "item-hours-add": "{@item-add-format('{0}', '{1}', '{2}', 'Stunde', 'Stunden')}", + "item-hours-subtract": "{@item-subtract-format('{0}', '{1}', '{2}', 'Stunde', 'Stunden')}", + "item-days": "{@item-state-format('{0}', '{1}', 'Tage')}", + "item-days-add": "{@item-add-format('{0}', '{1}', '{2}', 'Tag', 'Tage')}", + "item-days-subtract": "{@item-subtract-format('{0}', '{1}', '{2}', 'Tag', 'Tage')}" + }, + "damage": { + "name": "Schaden" + }, + "goal": { + "name": "Ziele" + }, + "items-blocks": { + "name": "Items & Blöcke" + }, + "challenges": { + "name": "Challenges" + }, + "settings": { + "name": "Einstellungen" + }, + "custom": { + "name": "Individuelle Challenges" + } + }, + "category": { + "desc-most-points": [ + "Der Spieler mit den *meisten Punkten*", + "*gewinnt*, wenn der Timer *abläuft*" + ], + "misc_challenge": { + "menu": "Sonstige", + "desc": [ + "Challenges, die *keiner Kategorie*", + "zugeordnet werden können" + ], + "info": [ + "{@info-format('Aktiviert', '{0}/{1}')}" + ] + }, + "randomizer": { + "menu": "Randomizer", + "desc": [ + "Erlebe ein komplett", + "*durcheinandergebrachtes* Spiel" + ] + }, + "limited_time": { + "menu": "Limitierte Zeit", + "desc": [ + "Du wirst bei verschiedenen", + "Faktoren *zeitlich eingeschränkt*" + ] + }, + "force": { + "menu": "Zwischenziele", + "name": "*{@menu} (Force)*", + "desc": [ + "Du musst *bestimmte Zwischenziele*", + "erfüllen, sonst stirbst du" + ] + }, + "world": { + "menu": "Welteinfluss", + "desc": [ + "Die Welt wird nicht mehr", + "*wiedererkennbar* sein" + ] + }, + "damage": { + "menu": "Schaden", + "desc": [ + "Du wirst auf *verschiedenste*", + "Arten *Schaden* nehmen" + ] + }, + "effect": { + "menu": "Effekte", + "desc": [ + "Erlebe verrückte *Effekte*" + ] + }, + "inventory": { + "menu": "Inventar", + "desc": [ + "Dein *Inventar* wird *verdreht*" + ] + }, + "movement": { + "menu": "Bewegung", + "desc": [ + "Du wirst in deinen *Bewegungen*", + "*eingeschränkt*" + ] + }, + "entities": { + "menu": "Entities", + "desc": [ + "Entities werden *verändert*" + ] + }, + "extra_world": { + "menu": "Extra Welt", + "desc": [ + "Challenges, die in einer", + "*anderen Welt* spielen" + ] + }, + "misc_goal": { + "menu": "Sonstige Ziele", + "desc": [ + "Ziele, die *keiner Kategorie*", + "zugeordnet werden können" + ], + "info": "{@info-format('Aktuell', '{2}')}" + }, + "kill_entity": { + "menu": "Entity töten", + "desc": [ + "Töte *bestimmte Entities*,", + "um zu gewinnen" + ] + }, + "score_points": { + "menu": "Punkte sammeln", + "desc": [ + "Erziele die *meisten Punkte* in", + "einem *bestimmten Bereich*", + " ", + "{@desc-most-points}" + ] + }, + "fastest_time": { + "menu": "Schnellste Zeit", + "desc": [ + "Der *schnellste Spieler*, der das Ziel", + "erreicht *gewinnt* die Challenge" + ] + }, + "force_battle": { + "menu": "Force Battles", + "desc": [ + "Erfülle die *vorgegebenen Zwischenziele*,", + "um Punkte zu erhalten.", + " ", + "{@desc-most-points}" + ] + } + }, + "challenge": { + "difficulty": { + "name": "*Schwierigkeit*", + "desc": [ + "Ändert die *Schwierigkeit*", + "(*Difficulty*) des Spiels" + ], + "command-set": "Schwierigkeit auf {0} geändert", + "command-current": "Die derzeitige Schwierigkeit ist {0}" + }, + "regeneration": { + "name": "*Regeneration*", + "desc": [ + "Stellt ein, *ob* und", + "*wie* man *regeneriert*" + ] + }, + "one-life": { + "name": "*Ein Teamleben*", + "desc": [ + "*Jeder* stirbt, wenn *einer stirbt*" + ] + }, + "respawn": { + "name": "*Respawn*", + "desc": [ + "Wenn du *stirbst*, wirst du nicht zu einem *Zuschauer*" + ] + }, + "split-health": { + "name": "*Geteilte Herzen*", + "desc": [ + "Stellt ein, ob sich *alle*", + "*Spieler* eine *Gesundheit teilen*" + ] + }, + "damage-display": { + "name": "*Damage Display*", + "desc": [ + "Es wird im Chat angezeigt,", + "wenn jemand *Schaden* bekommt" + ] + }, + "language": { + "name": "*Sprache*", + "desc": [ + "Ändert die *Sprache* des Plugins" + ], + "command-disabled": "Diese Funktion ist derzeit deaktiviert", + "command-unknown": "Diese Sprache ({0}) wird nicht unterstützt", + "command-current": "Die derzeitige Sprache ist {0}", + "command-changing": "Die Sprache wird geändert...", + "command-changed": "Die Sprache wurde auf {0} ({1}) gesetzt" + }, + "pregame-movement": { + "name": "*Pregame Movement*", + "desc": [ + "Du kannst dich *bewegen*,", + "bevor der Timer *gestartet* wurde" + ], + "title": [ + "Warte..", + "{@symbol.arrow} Der Timer ist gestoppt.." + ] + }, + "death-message": { + "name": "*Todesnachrichten*", + "desc": [ + "Schaltet *Todesnachrichten* ein/aus" + ] + }, + "health-display": { + "name": "*Health Display*", + "desc": [ + "Die *Herzen* aller Spieler", + "werden in der *Tablist* angezeigt" + ] + }, + "position": { + "name": "*Positions*", + "desc": [ + "Erlaubt es dir *Positionen*", + "mit */pos* zu *markieren*" + ] + }, + "death-position": { + "name": "*Death Position*", + "desc": [ + "Wenn du stirbst, wird mit */pos* ", + "eine *Position an deinem Todespunkt* erstellt" + ] + }, + "glow": { + "name": "*Playerglow*", + "desc": [ + "*Spieler* sind durch die *Wand* sichtbar" + ] + }, + "no-item-damage": { + "name": "*Kein Itemschaden*", + "desc": [ + "*Items* sind *unzerstörbar*" + ] + }, + "mob-griefing": { + "name": "*Mob Griefing*", + "desc": [ + "Monster können *nichts zerstören*" + ] + }, + "keep-inventory": { + "name": "*Keep Inventory*", + "desc": [ + "Du verlierst keine *Items*,", + "wenn du *stirbst*" + ] + }, + "backpack": { + "name": "*Backpack*", + "desc": [ + "Erlaubt es dir, *deinen Backpack* oder den", + "*Team Backpack* mit */backpack* zu öffnen" + ] + }, + "enderchest-command": { + "name": "*Enderchest Command*", + "desc": [ + "Wenn du */ec* ausführst, öffnet", + "sich deine *Enderchest*" + ] + }, + "timber": { + "name": "*Timber*", + "desc": [ + "Du kannst einen *Baum* zerstören,", + "indem du *einen Block* des Baumes abbaust" + ] + }, + "pvp": { + "name": "*PvP*", + "desc": [] + }, + "no-hit-delay": { + "name": "*NoHitDelay*", + "desc": [ + "Nachdem du *Schaden* genommen hast,", + "kannst du *sofort* wieder Schaden *bekommen*" + ] + }, + "max-health": { + "name": "*Maximale Herzen*", + "desc": [ + "Stellt ein, wie viele", + "Herzen man hat" + ] + }, + "damage-multiplier": { + "name": "*Damage Multiplier*", + "desc": [ + "Schaden, den du nimmst, wird *multipliziert*" + ] + }, + "cut-clean": { + "name": "*CutClean*", + "desc": [ + "Verschiedene *Einstellungen*, die", + "das *Farmen* von Items *einfacher* machen" + ] + }, + "no-offhand": { + "name": "*Keine Offhand*", + "desc": [ + "Die *zweite Hand* wird geblockt" + ] + }, + "immediate-respawn": { + "name": "*Direkter Respawn*", + "desc": [ + "Wenn du stirbst, *respawnst* du *automatisch,*", + "ohne den *Death Screen* zu sehen" + ] + }, + "slot-limit": { + "name": "*Inventar Slots*", + "desc": [ + "Stellt ein, wie viele *Inventar*", + "*Slots* nutzbar sind" + ], + "settings": "{0} von max. {1} Slots" + }, + "old-pvp": { + "name": "*1.8 PvP*", + "desc": [ + "Das *alte 1.8 PvP System* wird genutzt", + "Es gibt keinen *Attack Cooldown*" + ] + }, + "totem-save-death": { + "name": "*Challenge Tod Rettung*", + "desc": [ + "Wenn du durch eine Challenge *instant*", + "*stirbst*, können *Totems* dich retten" + ] + }, + "soup": { + "name": "*Suppen Heilung*", + "desc": [ + "Wenn du eine *Pilzsuppe* benutzt,", + "wirst du um *4 Herzen* geheilt" + ] + }, + "hardcore-hearts": { + "name": "*Hardcore Herzen*", + "desc": [ + "Die *Herzen* werden im *Hardcore-Stil* angezeigt", + "Um die Änderung zu sehen, *musst* du *rejoinen*" + ] + }, + "random-challenge": { + "name": "*Random Challenge*", + "desc": [ + "In einem *gesetzten Intervall*", + "wird eine *zufällige Challenge* aktiviert" + ], + "challenge-enabled": [ + "Die Challenge {0} wurde aktiviert", + "{1}" + ], + "bossbar-waiting": "{@bossbar.format('Warten auf neue Challenge..')}", + "bossbar-current": "{@bossbar.format('Challenge {0}')}" + }, + "randomized-hp": { + "name": "*Zufällige HP*", + "desc": [ + "Die *Leben* aller *Mobs*", + "sind *zufällig*" + ] + }, + "block-randomizer": { + "name": "*Block Randomizer*", + "desc": [ + "Jeder *Block* droppt ein *zufälliges Item*" + ] + }, + "crafting-randomizer": { + "name": "*Crafting Randomizer*", + "desc": [ + "Wenn du *etwas craftest*, bekommst du ein *zufälliges Item*" + ] + }, + "hotbar-randomizer": { + "name": "*HotBar Randomizer*", + "desc": [ + "Alle *paar Minuten* erhält jeder Spieler *zufällige Items*" + ] + }, + "entity-loot-randomizer": { + "name": "*Entity Loot Randomizer*", + "desc": [ + "Alle Mob Drops sind *zufällig vertauscht*." + ], + "command-disabled": "Die Entity Loot Randomizer Challenge ist aktuell deaktiviert", + "command-nothing": "Der Loot von {0} wird durch kein spezielles Entity gedroppt", + "command-result": [ + "{0} droppt den Loot von {1}", + "Der Loot von {0} wird von {2} gedroppt" + ] + }, + "mob-randomizer": { + "name": "*Mob Randomizer*", + "desc": [ + "Wenn ein *Entity* spawnt, spawnt ein *anderes*" + ] + }, + "random-dropping": { + "name": "*Zufälliges Item Droppen*", + "desc": [ + "Alle paar Sekunden wird ein *zufälliges*", + "*Item* aus deinem Inventar *gedroppt*" + ] + }, + "random-item-removing": { + "name": "*Zufälliges Item Löschen*", + "desc": [ + "Alle paar Sekunden wird ein *zufälliges*", + "*Item* aus deinem Inventar *gelöscht*" + ] + }, + "random-swapping": { + "name": "*Zufälliges Item Mischen*", + "desc": [ + "Alle paar Sekunden wird ein", + "*zufälliges Item* aus deinem Inventar", + "mit einem anderem *getauscht*" + ] + }, + "random-item": { + "name": "*Random Items*", + "desc": [ + "Ein *zufälliger Spieler* erhält alle paar", + "*Sekunden* ein *zufälliges Item*" + ] + }, + "random-event": { + "name": "*Random Events*", + "desc": [ + "Alle *paar Minuten* wird eines von", + "*{0} random Events* aktiviert" + ], + "entities": [ + "Ist das hier ein Zoo?", + "Wo kommt ihr denn her?", + "Was macht ihr denn hier?" + ], + "fly": [ + "Guten Flug :)", + "I believe I can fly..", + "So fühlt sich also fliegen an" + ], + "hole": [ + "Du bist aber ganz schön tief gefallen", + "Von ganz oben nach ganz unten..", + "Wo kommt denn das Loch her?" + ], + "ores": [ + "Wo sind denn die ganzen Erze hin?", + "Gibt es hier keine Erze?", + "Gab es hier mal Erze?" + ], + "sickness": [ + "Bist du etwa krank?", + "Was geht denn jetzt ab" + ], + "speed": [ + "Sonic? Bist du es?", + "Woahh! Das ist aber schnell" + ], + "webs": [ + "Liegen die schon lange hier?" + ] + }, + "mob-damage-teleport": { + "name": "*Mob Tausch Beim Schlagen*", + "desc": [ + "Jedes mal, wenn du einen *Mob schlägst*,", + "tauschst du mit einem *zufälligem Mob* die Position" + ] + }, + "force-height": { + "name": "*Force Height*", + "desc": [ + "Alle *paar Minuten* musst du auf", + "eine *bestimmte Höhe* oder du stirbst" + ], + "bossbar-instruction": "{@bossbar.format-arg('Höhe {0}', '{1}')}", + "bossbar-waiting": "{@bossbar.format('Warten auf nächste Höhe..')}", + "fail": "{0} war auf der falschen Höhe ({1})", + "success": "Alle Spieler waren auf der richtigen Höhe" + }, + "force-block": { + "name": "*Force Block*", + "desc": [ + "Alle *paar Minuten* musst du auf", + "einen *bestimmten Block* oder du stirbst" + ], + "bossbar-instruction": "{@symbol.arrow} Block {0} {@symbol.vertical} {1}", + "bossbar-waiting": "{@symbol.arrow} Warten auf nächsten Block..", + "fail": "{0} war auf dem falschen Block ({1})", + "success": "Alle Spieler waren auf dem richtigen Block" + }, + "force-mob": { + "name": "*Force Mob*", + "desc": [ + "Alle *paar Minuten* musst du", + "ein *bestimmtes Entity* killen oder du stirbst" + ], + "bossbar-instruction": "{@symbol.arrow} Mob {0} {@symbol.vertical} {1}", + "bossbar-waiting": "{@symbol.arrow} Warten auf nächsten Mob..", + "fail": "Das Mob {0} wurde nicht getötet", + "success": "{0} hat das Mob {1} getötet" + }, + "force-item": { + "name": "*Force Item*", + "desc": [ + "Alle *paar Minuten* musst du", + "ein *bestimmtes Item* finden oder du stirbst" + ], + "bossbar-instruction": "{@symbol.arrow} Item {0} {@symbol.vertical} {1}", + "bossbar-waiting": "{@symbol.arrow} Warten auf nächstes Item..", + "fail": "Das Item {0} wurde nicht gefunden", + "success": "{0} hat das Item {1} gefunden" + }, + "force-biome": { + "name": "*Force Biome*", + "desc": [ + "Alle *paar Minuten* musst du in", + "ein *bestimmtes Biom* oder du stirbst", + "Je *seltener* das Biom ist, desto *mehr Zeit* hast du" + ], + "bossbar-instruction": "{@symbol.arrow} Biom {0} {@symbol.vertical} {1}", + "bossbar-waiting": "{@symbol.arrow} Warten auf nächstes Biom..", + "fail": "Das Biom {0} wurde nicht gefunden", + "success": "{0} hat das Biom {1} gefunden" + }, + "hydra": { + "name": "*Hydra*", + "desc": [ + "Wenn du einen *Mob* tötest,", + "spawnen *zwei* neue" + ] + }, + "hydra-plus": { + "name": "*Hydra Plus*", + "desc": [ + "Wenn du einen *Mob* tötest,", + "spawnen *doppelt* so viele", + "wie beim *vorherigen* mal", + " ", + "Maximum beträgt *512* Mobs gleichzeitig" + ] + }, + "duped-spawning": { + "name": "*Doppeltes Spawning*", + "desc": [ + "Wenn ein Monster *spawnt*,", + "spawnt es *zweimal*" + ] + }, + "jump-entity": { + "name": "*Jump Entity*", + "desc": [ + "Wenn du *springst*, *spawnt* ein", + "zufälliges *Entity*" + ] + }, + "invisible-mobs": { + "name": "*Unsichtbare Mobs*", + "desc": [ + "Alle *Mobs* haben einen", + "*Unsichtbarkeits* Effekt" + ] + }, + "stone-sight": { + "name": "*Stein Blick*", + "desc": [ + "*Mobs*, denen du in die *Augen*", + "*schaust*, werden zu *Stein*" + ] + }, + "mob-sight-damage": { + "name": "*Mob Blick Schaden*", + "desc": [ + "Wenn du einen *Mob* in die *Augen*", + "*schaust*, erleidest du *Schaden*" + ] + }, + "all-mobs-to-death-position": { + "name": "*Alle Monster zum Todespunkt*", + "desc": [ + "Wenn ein *Mob* von einem Spieler", + "*getötet* wird, werden *alle* anderen", + "Monster vom *selben Typen* zum", + "*Todespunkt* teleportiert" + ] + }, + "respawn-end": { + "name": "*Mobs respawnen im End*", + "desc": [ + "Mobs, die *getötet werden*,", + "respawnen im *End*" + ], + "bossbar": "{@symbol.arrow} Respawnte Mobs im End {@symbol.vertical} {0}" + }, + "mob-transformation": { + "name": "*Mob Verwandlung*", + "desc": [ + "Wenn du einen Mob schlägst, *verwandelt* sich", + "dieser in den *letzen Mob*, den du *geschlagen* hast" + ], + "bossbar": "{@symbol.arrow} Letzter Mob {@symbol.vertical} {0}" + }, + "block-mobs": { + "name": "*Mob Blöcke*", + "desc": [ + "Aus jedem abgebautem Block, *spawnt ein Mob*,", + "dass *getötet* werden muss, um den Block *zu erhalten*" + ] + }, + "damage-per-block": { + "name": "*Schaden pro Block*", + "desc": [ + "Du bekommst *Schaden* durch", + "jeden *Block*, den du gehst" + ] + }, + "sneak-damage": { + "name": "*Schaden pro Schleichen*", + "desc": [ + "Du *erleidest* den gesetzten", + "*Schaden*, wenn du *schleichst*" + ], + "failed": "{0} ist geschlichen" + }, + "jump-damage": { + "name": "*Schaden pro Sprung*", + "desc": [ + "Du *erleidest* den gesetzen", + "*Schaden*, wenn du *springst*" + ], + "failed": "{0} ist gesprungen" + }, + "block-break-damage": { + "name": "*Block Break Damage*", + "desc": [ + "Wenn du einen *Block abbaust*,", + "*erleidest* du die gesetze Anzahl *schaden*" + ] + }, + "block-place-damage": { + "name": "*Block Place Damage*", + "desc": [ + "Wenn du einen *Block plazierst*,", + "*erleidest* du die gesetze Anzahl *schaden*" + ] + }, + "advancement-damage": { + "name": "*Advancement Schaden*", + "desc": [ + "Du bekommst für jedes neue *Advancement*", + "die gesetze Anzahl *Schaden*" + ] + }, + "damage-item": { + "name": "*Schaden pro Item*", + "desc": [ + "Wenn du ein *Item aufhebst* oder es", + "in deinem Inventar *anklickst* erleidest", + "du *0,5 {@symbol.heart}* multipliziert mit der Anzahl der Items" + ] + }, + "water-allergy": { + "name": "*Wasserallergie*", + "desc": [ + "Wenn du in *Wasser* bist,", + "*erleidest* du den gesetzen Schaden" + ] + }, + "death-on-fall": { + "name": "*Tod bei Fallschaden*", + "desc": [ + "Wenn du *Fallschaden* erleidest,", + "*stirbst* du sofort" + ] + }, + "reversed-damage": { + "name": "*Reversed Damage*", + "desc": [ + "Wenn du Entities *schlägst* oder *abschießt*,", + "bekommst du den *gleichen Schaden*" + ] + }, + "freeze": { + "name": "*Freeze Challenge*", + "desc": [ + "Für *jedes Herz*, das du *Schaden* erleidest, kannst", + "du dich für eine bestimmte Zeit *nicht bewegen*" + ] + }, + "delay-damage": { + "name": "*Verzögerter Schaden*", + "desc": [ + "Der *schaden* von allen *Spielern* ist", + "zusammenaddiert und wird nach einer bestimmten *Zeit* hinzugefügt." + ] + }, + "chunk-effect": { + "name": "*Zufällige Chunk Effekte*", + "desc": [ + "In *jedem Chunk* bekommst du", + "einen *zufälligen Effekt*" + ] + }, + "block-effect": { + "name": "*Zufällige Block Effekte*", + "desc": [ + "Auf *jedem Block* bekommst du", + "einen *zufälligen Effekt*" + ] + }, + "entity-effect": { + "name": "*Mobs Haben Random Effekte*", + "desc": [ + "*Jedes Mob* hat einen zufälligen", + "Effekt auf *höchster Stufe*" + ] + }, + "random-effect": { + "name": "*Random Effekte*", + "desc": [ + "Du bekommst in einem gesetzen *Intervall*", + "einen *zufälligen Trank Effekt*" + ] + }, + "permanent-effect-on-damage": { + "name": "*Permanente Effekte*", + "desc": [ + "Du bekommst immer, wenn du *Schaden*", + "erleidest, einen *zufälligen Effekt*" + ], + "new-effect": "Effekt {0} {1}" + }, + "infection": { + "name": "*Infection Challenge*", + "desc": [ + "Du musst *2 Blöcke* Abstand von allen ", + "*Mobs* halten oder du wirst *krank*" + ] + }, + "surface-hole": { + "name": "*Surface Hole*", + "desc": [ + "Hinter dir *verschwindet* der", + "*Boden* bis ins *Void*" + ] + }, + "bedrock-walls": { + "name": "*Bedrock Walls*", + "desc": [ + "Hinter dir *spawnen* riesige", + "*Wände* aus *Bedrock*" + ] + }, + "bedrock-path": { + "name": "*Bedrock Path*", + "desc": [ + "*Unter dir* entsteht die", + "ganze Zeit *Bedrock*" + ] + }, + "floor-is-lava": { + "name": "*Der Boden ist Lava*", + "desc": [ + "Alle *Blöcke* unter dir verwandeln sich", + "erst zu *Magma* und dann zu *Lava*" + ] + }, + "chunk-deconstruction": { + "name": "*Chunk Deconstruction*", + "desc": [ + "*Chunks*, in denen sich Spieler befinden,", + "*bauen* sich von *oben* aus ab" + ] + }, + "all-blocks-disappear": { + "name": "*Alle Blöcke verschwinden*", + "desc": [ + "Bei verschiedenen *Interaktionen*", + "verschwinden alle *Blöcke* im *Chunk*", + "eines *bestimmten Types*" + ] + }, + "anvil-rain": { + "name": "*Amboss Regen*", + "desc": [ + "Vom *Himmel* fallen *Ambosse*" + ] + }, + "tsunami": { + "name": "*Tsunami*", + "desc": [ + "In einem *gesetztem Intervall*", + "*steigt* das *Wasser* in der *Overworld*", + "und die *Lava* in im *Nether*", + " ", + "Sollte mit wenigen Personen gespielt werden!" + ], + "bossbar-lava": "{@symbol.arrow} Lavahöhe: {0}", + "bossbar-water": "{@symbol.arrow} Wasserhöhe: {0}" + }, + "repeat-in-chunk": { + "name": "*Wiederholende Chunks*", + "desc": [ + "Blöcke die *platziert oder zerstört* werden,", + "werden in *jedem Chunk* platziert / zerstört" + ] + }, + "snake": { + "name": "*Snake*", + "desc": [ + "*Jeder Spieler* zieht eine", + "tödliche Linie hinter sich her" + ], + "failed": "{0} ist über die Linie getreten" + }, + "blocks-fly": { + "name": "*Blöcke fliegen in die Luft*", + "desc": [ + "*Blöcke*, auf denen du *gelaufen* bist,", + "fliegen nach *einer Sekunde* in die *Luft*" + ] + }, + "blocks-disappear-time": { + "name": "*Blöcke verschwinden nach Zeit*", + "desc": [ + "Blöcke, die du *platzierst*, *verschwinden*", + "nach ein *paar Sekunden* wieder" + ] + }, + "loop": { + "name": "*Wiederholungs Challenge*", + "desc": [ + "Verschiedene Aktionen *wiederholen* sich", + "unendlich oft, bis ein Spieler *schleicht*" + ], + "cleared": "{0} Loops abgebrochen" + }, + "ice-floor": { + "name": "*Eisboden*", + "desc": [ + "Unter dir wird *Luft* zu einem", + "*3x3* Boden aus *Eis*" + ], + "bossbar": "{@symbol.arrow} Eisboden {@symbol.vertical} {0}" + }, + "level-border": { + "name": "*Level = Border*", + "desc": [ + "Die *Border-Größe* passt sich dem *Spieler*", + "mit den *meisten Leveln* an." + ], + "bossbar": "{@symbol.arrow} Border Größe {@symbol.vertical} {0}" + }, + "chunk-deletion": { + "name": "*Chunk Löschung*", + "desc": [ + "*Chunks*, in denen sich *Spieler* befinden,", + "werden nach gegebener *Zeit* komplett *gelöscht*" + ], + "bossbar": "{@symbol.arrow} Zeit übrig im Chunk {0}s" + }, + "permanent-item": { + "name": "*Permanente Items*", + "desc": [ + "*Items* können nicht gedroppt", + "oder *weggelegt* werden" + ] + }, + "no-duped-items": { + "name": "*Keine Doppelten Items*", + "desc": [ + "Wenn *2 Spieler* das gleiche *Item* im", + "Inventar haben, *sterben* beide" + ], + "failed": "{0} und {1} hatten beide {2} im Inventar" + }, + "damage-inv-clear": { + "name": "*Damage Inventory Clear*", + "desc": [ + "Die *Inventare* aller Spieler werden *geleert*,", + "wenn ein *Spieler* Schaden erleidet" + ] + }, + "uncraft-items": { + "name": "*Items craften sich zurück*", + "desc": [ + "Alle *Items* in deinem Inventar *craften*", + "sich alle paar Sekunden *zurück*" + ] + }, + "missing-items": { + "name": "*Items Fehlen*", + "desc": [ + "Alle paar Minuten *verschwindet* ein *Item* aus", + "deinem *Inventar* und du musst *erraten*, welches" + ], + "inventory": "{0}Welches Item fehlt?", + "inventory-open": "[GUI öffnen]" + }, + "pickup-launch": { + "name": "*Pickup Boost*", + "desc": [ + "Wenn du ein *Item aufhebst*,", + "wirst du *in die Luft* geschleudert" + ] + }, + "block-chunk-item-remove": { + "name": "*Movement Item Remove*", + "desc": [ + "Es wird für jeden *Block* / *Chunk*,", + "den du dich *fortbewegst*, ein Item", + "aus deinem Inventar *gelöscht*" + ], + "block": "Block", + "chunk": "Chunk" + }, + "traffic-light": { + "name": "*Ampelchallenge*", + "desc": [ + "Die *Ampel* schaltet alle paar Minuten um", + "Wenn du bei *rot* gehst, stirbst du" + ], + "fail": "{0} ist über rot gegangen" + }, + "hunger-block": { + "name": "*Hunger pro Block*", + "desc": [ + "Du bekommst *Hunger* durch", + "jeden *Block*, den du gehst" + ] + }, + "only-down": { + "name": "*Nur nach unten*", + "desc": [ + "Wenn du *einen Block* nach", + "*oben* gehst, *stirbst* du" + ], + "failed": "{0} ist einen Block nach oben gegangen" + }, + "only-dirt": { + "name": "*Only Dirt*", + "desc": [ + "Wenn du nicht auf *Erde*", + "stehst, *stirbst* du" + ], + "failed": "{0} stand nicht auf Erde" + }, + "higher-jumps": { + "name": "*Higher Jumps*", + "desc": [ + "*Umso öfter* du springst,", + "*desto höher* springst du" + ] + }, + "always-running": { + "name": "*Always Running*", + "desc": [ + "Du kannst *nicht aufhören*, vorwärts zu laufen" + ] + }, + "dont-stop-running": { + "name": "*Nicht stehen bleiben*", + "desc": [ + "Du darfst nur eine bestimmte Zeit", + "*stehen bleiben* bevor du *stirbst*" + ], + "bossbar": "{@symbol.arrow} Bewege dich in {@symbol.vertical} {0}", + "stopped-moving": "{0} hat sich zu lange nicht bewegt" + }, + "no-mouse-move": { + "name": "*Mausbewegung Schaden*", + "desc": [ + "Wenn du deinen *Blick bewegst*,", + "erleidest du den *gesetzen Schaden*" + ], + "failed": "{0} hat seine Maus bewegt" + }, + "five-hundred-blocks": { + "name": "*500 Blöcke*", + "desc": [ + "*Alle* 500 Blöcke, die du *läufst*,", + "bekommst du *64* eines *zufälliges Items*.", + "Es droppen *keine Items* von", + "*Blöcken* und *Entities* mehr." + ], + "bossbar": "{@symbol.arrow} Blöcke Gelaufen {@symbol.vertical} {0} / {1}", + "subtitle": "{0} Blöcke" + }, + "max-biome-time": { + "name": "*Maximale Biom Zeit*", + "desc": [ + "Die *Zeit*, die du in jedem *Biom*", + "sein darfst, ist *begrenzt*" + ], + "bossbar": "{@symbol.arrow} Zeit übrig in {0} {@symbol.vertical} {1}s" + }, + "max-height-time": { + "name": "*Maximale Höhen Zeit*", + "desc": [ + "Die *Zeit*, die du auf jeder *Höhe*", + "sein darfst, ist *begrenzt*" + ], + "bossbar": "{@symbol.arrow} Zeit übrig auf {0} {@symbol.vertical} {1}s" + }, + "water-mlg": { + "name": "*Water MLG*", + "desc": [ + "Du musst *immer wieder*", + "einen *Water MLG* absolvieren" + ] + }, + "jump-and-run": { + "name": "*JumpAndRun*", + "desc": [ + "In einem gesetzten *Intervall* muss ein", + "*zufälliger Spieler* ein *JumpAndRun* absolvieren", + "Schafft er es *nicht*, *stirbt* er" + ], + "actionbar": "{@actionbar.format('*Jump & Run* {@symbol.vertical} {0} / {1}')}", + "countdown": "Nächstes JumpAndRun in {0} Sekunden", + "countdown-one": "Nächstes JumpAndRun in einer Sekunde", + "finished": "{0} hat das JumpAndRun geschafft" + }, + "one-durability": { + "name": "*Eine Haltbarkeit*", + "desc": [ + "*Items* gehen nach *einer* Benutzung *kaputt*" + ] + }, + "no-trading": { + "name": "*Kein Handeln*", + "desc": [ + "Du kannst *nicht* mit", + "Villager *handeln*" + ] + }, + "no-exp": { + "name": "*Keine XP*", + "desc": [ + "Wenn du *XP* aufsammelst, stirbst du" + ], + "picked-up": "{0} hat XP aufgesammelt" + }, + "food-once": { + "name": "*Food Once*", + "desc": [ + "Du kannst jedes *Essen*", + "nur einmal *essen*" + ], + "failed": "{0} ist an {1} erstickt", + "new-food": "Du hast {1} gegessen", + "new-food-team": "{0} hat {1} gegessen", + "everyone": "Jeder", + "player": "Spieler" + }, + "consume-launch": { + "name": "*Essens Boost*", + "desc": [ + "Wenn du ein *Item isst*,", + "wirst du *in die Luft* geschleudert" + ] + }, + "low-drop-rate": { + "name": "*Low Drop Chance*", + "desc": [ + "Die *Dropchance* jedes *Blockes* wird auf die", + "angegebene *Prozentzahl* gesetzt" + ] + }, + "ender-games": { + "name": "*Ender Games*", + "desc": [ + "Alle *paar Minuten* wirst du", + "mit einem *zufälligem Entity* aus", + "einem *200 Block* Radius *getauscht*" + ], + "teleport": "Du wurdest mit {0} getauscht" + }, + "invert-health": { + "name": "*Invert Health*", + "desc": [ + "Alle paar Minuten werden deine *Herzen invertiert*.", + "Wenn du *8 Herzen* hast,", + "hast du danach *2 Herzen* und umgekehrt." + ], + "inverted": "Deine Herzen wurden invertiert" + }, + "no-shared-advancements": { + "name": "*Keine Gleichen Advancements*", + "desc": [ + "Spieler dürfen *nicht* die *gleichen Advancements*", + "abschließen, sonst *stirbt* der *Spieler*" + ] + }, + "quiz": { + "name": "*Quiz*", + "desc": [ + "Alle *paar Minuten* muss ein *zufälliger*", + "*Spieler* eine *Quizfrage* beantworten" + ] + }, + "goal-ender-dragon": { + "name": "*Enderdrache*", + "desc": [ + "Töte den *Enderdrachen* um zu gewinnen" + ] + }, + "goal-wither": { + "name": "*Wither*", + "desc": [ + "Töte einen *Wither* um zu gewinnen" + ] + }, + "goal-elder-guardian": { + "name": "*Elder Guardian*", + "desc": [ + "Töte einen *Großen Wächter* um zu gewinnen" + ] + }, + "goal-warden": { + "name": "*Warden*", + "desc": [ + "Töte einen *Warden* um zu gewinnen" + ] + }, + "goal-all-bosses": { + "name": "*Alle Bosse*", + "desc": [ + "Es müssen *alle Bosse* einmal", + "*getötet* werden, um zu *gewinnen*", + " ", + "({@goal-ender-dragon.name}, {@goal-wither.name}, {@goal-elder-guardian.name})" + ] + }, + "goal-all-bosses-new": { + "name": "*Alle Bosse (+ Warden)*", + "desc": [ + "Es müssen *alle Bosse* einmal", + "*getötet* werden, um zu *gewinnen*", + " ", + "({@goal-ender-dragon.name}, {@goal-wither.name}, {@goal-elder-guardian.name}, {@goal-warden.name})" + ] + }, + "iron-golem": { + "name": "*Eisengolem*", + "desc": [ + "Töte einen *Eisengolem* um zu gewinnen" + ] + }, + "snow-golem": { + "name": "*Schneemann*", + "desc": [ + "Töte einen *Schneemann* um zu gewinnen" + ] + }, + "all-mobs": { + "name": "*Alle Mobs*", + "desc": [ + "Es müssen *alle Mobs* einmal", + "*getötet* werden, um zu *gewinnen*" + ] + }, + "all-monster": { + "name": "*Alle Monster*", + "desc": [ + "Es müssen *alle Monster* einmal", + "*getötet* werden, um zu *gewinnen*" + ] + }, + "most-deaths": { + "name": "*Meiste Tode*", + "desc": [ + "Wer die meisten *verschiedenen Tode*", + "sammelt, *gewinnt*" + ] + }, + "most-items": { + "name": "*Meisten Items*", + "desc": [ + "Wer die meisten *verschiedenen Items*", + "findet, *gewinnt*" + ] + }, + "mine-most-blocks": { + "name": "*Meisten Blöcke*", + "desc": [ + "Wer die *meisten Blöcke* abbaut, gewinnt" + ] + }, + "most-xp": { + "name": "*Meiste XP*", + "desc": [ + "Wer die meiste *XP sammelt*, gewinnt" + ] + }, + "most-emeralds": { + "name": "*Meisten Emeralds*", + "desc": [ + "Der Spieler mit den *meisten*", + "*Emeralds* gewinnt" + ] + }, + "most-ores": { + "name": "*Meiste Erze*", + "desc": [ + "Der Spieler, der am *meisten Erze*", + "*abgebaut* hat, gewinnt" + ] + }, + "eat-most": { + "name": "*Am Meisten Essen*", + "desc": [ + "Der Spieler, der am *meisten isst*, gewinnt" + ] + }, + "first-one-to-die": { + "name": "*Erster Tod*", + "desc": [ + "Wer als *erstes stirbt*, gewinnt" + ] + }, + "collect-wood": { + "name": "*Holzarten Sammeln*", + "desc": [ + "Wer als *erstes* alle *Holzarten*, die", + "*eingestellt* sind, gesammelt hat, gewinnt" + ] + }, + "finish-raid": { + "name": "*Raid Gewinnen*", + "desc": [ + "Der erste Spieler, der einen *Raid*", + "*abschließt*, gewinnt" + ] + }, + "all-advancements": { + "name": "*Alle Advancements*", + "desc": [ + "Der Spieler, der als erstes *alle*", + "Errungenschaften *erhalten hat*, gewinnt" + ] + }, + "max-height": { + "name": "*Maximale Höhe*", + "desc": [ + "Der Spieler, der als *erstes* die", + "Höhe *{0}* erreicht hat, gewinnt" + ] + }, + "min-height": { + "name": "*Minimale Höhe*", + "desc": [ + "Der Spieler, der als *erstes* die", + "Höhe *{0}* erreicht hat, gewinnt" + ] + }, + "race": { + "name": "*Wettrennen*", + "desc": [ + "Der Spieler, der als *erstes* an", + "einer *zufälligen* Position ist, gewinnt" + ] + }, + "find-elytra": { + "name": "*Elytra Finden*", + "desc": [ + "Der Spieler, der als *erstes*", + "eine *Elytra findet*, gewinnt" + ] + }, + "eat-cake": { + "name": "*Kuchen Essen*", + "desc": [ + "Der Spieler, der als *erstes*", + "einen *Kuchen isst*, gewinnt" + ] + }, + "collect-horse-armor": { + "name": "*Sammle Pferderüstungen*", + "desc": [ + "Der Spieler, der als *erstes*", + "*alle Pferderüstungen* hat, gewinnt" + ] + }, + "collect-ice": { + "name": "*Sammle Eisblöcke*", + "desc": [ + "Der Spieler, der als *erstes*", + "*alle Eisblöcke* und Schnee hat, gewinnt" + ] + }, + "collect-swords": { + "name": "*Sammle Schwerter*", + "desc": [ + "Der Spieler, der als *erstes*", + "*alle Schwerter* hat, gewinnt" + ] + }, + "collect-workstations": { + "name": "*Sammle Arbeitsblöcke*", + "desc": [ + "Der Spieler, der als *erstes*", + "*alle Villager Arbeitsblöcke* hat, gewinnt" + ] + }, + "get-full-health": { + "name": "*Regeneriere Volle Leben*", + "desc": [ + "The first player to gain full health wins." + ] + }, + "force-item-battle": { + "name": "*Force Item Battle*", + "desc": [ + "Jeder Spieler bekommt ein *zufälliges Item*,", + "das er finden muss.", + "Wer am Ende die *meisten Items* hat, gewinnt" + ] + }, + "force-mob-battle": { + "name": "*Force Mob Battle*", + "desc": [ + "Jeder Spieler bekommt ein *zufälliges Mob*,", + "das er töten muss." + ] + }, + "force-advancement-battle": { + "name": "*Force Advancement Battle*", + "desc": [ + "Jeder Spieler bekommt ein *zufälliges*", + "*Advancement*, welches er erreichen muss." + ] + }, + "force-block-battle": { + "name": "*Force Block Battle*", + "desc": [ + "Jeder Spieler bekommt einen *zufälligen*", + "*Block*, auf welchem er stehen muss" + ] + }, + "force-biome-battle": { + "name": "*Force Biome Battle*", + "desc": [ + "Jeder Spieler bekommt ein *zufälliges Biom*,", + "das er betreten muss" + ] + }, + "force-damage-battle": { + "name": "*Force Damage Battle*", + "desc": [ + "Jeder Spieler bekommt eine *zufällige Anzahl Schaden*,", + "die er *erhalten* muss" + ] + }, + "force-height-battle": { + "name": "*Force Height Battle*", + "desc": [ + "Jeder Spieler bekommt eine *zufällige Höhe*,", + "auf der er sich befinden muss." + ] + }, + "force-position-battle": { + "name": "*Force Position Battle*", + "desc": [ + "Jeder Spieler bekommt eine *zufällige Position*,", + "die er erreichen muss." + ] + }, + "extreme-force-battle": { + "name": "*Extreme Force Battle*", + "desc": [ + "Jeder Spieler bekommt ein *zufälliges Ziel*,", + "welches er erreichen muss" + ] + }, + "last-man-standing": { + "name": "*Last Man Standing*", + "desc": [ + "Wer *am Ende* noch *lebt*, gewinnt" + ] + }, + "collect-all-items": { + "name": "*Alle Items*", + "desc": [ + "Finde *alle Items*, die es *in Minecraft gibt*" + ] + }, + "damage-teleport": { + "name": "*Schaden Random Teleport*", + "desc": [ + "Du wirst *zufällig teleportiert*,", + "wenn du *Schaden* erleidest" + ] + }, + "zero-hearts": { + "name": "*Null Herzen*", + "desc": [ + "Nach einer *Schutzzeit* musst du", + "dauerhaft Absorption bekommen" + ], + "bossbar": "{@symbol.arrow} Schutzzeit {@symbol.vertical} {0}s" + } + }, + "title": { + "timer-started": [ + " ", + "{@symbol.arrow} Timer fortgesetzt" + ], + "timer-paused": [ + " ", + "{@symbol.arrow} Timer pausiert" + ], + "challenge-enabled": [ + "{0}", + "{@symbol.check} {@symbol.vertical} Aktiviert" + ], + "challenge-disabled": [ + "{0}", + "{@symbol.x} Deaktiviert" + ], + "challenge-value-changed": [ + "{0}", + "{@symbol.arrow} {1}" + ], + "goal-enabled": [ + "{0}", + "{@symbol.check} {@symbol.vertical} Ziel gewählt" + ], + "goal-disabled": [ + "{0}", + "{@symbol.x} Ziel deaktiviert" + ] + }, + "command": { + "skip-timer": { + "none": "Es ist keine Challenge aktiviert, dessen Timer übersprungen werden könnte", + "done": "Die Timer folgender Challenges wurden übersprungen: {0}" + } + }, + "challenge-end": { + "timer-hit-zero": [ + " ", + "Die Challenge ist vorbei!", + "Seed: {2}", + " " + ], + "timer-hit-zero-winner": [ + " ", + "Die Challenge ist vorbei!", + "Gewinner: {1}", + "Seed: {2}", + " " + ], + "goal-reached": [ + " ", + "Die Challenge wurde beendet!", + "Zeit benötigt: {0}", + "Seed: {2}", + " " + ], + "goal-reached-winner": [ + " ", + "Die Challenge wurde beendet!", + "Gewinner: {1}", + "Zeit benötigt: {0}", + "Seed: {2}", + " " + ], + "goal-failed": [ + " ", + "Die Challenge ist vorbei! #FeelsBadMan {@symbol.cross}", + "Zeit verschwendet: {0}", + "Seed: {2}", + " " + ] + }, + "server-reset": { + "restart": [ + " ", + " ", + "» Serverreset", + " ", + "Reset durch {0}", + "Der Server startet nun neu", + " ", + " " + ], + "stop": [ + " ", + " ", + "» Serverreset", + " ", + "Reset durch {0}", + "Der Server wird nun gestoppt", + " ", + " " + ] + }, + "syntax": "Bitte nutze /{0}", + "reload": "Challenges Plugin wird neu geladen...", + "reload-failed": "Ein Fehler ist während dem Reload aufgetreten", + "reload-success": "Challenges Plugin wurde erfolgreich neu geladen", + "player-command": "Dazu musst du ein Spieler sein!", + "no-permission": "Dazu hast du keine Rechte", + "enabled": "Aktiviert", + "disabled": "Deaktiviert", + "customize": "Anpassen", + "navigate-back": "« Zurück", + "navigate-next": "» Weiter", + "seconds": "Sekunden", + "second": "Sekunde", + "minutes": "Minuten", + "minute": "Minute", + "hours": "Stunden", + "hour": "Stunde", + "amplifier": "Stärke", + "open": "Öffnen", + "everyone": "Alle", + "player": "Aktiver Spieler", + "none": "Nichts", + "inventory-color": "", + "confirm-reset": "Bestätige den Reset mit /{0}", + "no-fresh-reset": [ + "Der Server kann nicht resettet werden", + "Die Challenge wurde noch nicht gestartet" + ], + "new-challenge-suffix": "{@challenge.suffix-format('Neu!')}", + "updated-challenge-suffix": "{@challenge.suffix-format('Update!')}", + "feature-disabled": "Diese Funktion ist derzeit deaktiviert", + "challenge-disabled": "Diese Challenge ist derzeit deaktiviert", + "timer-not-started": "Der Timer wurde noch nicht gestartet", + "timer-was-set": "Der Timer wurde auf {0} gesetzt", + "timer-already-started": "Der Timer läuft bereits", + "timer-already-paused": "Der Timer ist bereits pausiert", + "timer-mode-set-down": "Der Timer zählt nun runter", + "timer-mode-set-up": "Der Timer zählt nun hoch", + "no-database-connection": "Es gibt keine Datenbankverbindung", + "fetching-data": "Daten werden abgerufen..", + "no-such-material": "Dieses Material gibt es nicht", + "not-an-item": "{0} ist kein Item", + "no-such-entity": "Dieses Entity existiert nicht", + "not-alive": "{0} ist kein lebendes Entity", + "no-loot": "{0} hat keine Drops", + "deprecated-plugin-version": [ + " ", + "Ein neues Update ist verfügbar!", + "Download: {0}", + " " + ], + "deprecated-config-version": [ + "Deine Plugin Config ist veraltet ({1} \\< {0})", + "Du kannst die alte Config löschen oder die fehlenden Einstellungen manuell hinzufügen" + ], + "missing-config-settings": "Folgende Einstellungen fehlen in der Config: {0}", + "missing-config-settings-separator": ", ", + "no-missing-config-settings": [ + "Es fehlen keine Einstellungen in der Config.", + "Du kannst die Version ohne bedenken selbst auf {0} stellen." + ], + "unsuported-language": [ + "Diese Sprache ({0}) wird nicht unterstützt" + ], + "not-op": [ + "Um dieses Plugin zu nutzen, musst du die Berechtigung haben. Gib dir die Berechtigung in der Serverkonsole mit: /op [name]" + ], + "join-message": "{0} hat den Server betreten", + "quit-message": "{0} hat den Server verlassen", + "timer-paused-message": [ + "Der Timer ist noch pausiert", + "Nutze /timer resume um ihn zu starten" + ], + "cheats-detected": [ + "{0} hat gecheated", + "Es können keine weiteren Statistiken gesammelt werden" + ], + "cheats-already-detected": [ + "Auf diesem Server wurde gecheated", + "Es können keine weiteren Statistiken gesammelt werden" + ], + "custom_challenges-reset": "Die Lokalen Challenges wurden erfolgreich zurückgesetzt", + "config-reset": "Die Lokalen Einstellungen wurden erfolgreich zurückgesetzt", + "player-config-loaded": "Deine Einstellungen wurden erfolgreich geladen", + "player-config-saved": "Deine Einstellungen wurden erfolgreich gespeichert", + "player-config-reset": "Deine Einstellungen wurden erfolgreich zurückgesetzt", + "player-custom_challenges-loaded": "Deine Challenges wurden erfolgreich geladen", + "player-custom_challenges-saved": "Deine Challenges wurden erfolgreich gespeichert", + "player-custom_challenges-reset": "Deine Challenges wurden erfolgreich zurückgesetzt", + "item-prefix": "» ", + "item-setting-info": "➟ {0}", + "stat-dragon-killed": "Drachen getötet", + "stat-deaths": "Tode", + "stat-entity-kills": "Kills", + "stat-damage-dealt": "Schaden ausgeteilt", + "stat-damage-taken": "Schaden genommen", + "stat-blocks-mined": "Blöcke abgebaut", + "stat-blocks-placed": "Blöcke platziert", + "stat-blocks-traveled": "Blöcke gereist", + "stat-challenges-played": "Challenges gespielt", + "stat-jumps": "Sprünge", + "stats-of": "» Stats von {0}", + "stats-display": "» {0} ({1}. Platz)", + "stats-leaderboard-display": [ + "» {0}", + "{1} {2}", + "{3}. Platz" + ], + "position": "{4} - {0}, {1}, {2} ({3}) {5}m", + "positions-disabled": "Positionen sind deaktiviert", + "position-other-world": "Diese Position befindet sich in einer anderen Welt ({0})", + "position-not-exists": "Die Position {0} existiert nicht", + "position-already-exists": "Die Position {0} existiert bereits", + "position-set": "{5} hat {4} {0}, {1}, {2} ({3}) erstellt", + "position-deleted": "{5} hat {4} {0}, {1}, {2} ({3}) gelöscht", + "no-positions": [ + "Es sind keine Positionen in dieser Welt gesetzt", + "Erstelle eine mit /{0}" + ], + "no-positions-global": [ + "Es sind keine Positionen gesetzt", + "Erstelle eine mit /{0}" + ], + "command-no-target": "Es wurde kein Spieler gefunden", + "command-heal-healed": "Du wurdest geheilt", + "command-heal-healed-others": "Du hast {0} Spieler geheilt", + "command-gamemode-gamemode-changed": "Du wurdest in den Gamemode {0} gesetzt", + "command-gamemode-gamemode-changed-others": "Du hast {1} Spieler in den Gamemode {0} gesetzt", + "command-village-search": "Es wird nach einem Dorf gesucht..", + "command-village-teleport": "Du wurdest in ein Dorf teleportiert", + "command-village-not-found": "Es wurde kein neues Dorf gefunden", + "command-weather-set-clear": "Wetter zu klar geändert", + "command-weather-set-rain": "Wetter zu regnerisch geändert", + "command-weather-set-thunder": "Wetter zu stürmisch geändert", + "command-invsee-open": "Inventar von {0} geöffnet", + "command-enderchest-open": "Du hast deine Enderchest geöffnet", + "command-search-nothing": "{0} wird durch keinen speziellen Block gedroppt", + "command-search-result": "{0} droppt aus {1}", + "command-time-set": "Die Zeit wurde auf {0} Ticks (ca. {1}) geändert", + "command-time-set-exact": "Die Zeit wurde auf {0} ({1} Ticks) geändert", + "command-time-query": [ + "» Derzeitige Ingamezeiten", + "Spielzeit {0} Ticks (Tag {1})", + "Tageszeit {2} Ticks (ca. {3})" + ], + "command-time-noon": "Mittag", + "command-time-night": "Nacht", + "command-time-midnight": "Mitternacht", + "command-time-day": "Tag", + "command-fly-enabled": "Du kannst nun fliegen", + "command-fly-disabled": "Du kannst nun nicht mehr fliegen", + "command-fly-toggled-others": "Du hast Fly für {0} Spieler verändert", + "command-feed-fed": "Dein Hunger wurde gestillt", + "command-feed-others": "Du hast den Hunger von {0} Spieler *gestillt*", + "command-gamestate-reload": "Der Gamestate wurde neu geladen", + "command-gamestate-reset": "Der Gamestate wurde zurückgesetzt", + "command-world-teleport": "Du wirst in die Welt {0} teleportiert", + "command-back-no-locations": "Du hast dich noch nicht teleportiert", + "command-back-teleported": "Du wurdest {0} Position zurück teleportiert", + "command-back-teleported-multiple": "Du wurdest {0} Positionen zurück teleportiert", + "command-result-no-battle-active": "Es ist aktuell kein Force-Battle aktiviert", + "command-god-mode-enabled": "Du bist nun im God-Mode", + "command-god-mode-disabled": "Du bist nun nicht mehr im God-Mode", + "command-god-mode-toggled-others": "{0} Spieler sind jetzt im God-Mode", + "player-damage-display": "{0} nahm {1} Schaden durch {2}", + "death-message": "{0} ist gestorben", + "death-message-cause": "{0} ist durch {1} gestorben", + "unable-to-find-fortress": "Es konnte keine Festung gefunden werden", + "unable-to-find-bastion": "Es konnte keine Bastion gefunden werden", + "death-collected": "Todesgrund {0} wurde registriert", + "item-collected": "Item {0} wurde registriert", + "items-to-collect": "Items zu sammeln » {0}", + "backpacks-disabled": "Rucksäcke sind derzeit deaktiviert", + "backpack-opened": "Du hast den {0} geöffnet", + "top-to-overworld": "Du wurdest zur Overworld teleportiert", + "top-to-surface": "Du wurdest zur Oberfläche teleportiert", + "all-items-skipped": "Item {0} geskippt", + "all-items-already-finished": "Es wurden bereits alle Items gefunden", + "all-items-found": "Das Item {0} wurde von {1} registriert", + "mob-kill": "{0} wurde besiegt ({1} / {2})", + "all-advancements-goal": "Advancements » {0}", + "height-reached": "{0} hat Höhe {1} erreicht!", + "race-goal-reached": "{0} hat das Ziel erreicht!", + "points-change": "{0} Punkte", + "force-item-battle-found": "Du hast {0} gefunden!", + "force-item-battle-new-item": "Item zu suchen: {0}", + "force-item-battle-leaderboard": "Force Item Battle Leaderboard", + "force-mob-battle-killed": "Du hast {0} gefunden!", + "force-mob-battle-new-mob": "Mob zu suchen: {0}", + "force-mob-battle-leaderboard": "Force Mob Battle Leaderboard", + "force-advancement-battle-completed": "Du hast {0} erzielt!", + "force-advancement-battle-new-advancement": "Nächstes Advancement: {0}", + "force-advancement-battle-leaderboard": "Force Advancement Battle Leaderboard", + "force-block-battle-found": "Du hast {0} gefunden!", + "force-block-battle-new-block": "Block zu suchen: {0}", + "force-block-battle-leaderboard": "Force Block Battle Leaderboard", + "force-battle-leaderboard-entry": "{0}#{1} » {2} {3}", + "force-battle-block-target-display": "Block: {0}", + "force-battle-item-target-display": "Item: {0}", + "force-battle-height-target-display": "Höhe: {0}", + "force-battle-mob-target-display": "Mob: {0}", + "force-battle-biome-target-display": "Biom: {0}", + "force-battle-damage-target-display": "Schaden: {0} ❤", + "force-battle-advancement-target-display": "Advancement: {0}", + "force-battle-position-target-display": "Position: {0}", + "extreme-force-battle-new-height": "Höhe zu erreichen: {0}", + "extreme-force-battle-reached-height": "Du hast die Höhe {0} erreicht!", + "extreme-force-battle-new-biome": "Biom zu finden: {0}", + "extreme-force-battle-found-biome": "Du hast das Biom {0} gefunden!", + "extreme-force-battle-new-damage": "Schaden zu nehmen: {0} ❤", + "extreme-force-battle-took-damage": "Du hast {0} ❤ Schaden genommen!", + "extreme-force-battle-position": "X: {0} Z: {1}", + "extreme-force-battle-new-position": "Position zu erreichen: {0}", + "extreme-force-battle-reached-position": "Du hast die Position {0} erreicht!", + "extreme-force-battle-leaderboard": "Extreme Force Battle Leaderboard", + "force-biome-battle-leaderboard": "Force Biome Battle Leaderboard", + "force-damage-battle-leaderboard": "Force Damage Battle Leaderboard", + "force-height-battle-leaderboard": "Force Height Battle Leaderboard", + "force-position-battle-leaderboard": "Force Position Battle Leaderboard", + "quiz-how-to": "Schreibe deine Antwort mit /guess \\", + "quiz-right-answer": "{0} ist die richtige Antwort!", + "quiz-right-answer-other": "{0} hat die Frage richtig beantwortet", + "quiz-wrong-answer": "{0} ist eine falsche Antwort!", + "quiz-wrong-answer-other": "{0} hat die Frage falsch beantwortet", + "quiz-time-up": "Die Zeit ist abgelaufen!", + "quiz-cancel": "Die Frage wurde abgebrochen!", + "quiz-right-answer-was": "Die richtige Antwort lautete: {0}", + "quiz-right-answer-was-multiple": "Die richtigen Antworten lauteten: {0}", + "quiz-question-often-have": "Wie oft hast du {0}{1}?", + "quiz-question-often-be": "Wie oft bist du {0}{1}?", + "quiz-question-far-be": "Wie weit bist du {0}?", + "quiz-question-most": "Was hast du von diesen {1} am meisten {0}?", + "quiz-question-damage-have": "Wie viel Schaden hast du {0}{1}?", + "quiz-question-damage-taken-have": "Wie viel Schaden hast du durch {0}{1}?", + "quiz-verb-traveled": "gelaufen", + "quiz-verb-jumped": "gesprungen", + "quiz-verb-sneaked": "geschlichen", + "quiz-verb-killed": "getötet", + "quiz-verb-damaged": "zugefügt", + "quiz-verb-broken": "abgebaut", + "quiz-verb-placed": "platziert", + "quiz-verb-dropped": "gedropped", + "quiz-verb-suffered": "erlitten", + "bossbar-timer-paused": "» Der Timer ist pausiert", + "bossbar-all-items-current-max": "» {0} {1} / {2}", + "bossbar-all-items-finished": "» Alle Items gefunden", + "bossbar-race-goal-info": "» Ziel X: {0} / Z: {1} {2} Blöcke", + "bossbar-race-goal": "» Ziel X: {0} / Z: {1}", + "bossbar-first-at-height-goal": "» Ziel Y: {0}", + "bossbar-kill-all-bosses": "» Alle Bosse {0}/{1}", + "bossbar-kill-all-mobs": "» Alle Mobs {0}/{1}", + "bossbar-kill-all-monster": "» Alle Monster {0}/{1}", + "subtitle-time-seconds": "{0} Sekunden", + "subtitle-time-seconds-range": "{0}-{1} Sekunden", + "subtitle-time-minutes": "{0} Minuten", + "subtitle-launcher-description": "Stärke {0}", + "subtitle-range-blocks": "Reichweite: {0} Blöcke", + "scoreboard-title": "» Challenge", + "scoreboard-leaderboard": "#{0} {1} » {2}", + "your-place": "Dein Platz » {0}", + "title-timer-started": [ + " ", + "» Timer fortgesetzt" + ], + "title-timer-paused": [ + " ", + "» Timer pausiert" + ], + "title-challenge-enabled": [ + "{0}", + "Aktiviert" + ], + "title-challenge-disabled": [ + "{0}", + "Deaktiviert" + ], + "title-challenge-value-changed": [ + "{0}", + "» {1}" + ], + "item-menu-start": "Start Challenge /start ", + "item-menu-challenges": "Challenges /challenge ", + "item-menu-timer": "Timer /timer ", + "item-menu-leaderboard": "Leaderboard /leaderboard ", + "item-menu-stats": "Statistiken /stats ", + "menu-main-title": "{@menu.title-format('Menu')}", + "menu-timer": "Timer", + "menu-goal": "Ziel", + "menu-damage": "Schaden", + "menu-item_blocks": "Blöcke & Items", + "menu-challenges": "Challenges", + "menu-settings": "Einstellungen", + "menu-custom": "Individuelle Challenges", + "lore-category-activated-count": "Aktiviert » {0}/{1}", + "lore-category-activated": "Aktiviert » Ja", + "lore-category-deactivated": "Aktiviert » Nein", + "item-time-seconds-description": "» Zeit: {0} Sekunden", + "item-time-seconds-range-description": "» Zeit: {0}-{1} Sekunden", + "item-time-minutes-description": "» Zeit: {0} Minuten", + "item-heart-damage-description": "» Schaden: {0} ", + "item-heart-start-description": "» Start: {0} ", + "item-max-health-description": "» Maximale Leben: {0} ", + "item-chance-description": "» Chance: {0}%", + "item-launcher-description": "» Stärke: {0}", + "item-permanent-effect-target-player-description": "» Nur der aktive Spieler erhält den Effekt", + "item-permanent-effect-target-everyone-description": "» Alle erhalten den Effekt", + "item-blocks-description": "» Blöcke zu laufen: {0}", + "item-range-blocks-description": "» Reichweite: {0} Blöcke", + "item-force-battle-goal-jokers": [ + "Anzahl der Joker", + "Die *Anzahl* der *Joker*,", + "die jeder Spieler hat" + ], + "item-force-battle-show-scoreboard": [ + "Scoreboard anzeigen" + ], + "item-force-battle-duped-targets": [ + "Doppelte Ziele", + "Ziele können *mehrfach* vorkommen" + ], + "item-force-position-battle-radius": [ + "Radius", + "Der *maximale Radius*, in dem sich die", + "Positionen befinden können" + ], + "item-language-setting": [ + "Sprache", + "Setze die *Sprache*" + ], + "item-language-setting-german": "Deutsch", + "item-language-setting-english": "English", + "item-death-message-setting-vanilla": "Vanilla", + "item-backpack-setting-team": "Team", + "item-backpack-setting-player": "Player", + "menu-cut-clean-setting-settings": "CutClean", + "item-cut-clean-gold-setting": [ + "Gold", + "*Golderz* wird direkt zu *Goldbarren*" + ], + "item-cut-clean-iron-setting": [ + "Iron", + "*Eisenerz* wird direkt zu *Eisenbarren*" + ], + "item-cut-clean-coal-setting": [ + "Coal", + "*Kohleerz* wird direkt zu *Fackeln*" + ], + "item-cut-clean-flint-setting": [ + "Flint", + "*Gravel* droppt immer *Flint*" + ], + "item-cut-clean-vein-setting": [ + "Ore Veins", + "*Erz Venen* werden direkt abgebaut" + ], + "item-cut-clean-inventory-setting": [ + "Direkt ins Inventar", + "*Items* werden, *anstatt gedroppt* zu werden,", + "*direkt* ins *Inventar* hinzugefügt" + ], + "item-cut-clean-food-setting": [ + "Gebratenes Essen", + "*Rohes Fleisch* wird direkt zu *gebratenem Fleisch*" + ], + "no-hunger-setting": [ + "Kein Hunger", + "Du bekommst keinen *Hunger*" + ], + "item-timber-setting-logs": "Baumstämme", + "item-timber-setting-logs-and-leaves": "Baumstämme und Blätter", + "top-command-setting": [ + "Top Command", + "Mit */top* kannst du dich", + "zur *Oberfläche* oder in", + "die *Overworld* teleportieren" + ], + "item-fortress-spawn-setting": [ + "Festungs Spawn", + "Wenn du in den *Nether* gehst,", + "spawnst du immer in einer *Festung*" + ], + "item-bastion-spawn-setting": [ + "Bastions Spawn", + "Wenn du in den *Nether* gehst,", + "spawnst du immer in einer *Bastion*" + ], + "item-regeneration-setting-not_natural": "Nicht natürlich", + "menu-all-blocks-disappear-challenge-settings": "Alle Blöcke verschwinden", + "item-all-blocks-disappear-break-challenge": [ + "Beim Abbauen", + "Wenn du einen Block *abbaust*, werden", + "*alle Blöcke* des *selben Types zerstört*" + ], + "item-all-blocks-disappear-place-challenge": [ + "Beim Platzieren", + "Wenn du einen Block *platzierst*, werden", + "*alle Blöcke* des *selben Types zerstört*" + ], + "menu-random-effect-challenge-settings": "Random Effekte", + "item-random-effect-time-challenge": [ + "Intervall", + "Das *Intervall*, in dem man", + "einen *Effekt* erhält" + ], + "item-random-effect-length-challenge": [ + "Länge", + "Die *Länge*, die der", + "*Effekt* anhält" + ], + "item-random-effect-amplifier-challenge": [ + "Stärke", + "Die *Stärke*, die der", + "*Effekt* hat" + ], + "menu-anvil-rain-challenge-settings": "Amboss Regen", + "item-anvil-rain-time-challenge": [ + "Intervall", + "Das *Intervall*, in", + "dem *Ambosse* spawnen" + ], + "item-anvil-rain-range-challenge": [ + "Range", + "Die *Reichweite*, in", + "der *Ambosse* spawnen" + ], + "item-anvil-rain-count-challenge": [ + "Anzahl", + "Die *Anzahl*, an *Ambossen*,", + "die in einem *Chunk* spawnen" + ], + "item-anvil-rain-damage-challenge": [ + "Schaden", + "Der *Schaden*, die", + "die *Ambosse* machen" + ], + "item-collect-wood-goal-overworld": "Overworld", + "item-collect-wood-goal-nether": "Nether", + "item-collect-wood-goal-both": "Beide", + "menu-force-item-battle-goal-settings": "Force Item Battle", + "item-force-item-battle-goal-give-item": [ + "Item bei Skippen geben", + "Wenn ein Spieler ein Item *skippt*,", + "wird dieses in sein *Inventar hinzugefügt*" + ], + "menu-force-mob-battle-goal-settings": "Force Mob Battle", + "menu-force-advancement-battle-goal-settings": "Force Advancement Battle", + "menu-force-block-battle-goal-settings": "Force Block Battle", + "item-force-block-battle-goal-give-block": [ + "Block bei Skippen geben", + "Wenn ein Spieler einen Block *skippt*,", + "wird dieser in sein *Inventar hinzugefügt*" + ], + "menu-force-biome-battle-goal-settings": "Force Biome Battle", + "menu-force-damage-battle-goal-settings": "Force Damage Battle", + "menu-force-height-battle-goal-settings": "Force Height Battle", + "menu-force-position-battle-goal-settings": "Force Position Battle", + "menu-extreme-force-battle-goal-settings": "Extreme Force Battle", + "item-damage-rule-none": [ + "Genereller Schaden", + "Stellt ein, ob du Schaden bekommen kannst" + ], + "item-damage-rule-fire": [ + "Feuer Schaden", + "Stellt ein, ob du Schaden durch", + "*Lava* und *Feuer* bekommen kannst" + ], + "item-damage-rule-attack": [ + "Angriff Schaden", + "Stellt ein, ob du Schaden durch", + "*Nahkampfangriffe von Entities* bekommen kannst" + ], + "item-damage-rule-projectile": [ + "Projektil Schaden", + "Stellt ein, ob du Schaden durch", + "*Projektile* bekommen kannst" + ], + "item-damage-rule-fall": [ + "Fallschaden", + "Stellt ein, ob du *Fallschaden* bekommen kannst" + ], + "item-damage-rule-explosion": [ + "Explosions Schaden", + "Stellt ein, ob du *Explosions Schaden* bekommen kannst" + ], + "item-damage-rule-drowning": [ + "Ertrink Schaden", + "Stellt ein, ob du Schaden durch", + "*Ertrinken* bekommen kannst" + ], + "item-damage-rule-block": [ + "Block Schaden", + "Stellt ein, ob du Schaden durch", + "*Fallende Blöcke* bekommen kannst" + ], + "item-damage-rule-magic": [ + "Magie Schaden", + "Stellt ein, ob du Schaden durch", + "*Gift*, *Wither* und andere *Tränke* bekommen kannst" + ], + "item-damage-rule-freeze": [ + "Frost Schaden", + "Stellt ein, ob du Schaden durch", + "*Frost* bekommen kannst" + ], + "item-block-material": [ + "{0}", + "Stellt ein, ob *{1}*", + "genutzt werden *kann*" + ], + "custom-limit": "Du hast das Limit von {0} Challenges erreicht", + "custom-not-deleted": "Diese Challenge existiert noch nicht!", + "custom-saved": "Challenge wurde lokal gespeichert", + "custom-saved-db": [ + "Um in Datenbank zu Speichern benutze /db save customs", + "Achtung: Alte Einstellungen werden dabei überschrieben!" + ], + "custom-no-changes": "Du hast an der Challenge keine Änderungen gemacht", + "custom-name-info": "Schreibe den Namen der Challenge in den Chat", + "custom-command-info": [ + "Schreibe den Command den der Spieler ausführen soll ohne / in den Chat", + "Erlaubte Commands: {0}", + "Weitere Commands können in der Config erlaubt werden" + ], + "custom-command-not-allowed": "Der Command {0} ist in der Config nicht als erlaubter Command angegeben", + "custom-chars-max_length": "Du hast die Maximale Anzahl von {0} Zeichen überschritten", + "custom-not-loaded": [ + " ", + "Es sind derzeit keine Custom Challenges geladen.", + "Du vermisst deine Challenges? /db load customs", + "Du hast Probleme beim Speichern?", + "Speichere vorm verlassen manuell /db save customs", + " " + ], + "custom-main-view-challenges": "Challenges Ansehen", + "custom-main-create-challenge": "Challenge Erstellen", + "custom-title-trigger": "Auslöser", + "custom-title-action": "Aktion", + "custom-title-view": "Gespeichert", + "custom-sub-finish": "Fertig", + "item-custom-info-delete": [ + "Löschen", + "*Achtung* diese Aktion kann *nicht*", + "rückgängig gemacht werden" + ], + "item-custom-info-save": "Speichern", + "item-custom-info-trigger": [ + "Auslöser", + "*Klicke* um einzustellen, was passieren", + "muss, damit die *Aktion* ausgeführt wird" + ], + "item-custom-info-action": [ + "Aktion", + "*Klicke* um einzustellen, was passieren", + "soll, wenn der *Auslöser* erfüllt ist" + ], + "item-custom-info-material": [ + "Anzeige Item", + "*Klicke* um das Anzeigeitem zu ändern" + ], + "item-custom-info-name": [ + "Name", + "*Klicke* um den Namen über den Chat zu ändern", + "Maximale Zeichenanzahl: 50" + ], + "custom-info-currently": "Eingestellt » ", + "custom-info-trigger": "Auslöser", + "custom-info-action": "Aktion", + "item-custom-trigger-jump": [ + "Spieler Springt" + ], + "item-custom-trigger-sneak": [ + "Spieler Schleicht" + ], + "item-custom-trigger-move_block": [ + "Spieler Läuft Einen Block" + ], + "item-custom-trigger-death": [ + "Entity Stirbt" + ], + "item-custom-trigger-damage": [ + "Entity Erleidet Schaden" + ], + "item-custom-trigger-damage-any": [ + "Jeglicher Grund" + ], + "item-custom-trigger-damage_by_player": [ + "Entity Bekommt Schaden Von Spieler" + ], + "item-custom-trigger-intervall": [ + "Intervall" + ], + "item-custom-trigger-intervall-second": [ + "Jede Sekunde" + ], + "item-custom-trigger-intervall-seconds": [ + "Alle {0} Sekunden" + ], + "item-custom-trigger-intervall-minutes": [ + "Alle {0} Minuten" + ], + "item-custom-trigger-block_place": [ + "Block Platziert" + ], + "item-custom-trigger-block_break": [ + "Block Zerstört" + ], + "item-custom-trigger-consume_item": [ + "Item Konsumieren" + ], + "item-custom-trigger-pickup_item": [ + "Item Aufheben" + ], + "item-custom-trigger-drop_item": [ + "Spieler Droppt Item" + ], + "item-custom-trigger-advancement": [ + "Spieler Erhält Errungenschaft" + ], + "item-custom-trigger-hunger": [ + "Spieler Verliert Hunger" + ], + "item-custom-trigger-move_down": [ + "Block Nach Unten Bewegen" + ], + "item-custom-trigger-move_up": [ + "Block Nach Oben Bewegen" + ], + "item-custom-trigger-move_camera": [ + "Kamera Bewegen" + ], + "item-custom-trigger-stands_on_specific_block": [ + "Spieler Ist Auf Bestimmten Block" + ], + "item-custom-trigger-stands_not_on_specific_block": [ + "Spieler Ist Nicht Auf Bestimmten Block" + ], + "item-custom-trigger-gain_xp": [ + "Spieler Bekommt XP" + ], + "item-custom-trigger-level_up": [ + "Spieler Levelt Auf" + ], + "item-custom-trigger-item_craft": [ + "Spieler Craftet Item" + ], + "item-custom-trigger-in_liquid": [ + "Spieler In Flüssigkeit" + ], + "item-custom-trigger-get_item": [ + "Item bekommen", + "Aktion wird für *jedes* anklicken oder aufheben ausgeführt" + ], + "item-custom-action-cancel": [ + "Auslöser Abbrechen", + "Verhindert, dass der Auslöser ausgeführt wird.", + "Nicht abrechenbare Auslöser: *Springen*, *Sneaken*, *Töten*", + "*Advancement*, *Auf Leveln*, *In Flüssigkeit*" + ], + "item-custom-action-command": [ + "Command Ausführen", + "Lasse Spieler einen Command ausführen lassen", + "Die Commands werden für Spieler mit */execute as* von", + "der Konsole ausgeführt.", + "Erlaubte Commands werden in der Config eingestellt.", + "Der Spieler braucht *keine Rechte* auf den Command haben.", + "Spieler können *keine Plugin Commands* ausführen." + ], + "item-custom-action-kill": [ + "Töten", + "Töte Entities" + ], + "item-custom-action-damage": [ + "Schaden", + "Füge Entities Schaden zu" + ], + "item-custom-action-heal": [ + "Heilen", + "Heile Entities" + ], + "item-custom-action-hunger": [ + "Hunger", + "Füge Spielern Hunger hinzu" + ], + "item-custom-action-max_health": [ + "Maximale Leben Verändern", + "Verändere die Maximalen Leben von Spielern", + "Wird mit einem */gamestate reset* zurückgesetzt" + ], + "item-custom-action-max_health-offset": [ + "Veränderung", + "Wähle aus wie viele Leben verändert werden sollen" + ], + "item-custom-action-spawn_entity": [ + "Entity Spawnen", + "Spawne ein Entity bestimmten Types" + ], + "item-custom-action-random_mob": [ + "Zufälliges Entity", + "Spawne ein zufälliges Entity" + ], + "item-custom-action-random_item": [ + "Zufälliges Item", + "Gebe Spielern zufällige Items" + ], + "item-custom-action-uncraft_inventory": [ + "Inventar Zurück-Craften", + "Lasse das Inventar von Spielern Zurück-Craften" + ], + "item-custom-action-boost_in_air": [ + "In Luft Schleudern", + "Schleudere Entities in die Luft" + ], + "item-custom-action-boost_in_air-strength": [ + "Stärke" + ], + "item-custom-action-potion_effect": [ + "Trank Effekt", + "Gebe Entities einen bestimmten Trank Effekt" + ], + "item-custom-action-permanent_effect": [ + "Permanenten Trank Effekt", + "Füge Spieler einen Permanenten Effekt hinzu.", + "Die Aktion nutzt die Einstellungen", + "von der Permanenten Effekt Challenge." + ], + "item-custom-action-random_effect": [ + "Zufälliger Trank Effekt", + "Gebe Entities einen zufälligen Trank Effekt" + ], + "item-custom-action-clear_inventory": [ + "Inventar Leeren", + "Leere das Inventar von Spielern komplett" + ], + "item-custom-action-drop_random_item": [ + "Item Aus Inventar Droppen", + "Droppe ein Item aus dem Inventar auf den Boden" + ], + "item-custom-action-remove_random_item": [ + "Item Aus Inventar Entfernen", + "Entferne ein Item aus dem Inventar" + ], + "item-custom-action-swap_random_item": [ + "Items Im Inventar Tauschen", + "Tausche zwei Item im Inventar" + ], + "item-custom-action-freeze": [ + "Freeze", + "Friere Mobs Zeitweise ein.", + "Die Aktion nutzt die Einstellungen", + "von der Freeze On Damage Challenge." + ], + "item-custom-action-invert_health": [ + "Invert Health", + "Invertiere die Herzen eines Spielers.", + "Wenn du *8 Herzen* hast,", + "hast du danach *2 Herzen* und umgekehrt." + ], + "item-custom-action-water_mlg": [ + "Water MLG", + "Alle Spieler müssen einen Water MLG machen" + ], + "item-custom-action-win": [ + "Gewinnen", + "Die Challenge wird von *bestimmten Spielern* gewonnen" + ], + "item-custom-action-random_hotbar": [ + "Zufällige Hotbar", + "Das Inventar wird geleert und der Spieler", + "bekommt zufällige Items in die HotBar" + ], + "item-custom-action-modify_border": [ + "World Border Verändern", + "Mache die Worldborder *größer* oder *kleiner*" + ], + "item-custom-action-modify_border-change": [ + "Veränderung" + ], + "item-custom-action-swap_mobs": [ + "Mobs tauschen", + "Tausche ein Mob mit einem zufälligen", + "anderem Mob aus der gleichen Welt" + ], + "item-custom-action-place_structure": [ + "Struktur Platzieren", + "Platziert eine Struktur" + ], + "item-custom-action-place_structure-random": "Zufällige Struktur", + "item-custom-setting-target-current": [ + "Aktives Entity", + "Die Aktion wird für das *aktive Entity* ausgeführt" + ], + "item-custom-setting-target-every_mob": [ + "Alle Mobs", + "Die Aktion wird für *alle Mobs* ausgeführt" + ], + "item-custom-setting-target-every_mob_except_current": [ + "Alle Mobs Außer Aktives", + "Die Aktion wird für *alle Mobs*", + "*außer* das Aktive ausgeführt ausgeführt" + ], + "item-custom-setting-target-every_mob_except_players": [ + "Alle Mobs Außer Spieler", + "Die Aktion wird für *alle Mobs*", + "*außer* Spieler ausgeführt" + ], + "item-custom-setting-target-random_player": [ + "Zufälliger Spieler", + "Die Aktion wird für einen *zufälligen Spieler* ausgeführt" + ], + "item-custom-setting-target-every_player": [ + "Alle Spieler", + "Die Aktion wird für *jeden Spieler* ausgeführt" + ], + "item-custom-setting-target-current_player": [ + "Aktiver Spieler", + "Die Aktion wird für den *aktiven Spieler* ausgeführt", + "Wenn das Entity kein Spieler ist, wird nichts passieren" + ], + "item-custom-setting-target-console": [ + "Konsole", + "Die Aktion wird für die *Konsole* ausgeführt" + ], + "item-custom-setting-entity_type-any": "Jegliches Entity", + "item-custom-setting-entity_type-player": "Spieler", + "item-custom-setting-block-any": "Jeglicher Block", + "item-custom-setting-item-any": "Jegliches Item", + "custom-subsetting-target_entity": "Ziel Entity", + "custom-subsetting-entity_type": "Entity Typ", + "custom-subsetting-liquid": "Flüssigkeit", + "custom-subsetting-time": "Zeit", + "custom-subsetting-damage_cause": "Schadens Art", + "custom-subsetting-amount": "Anzahl", + "custom-subsetting-value": "Werte Editor", + "custom-subsetting-health_offset": "Veränderung", + "custom-subsetting-length": "Länge", + "custom-subsetting-amplifier": "Stärke", + "custom-subsetting-change": "Veränderung", + "custom-subsetting-swap_targets": "Tausch Ziele" +} diff --git a/language/locales/en.json b/language/locales/en.json new file mode 100644 index 000000000..714a1746e --- /dev/null +++ b/language/locales/en.json @@ -0,0 +1,2181 @@ +{ + "generic": { + "undefined": "undefined", + "unknown": "unknown", + "disabled": "Disabled", + "enabled": "Enabled", + "customized": "Customize", + "console": "Console" + }, + "language": { + "de": "German", + "en": "English" + }, + "challenge": { + "regeneration": { + "name": "*Regeneration*", + "desc": [ + "Sets *whether* and", + "*how* to *regenerate*" + ] + }, + "one-life": { + "name": "*One Teamlife*", + "desc": [ + "*Everyone* dies when *one player dies*" + ] + }, + "respawn": { + "name": "*Respawn*", + "desc": [ + "When you *die*, you won't be a *spectator*" + ] + }, + "split-health": { + "name": "*Split Health*", + "desc": [ + "Sets whether *all players*", + "share the same *health*" + ] + }, + "damage-display": { + "name": "*Damage Display*", + "desc": [ + "It will be displayed in the *chat*", + "when anybody takes *damage*" + ] + }, + "death-message": { + "name": "*Death messages*", + "desc": [ + "Toggles *death messages*" + ] + }, + "health-display": { + "name": "*Health Display*", + "desc": [ + "The *hearts* of all players", + "will be showed in the *tablist*" + ] + }, + "position": { + "name": "*Positions*", + "desc": [ + "Allows you to mark *positions*", + "with */pos*" + ] + }, + "death-position": { + "name": "*Death Position*", + "desc": [ + "When you die, */pos* creates", + "a position at your death point" + ] + }, + "glow": { + "name": "*Player Glow*", + "desc": [ + "*Players* are visible through *walls*" + ] + }, + "no-item-damage": { + "name": "*No Item Damage*", + "desc": [ + "*Items* are *unbreakable*" + ] + }, + "mob-griefing": { + "name": "*Mob Griefing*", + "desc": [ + "Monsters *can't destroy* anything" + ] + }, + "keep-inventory": { + "name": "*Keep Inventory*", + "desc": [ + "You don't lose any *items*", + "when you die" + ] + }, + "backpack": { + "name": "*Backpack*", + "desc": [ + "Allows you to open *your backpack* or", + "the *team backpack* with */backpack*" + ] + }, + "enderchest-command": { + "name": "*Enderchest Command*", + "desc": [ + "When you execute */ec*,", + "your *Enderchest* opens" + ] + }, + "timber": { + "name": "*Timber*", + "desc": [ + "You can destroy a *tree*", + "by breaking down *a single block* of the tree" + ] + }, + "pvp": { + "name": "*PvP*", + "desc": [] + }, + "no-hit-delay": { + "name": "*NoHitDelay*", + "desc": [ + "After you've *taken* damage", + "you can *get* damage *immediately* again" + ] + }, + "max-health": { + "name": "*Max health*", + "desc": [ + "Sets the *max health*", + "for *all players*" + ] + }, + "damage-multiplier": { + "name": "*Damage Multiplier*", + "desc": [ + "Damage you take will be *multiplied*" + ] + }, + "cut-clean": { + "name": "*CutClean*", + "desc": [ + "Different *settings* to simplify", + "the *farming* of items" + ] + }, + "no-offhand": { + "name": "*No Offhand*", + "desc": [ + "The *second hand* will be blocked" + ] + }, + "immediate-respawn": { + "name": "*Direct Respawn*", + "desc": [ + "When you *die* you *respawn* automatically", + "*without* seeing the *death screen*" + ] + }, + "slot-limit": { + "name": "*Inventory Slots*", + "desc": [ + "Sets how many *inventory*", + "*slots* are useable" + ] + }, + "old-pvp": { + "name": "*1.8 PvP*", + "desc": [ + "The *old 1.8 PvP System* will be used", + "There will be no *attack damage cooldown*" + ] + }, + "totem-save-death": { + "name": "*Challenge Death Rescue*", + "desc": [ + "If you *instant die* from a *challenge*", + "*totems* can *rescue* you" + ] + }, + "soup": { + "name": "*Soup healing*", + "desc": [ + "When you use a *mushroom soup*", + "you will be healed for *4 hearts*" + ] + }, + "random-challenge": { + "name": "*Random Challenge*", + "desc": [ + "In a set *interval* a random", + "*challenge* will be *activated*" + ] + }, + "randomized-hp": { + "name": "*Randomized HP*", + "desc": [ + "The *health* of all mobs", + "is randomized" + ] + }, + "block-randomizer": { + "name": "*Block Randomizer*", + "desc": [ + "Each *block* drops a *random item*" + ] + }, + "crafting-randomizer": { + "name": "*Crafting Randomizer*", + "desc": [ + "If you *craft* something you will get another *random item*" + ] + }, + "hotbar-randomizer": { + "name": "*HotBar Randomizer*", + "desc": [ + "Every *few minutes* every player gets *random items*" + ] + }, + "entity-loot-randomizer": { + "name": "*Entity Loot Randomizer*", + "desc": [ + "All mob drops are *randomly swapped*." + ], + "command-disabled": "The entity loot randomizer challenge is currently deactivated", + "command-nothing": "The loot of {0} isn't dropped by any specific entity", + "command-result": [ + "{0} drops the loot of {1}", + "The loot of {0} is dropped by {2}" + ] + }, + "mob-randomizer": { + "name": "*Mob Randomizer*", + "desc": [ + "When an *Entity* spawns, it spawns *twice*" + ] + }, + "random-dropping": { + "name": "*Random Item Dropping*", + "desc": [ + "Every few seconds a *random item*", + "will be *dropped* from your *inventory*" + ] + }, + "random-item-removing": { + "name": "*Random Item Removing*", + "desc": [ + "Every few seconds a *random item*", + "will be *removed* from your *inventory*" + ] + }, + "random-swapping": { + "name": "*Random Item Swapping*", + "desc": [ + "Every few seconds a *random item*", + "will be *swapped* with *another item*", + "in your *inventory*" + ] + }, + "random-item": { + "name": "*Random Items*", + "desc": [ + "A *random player* gets a *random item*", + "every *few seconds*" + ] + }, + "random-event": { + "name": "*Random Events*", + "desc": [ + "Every *few minutes* one of", + "*{0} random Events* will be activated" + ], + "entities": [ + "Is this a zoo?", + "Where did this come from?", + "What are you doing here?" + ], + "fly": [ + "Good flight :)", + "I believe I can fly..", + "So this is what flying feels like" + ], + "hole": [ + "But you fell pretty deep", + "From the very top to the very bottom..", + "Where did this hole come from?" + ], + "ores": [ + "Where did all the ores go?", + "Aren't there any ores here?", + "Was there any ore here??" + ], + "sickness": [ + "Are you sick??", + "What's going on now?!" + ], + "speed": [ + "Sonic? Is it you?", + "Woahh! That's fast" + ], + "webs": [ + "Have they been here for a long time?" + ] + }, + "mob-damage-teleport": { + "name": "*Mob Swap On Hit*", + "desc": [ + "Every time you *hit a mob*, you", + "swap positions with a *random mob*" + ] + }, + "force-height": { + "name": "*Force Height*", + "desc": [ + "Every *few minutes* you have to be", + "on a *certain height*, else you die" + ], + "bossbar-instruction": "{@symbol.arrow} Height {0} {@symbol.vertical} {1}", + "bossbar-waiting": "{@symbol.arrow} Waiting for next height..", + "fail": "{0} was on the wrong height ({1})", + "success": "All players were on the right height" + }, + "force-block": { + "name": "*Force Block*", + "desc": [ + "Every *few minutes* you have to be", + "on a *certain block*, else you die" + ], + "bossbar-instruction": "{@symbol.arrow} Block {0} {@symbol.vertical} {1}", + "bossbar-waiting": "{@symbol.arrow} Waiting for next block..", + "fail": "{0} was on the wrong block ({1})", + "success": "All players were on the right block" + }, + "force-mob": { + "name": "*Force Mob*", + "desc": [ + "Every *few minutes* you have to", + "*kill* a *certain mob*, else you die" + ], + "bossbar-instruction": "{@symbol.arrow} Mob {0} {@symbol.vertical} {1}", + "bossbar-waiting": "{@symbol.arrow} Waiting for next mob..", + "fail": "The mob {0} hasn't been killed", + "success": "{0} killed the mob {1}" + }, + "force-item": { + "name": "*Force Item*", + "desc": [ + "Every *few minutes* you have to get", + "a *certain item*, else you die" + ], + "bossbar-instruction": "{@symbol.arrow} Item {0} {@symbol.vertical} {1}", + "bossbar-waiting": "{@symbol.arrow} Waiting for next item..", + "fail": "Item {0} hasn't been found", + "success": "{0} found the item {1}" + }, + "force-biome": { + "name": "*Force Biome*", + "desc": [ + "Every *few minutes* you have to be", + "in a *certain biome*, else you die", + "The *rarer* the biome, the *more time* you have" + ], + "bossbar-instruction": "{@symbol.arrow} Biome {0} {@symbol.vertical} {1}", + "bossbar-waiting": "{@symbol.arrow} Waiting for next biome..", + "fail": "The biome {0} hasn't been found", + "success": "{0} found the biome {1}" + }, + "hydra": { + "name": "*Hydra*", + "desc": [ + "If you *kill* a mob", + "*two new* are spawning" + ] + }, + "hydra-plus": { + "name": "*Hydra Plus*", + "desc": [ + "If you kill a *mob* it", + "spawns *twice* as many", + "times as the *previous* time", + " ", + "Maximum are *512* Mobs each time" + ] + }, + "duped-spawning": { + "name": "*Duped Spawning*", + "desc": [ + "If a mob *spawns*", + "it spawns *two times*" + ] + }, + "jump-entity": { + "name": "*Jump Entity*", + "desc": [ + "A *random entity* spawns", + "everytime you *jump*" + ] + }, + "invisible-mobs": { + "name": "*Invisible Mobs*", + "desc": [ + "All *Mobs* have an", + "*invisibility* effect" + ] + }, + "stone-sight": { + "name": "*Stone Sight*", + "desc": [ + "*Mobs* that you look in the", + "*eyes* turn to stone" + ] + }, + "mob-sight-damage": { + "name": "*Mob Sight Damage*", + "desc": [ + "When you look into the *eyes* of an", + "*entity*, you get *damage*" + ] + }, + "all-mobs-to-death-position": { + "name": "*All Mobs To Death Point*", + "desc": [ + "If a *Mob* gets *killed* by a player", + "all mobs of the *same type* will be", + "*teleported* to its *death point*" + ] + }, + "respawn-end": { + "name": "*Mobs Respawn In End*", + "desc": [ + "*Killed mobs* respawn in *end dimension*" + ], + "bossbar": "{@symbol.arrow} Respawned Mobs in End {@symbol.vertical} {0}" + }, + "mob-transformation": { + "name": "*Mob Transformation*", + "desc": [ + "When you hit a mob, it *turns*", + "into the last mob *you* hit" + ], + "bossbar": "{@symbol.arrow} Last mob {@symbol.vertical} {0}" + }, + "block-mobs": { + "name": "*Mob Blocks*", + "desc": [ + "A *random mob* spawns out of *every broken block*", + "and to *get the block* you have to *kill it*" + ] + }, + "damage-per-block": { + "name": "*Damage per Block*", + "desc": [ + "You take *damage* for", + "every *block* you walk" + ] + }, + "sneak-damage": { + "name": "*Damage per Sneak*", + "desc": [ + "You *take* the set amount", + "of *damage* if you *sneak*" + ], + "failed": "{0} sneaked" + }, + "jump-damage": { + "name": "*Damage per Jump*", + "desc": [ + "You *take* the set amount", + "of *damage* if you *jump*" + ], + "failed": "{0} jumped" + }, + "block-break-damage": { + "name": "*Block Break Damage*", + "desc": [ + "If you *break* a *block*, you", + "will *take* the set amount of *damage*" + ] + }, + "block-place-damage": { + "name": "*Block Place Damage*", + "desc": [ + "If you *place* a *block*, you", + "will *take* the set amount of *damage*" + ] + }, + "advancement-damage": { + "name": "*Advancement Damage*", + "desc": [ + "You *take* the set amount of *damage*", + "for every new *advancement*" + ] + }, + "damage-item": { + "name": "*Damage Per Item*", + "desc": [ + "When you *pickup* or *click* an item", + "in your *inventory* you take the", + "*amount* of the items as *damage*" + ] + }, + "water-allergy": { + "name": "*Water Allergy*", + "desc": [ + "You *take* the set amount of *damage*", + "while you are in *water*" + ] + }, + "death-on-fall": { + "name": "*Death On Fall Damage*", + "desc": [ + "You *die instantly*, when", + "you take *fall damage*" + ] + }, + "reversed-damage": { + "name": "*Reversed Damage*", + "desc": [ + "If you deal damage to entites", + "you take the same damage" + ] + }, + "freeze": { + "name": "*Freeze Challenge*", + "desc": [ + "For each heart of *damage*, you'll be", + "*frozen* for a certain time" + ] + }, + "delay-damage": { + "name": "*Damage delay*", + "desc": [ + "All *damage* from all *players* is", + "added up and dealt after *5 minutes*." + ] + }, + "chunk-effect": { + "name": "*Random Chunk Effects*", + "desc": [ + "In *each chunk* you'll get", + "a random *potion effect*" + ] + }, + "block-effect": { + "name": "*Random Block Effects*", + "desc": [ + "On *each block* you'll get", + "a random *potion effect*" + ] + }, + "entity-effect": { + "name": "*Mobs Got Random Effects*", + "desc": [ + "*Every Mob* has a random", + "potion effect with *max amplifier*" + ] + }, + "random-effect": { + "name": "*Random Effects*", + "desc": [ + "You get a *random potion effect*", + "in a set *interval*" + ] + }, + "permanent-effect-on-damage": { + "name": "*Permanent Effects*", + "desc": [ + "Everytime you *take damage* you get", + "a random *permanent potion effect*" + ], + "new-effect": "Effect {0} {1}" + }, + "infection": { + "name": "*Infection Challenge*", + "desc": [ + "You have to keep *2 blocks* away", + "from all *mobs* or you will *get* sick" + ] + }, + "surface-hole": { + "name": "*Surface Hole*", + "desc": [ + "The *floor* is disappearing", + "to *void* behind you" + ] + }, + "bedrock-walls": { + "name": "*Bedrock Walls*", + "desc": [ + "Huge *walls of bedrock*", + "are *generating* behind you" + ] + }, + "bedrock-path": { + "name": "*Bedrock Path*", + "desc": [ + "*Bedrock *generates* under you*", + "the whole time" + ] + }, + "floor-is-lava": { + "name": "*The Floor Is Lava*", + "desc": [ + "*Blocks* below you transform first", + "to *magma* and then to *lava*" + ] + }, + "chunk-deconstruction": { + "name": "*Chunk Deconstruction*", + "desc": [ + "*Chunks* that players are in", + "*break* down from *above*" + ] + }, + "all-blocks-disappear": { + "name": "*All Blocks Disappear*", + "desc": [ + "With different *interactions* all", + "*blocks* of a certain type", + "disappear in the same chunk" + ] + }, + "anvil-rain": { + "name": "*Anvil Rain*", + "desc": [ + "*Anvils* are falling from the *sky*" + ] + }, + "tsunami": { + "name": "*Tsunami*", + "desc": [ + "In a *set interval* ", + "the water rises in the *Overworld*", + "and the *lava* in the nether", + " ", + "Should be played with a *few people*!" + ], + "bossbar-lava": "{@symbol.arrow} Lavaheight: {0}", + "bossbar-water": "{@symbol.arrow} Waterheight: {0}" + }, + "repeat-in-chunk": { + "name": "*Repeated Chunk*", + "desc": [ + "Blocks that are *placed or destroyed*", + "will be placed / destroyed in *every chunk*" + ] + }, + "snake": { + "name": "*Snake*", + "desc": [ + "Each player draws a *deadly line*", + "behind them" + ], + "failed": "{0} stepped over the line" + }, + "blocks-fly": { + "name": "*Blocks Fly in Air*", + "desc": [ + "*Blocks* you've *walked* on fly", + "into the air after *one second*" + ] + }, + "blocks-disappear-time": { + "name": "*Blocks Disappear After Time*", + "desc": [ + "Placed *blocks*, will *disappear*", + "after a *few seconds*" + ] + }, + "loop": { + "name": "*Loop Challenge*", + "desc": [ + "Certain actions are *looped*", + "until a player *sneaks*" + ], + "cleared": "{0} Loops cancelled" + }, + "ice-floor": { + "name": "*Ice Floor*", + "desc": [ + "*Air* will be replaced in a", + "*3x3* area with *packed ice*" + ], + "bossbar": "{@symbol.arrow} Ice floor {@symbol.vertical} {0}" + }, + "level-border": { + "name": "*Level = Border*", + "desc": [ + "The *border size* adjusts to *the player*", + "with the *most levels*." + ], + "bossbar": "{@symbol.arrow} Border size {@symbol.vertical} {0}" + }, + "chunk-deletion": { + "name": "*Chunk Deletion*", + "desc": [ + "*Chunks* that players are in *delete*", + "completely after the given *time*" + ], + "bossbar": "{@symbol.arrow} Time left in chunk {0}s" + }, + "permanent-item": { + "name": "*Permanent Items*", + "desc": [ + "*Items* cannot be dropped", + "or put *away*" + ] + }, + "no-duped-items": { + "name": "*No Duped Items*", + "desc": [ + "Players are *not allowed* to have", + "the *same item* in their *inventories*", + "at the same time" + ], + "failed": "{0} and {1} both had {2} in their inventory" + }, + "damage-inv-clear": { + "name": "*Damage Inventory Clear*", + "desc": [ + "Player *inventories* are *cleared*", + "when a *player* takes damage" + ] + }, + "uncraft-items": { + "name": "*Items Crafting Back*", + "desc": [ + "*Items* in your inventory are", + "*crafting* back all few seconds" + ] + }, + "missing-items": { + "name": "*Items Missing*", + "desc": [ + "Every few minutes a *random item disappears* from", + "your *inventory* and you have to *guess* which it was" + ], + "inventory": "{0}Which item is missing?", + "inventory-open": "[Open GUI]" + }, + "pickup-launch": { + "name": "*Pickup Boost*", + "desc": [ + "When you *pick up* an *item*", + "you will be *launched* into the air" + ] + }, + "block-chunk-item-remove": { + "name": "*Movement Item Remove*", + "desc": [ + "A random item will be removed from", + "your inventory for every", + "*block* / *chunk* you walk" + ], + "block": "Block", + "chunk": "Chunk" + }, + "traffic-light": { + "name": "*Traffic Light Challenge*", + "desc": [ + "The *traffic light* switches every few minutes.", + "If you go on *red*, you die" + ], + "fail": "{0} went over red" + }, + "hunger-block": { + "name": "*Hunger per Block*", + "desc": [ + "You lose *food* for", + "every *block* you walk" + ] + }, + "only-down": { + "name": "*Only Down*", + "desc": [ + "If you go *up* by *a block*, you *die*" + ], + "failed": "{0} went up one block" + }, + "only-dirt": { + "name": "*Only Dirt*", + "desc": [ + "You must stay on *dirt*", + "otherwise you will *die*" + ], + "failed": "{0} did not stand on dirt" + }, + "higher-jumps": { + "name": "*Higher Jumps*", + "desc": [ + "The more *you jump*, the *higher* you jump" + ] + }, + "always-running": { + "name": "*Always Running*", + "desc": [ + "You *cannot stop* to *walk forwards*" + ] + }, + "dont-stop-running": { + "name": "*Dont stop running*", + "desc": [ + "You are only allowed to stand *still*", + "a certain *time* before you *die*" + ], + "bossbar": "{@symbol.arrow} Move in {@symbol.vertical} {0}", + "stopped-moving": "{0} hasn't moved for too long" + }, + "no-mouse-move": { + "name": "*Mouse Movement Damage*", + "desc": [ + "You take *damage* everytime", + "you *move* your *view*" + ], + "failed": "{0} moved his mouse" + }, + "five-hundred-blocks": { + "name": "*500 Blocks*", + "desc": [ + "*Every 500 Blocks walked* players", + "will get a *64 stack* of a random item.", + "*Blocks* and *Entities* won't *drop* any items." + ], + "bossbar": "{@symbol.arrow} Blocks Walked {@symbol.vertical} {0} / {1}", + "subtitle": "{0} Blocks" + }, + "max-biome-time": { + "name": "*Max Biome Time*", + "desc": [ + "The *time* that you may spend", + "in every *biome* is limited" + ], + "bossbar": "{@symbol.arrow} Time left in {0} {@symbol.vertical} {1}s" + }, + "max-height-time": { + "name": "*Max Height Time*", + "desc": [ + "The *time* that you may spend", + "on every *height* is limited" + ], + "bossbar": "{@symbol.arrow} Time left on {0} {@symbol.vertical} {1}s" + }, + "water-mlg": { + "name": "*Water MLG*", + "desc": [ + "You have to do a *Water MLG*", + "over and over again" + ] + }, + "jump-and-run": { + "name": "*Jump and Run*", + "desc": [ + "Every *few minutes* you have to do a random", + "*jump and run* which gets *harder* every time" + ], + "countdown": "Next JumpAndRun in {0} seconds", + "countdown-one": "Next JumpAndRun in one second", + "finished": "{0} finished the JumpAndRun" + }, + "one-durability": { + "name": "*One Durability*", + "desc": [ + "Items are *destroyed* after one *use*" + ] + }, + "no-trading": { + "name": "*No Trading*", + "desc": [ + "You *cannot* trade", + "with villagers" + ] + }, + "no-exp": { + "name": "*No EXP*", + "desc": [ + "If you pickup *EXP* you die" + ], + "picked-up": "{0} collected EXP" + }, + "food-once": { + "name": "*Food Once*", + "desc": [ + "Each *food* can be*", + "*eaten* only once" + ], + "failed": "{0} suffocated by {1}", + "new-food": "You ate {1}", + "new-food-team": "{0} ate {1}", + "everyone": "Everyone", + "player": "Player" + }, + "consume-launch": { + "name": "*Consume Boost*", + "desc": [ + "When you *eat* an *item*", + "you will be *launched* into the air" + ] + }, + "low-drop-rate": { + "name": "*Low Drop Chance*", + "desc": [ + "The *drop chance* of each *block*", + "will be set to the defined *percentage*" + ] + }, + "ender-games": { + "name": "*Ender Games*", + "desc": [ + "Every *few minutes* you will be", + "*swapped* with a *random entity*", + "in a *200 blocks* range" + ], + "teleport": "Swapped with {0}" + }, + "invert-health": { + "name": "*Invert Health*", + "desc": [ + "Every few minutes the *hearts are inverted*.", + "If you have *8 hearts*, you will have *2 hearts*", + "and the other way around" + ], + "inverted": "Your hearts have been inverted" + }, + "no-shared-advancements": { + "name": "*No Shared Advancements*", + "desc": [ + "You're *not allowed* to get *advancements* someone else", + "*already did*. Else *you'll die*." + ] + }, + "quiz": { + "name": "*Quiz*", + "desc": [ + "Every *few minutes* a *random player*", + "must answer a *quiz question*" + ] + }, + "iron-golem": { + "name": "*Iron Golem*", + "desc": [ + "Kill an *Iron Golem* to win" + ] + }, + "snow-golem": { + "name": "*Snowman*", + "desc": [ + "Kill a *Snowman* to win" + ] + }, + "all-mobs": { + "name": "*All Mobs*", + "desc": [ + "Each mob has to be killed once to win" + ] + }, + "all-monster": { + "name": "*All Monsters*", + "desc": [ + "Each monster has to be killed once to win" + ] + }, + "most-deaths": { + "name": "*Most Deaths*", + "desc": [ + "Who *collects* the most *different deaths* wins" + ] + }, + "most-items": { + "name": "*Most Items*", + "desc": [ + "Who *collects* the most *different items* wins" + ] + }, + "mine-most-blocks": { + "name": "*Most Blocks*", + "desc": [ + "Who *breaks* the most *blocks* wins" + ] + }, + "most-xp": { + "name": "*Most XP*", + "desc": [ + "Who *collects* the most *EXP* wins" + ] + }, + "most-emeralds": { + "name": "*Most Emeralds*", + "desc": [ + "The player with the *most*", + "*emeralds* wins" + ] + }, + "most-ores": { + "name": "*Most Ores*", + "desc": [ + "The player that mines the most ores wins" + ] + }, + "eat-most": { + "name": "*Eat most*", + "desc": [ + "The player that fills the mods hunger bars *wins*" + ] + }, + "first-one-to-die": { + "name": "*First Death*", + "desc": [ + "Who *dies* first wins" + ] + }, + "collect-wood": { + "name": "*Collect Wood*", + "desc": [ + "Who first collected all types of wood set wins" + ] + }, + "finish-raid": { + "name": "*Finish Raid*", + "desc": [ + "The first player that *finishes* a *raid* wins" + ] + }, + "all-advancements": { + "name": "*All Advancements*", + "desc": [ + "The first player that *gets* all *advancements* wins" + ] + }, + "max-height": { + "name": "*Maximum Height*", + "desc": [ + "The *first* player to reach", + "*Y = {0}* wins" + ] + }, + "min-height": { + "name": "*Minimum Height*", + "desc": [ + "The *first* player to reach", + "*Y = {0}* wins" + ] + }, + "race": { + "name": "*Race*", + "desc": [ + "The *first* player to *reach* a", + "*random* location in the overworld wins" + ] + }, + "find-elytra": { + "name": "*Find Elytra*", + "desc": [ + "The *player* that finds an elytra *wins*" + ] + }, + "eat-cake": { + "name": "*Eat Cake*", + "desc": [ + "The player that *eats a cake* first *wins*" + ] + }, + "collect-horse-armor": { + "name": "*Collect Horse Armor*", + "desc": [ + "The player that *collects* every", + "horse armor first *wins*" + ] + }, + "collect-ice": { + "name": "*Collect Ice Blocks*", + "desc": [ + "The player that *collects* every", + "ice blocks and snow first *wins*" + ] + }, + "collect-swords": { + "name": "*Collect Swords*", + "desc": [ + "The player that *collects* every", + "sword first *wins*" + ] + }, + "collect-workstations": { + "name": "*Collect Workstations*", + "desc": [ + "The player that *collects* every", + "villager workstation first *wins*" + ] + }, + "get-full-health": { + "name": "*Get Full Health*", + "desc": [ + "The first player to gain full health wins." + ] + }, + "force-item-battle": { + "name": "*Force Item Battle*", + "desc": [ + "Each player gets *a random item* that", + "he has *to find*.", + "The player that *found* the *most items*, wins." + ] + }, + "force-mob-battle": { + "name": "*Force Mob Battle*", + "desc": [ + "Each player gets *a random mob* that", + "he has to *kill*.", + "The player that *killed* the *most mobs*, wins." + ] + }, + "force-advancement-battle": { + "name": "*Force Advancement Battle*", + "desc": [ + "Each player gets a *random advancement*,", + "that he has to complete." + ] + }, + "force-block-battle": { + "name": "*Force Block Battle*", + "desc": [ + "Every player gets a *random*", + "*block*, on which he has to stand" + ] + }, + "force-biome-battle": { + "name": "*Force Biome Battle*", + "desc": [ + "Each player gets a *random biome*,", + "that he has to *enter*." + ] + }, + "force-damage-battle": { + "name": "*Force Damage Battle*", + "desc": [ + "Each player gets a *random damage amount*,", + "that he has to *take*." + ] + }, + "force-height-battle": { + "name": "*Force Height Battle*", + "desc": [ + "Each player gets a *random height*,", + "that he has to *reach*." + ] + }, + "force-position-battle": { + "name": "*Force Position Battle*", + "desc": [ + "Each player gets a *random position*,", + "that he has to *reach*." + ] + }, + "extreme-force-battle": { + "name": "*Extreme Force Battle*", + "desc": [ + "Each player gets a *random target*,", + "that he has to reach." + ] + }, + "last-man-standing": { + "name": "*Last Man Standing*", + "desc": [ + "Who survived until the end wins" + ] + }, + "collect-all-items": { + "name": "*All Items*", + "desc": [ + "Find *all items* that are in *Minecraft*" + ] + }, + "damage-teleport": { + "name": "*Random Teleport On Damage*", + "desc": [ + "You'll be teleported randomly", + "when you take damage" + ] + }, + "zero-hearts": { + "name": "*Zero Hearts*", + "desc": [ + "After a *protection time* you have to", + "get *absorption permanently* else you will die" + ], + "bossbar": "{@symbol.arrow} Protection time {@symbol.vertical} {0}s" + } + }, + "syntax": "Please use /{0}", + "reload": "Challenges Plugin is reloading...", + "reload-failed": "An error &7occurred while reloading the plugin", + "reload-success": "Challenges Plugin successfully reloaded", + "player-command": "You must be a player!", + "no-permission": "You don't have permissions to do this", + "enabled": "Activated", + "disabled": "Deactivated", + "customize": "Customize", + "navigate-back": "« Back", + "navigate-next": "» Next", + "seconds": "seconds", + "second": "second", + "minutes": "minutes", + "minute": "minute", + "hours": "hours", + "hour": "hour", + "amplifier": "amplifier", + "open": "Open", + "everyone": "Everyone", + "player": "Active player", + "none": "None", + "inventory-color": "", + "timer-counting-up": "» Timer counting up", + "timer-counting-down": "» Timer counting down", + "timer-is-paused": "» Timer paused", + "timer-is-running": "» Timer started", + "confirm-reset": "Confirm reset with /{0}", + "no-fresh-reset": [ + "The Server can't be reset yet", + "The Challenge hasn't been started" + ], + "new-challenge": "New!", + "updated-challenge": "Updated!", + "feature-disabled": "This function is currently deactivated", + "challenge-disabled": "This challenge is currently deactivated", + "stopped-message": "Timer paused ", + "count-up-message": "Time: {0} ", + "count-down-message": "Time: {0} ", + "timer-not-started": "The timer hasn't been started", + "timer-was-started": "The timer has been started", + "timer-was-paused": "The timer has been paused", + "timer-was-set": "The timer has ben set on {0}", + "timer-already-started": "The timer is already running", + "timer-already-paused": "The timer is already paused", + "timer-mode-set-down": "The timer is counting down", + "timer-mode-set-up": "The timer is counting up", + "no-database-connection": "There is no database connection", + "fetching-data": "Data is being retrieved..", + "undefined": "undefined", + "no-such-material": "This material doesn't exist", + "not-an-item": "{0} is not an item", + "no-such-entity": "This entity doesn't exist", + "not-alive": "{0} is not a living entity", + "no-loot": "{0} doesn't have any drops", + "deprecated-plugin-version": [ + " ", + "An update for the plugin is available", + "Download: {0}", + " " + ], + "deprecated-config-version": [ + "The plugin config version is outdated ({1} \\< {0})", + "You can either manually add all missing settings or delete the old one" + ], + "missing-config-settings": "There are missing config settings: {0}", + "missing-config-settings-separator": ", ", + "no-missing-config-settings": [ + "There are no missing config settings.", + "You can manually update it to {0}" + ], + "unsuported-language": [ + "The language ({0}) is not supported" + ], + "not-op": [ + "To use this plugin you need to have permissions. Give yourself permissions in the Server Console with: /op [name]" + ], + "join-message": "{0} has joined the server", + "quit-message": "{0} has left the server", + "timer-paused-message": [ + "The timer is paused", + "Use /timer resume to start it" + ], + "cheats-detected": [ + "{0} has cheated", + "No further statistics can be collected" + ], + "cheats-already-detected": [ + "On this server has been cheated", + "No further statistics can be collected" + ], + "custom_challenges-reset": "The lokal settings were reset successfully", + "config-reset": "The local settings were reset successfully", + "player-config-loaded": "Your settings have been loaded successfully", + "player-config-saved": "Your settings have been saved successfully", + "player-config-reset": "Your settings were reset successfully", + "player-custom_challenges-loaded": "Your challenges have been loaded successfully", + "player-custom_challenges-saved": "Your challenges have been saved successfully", + "player-custom_challenges-reset": "Your challenges were successfully reset", + "item-prefix": "» ", + "item-setting-info": "➟ {0}", + "stat-dragon-killed": "Dragons killed", + "stat-deaths": "Deaths", + "stat-entity-kills": "Kills", + "stat-damage-dealt": "Damage dealt", + "stat-damage-taken": "Damage taken", + "stat-blocks-mined": "Blocks destroyed", + "stat-blocks-placed": "Blocks placed", + "stat-blocks-traveled": "Blocks travelled", + "stat-challenges-played": "Challenges played", + "stat-jumps": "Jumps", + "stats-of": "» Stats of {0}", + "stats-display": "» {0} ({1}. Platz)", + "stats-leaderboard-display": [ + "» {0}", + "{1} {2}", + "{3}. Place" + ], + "position": "{4} - {0}, {1}, {2} ({3}) {5}m", + "positions-disabled": "Positions are deactivated", + "position-other-world": "This position is in another world ({0})", + "position-not-exists": "The position {0} doesn't exist", + "position-already-exists": "The position {0} already exist", + "position-set": "{5} created position {4} {0}, {1}, {2} ({3})", + "position-deleted": "{5} deleted {4} {0}, {1}, {2} ({3})", + "no-positions": [ + "There are no positions set in this world", + "Create on with /{0}" + ], + "no-positions-global": [ + "There are no positions set", + "Create on with /{0}" + ], + "command-no-target": "No players has been found", + "command-heal-healed": "You have been healed", + "command-heal-healed-others": "You healed {0} player/s", + "command-gamemode-gamemode-changed": "Your gamemode has been changed to {0}", + "command-gamemode-gamemode-changed-others": "The gamemode of {1} player/s has been changed to {0}", + "command-village-search": "A village is being searched..", + "command-village-teleport": "You have been teleported to a village", + "command-village-not-found": "No new village was found", + "command-weather-set-clear": "Weather was changed to clear", + "command-weather-set-rain": "Weather was changed to rainy", + "command-weather-set-thunder": "Weather was changed to thundery", + "command-invsee-open": "Inventory of {0} opened", + "command-enderchest-open": "You opened your Enderchest", + "command-difficulty-change": "Difficulty changed to {0}", + "command-difficulty-current": "Current difficulty is {0}", + "command-search-nothing": "{0} is not dropped by any special block", + "command-search-result": "{0} drops from {1}", + "command-time-set": "Time was changed to {0} Ticks (ca. {1})", + "command-time-set-exact": "Time was changed to {0} ({1} Ticks)", + "command-time-query": [ + "» Current ingame times", + "Playtime {0} Ticks (Tag {1})", + "Time of day {2} Ticks (ca. {3})" + ], + "command-time-noon": "Noon", + "command-time-night": "Night", + "command-time-midnight": "Midnight", + "command-time-day": "Day", + "command-fly-enabled": "You can fly now", + "command-fly-disabled": "You can no longer fly", + "command-fly-toggled-others": "You toggled fly for {0} player/s", + "command-feed-fed": "Your appetite was sated", + "command-feed-others": "You satiated the appetite of {0} player/s", + "command-gamestate-reload": "The gamestate was reloaded", + "command-gamestate-reset": "The gamestate was reset", + "command-world-teleport": "You'll be teleported into the {0}", + "command-back-no-locations": "You weren't teleported yet", + "command-back-teleported": "You were teleported {0} location back", + "command-back-teleported-multiple": "You were teleported {0} locations back", + "command-result-no-battle-active": "There is currently no Force Battle enabled", + "command-god-mode-enabled": "You are now in God mode", + "command-god-mode-disabled": "You are no longer in God mode", + "command-god-mode-toggled-others": "{0} players are now in God mode", + "player-damage-display": "{0} took {1} damage by {2}", + "death-message": "{0} died", + "death-message-cause": "{0} died by {1}", + "unable-to-find-fortress": "No fortress could be found", + "unable-to-find-bastion": "No bastion could be found", + "death-collected": "Death reason {0} registered", + "item-collected": "Item {0} registered", + "items-to-collect": "Items to collect » {0}", + "backpacks-disabled": "Backpacks are currently deactivated", + "backpack-opened": "You opened the {0}", + "top-to-overworld": "You have been teleported to the overworld", + "top-to-surface": "You have been teleported to the top", + "random-challenge-enabled": "The challenge {0} has been activated", + "all-items-skipped": "Item {0} skipped", + "all-items-already-finished": "All items has been already found", + "all-items-found": "Item {0} registered by {1}", + "mob-kill": "{0} has been killed ({1} / {2})", + "all-advancements-goal": "Advancements » {0}", + "height-reached": "{0} reached Y = {1} first!", + "race-goal-reached": "{0} reached the goal!", + "points-change": "{0} Points", + "force-item-battle-found": "You've found {0}!", + "force-item-battle-new-item": "Item to find: {0}", + "force-item-battle-leaderboard": "Force Item Battle Leaderboard", + "force-mob-battle-killed": "You've killed {0}!", + "force-mob-battle-new-mob": "Mob to kill: {0}", + "force-mob-battle-leaderboard": "Force Mob Battle Leaderboard", + "force-advancement-battle-completed": "You've completed {0}!", + "force-advancement-battle-new-advancement": "Nächstes Advancement: {0}", + "force-advancement-battle-leaderboard": "Force Advancement Battle Leaderboard", + "force-block-battle-found": "You've found {0}!", + "force-block-battle-new-block": "Block to find: {0}", + "force-block-battle-leaderboard": "Force Block Battle Leaderboard", + "force-battle-leaderboard-entry": "{0}#{1} » {2} {3}", + "force-battle-block-target-display": "Block: {0}", + "force-battle-item-target-display": "Item: {0}", + "force-battle-height-target-display": "Height: {0}", + "force-battle-mob-target-display": "Mob: {0}", + "force-battle-biome-target-display": "Biome: {0}", + "force-battle-damage-target-display": "Damage: {0} ❤", + "force-battle-advancement-target-display": "Advancement: {0}", + "force-battle-position-target-display": "Position: {0}", + "extreme-force-battle-new-height": "Height to reach: {0}", + "extreme-force-battle-reached-height": "You've reached height {0}!", + "extreme-force-battle-new-biome": "Biome to find: {0}", + "extreme-force-battle-found-biome": "You've found the biome {0}!", + "extreme-force-battle-new-damage": "Damage to take: {0} ❤", + "extreme-force-battle-took-damage": "You took {0} ❤ damage!", + "extreme-force-battle-position": "X: {0} Z: {1}", + "extreme-force-battle-new-position": "Position to reach: {0}", + "extreme-force-battle-reached-position": "You've reached the position {0}!", + "extreme-force-battle-leaderboard": "Extreme Force Battle Leaderboard", + "force-biome-battle-leaderboard": "Force Biome Battle Leaderboard", + "force-damage-battle-leaderboard": "Force Damage Battle Leaderboard", + "force-height-battle-leaderboard": "Force Height Battle Leaderboard", + "force-position-battle-leaderboard": "Force Position Battle Leaderboard", + "quiz-how-to": "Write your answer with /guess \\", + "quiz-right-answer": "{0} is the right answer!", + "quiz-right-answer-other": "{0} answered the question correctly!", + "quiz-wrong-answer": "{0} is a wrong answer!", + "quiz-wrong-answer-other": "{0} answered the question incorrectly!", + "quiz-time-up": "The time is up!", + "quiz-cancel": "The question was cancelled!", + "quiz-right-answer-was": "The right answer was: {0}", + "quiz-right-answer-was-multiple": "the right answers were: {0}", + "quiz-question-often-have": "How often have you{1} {0}?", + "quiz-question-often-be": "How often did you{1} {0}?", + "quiz-question-far-be": "How far did you {0}?", + "quiz-question-most": "What do you have the most of these {1} {0}?", + "quiz-question-damage-have": "How much damage have you {0}", + "quiz-question-damage-taken-have": "How much damage have you taken from {0}", + "quiz-verb-traveled": "walk", + "quiz-verb-jumped": "jump", + "quiz-verb-sneaked": "sneak", + "quiz-verb-killed": "killed", + "quiz-verb-damaged": "hurt", + "quiz-verb-broken": "broken", + "quiz-verb-placed": "placed", + "quiz-verb-dropped": "dropped", + "quiz-verb-suffered": "suffered", + "bossbar-timer-paused": "» The timer is paused", + "bossbar-random-challenge-waiting": "» Waiting for new challenge..", + "bossbar-random-challenge-current": "» Challenge {0}", + "bossbar-all-items-current-max": "» {0} {1} / {2}", + "bossbar-all-items-finished": "» All items found", + "bossbar-race-goal-info": "» Goal X: {0} / Z: {1} {2} Blocks", + "bossbar-race-goal": "» Goal X: {0} / Z: {1}", + "bossbar-first-at-height-goal": "» Goal Y: {0}", + "bossbar-kill-all-bosses": "» All Bosses {0}/{1}", + "bossbar-kill-all-mobs": "» All Mobs {0}/{1}", + "bossbar-kill-all-monster": "» All Monsters {0}/{1}", + "subtitle-time-seconds": "{0} seconds", + "subtitle-time-seconds-range": "{0}-{1} seconds", + "subtitle-time-minutes": "{0} minutes", + "subtitle-launcher-description": "Power {0}", + "subtitle-range-blocks": "Range: {0} Blöcke", + "scoreboard-title": "» Challenge", + "scoreboard-leaderboard": "#{0} {1} » {2}", + "your-place": "Your place » {0}", + "server-reset": [ + "————————————————————", + " ", + "» Server reset", + " ", + "Reset by {0}", + "The server is restarting", + " ", + "————————————————————" + ], + "challenge-end-timer-hit-zero": [ + " ", + "The challenge is over!", + "Seed: {2}", + " " + ], + "challenge-end-timer-hit-zero-winner": [ + " ", + "The challenge is over!", + "Gewinner: {1}", + "Seed: {2}", + " " + ], + "challenge-end-goal-reached": [ + " ", + "The challenge was ended!", + "Time needed: {0}", + "Seed: {2}", + " " + ], + "challenge-end-goal-reached-winner": [ + " ", + "The challenge was ended!", + "Winner: {1}", + "Time needed: {0}", + "Seed: {2}", + " " + ], + "challenge-end-goal-failed": [ + " ", + "The challenge is over! #FeelsBadMan ✞", + "Time wasted: {0}", + "Seed: {2}", + " " + ], + "title-timer-started": [ + " ", + "» Timer continued" + ], + "title-timer-paused": [ + " ", + "» Timer paused" + ], + "title-challenge-enabled": [ + "{0}", + "Activated" + ], + "title-challenge-disabled": [ + "{0}", + "Deactivated" + ], + "title-challenge-value-changed": [ + "{0}", + "» {1}" + ], + "item-menu-start": "Start Challenge /start ", + "item-menu-challenges": "Challenges /challenge ", + "item-menu-timer": "Timer /timer ", + "item-menu-leaderboard": "Leaderboard /leaderboard ", + "item-menu-stats": "Statistics /stats ", + "menu-title": "Menu", + "menu-timer": "Timer", + "menu-goal": "Goal", + "menu-damage": "Schaden", + "menu-item_blocks": "Blocks & Items", + "menu-challenges": "Challenges", + "menu-settings": "Settings", + "menu-custom": "Custom Challenges", + "lore-category-activated-count": "Activated » {0}/{1}", + "lore-category-activated": "Activated » Yes", + "lore-category-deactivated": "Activated » No", + "category-misc_challenge": [ + "Miscellaneous", + "Challenges that *couldn't be*", + "*assigned* with a category" + ], + "category-randomizer": [ + "Randomizer", + "Experience a *randomized gameplay*" + ], + "category-limited_time": [ + "Limited Time", + "Some things are timely restricted" + ], + "category-force": [ + "Force", + "You have to fulfill specific", + "*intermediate goals* to survive" + ], + "category-world": [ + "World Change", + "The world will be *modified* significant" + ], + "category-damage": [ + "Schaden", + "New *damage rules*" + ], + "category-effect": [ + "Effekte", + "Have fun with *lots of effects*" + ], + "category-inventory": [ + "Inventory", + "You'll have problems managing *your inventory*" + ], + "category-movement": [ + "Bewegung", + "You're *restricted in your movements*" + ], + "category-entities": [ + "Entities", + "Entities will be *modified*" + ], + "category-extra_world": [ + "Extra Welt", + "Challenges that will *send*", + "you to *another world*" + ], + "category-misc_goal": [ + "Miscellaneous", + "Goals that *couldn't be*", + "*assigned* with a category" + ], + "category-kill_entity": [ + "Entities töten", + "Kill *specific entities* to win" + ], + "category-score_points": [ + "Best Score", + "Get the best score *to win*" + ], + "category-fastest_time": [ + "Fastest Time", + "Be the fastest *to win*" + ], + "category-force_battle": [ + "Force Battles", + "Fulfill the given *intermediate goals*", + "to earn points.", + " ", + "The player with the *most points* wins." + ], + "item-time-seconds-description": "» Time: {0} seconds", + "item-time-seconds-range-description": "» Time: {0}-{1} Sekunden", + "item-time-minutes-description": "» Time: {0} minutes", + "item-heart-damage-description": "» Damage: {0} ", + "item-heart-start-description": "» Start: {0} ", + "item-max-health-description": "» Max health: {0} ", + "item-chance-description": "» Chance: {0}%", + "item-launcher-description": "» Strength: {0}", + "item-permanent-effect-target-player-description": "» Only the active players gets the effect", + "item-permanent-effect-target-everyone-description": "» All players are getting the effect", + "item-blocks-description": "» Blocks to walk: {0}", + "item-range-blocks-description": "» Range: {0} Block", + "item-force-battle-goal-jokers": [ + "Number of jokers", + "The *amount* of *jokers*", + "hat every player has" + ], + "item-force-battle-show-scoreboard": [ + "Show Scoreboard" + ], + "item-force-battle-duped-targets": [ + "Duped Targets", + "Targets can occur *multiple times*" + ], + "item-force-position-battle-radius": [ + "Radius", + "The *maximum radius*, in which the", + "positions will be located" + ], + "item-difficulty-setting": [ + "Difficulty", + "Sets the *Difficulty*" + ], + "item-language-setting": [ + "Language", + "Sets the *Language*" + ], + "item-language-setting-german": "Deutsch", + "item-language-setting-english": "English", + "item-death-message-setting-vanilla": "Vanilla", + "item-backpack-setting-team": "Team", + "item-backpack-setting-player": "Player", + "menu-cut-clean-setting-settings": "CutClean", + "item-cut-clean-gold-setting": [ + "Gold", + "*Gold ore* will be directly dropped as *Gold ingot*" + ], + "item-cut-clean-iron-setting": [ + "Iron", + "*Iron ore* will be directly dropped as *Iron ingot*" + ], + "item-cut-clean-coal-setting": [ + "Coal", + "*Coal* will be directly dropped as *torches*" + ], + "item-cut-clean-flint-setting": [ + "Flint", + "*Gravel* will always drop *flint*" + ], + "item-cut-clean-vein-setting": [ + "Ore Veins", + "*Ore veins* will be directly destroyed" + ], + "item-cut-clean-inventory-setting": [ + "Direct Into Inventory", + "*Items* will be put *directly* into your", + "*inventory* instead of dropping" + ], + "item-cut-clean-food-setting": [ + "Cooked Food", + "*Raw meat* will be directly dropped as *cooked meat*" + ], + "no-hunger-setting": [ + "No Hunger", + "You don't get *hungry*" + ], + "pregame-movement-setting": [ + "Pregame Movement", + "You can *move* before", + "the game has been *started*" + ], + "item-timber-setting-logs": "Logs", + "item-timber-setting-logs-and-leaves": "Logs and Leaves", + "top-command-setting": [ + "Top Command", + "You can *teleport* to the *top*", + "of the world or to the *overworld*", + "with /top" + ], + "item-fortress-spawn-setting": [ + "Fortress Spawn", + "When you go into the *nether*", + "you will always spawn in a *fortress*" + ], + "item-bastion-spawn-setting": [ + "Bastion Spawn", + "When you go into the *nether*", + "you will always spawn in a *bastion*" + ], + "item-regeneration-setting-not_natural": "Not Natural", + "menu-all-blocks-disappear-challenge-settings": "All blocks disappear", + "item-all-blocks-disappear-break-challenge": [ + "By breaking", + "If you *break* a *block* all blocks", + "of the same types disappear" + ], + "item-all-blocks-disappear-place-challenge": [ + "By Placing", + "If you *place* a *block* all blocks", + "of the same types disappear" + ], + "menu-random-effect-challenge-settings": "Random Effects", + "item-random-effect-time-challenge": [ + "Interval", + "The *interval* you get the *effect* in" + ], + "item-random-effect-length-challenge": [ + "Length", + "The *length* you have the *effect*" + ], + "item-random-effect-amplifier-challenge": [ + "Amplifier", + "The *amplifier* the effect has" + ], + "menu-anvil-rain-challenge-settings": "Anvil Rain", + "item-anvil-rain-time-challenge": [ + "Interval", + "The *interval*, the *anvils* are spawning in" + ], + "item-anvil-rain-range-challenge": [ + "Range", + "The *range* of chunks, the *anvils* are spawning in" + ], + "item-anvil-rain-count-challenge": [ + "Amount", + "The *amount* of anvils that", + "are spawning in one chunk" + ], + "item-anvil-rain-damage-challenge": [ + "Damage", + "The *damage* you take from an *anvil*" + ], + "item-dragon-goal": [ + "Ender Dragon", + "Kill the *Ender Dragon* to win" + ], + "item-wither-goal": [ + "Wither", + "Kill a *Wither* to win" + ], + "item-elder-guardian-goal": [ + "Elder Guardian", + "Kill an *Elder Guardian* to win" + ], + "item-warden-goal": [ + "Warden", + "Kill an *Warden* to win" + ], + "item-collect-wood-goal-overworld": "Overworld", + "item-collect-wood-goal-nether": "Nether", + "item-collect-wood-goal-both": "Both", + "item-all-bosses-goal": [ + "All Bosses", + "Each boss must has to be killed once to win" + ], + "item-all-bosses-new-goal": [ + "All Bosses (+ Warden)", + "Each boss must has to be killed once to win" + ], + "menu-force-item-battle-goal-settings": "Force Item Battle", + "item-force-item-battle-goal-give-item": [ + "Give Item On Skip", + "If a player *skips* an item,", + "they will *receive* it" + ], + "menu-force-mob-battle-goal-settings": "Force Mob Battle", + "menu-force-advancement-battle-goal-settings": "Force Advancement Battle", + "menu-force-block-battle-goal-settings": "Force Block Battle", + "item-force-block-battle-goal-give-block": [ + "Give Block On Skip", + "If a player *skips* a block,", + "they will *receive* it" + ], + "menu-force-biome-battle-goal-settings": "Force Biome Battle", + "menu-force-damage-battle-goal-settings": "Force Damage Battle", + "menu-force-height-battle-goal-settings": "Force Height Battle", + "menu-force-position-battle-goal-settings": "Force Position Battle", + "menu-extreme-force-battle-goal-settings": "Extreme Force Battle", + "item-damage-rule-none": [ + "General Damage", + "Sets whether you can get damage or not" + ], + "item-damage-rule-fire": [ + "Fire Damage", + "Sets whether you get *damage* from *Fire* and *Lava*" + ], + "item-damage-rule-attack": [ + "Attack Damage", + "Sets whether you get *damage* from *Melee Attacks* of entites" + ], + "item-damage-rule-projectile": [ + "Projectile Damage", + "Sets whether you get *damage* from *Projectiles*" + ], + "item-damage-rule-fall": [ + "Fall Damage", + "Sets whether you get *damage* from *Fall Damage" + ], + "item-damage-rule-explosion": [ + "Explosion Damage", + "Sets whether you get *damage* from *Explosions" + ], + "item-damage-rule-drowning": [ + "Drowning Damage", + "Sets whether you get *damage* from *Drowning" + ], + "item-damage-rule-block": [ + "Block Damage", + "Sets whether you get *damage* from *Falling Blocks" + ], + "item-damage-rule-magic": [ + "Magic Damage", + "Sets whether you get *damage* from", + "*Poison, Wither or other Potions" + ], + "item-damage-rule-freeze": [ + "Freeze Damage", + "Sets whether you get *damage* from *Freezing*" + ], + "item-block-material": [ + "{0}", + "Sets whether *{1}* can be used" + ], + "custom-limit": "You've reached the limit of {0} challenges", + "custom-not-deleted": "Challenge doesn't exist yet!", + "custom-saved": "Challenge saved locally", + "custom-saved-db": [ + "To save it in your database use /db save customs", + "Warning: Old challenges will be overwritten!" + ], + "custom-no-changes": "You haven't made any changes", + "custom-name-info": "Type the new name into the chat", + "custom-command-info": [ + "Type the command without / in chat", + "Allowed commands: {0}", + "Other commands can be allowed in the config" + ], + "custom-command-not-allowed": "Command {0} is not set as allowed command in config", + "custom-chars-max_length": "You've reached the limit of {0} characters", + "custom-not-loaded": [ + " ", + "There are no currently loaded challenges.", + "You're missing your challenges? /db load customs", + "You've got problems with saving them?", + "Save your challenges before leaving with /db save customs", + " " + ], + "custom-main-view-challenges": "View Challenges", + "custom-main-create-challenge": "Create Challenge", + "custom-title-trigger": "Trigger", + "custom-title-action": "Action", + "custom-title-view": "View", + "custom-sub-finish": "Finished", + "item-custom-info-delete": [ + "Delete", + "*Warning* This Action cannot be made *undone*" + ], + "item-custom-info-save": "Save", + "item-custom-info-trigger": [ + "Trigger", + "*Click here* to set what has to be happening", + "for the *action* to execute" + ], + "item-custom-info-action": [ + "Action", + "*Click here* to set what should happen", + "once the *trigger* is met" + ], + "item-custom-info-material": [ + "Display Item", + "*Click here* to change the display item" + ], + "item-custom-info-name": [ + "Name", + "*Click here* to change the name via chat", + "Max Characters: 50" + ], + "custom-info-currently": "Set » ", + "custom-info-trigger": "Trigger", + "custom-info-action": "Action", + "item-custom-trigger-jump": [ + "Player Jumps" + ], + "item-custom-trigger-sneak": [ + "Player Sneaks" + ], + "item-custom-trigger-move_block": [ + "Player Walks A Block" + ], + "item-custom-trigger-death": [ + "Entity Dies" + ], + "item-custom-trigger-damage": [ + "Entity Takes Damage" + ], + "item-custom-trigger-damage-any": [ + "Any Cause" + ], + "item-custom-trigger-damage_by_player": [ + "Entity Takes Damage By Player" + ], + "item-custom-trigger-intervall": [ + "Interval" + ], + "item-custom-trigger-intervall-second": [ + "Each Second" + ], + "item-custom-trigger-intervall-seconds": [ + "Every {0} Seconds" + ], + "item-custom-trigger-intervall-minutes": [ + "Every {0} Minutes" + ], + "item-custom-trigger-block_place": [ + "Block Placed" + ], + "item-custom-trigger-block_break": [ + "Block Destroyed" + ], + "item-custom-trigger-consume_item": [ + "Consume Item" + ], + "item-custom-trigger-pickup_item": [ + "Pickup Item" + ], + "item-custom-trigger-drop_item": [ + "Player Dropped Item" + ], + "item-custom-trigger-advancement": [ + "Player Gets Advancement" + ], + "item-custom-trigger-hunger": [ + "Player Looses Hunger" + ], + "item-custom-trigger-move_down": [ + "Player Moves Block Down" + ], + "item-custom-trigger-move_up": [ + "Player Moves Block Up" + ], + "item-custom-trigger-move_camera": [ + "Moves Camera" + ], + "item-custom-trigger-stands_on_specific_block": [ + "Player Is On Specific Block" + ], + "item-custom-trigger-stands_not_on_specific_block": [ + "Player Is Not On Specific Block" + ], + "item-custom-trigger-gain_xp": [ + "Player Gets XP" + ], + "item-custom-trigger-level_up": [ + "Player Gets Level" + ], + "item-custom-trigger-item_craft": [ + "Player Crafts Item" + ], + "item-custom-trigger-in_liquid": [ + "Player Is In Liquid" + ], + "item-custom-trigger-get_item": [ + "Get Item", + "Action will be executed *every time*", + "item is clicked or picked up" + ], + "item-custom-action-cancel": [ + "Cancel Trigger", + "Prevent that the trigger will be executed", + "Non preventable Trigger: *Jump*, *Sneak*, *Death*", + "*Advancement*, *Level Up*, *In Liquid*" + ], + "item-custom-action-command": [ + "Execute Command", + "Make players execute commands.", + "Commands are executed for players via */execute as*.", + "Allowed commands can be set in plugin config.", + "The player doesn't need the *permission* to the commands.", + "Player aren't able to execute *plugin commands*." + ], + "item-custom-action-kill": [ + "Kill", + "Kill entities" + ], + "item-custom-action-damage": [ + "Damage", + "Hurt entities" + ], + "item-custom-action-heal": [ + "Heal", + "Restore entity health" + ], + "item-custom-action-hunger": [ + "Hunger", + "Make Entities get hunger" + ], + "item-custom-action-max_health": [ + "Change Max Health", + "Modify the max health of players.", + "Will be reset with */gamestate reset*" + ], + "item-custom-action-max_health-offset": [ + "Health Change", + "Choose how the max health should be changed" + ], + "item-custom-action-spawn_entity": [ + "Spawn Entity", + "Spawn an entity with a specific type" + ], + "item-custom-action-random_mob": [ + "Random Entity", + "Spawn a random entity" + ], + "item-custom-action-random_item": [ + "Random Item", + "Give random items to players" + ], + "item-custom-action-uncraft_inventory": [ + "Uncraft Inventory", + "Make players inventories uncraft" + ], + "item-custom-action-boost_in_air": [ + "Boost In Air", + "Boost entities into the air" + ], + "item-custom-action-boost_in_air-strength": [ + "Amplifier" + ], + "item-custom-action-potion_effect": [ + "Potion Effect", + "Add a potion effect to entities" + ], + "item-custom-action-permanent_effect": [ + "Permanent Potion Effect", + "Add a permanent potion effect to players.", + "Uses the settings of the permanent effect challenge." + ], + "item-custom-action-random_effect": [ + "Random Potion Effect", + "Add a random potion effect to entities" + ], + "item-custom-action-clear_inventory": [ + "Clear Inventory", + "Clear the inventory of players" + ], + "item-custom-action-drop_random_item": [ + "Drop Item From Inventory", + "Drop a random item from the inventory onto the floor" + ], + "item-custom-action-remove_random_item": [ + "Remove Item From Inventory", + "Remove a random item from the inventory" + ], + "item-custom-action-swap_random_item": [ + "Swap Items In Inventory", + "Swap two items in the inventory" + ], + "item-custom-action-freeze": [ + "Freeze", + "Temporarily freeze mobs", + "Uses the settings of the freeze challenge" + ], + "item-custom-action-invert_health": [ + "Invert Health", + "Invert the current health of players" + ], + "item-custom-action-water_mlg": [ + "Water MLG", + "All players have to do a water mlg to survive" + ], + "item-custom-action-jnr": [ + "Jump And Run", + "A random player has to a a jump and run", + "that gets longer everytime" + ], + "item-custom-action-win": [ + "Win", + "The challenge will be won *by specific players*" + ], + "item-custom-action-random_hotbar": [ + "Random Hotbar", + "The inventory is emptied and the player", + "gets a full hotbar of random items" + ], + "item-custom-action-modify_border": [ + "Modify World Border", + "Make the world border *bigger* or *tinier*" + ], + "item-custom-action-modify_border-change": [ + "Change" + ], + "item-custom-action-swap_mobs": [ + "Swap mobs", + "Swap a mob with another of the same world" + ], + "item-custom-action-place_structure": [ + "Place Structure", + "Places a structure" + ], + "item-custom-action-place_structure-random": "Random structure", + "item-custom-setting-target-current": [ + "Current Entity", + "The action will be executed for the *current entity*" + ], + "item-custom-setting-target-every_mob": [ + "Every Mob", + "The action will be executed for *every mob*" + ], + "item-custom-setting-target-every_mob_except_current": [ + "Every Mob Except Current", + "The action will be executed for *every mob*", + "*except* the current one" + ], + "item-custom-setting-target-every_mob_except_players": [ + "Every Mob Except Players", + "The action will be executed for *every mob except players*" + ], + "item-custom-setting-target-random_player": [ + "Random Player", + "The action will be executed for a *random player*" + ], + "item-custom-setting-target-every_player": [ + "Every Player", + "The action will be executed for *every player*" + ], + "item-custom-setting-target-current_player": [ + "Current Player", + "The action will be executed for the *active player*.", + "If the current entity is not a player nothing will be happen" + ], + "item-custom-setting-target-console": [ + "Console", + "The action will be executed for the *console*" + ], + "item-custom-setting-entity_type-any": "Any Entity", + "item-custom-setting-entity_type-player": "Player", + "item-custom-setting-block-any": "Any Block", + "item-custom-setting-item-any": "Any Item", + "custom-subsetting-target_entity": "Target Entity", + "custom-subsetting-entity_type": "Entity Type", + "custom-subsetting-liquid": "Liquid", + "custom-subsetting-time": "Time", + "custom-subsetting-damage_cause": "Damage Cause", + "custom-subsetting-amount": "Amount", + "custom-subsetting-value": "Value Editor", + "custom-subsetting-health_offset": "Change", + "custom-subsetting-length": "Length", + "custom-subsetting-amplifier": "Amplifier", + "custom-subsetting-change": "Change", + "custom-subsetting-swap_targets": "Swap Targets" +} diff --git a/language/locales/global.json b/language/locales/global.json new file mode 100644 index 000000000..df344bf81 --- /dev/null +++ b/language/locales/global.json @@ -0,0 +1,703 @@ +{ + "symbol": { + "arrow-back": "«", + "arrow": "»", + "chevron": "›", + "chevron-back": "‹", + "dart": "→", + "vertical": "┃", + "cross": "✞", + "check": "✔", + "x": "✘", + "heart": "❤", + "dot": "•", + "circle": "●", + "altert": "⚠", + "flag": "⚐", + "infinity": "∞", + "lock": "🔒", + "plus-minus": "±" + }, + "generic": { + "delimiter": ", " + }, + "arg-format": { + "hp": "{0} HP ({1} {@symbol.heart})", + "hearts": "{0} {@symbol.heart}", + "damage-cause": "{0}", + "damage-cause-source": "{0} ({1})", + "time": "{0} {1}", + "time-range": "{@time} {@symbol.plus-minus} {2} {3}" + }, + "prefix": { + "format": "{@symbol.vertical} {0} {@symbol.vertical} ", + "challenges": "{@format('Challenges')}", + "timer": "{@format('Timer')}", + "backpack": "{@format('Backpack')}", + "position": "{@format('Position')}", + "damage": "{@format('Damage')}", + "custom": "{@format('Custom')}" + }, + "item": { + "format": "{@symbol.dot} {0} {@symbol.dot}", + "format-with-command": "{@format('{0} {@symbol.vertical} {1}')}" + }, + "actionbar": { + "format": "{@symbol.dot} {0} {@symbol.dot}" + }, + "bossbar": { + "format": "{@symbol.arrow} {0}", + "format-arg": "{@format} {@symbol.vertical} {1}" + }, + "scoreboard": { + "title-format": "{@symbol.arrow} {0}", + "title": "{@title-format('Challenges')}" + }, + "timer": { + "bar": { + "format": { + "seconds": "{mm}:{ss}", + "minutes": "{mm}:{ss}", + "hours": "{hh}:{mm}:{ss}", + "day": "{d} {@generic.day} {hh}:{mm}:{ss}", + "days": "{d} {@generic.days} {hh}:{mm}:{ss}" + } + } + }, + "menu": { + "title-prefix": "{@symbol.arrow} ", + "title-delimiter": " {@symbol.vertical} ", + "title-colored": "{0}", + "title-format": "{@title-prefix}{@title-colored('{0}')}", + "title-format-page": "{@title-format('{0}')}{@title-delimiter}{@title-colored('{1}')}", + "title-name-format-sub": "{@title-colored('{0}')}{@title-delimiter}{@title-colored('{1}')}", + "item-format": "{@symbol.arrow} {0}", + "goal": { + "display": "{@name}" + }, + "timer": { + "display": "{@name}" + }, + "damage": { + "display": "{@name}" + }, + "items-blocks": { + "display": "{@name}" + }, + "challenges": { + "display": "{@name}" + }, + "settings": { + "display": "{@name}" + }, + "custom": { + "display": "{@name}" + } + }, + "category": { + "info-format": [ + " ", + "{0} {@symbol.circle} {1}" + ], + "misc_challenge": { + "*colorize*": "{0}", + "name": "*{@menu}*" + }, + "randomizer": { + "*colorize*": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "limited_time": { + "*colorize*": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "force": { + "*colorize*": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "world": { + "*colorize*": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "damage": { + "*colorize*": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "effect": { + "*colorize*": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "inventory": { + "*colorize*": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "movement": { + "*colorize*": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "entities": { + "*colorize*": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "extra_world": { + "*colorize*": "{0}", + "name": "*{@menu}*", + "info": "{@misc_challenge.info}" + }, + "misc_goal": { + "*colorize*": "{0}", + "name": "*{@menu}*" + }, + "kill_entity": { + "*colorize*": "{0}", + "name": "*{@menu}*", + "info": "{@misc_goal.info}" + }, + "score_points": { + "*colorize*": "{0}", + "name": "*{@menu}*", + "info": "{@misc_goal.info}" + }, + "fastest_time": { + "*colorize*": "{0}", + "name": "*{@menu}*", + "info": "{@misc_goal.info}" + }, + "force_battle": { + "*colorize*": "{0}", + "name": "*{@menu}*", + "info": "{@misc_goal.info}" + } + }, + "challenge": { + "display-format": [ + "{@symbol.arrow} {0}", + " ", + "{1}" + ], + "suffix-format": " {@symbol.vertical} {0}", + "settings-format": "{@symbol.dart} {0}", + "settings-format-lore": [ + " ", + "{@symbol.chevron} {0}" + ], + "subsettings-format": "{@settings-format}", + "subsettings-format-lore": "{@settings-format-lore}", + "settings-modifier-value": "{0}", + "settings-modifier-multiplier": "{0}x", + "settings-modifier-time": "{@generic.time}: {0}", + "difficulty": { + "*colorize*": "{0}" + }, + "regeneration": { + "*colorize*": "{0}" + }, + "one-life": { + "*colorize*": "{0}" + }, + "respawn": { + "*colorize*": "{0}" + }, + "split-health": { + "*colorize*": "{0}" + }, + "damage-display": { + "*colorize*": "{0}" + }, + "language": { + "*colorize*": "{0}" + }, + "pregame-movement": { + "*colorize*": "{0}" + }, + "death-message": { + "*colorize*": "{0}" + }, + "health-display": { + "*colorize*": "{0}" + }, + "position": { + "*colorize*": "{0}" + }, + "death-position": { + "*colorize*": "{0}" + }, + "glow": { + "*colorize*": "{0}" + }, + "no-item-damage": { + "*colorize*": "{0}" + }, + "mob-griefing": { + "*colorize*": "{0}" + }, + "keep-inventory": { + "*colorize*": "{0}" + }, + "backpack": { + "*colorize*": "{0}" + }, + "enderchest-command": { + "*colorize*": "{0}" + }, + "timber": { + "*colorize*": "{0}" + }, + "pvp": { + "*colorize*": "{0}" + }, + "no-hit-delay": { + "*colorize*": "{0}" + }, + "max-health": { + "*colorize*": "{0}" + }, + "damage-multiplier": { + "*colorize*": "{0}" + }, + "cut-clean": { + "*colorize*": "{0}" + }, + "no-offhand": { + "*colorize*": "{0}" + }, + "immediate-respawn": { + "*colorize*": "{0}" + }, + "slot-limit": { + "*colorize*": "{0}" + }, + "old-pvp": { + "*colorize*": "{0}" + }, + "totem-save-death": { + "*colorize*": "{0}" + }, + "soup": { + "*colorize*": "{0}" + }, + "hardcore-hearts": { + "*colorize*": "{0}" + }, + "random-challenge": { + "*colorize*": "{0}" + }, + "randomized-hp": { + "*colorize*": "{0}" + }, + "block-randomizer": { + "*colorize*": "{0}" + }, + "crafting-randomizer": { + "*colorize*": "{0}" + }, + "hotbar-randomizer": { + "*colorize*": "{0}" + }, + "entity-loot-randomizer": { + "*colorize*": "{0}" + }, + "mob-randomizer": { + "*colorize*": "{0}" + }, + "random-dropping": { + "*colorize*": "{0}" + }, + "random-item-removing": { + "*colorize*": "{0}" + }, + "random-swapping": { + "*colorize*": "{0}" + }, + "random-item": { + "*colorize*": "{0}" + }, + "random-event": { + "*colorize*": "{0}" + }, + "mob-damage-teleport": { + "*colorize*": "{0}" + }, + "force-height": { + "*colorize*": "{0}" + }, + "force-block": { + "*colorize*": "{0}" + }, + "force-mob": { + "*colorize*": "{0}" + }, + "force-item": { + "*colorize*": "{0}" + }, + "force-biome": { + "*colorize*": "{0}" + }, + "hydra": { + "*colorize*": "{0}" + }, + "hydra-plus": { + "*colorize*": "{0}" + }, + "duped-spawning": { + "*colorize*": "{0}" + }, + "jump-entity": { + "*colorize*": "{0}" + }, + "invisible-mobs": { + "*colorize*": "{0}" + }, + "stone-sight": { + "*colorize*": "{0}" + }, + "mob-sight-damage": { + "*colorize*": "{0}" + }, + "all-mobs-to-death-position": { + "*colorize*": "{0}" + }, + "respawn-end": { + "*colorize*": "{0}" + }, + "mob-transformation": { + "*colorize*": "{0}" + }, + "block-mobs": { + "*colorize*": "{0}" + }, + "damage-per-block": { + "*colorize*": "{0}" + }, + "sneak-damage": { + "*colorize*": "{0}" + }, + "jump-damage": { + "*colorize*": "{0}" + }, + "block-break-damage": { + "*colorize*": "{0}" + }, + "block-place-damage": { + "*colorize*": "{0}" + }, + "advancement-damage": { + "*colorize*": "{0}" + }, + "damage-item": { + "*colorize*": "{0}" + }, + "water-allergy": { + "*colorize*": "{0}" + }, + "death-on-fall": { + "*colorize*": "{0}" + }, + "reversed-damage": { + "*colorize*": "{0}" + }, + "freeze": { + "*colorize*": "{0}" + }, + "delay-damage": { + "*colorize*": "{0}" + }, + "chunk-effect": { + "*colorize*": "{0}" + }, + "block-effect": { + "*colorize*": "{0}" + }, + "entity-effect": { + "*colorize*": "{0}" + }, + "random-effect": { + "*colorize*": "{0}" + }, + "permanent-effect-on-damage": { + "*colorize*": "{0}" + }, + "infection": { + "*colorize*": "{0}" + }, + "surface-hole": { + "*colorize*": "{0}" + }, + "bedrock-walls": { + "*colorize*": "{0}" + }, + "bedrock-path": { + "*colorize*": "{0}" + }, + "floor-is-lava": { + "*colorize*": "{0}" + }, + "chunk-deconstruction": { + "*colorize*": "{0}" + }, + "all-blocks-disappear": { + "*colorize*": "{0}" + }, + "anvil-rain": { + "*colorize*": "{0}" + }, + "tsunami": { + "*colorize*": "{0}" + }, + "repeat-in-chunk": { + "*colorize*": "{0}" + }, + "snake": { + "*colorize*": "{0}" + }, + "blocks-fly": { + "*colorize*": "{0}" + }, + "blocks-disappear-time": { + "*colorize*": "{0}" + }, + "loop": { + "*colorize*": "{0}" + }, + "ice-floor": { + "*colorize*": "{0}" + }, + "level-border": { + "*colorize*": "{0}" + }, + "chunk-deletion": { + "*colorize*": "{0}" + }, + "permanent-item": { + "*colorize*": "{0}" + }, + "no-duped-items": { + "*colorize*": "{0}" + }, + "damage-inv-clear": { + "*colorize*": "{0}" + }, + "uncraft-items": { + "*colorize*": "{0}" + }, + "missing-items": { + "*colorize*": "{0}" + }, + "pickup-launch": { + "*colorize*": "{0}" + }, + "block-chunk-item-remove": { + "*colorize*": "{0}" + }, + "traffic-light": { + "*colorize*": "{0}" + }, + "hunger-block": { + "*colorize*": "{0}" + }, + "only-down": { + "*colorize*": "{0}" + }, + "only-dirt": { + "*colorize*": "{0}" + }, + "higher-jumps": { + "*colorize*": "{0}" + }, + "always-running": { + "*colorize*": "{0}" + }, + "dont-stop-running": { + "*colorize*": "{0}" + }, + "no-mouse-move": { + "*colorize*": "{0}" + }, + "five-hundred-blocks": { + "*colorize*": "{0}" + }, + "max-biome-time": { + "*colorize*": "{0}" + }, + "max-height-time": { + "*colorize*": "{0}" + }, + "water-mlg": { + "*colorize*": "{0}" + }, + "jump-and-run": { + "*colorize*": "{0}" + }, + "one-durability": { + "*colorize*": "{0}" + }, + "no-trading": { + "*colorize*": "{0}" + }, + "no-exp": { + "*colorize*": "{0}" + }, + "food-once": { + "*colorize*": "{0}" + }, + "consume-launch": { + "*colorize*": "{0}" + }, + "low-drop-rate": { + "*colorize*": "{0}" + }, + "ender-games": { + "*colorize*": "{0}" + }, + "invert-health": { + "*colorize*": "{0}" + }, + "no-shared-advancements": { + "*colorize*": "{0}" + }, + "quiz": { + "*colorize*": "{0}" + }, + "goal-ender-dragon": { + "*colorize*": "{0}" + }, + "goal-wither": { + "*colorize*": "{0}" + }, + "goal-elder-guardian": { + "*colorize*": "{0}" + }, + "goal-warden": { + "*colorize*": "{0}" + }, + "goal-all-bosses": { + "*colorize*": "{0}" + }, + "goal-all-bosses-new": { + "*colorize*": "{0}" + }, + "iron-golem": { + "*colorize*": "{0}" + }, + "snow-golem": { + "*colorize*": "{0}" + }, + "all-mobs": { + "*colorize*": "{0}" + }, + "all-monster": { + "*colorize*": "{0}" + }, + "most-deaths": { + "*colorize*": "{0}" + }, + "most-items": { + "*colorize*": "{0}" + }, + "mine-most-blocks": { + "*colorize*": "{0}" + }, + "most-xp": { + "*colorize*": "{0}" + }, + "most-emeralds": { + "*colorize*": "{0}" + }, + "most-ores": { + "*colorize*": "{0}" + }, + "eat-most": { + "*colorize*": "{0}" + }, + "first-one-to-die": { + "*colorize*": "{0}" + }, + "collect-wood": { + "*colorize*": "{0}" + }, + "finish-raid": { + "*colorize*": "{0}" + }, + "all-advancements": { + "*colorize*": "{0}" + }, + "max-height": { + "*colorize*": "{0}" + }, + "min-height": { + "*colorize*": "{0}" + }, + "race": { + "*colorize*": "{0}" + }, + "find-elytra": { + "*colorize*": "{0}" + }, + "eat-cake": { + "*colorize*": "{0}" + }, + "collect-horse-armor": { + "*colorize*": "{0}" + }, + "collect-ice": { + "*colorize*": "{0}" + }, + "collect-swords": { + "*colorize*": "{0}" + }, + "collect-workstations": { + "*colorize*": "{0}" + }, + "get-full-health": { + "*colorize*": "{0}" + }, + "force-item-battle": { + "*colorize*": "{0}" + }, + "force-mob-battle": { + "*colorize*": "{0}" + }, + "force-advancement-battle": { + "*colorize*": "{0}" + }, + "force-block-battle": { + "*colorize*": "{0}" + }, + "force-biome-battle": { + "*colorize*": "{0}" + }, + "force-damage-battle": { + "*colorize*": "{0}" + }, + "force-height-battle": { + "*colorize*": "{0}" + }, + "force-position-battle": { + "*colorize*": "{0}" + }, + "extreme-force-battle": { + "*colorize*": "{0}" + }, + "last-man-standing": { + "*colorize*": "{0}" + }, + "collect-all-items": { + "*colorize*": "{0}" + }, + "damage-teleport": { + "*colorize*": "{0}" + }, + "zero-hearts": { + "*colorize*": "{0}" + } + } +} diff --git a/plugin/build.gradle.kts b/plugin/build.gradle.kts index c22543d48..5da565b54 100644 --- a/plugin/build.gradle.kts +++ b/plugin/build.gradle.kts @@ -52,7 +52,7 @@ tasks { processResources { from("../language") { into("language") - include("**/*.json") + include("locales/*.json", "languages.json") } // minify bundled json resources: doLast so we only modify the files AFTER they have been copied diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java index ad425afbe..4153a4141 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/DamageTeleportChallenge.java @@ -23,7 +23,7 @@ public class DamageTeleportChallenge extends SettingModifier { private static final int PLAYER = 1, EVERYONE = 2; public DamageTeleportChallenge() { - super(MenuType.CHALLENGES, null, 1, 2, new ItemStack(Material.SHULKER_SHELL), "item-damage-teleport-challenge"); + super(MenuType.CHALLENGES, null, 1, 2, new ItemStack(Material.SHULKER_SHELL), "damage-teleport"); } // @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index f9507c6e9..bf63cff0d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -31,7 +31,7 @@ public class ZeroHeartsChallenge extends SettingModifier { public ZeroHeartsChallenge() { - super(MenuType.CHALLENGES, null, 5, 30, 10, new ItemStack(Material.ENCHANTED_GOLDEN_APPLE), "zero-hearts-challenge"); + super(MenuType.CHALLENGES, null, 5, 30, 10, new ItemStack(Material.ENCHANTED_GOLDEN_APPLE), "zero-hearts"); } @Override @@ -39,7 +39,7 @@ protected void onEnable() { bossbar.setContent((bossbar, player) -> { int currentTime = getCurrentTime(); int maxTime = getValue() * 60; - bossbar.setTitle(Message.forName("bossbar-zero-hearts").asString(maxTime - currentTime)); + bossbar.setTitle(getChallengeMessageKey("bossbar"), maxTime - currentTime); bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(1 - ((float) currentTime / maxTime)); }); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java index 62c1cfa1a..e6e2d107a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java @@ -14,7 +14,7 @@ public class AdvancementDamageChallenge extends SettingModifier { public AdvancementDamageChallenge() { - super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 40, new ItemStack(Material.BOOK), "advancement-damage-challenge"); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 40, new ItemStack(Material.BOOK), "advancement-damage"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java index f6c411c0c..31979f563 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java @@ -12,7 +12,7 @@ public class BlockBreakDamageChallenge extends SettingModifier { public BlockBreakDamageChallenge() { - super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 60, new ItemStack(Material.GOLDEN_PICKAXE), "item-block-break-damage-challenge"); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 60, new ItemStack(Material.GOLDEN_PICKAXE), "block-break-damage"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java index f802de558..1583d7af6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java @@ -14,7 +14,7 @@ public class BlockPlaceDamageChallenge extends SettingModifier { public BlockPlaceDamageChallenge() { - super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 60, new ItemStack(Material.GOLD_BLOCK), "block-place-damange-challenge"); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 60, new ItemStack(Material.GOLD_BLOCK), "block-place-damage"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java index bcde16c2d..8c91c8b73 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java @@ -17,7 +17,7 @@ public class DamagePerBlockChallenge extends SettingModifier { public DamagePerBlockChallenge() { super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 40, new StandardItemBuilder.LeatherArmorBuilder(Material.LEATHER_BOOTS).setColor(Color.RED).build(), - "damage-per-block-challenge"); + "damage-per-block"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java index 91020a5c2..37437c367 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerItemChallenge.java @@ -16,7 +16,7 @@ public class DamagePerItemChallenge extends Setting { public DamagePerItemChallenge() { - super(MenuType.CHALLENGES, SettingCategory.DAMAGE, new ItemStack(Material.SHEARS), "damage-item-challenge"); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, new ItemStack(Material.SHEARS), "damage-item"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java index 07e8cd8f9..f6ba5f266 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DeathOnFallChallenge.java @@ -17,7 +17,7 @@ public class DeathOnFallChallenge extends Setting { public DeathOnFallChallenge() { - super(MenuType.CHALLENGES, SettingCategory.DAMAGE, new ItemStack(Material.FEATHER), "item-death-on-fall-challenge"); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, new ItemStack(Material.FEATHER), "death-on-fall"); } @EventHandler(priority = EventPriority.HIGH) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java index 0356fca35..7479054f6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -25,7 +26,7 @@ public class DelayDamageChallenge extends TimedChallenge { private final Map damageMap = new HashMap<>(); public DelayDamageChallenge() { - super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 64, 4, false, new ItemStack(Material.REDSTONE), "item-delay-damage"); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 64, 4, false, new ItemStack(Material.REDSTONE), "delay-damage"); } // @Nullable @@ -52,7 +53,7 @@ protected void onTimeActivation() { canGetDamage = true; for (Player player : Bukkit.getOnlinePlayers()) { player.damage(totalDamage); - Message.forName(("extreme-force-battle-took-damage")).send(player, Prefix.DAMAGE, totalDamage / 2); + MessageKey.of(("extreme-force-battle-took-damage")).send(player, Prefix.DAMAGE, totalDamage / 2); } canGetDamage = false; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java index 10b07b421..9c06711df 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java @@ -21,7 +21,7 @@ public class FreezeChallenge extends SettingModifier { public FreezeChallenge() { - super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 5, 60, 20, new ItemStack(Material.BLUE_ICE), "item-freeze-challenge"); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 5, 60, 20, new ItemStack(Material.BLUE_ICE), "freeze"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java index dde622ca8..e48a33450 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java @@ -3,7 +3,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -22,7 +21,7 @@ public class JumpDamageChallenge extends SettingModifier { public JumpDamageChallenge() { super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 60, new StandardItemBuilder.LeatherArmorBuilder(Material.LEATHER_BOOTS).setColor(Color.ORANGE).build(), - "jump-damage-challenge"); + "jump-damage"); } // @Nullable @@ -40,7 +39,7 @@ public void playValueChangeTitle() { public void onSneak(@NotNull PlayerJumpEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; - MessageKey.of("jump-damage-failed").broadcast(Prefix.CHALLENGES, event.getPlayer()); + getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, event.getPlayer()); event.getPlayer().setNoDamageTicks(0); event.getPlayer().damage(getValue()); event.getPlayer().setNoDamageTicks(0); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java index af12ee6dc..5c46c659e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/ReversedDamageChallenge.java @@ -13,7 +13,7 @@ public class ReversedDamageChallenge extends Setting { public ReversedDamageChallenge() { - super(MenuType.CHALLENGES, SettingCategory.DAMAGE, new ItemStack(Material.GOLDEN_SWORD), "reversed-damange-challenge"); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, new ItemStack(Material.GOLDEN_SWORD), "reversed-damage"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java index 8c205848b..61bc8fb34 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java @@ -19,7 +19,7 @@ public class SneakDamageChallenge extends SettingModifier { public SneakDamageChallenge() { super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 60, new StandardItemBuilder.LeatherArmorBuilder(Material.LEATHER_BOOTS).setColor(Color.YELLOW).build(), - "sneak-damage-challenge"); + "sneak-damage"); } // @Nullable @@ -38,7 +38,7 @@ public void onSneak(@NotNull PlayerToggleSneakEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (!event.isSneaking()) return; - Message.forName("sneak-damage-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); event.getPlayer().setNoDamageTicks(0); event.getPlayer().damage(getValue()); event.getPlayer().setNoDamageTicks(0); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java index ebda0f4dd..d3df9b29e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java @@ -15,7 +15,7 @@ public class WaterAllergyChallenge extends SettingModifier { public WaterAllergyChallenge() { - super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 40, new ItemStack(Material.CYAN_GLAZED_TERRACOTTA), "water-allergy-challenge"); + super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 40, new ItemStack(Material.CYAN_GLAZED_TERRACOTTA), "water-allergy"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java index 5c395667f..37a8a7223 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java @@ -39,7 +39,7 @@ public class BlockEffectChallenge extends Setting { private Map currentPotionEffects = new HashMap<>(); public BlockEffectChallenge() { - super(MenuType.CHALLENGES, SettingCategory.EFFECT, new ItemStack(Material.CARVED_PUMPKIN), "block-effect-challenge"); + super(MenuType.CHALLENGES, SettingCategory.EFFECT, new ItemStack(Material.CARVED_PUMPKIN), "block-effect"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java index 408017ad6..9f795095f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java @@ -37,7 +37,7 @@ public class ChunkRandomEffectChallenge extends Setting { private long worldSeed; public ChunkRandomEffectChallenge() { - super(MenuType.CHALLENGES, SettingCategory.EFFECT, new ItemStack(Material.CAULDRON), "chunk-effect-challenge"); + super(MenuType.CHALLENGES, SettingCategory.EFFECT, new ItemStack(Material.CAULDRON), "chunk-effect"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java index 7e6878301..e87d8106c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java @@ -20,7 +20,7 @@ public class EntityRandomEffectChallenge extends Setting { public EntityRandomEffectChallenge() { - super(MenuType.CHALLENGES, SettingCategory.EFFECT, new ItemStack(Material.PHANTOM_MEMBRANE), "entity-effect-challenge"); + super(MenuType.CHALLENGES, SettingCategory.EFFECT, new ItemStack(Material.PHANTOM_MEMBRANE), "entity-effect"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java index 366337d0c..99b61ce76 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/InfectionChallenge.java @@ -22,7 +22,7 @@ public class InfectionChallenge extends Setting { public InfectionChallenge() { - super(MenuType.CHALLENGES, SettingCategory.EFFECT, new ItemStack(Material.SLIME_BALL), "infection-challenge"); + super(MenuType.CHALLENGES, SettingCategory.EFFECT, new ItemStack(Material.SLIME_BALL), "infection"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java index da7eeac65..612b5cd45 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java @@ -4,7 +4,6 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -41,7 +40,7 @@ public class PermanentEffectOnDamageChallenge extends SettingModifier { private final Random random = new Random(); public PermanentEffectOnDamageChallenge() { - super(MenuType.CHALLENGES, SettingCategory.EFFECT, 1, 2, new ItemStack(Material.MAGMA_CREAM), "permanent-effect-on-damage-challenge"); + super(MenuType.CHALLENGES, SettingCategory.EFFECT, 1, 2, new ItemStack(Material.MAGMA_CREAM), "permanent-effect-on-damage"); } // @NotNull @@ -143,9 +142,9 @@ private void applyNewEffect(@NotNull Player player, @NotNull PotionEffectType po } if (effectsToEveryone()) { - MessageKey.of("new-effect").broadcast(Prefix.CHALLENGES, potionEffectType, amplifier); + getChallengeMessageKey("new-effect").broadcast(Prefix.CHALLENGES, potionEffectType, amplifier); } else { - MessageKey.of("new-effect").send(player, Prefix.CHALLENGES, potionEffectType, amplifier); + getChallengeMessageKey("new-effect").send(player, Prefix.CHALLENGES, potionEffectType, amplifier); } getGameStateData().set(path, effects); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java index d1b0bea4d..7a2b8714e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/RandomPotionEffectChallenge.java @@ -29,7 +29,7 @@ public class RandomPotionEffectChallenge extends MenuSetting { public RandomPotionEffectChallenge() { // super(Message.forName("menu-random-effect-challenge-settings")); - super(MenuType.CHALLENGES, SettingCategory.EFFECT, new ItemStack(Material.BREWING_STAND), "random-effect-challenge"); + super(MenuType.CHALLENGES, SettingCategory.EFFECT, new ItemStack(Material.BREWING_STAND), "random-effect"); // registerSetting("time", new NumberSubSetting( // () -> new LegacyItemBuilder(Material.CLOCK, Message.forName("item-random-effect-time-challenge")), // value -> null, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java index 7dc96d1e4..d630fc9fe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/AllMobsToDeathPoint.java @@ -18,7 +18,7 @@ public class AllMobsToDeathPoint extends Setting { public AllMobsToDeathPoint() { - super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.SPAWNER), "all-mobs-to-deaht-position"); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.SPAWNER), "all-mobs-to-death-position"); } @EventHandler diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java index 92df6aa8d..0d9b3abee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/BlockMobsChallenge.java @@ -25,7 +25,7 @@ public class BlockMobsChallenge extends Setting { public BlockMobsChallenge() { - super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.BRICKS), "block-mobs-challenge"); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.BRICKS), "block-mobs"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java index c239c796b..5736b6fa8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/DupedSpawningChallenge.java @@ -16,7 +16,7 @@ public class DupedSpawningChallenge extends Setting { private boolean inCustomSpawn = false; public DupedSpawningChallenge() { - super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.ELDER_GUARDIAN_SPAWN_EGG), "duped-spawning-challenge"); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.ELDER_GUARDIAN_SPAWN_EGG), "duped-spawning"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java index ad2144995..01e96e4f3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/HydraNormalChallenge.java @@ -11,7 +11,7 @@ public class HydraNormalChallenge extends HydraChallenge { public HydraNormalChallenge() { - super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.WITCH_SPAWN_EGG), "hydra-plus"); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.WITCH_SPAWN_EGG), "hydra"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java index 187778736..4a16c4298 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/InvisibleMobsChallenge.java @@ -25,7 +25,7 @@ public class InvisibleMobsChallenge extends Setting { public InvisibleMobsChallenge() { super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new StandardItemBuilder.PotionBuilder(Material.POTION).setColor(Color.WHITE).build(), - "invsible-mobs-challenge"); + "invisible-mobs"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java index 64ce4e70b..515d5113d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java @@ -19,7 +19,7 @@ public class MobSightDamageChallenge extends SettingModifier { public MobSightDamageChallenge() { - super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.SPIDER_EYE), "no-mob-sight-damage-challenge"); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.SPIDER_EYE), "mob-sight-damage"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java index 4a4d70c9d..ee52a92a2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java @@ -2,7 +2,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -24,7 +23,7 @@ public class MobTransformationChallenge extends Setting { public MobTransformationChallenge() { - super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.STONE_SWORD), "mob-transformation-challenge"); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.STONE_SWORD), "mob-transformation"); } @Override @@ -33,7 +32,7 @@ protected void onEnable() { bossbar.setColor(BossBar.Color.GREEN); EntityType type = getPlayerData(player).getEnum("type", EntityType.class); Object typeName = type == null ? "None" : type; - bossbar.setTitle(MessageKey.of("bossbar-mob-transformation"), typeName); + bossbar.setTitle(getChallengeMessageKey("bossbar"), typeName); }); bossbar.show(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java index 66f1e2982..9b88deb03 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java @@ -4,7 +4,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -35,14 +34,14 @@ public class MobsRespawnInEndChallenge extends Setting { private int totalMobsInEnd = 0; public MobsRespawnInEndChallenge() { - super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.ENDER_EYE), "respawn-end-challenge"); + super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.ENDER_EYE), "respawn-end"); } @Override protected void onEnable() { bossbar.setContent((bar, player) -> { bar.setColor(BossBar.Color.PURPLE); - bar.setTitle(MessageKey.of("bossbar-respawn-end"), totalMobsInEnd); + bar.setTitle(getChallengeMessageKey("bossbar"), totalMobsInEnd); }); bossbar.show(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java index 3895ce9f1..528778de6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/NewEntityOnJumpChallenge.java @@ -20,7 +20,7 @@ public class NewEntityOnJumpChallenge extends Setting { public NewEntityOnJumpChallenge() { super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new StandardItemBuilder.LeatherArmorBuilder(Material.LEATHER_BOOTS).setColor(Color.GREEN).build(), - "jump-entity-challenge"); + "jump-entity"); } @EventHandler(priority = EventPriority.HIGH) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java index 70d8f673f..cc0acd0b7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java @@ -5,6 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.WorldDependentChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Updated; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; @@ -18,6 +19,7 @@ import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.commons.common.config.Document; import org.bukkit.*; import org.bukkit.block.Block; @@ -51,9 +53,15 @@ public JumpAndRunChallenge() { super(MenuType.CHALLENGES, 1, 10, 5, new ItemStack(Material.ACACIA_STAIRS), "jump-and-run"); } + @NotNull + @Override + public LocalizableMessage getSettingsName() { + return MessageKey.of("generic.enabled"); + } + @Override public LocalizableMessage getSettingsDescription() { - return MessageKey.of("item-time-seconds-range-description").withArgs(getValue() * 60 - 30, getValue() * 60 + 30); + return MessageKey.of("challenge.settings-modifier-time").withArgs(ArgumentFormat.SECONDS_RANGE.apply(Tuple.of(getValue() * 60, 30))); } @Override @@ -73,11 +81,11 @@ protected void handleCountdown() { case 5: case 3: case 2: - MessageKey.of("jnr-countdown").broadcast(Prefix.CHALLENGES, getSecondsLeftUntilNextActivation()); + getChallengeMessageKey("countdown").broadcast(Prefix.CHALLENGES, getSecondsLeftUntilNextActivation()); SoundSample.BASS_OFF.broadcast(); break; case 1: - MessageKey.of("jnr-countdown-one").broadcast(Prefix.CHALLENGES); + getChallengeMessageKey("countdown-one").broadcast(Prefix.CHALLENGES); SoundSample.BASS_OFF.broadcast(); break; } @@ -159,7 +167,7 @@ protected void finishJumpAndRun(@NotNull Player player) { jumps++; jumpAndRunsDone++; - MessageKey.of("jnr-finished").broadcast(Prefix.CHALLENGES, player); + getChallengeMessageKey("finished").broadcast(Prefix.CHALLENGES, player); exitJumpAndRun(); SoundSample.KLING.broadcast(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java index 018f1830c..488ef3c6b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java @@ -4,7 +4,11 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.WorldDependentChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.commons.common.collection.pair.Tuple; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; @@ -19,14 +23,19 @@ public class WaterMLGChallenge extends WorldDependentChallenge { public WaterMLGChallenge() { - super(MenuType.CHALLENGES, 1, 10, 5, new ItemStack(Material.WATER_BUCKET), "water-mlg-challenge"); + super(MenuType.CHALLENGES, 1, 10, 5, new ItemStack(Material.WATER_BUCKET), "water-mlg"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 10, getValue() * 60 + 10); -// } + @NotNull + @Override + public LocalizableMessage getSettingsName() { + return MessageKey.of("generic.enabled"); + } + + @Override + public LocalizableMessage getSettingsDescription() { + return MessageKey.of("challenge.settings-modifier-time").withArgs(ArgumentFormat.SECONDS_RANGE.apply(Tuple.of(getValue() * 60, 10))); + } @Override public void playValueChangeTitle() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java index 1b08b0857..b00adc30e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java @@ -5,7 +5,6 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -38,7 +37,7 @@ public class ForceBiomeChallenge extends CompletableForceChallenge { private Biome biome; public ForceBiomeChallenge() { - super(MenuType.CHALLENGES, SettingCategory.FORCE, 2, 20, 5, new ItemStack(Material.CHAINMAIL_BOOTS), "force-biome-challenge"); + super(MenuType.CHALLENGES, SettingCategory.FORCE, 2, 20, 5, new ItemStack(Material.CHAINMAIL_BOOTS), "force-biome"); } // @Nullable @@ -57,24 +56,24 @@ public void playValueChangeTitle() { protected BiConsumer setupBossbar() { return (bossbar, player) -> { if (getState() == WAITING) { - bossbar.setTitle(MessageKey.of("bossbar-force-biome-waiting")); + bossbar.setTitle(getChallengeMessageKey("bossbar-waiting")); return; } bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(getProgress()); - bossbar.setTitle(MessageKey.of("bossbar-force-biome-instruction"), biome, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); + bossbar.setTitle(getChallengeMessageKey("bossbar-instruction"), biome, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); }; } @Override protected void broadcastFailedMessage() { - MessageKey.of("force-biome-fail").broadcast(Prefix.CHALLENGES, biome); + getChallengeMessageKey("fail").broadcast(Prefix.CHALLENGES, biome); } @Override protected void broadcastSuccessMessage(@NotNull Player player) { - MessageKey.of("force-biome-success").broadcast(Prefix.CHALLENGES, player, biome); + getChallengeMessageKey("success").broadcast(Prefix.CHALLENGES, player, biome); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java index c2e1a247e..bac8444e8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java @@ -4,7 +4,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -50,13 +49,13 @@ public void playValueChangeTitle() { protected BiConsumer setupBossbar() { return (bossbar, player) -> { if (getState() == WAITING) { - bossbar.setTitle(MessageKey.of("bossbar-force-block-waiting")); + bossbar.setTitle(getChallengeMessageKey("bossbar-waiting")); return; } bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(getProgress()); - bossbar.setTitle(MessageKey.of("bossbar-force-block-instruction"), block, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); + bossbar.setTitle(getChallengeMessageKey("bossbar-instruction"), block, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); }; } @@ -75,12 +74,12 @@ protected boolean isFailing(@NotNull Player player) { @Override protected void broadcastFailedMessage(@NotNull Player player) { - Message.forName("force-block-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), player.getLocation().subtract(0, 1, 0).getBlock().getType()); + getChallengeMessageKey("fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), player.getLocation().subtract(0, 1, 0).getBlock().getType()); } @Override protected void broadcastSuccessMessage() { - Message.forName("force-block-success").broadcast(Prefix.CHALLENGES); + getChallengeMessageKey("success").broadcast(Prefix.CHALLENGES); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java index ca52866a1..3c1a99ed2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java @@ -4,7 +4,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -30,7 +29,7 @@ public class ForceHeightChallenge extends EndingForceChallenge { private int height; public ForceHeightChallenge() { - super(MenuType.CHALLENGES, SettingCategory.FORCE, 2, 15, new ItemStack(Material.IRON_BOOTS), "force-height-challenge"); + super(MenuType.CHALLENGES, SettingCategory.FORCE, 2, 15, new ItemStack(Material.IRON_BOOTS), "force-height"); } // @Nullable @@ -49,13 +48,13 @@ public void playValueChangeTitle() { protected BiConsumer setupBossbar() { return (bossbar, player) -> { if (getState() == WAITING) { - bossbar.setTitle(MessageKey.of("bossbar-force-height-waiting")); + bossbar.setTitle(getChallengeMessageKey("bossbar-waiting")); return; } bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(getProgress()); - bossbar.setTitle(MessageKey.of("bossbar-force-height-instruction"), height, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); + bossbar.setTitle(getChallengeMessageKey("bossbar-instruction"), height, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); }; } @@ -66,12 +65,12 @@ protected boolean isFailing(@NotNull Player player) { @Override protected void broadcastFailedMessage(@NotNull Player player) { - MessageKey.of("force-height-fail").broadcast(Prefix.CHALLENGES, player, player.getLocation().getBlockY()); + getChallengeMessageKey("fail").broadcast(Prefix.CHALLENGES, player, player.getLocation().getBlockY()); } @Override protected void broadcastSuccessMessage() { - MessageKey.of("force-height-success").broadcast(Prefix.CHALLENGES); + getChallengeMessageKey("success").broadcast(Prefix.CHALLENGES); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java index 542acc94e..cfada5bcf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java @@ -4,7 +4,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; @@ -60,24 +59,24 @@ public void playValueChangeTitle() { protected BiConsumer setupBossbar() { return (bossbar, player) -> { if (getState() == WAITING) { - bossbar.setTitle(MessageKey.of("bossbar-force-item-waiting")); + bossbar.setTitle(getChallengeMessageKey("bossbar-waiting")); return; } bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(getProgress()); - bossbar.setTitle(MessageKey.of("bossbar-force-item-instruction"), item, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); + bossbar.setTitle(getChallengeMessageKey("bossbar-instruction"), item, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); }; } @Override protected void broadcastFailedMessage() { - Message.forName("force-item-fail").broadcast(Prefix.CHALLENGES, item); + getChallengeMessageKey("fail").broadcast(Prefix.CHALLENGES, item); } @Override protected void broadcastSuccessMessage(@NotNull Player player) { - Message.forName("force-item-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), item); + getChallengeMessageKey("success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), item); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java index b5fb9da46..139a15cd0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java @@ -3,7 +3,6 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; @@ -55,24 +54,24 @@ public void playValueChangeTitle() { protected BiConsumer setupBossbar() { return (bossbar, player) -> { if (getState() == WAITING) { - bossbar.setTitle(MessageKey.of("bossbar-force-mob-waiting")); + bossbar.setTitle(getChallengeMessageKey("bossbar-waiting")); return; } bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(getProgress()); - bossbar.setTitle(MessageKey.of("bossbar-force-mob-instruction"), entity, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); + bossbar.setTitle(getChallengeMessageKey("bossbar-instruction"), entity, ChallengeAPI.formatTime(getSecondsLeftUntilNextActivation())); }; } @Override protected void broadcastFailedMessage() { - MessageKey.of("force-mob-fail").broadcast(Prefix.CHALLENGES, entity); + getChallengeMessageKey("fail").broadcast(Prefix.CHALLENGES, entity); } @Override protected void broadcastSuccessMessage(@NotNull Player player) { - MessageKey.of("force-mob-success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), entity); + getChallengeMessageKey("success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), entity); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java index e2c921710..115e8d238 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java @@ -44,7 +44,7 @@ public class MissingItemsChallenge extends TimedChallenge implements PlayerComma private List materials; public MissingItemsChallenge() { - super(MenuType.CHALLENGES, SettingCategory.INVENTORY, 1, 10, 5, false, new ItemStack(Material.FISHING_ROD), "missing-items-challenge"); + super(MenuType.CHALLENGES, SettingCategory.INVENTORY, 1, 10, 5, false, new ItemStack(Material.FISHING_ROD), "missing-items"); } // @Nullable @@ -151,8 +151,8 @@ private void createMissingItemsInventory(@NotNull Player player, Consumer } private void sendInfoText(@NotNull Player player) { - String message = Message.forName("missing-items-inventory").asString("§7"); - String openMessage = Message.forName("missing-items-inventory-open").asString(); + String message = Message.forName("challenge.missing-items.inventory").asString("§7"); + String openMessage = Message.forName("challenge.missing-items.inventory-open").asString(); TextComponent messageComponent = new TextComponent(Prefix.CHALLENGES + message + " "); @@ -173,7 +173,7 @@ private boolean openGameInventory(@NotNull Player player) { } private Tuple generateMissingItemsInventory(@NotNull ItemStack itemStack) { - Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(Message.forName("missing-items-inventory").asString(Message.forName("inventory-color").asString()))); + Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(Message.forName("challenge.missing-items.inventory").asString(Message.forName("inventory-color").asString()))); int targetSlot = globalRandom.nextInt(inventory.getSize()); inventory.setItem(targetSlot, itemStack); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java index 1a54651de..e7287d7b6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MovementItemRemovingChallenge.java @@ -21,7 +21,7 @@ public class MovementItemRemovingChallenge extends SettingModifier { public static final int BLOCK = 1; public MovementItemRemovingChallenge() { - super(MenuType.CHALLENGES, SettingCategory.INVENTORY, 1, 2, 2, new ItemStack(Material.DETECTOR_RAIL), "block-chunk-item-remove-challenge"); + super(MenuType.CHALLENGES, SettingCategory.INVENTORY, 1, 2, 2, new ItemStack(Material.DETECTOR_RAIL), "block-chunk-item-remove"); } // @NotNull @@ -29,16 +29,16 @@ public MovementItemRemovingChallenge() { // public LegacyItemBuilder createSettingsItem() { // if (!isEnabled()) return DefaultItem.disabled(); // if (getValue() == BLOCK) -// return DefaultItem.create(Material.GRASS_BLOCK, Message.forName("item-block-chunk-item-remove-challenge-block")); -// return DefaultItem.create(Material.BOOK, Message.forName("item-block-chunk-item-remove-challenge-chunk")); +// return DefaultItem.create(Material.GRASS_BLOCK, Message.forName("challenge.block-chunk-item-remove.block")); +// return DefaultItem.create(Material.BOOK, Message.forName("challenge.block-chunk-item-remove.chunk")); // } @Override public void playValueChangeTitle() { if (getValue() == BLOCK) - ChallengeHelper.playChallengeValueTitle(this, Message.forName("item-block-chunk-item-remove-challenge-block")); + ChallengeHelper.playChallengeValueTitle(this, Message.forName("challenge.block-chunk-item-remove.block")); else - ChallengeHelper.playChallengeValueTitle(this, Message.forName("item-block-chunk-item-remove-challenge-chunk")); + ChallengeHelper.playChallengeValueTitle(this, Message.forName("challenge.block-chunk-item-remove.chunk")); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java index bb469bf97..060b05982 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/NoDupedItemsChallenge.java @@ -4,7 +4,6 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.CanInstaKillOnEnable; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -31,7 +30,7 @@ public class NoDupedItemsChallenge extends Setting { public NoDupedItemsChallenge() { - super(MenuType.CHALLENGES, SettingCategory.INVENTORY, new ItemStack(Material.OBSERVER), "no-duped-items-challenge"); + super(MenuType.CHALLENGES, SettingCategory.INVENTORY, new ItemStack(Material.OBSERVER), "no-duped-items"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @@ -64,7 +63,7 @@ private void checkInventories() { for (Player player : Bukkit.getOnlinePlayers()) { Triple result = checkInventory(player, blackList); if (result != null) { - MessageKey.of("no-duped-items-failed").broadcast( + getChallengeMessageKey("failed").broadcast( Prefix.CHALLENGES, result.getFirst(), result.getSecond(), diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java index 6eaf9e3b8..4b361b4f3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PermanentItemChallenge.java @@ -20,7 +20,7 @@ public class PermanentItemChallenge extends Setting { public PermanentItemChallenge() { - super(MenuType.CHALLENGES, SettingCategory.INVENTORY, new ItemStack(Material.VINE), "permanent-item-challenge"); + super(MenuType.CHALLENGES, SettingCategory.INVENTORY, new ItemStack(Material.VINE), "permanent-item"); } @EventHandler(priority = EventPriority.HIGH) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java index 610ba2b7d..e1e5be73e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/PickupItemLaunchChallenge.java @@ -19,7 +19,7 @@ public class PickupItemLaunchChallenge extends SettingModifier { public PickupItemLaunchChallenge() { - super(MenuType.CHALLENGES, SettingCategory.INVENTORY, 1, 10, 2, new ItemStack(Material.BOW), "pickup-launch-challenge"); + super(MenuType.CHALLENGES, SettingCategory.INVENTORY, 1, 10, 2, new ItemStack(Material.BOW), "pickup-launch"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java index 2ea295558..ca611c085 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java @@ -19,7 +19,7 @@ public class UncraftItemsChallenge extends TimedChallenge { public UncraftItemsChallenge() { - super(MenuType.CHALLENGES, null, 5, 60, 20, new ItemStack(Material.CRAFTING_TABLE), "uncraft-items-challenge"); + super(MenuType.CHALLENGES, null, 5, 60, 20, new ItemStack(Material.CRAFTING_TABLE), "uncraft-items"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 0bc7c4931..7a3e30311 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -4,7 +4,6 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Bukkit; @@ -23,7 +22,7 @@ public class EnderGamesChallenge extends TimedChallenge { public EnderGamesChallenge() { - super(MenuType.CHALLENGES, null, 1, 10, 5, false, new ItemStack(Material.ENDER_PEARL), "ender-games-challenge"); + super(MenuType.CHALLENGES, null, 1, 10, 5, false, new ItemStack(Material.ENDER_PEARL), "ender-games"); } // @Nullable @@ -63,7 +62,7 @@ private void teleportRandom(@NotNull Player player) { Location playerLocation = player.getLocation().clone(); player.teleport(targetEntity.getLocation()); - MessageKey.of("endergames-teleport").send(player, Prefix.CHALLENGES, targetEntity.getType()); + getChallengeMessageKey("teleport").send(player, Prefix.CHALLENGES, targetEntity.getType()); targetEntity.teleport(playerLocation); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java index 07e2be89c..97df72b44 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodLaunchChallenge.java @@ -18,7 +18,7 @@ public class FoodLaunchChallenge extends SettingModifier { public FoodLaunchChallenge() { - super(MenuType.CHALLENGES, null, 1, 10, 2, new ItemStack(Material.CAKE), "food-launch-challenge"); + super(MenuType.CHALLENGES, null, 1, 10, 2, new ItemStack(Material.CAKE), "consume-launch"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java index bbf43804b..d3cee10a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java @@ -4,7 +4,6 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Material; @@ -20,7 +19,7 @@ public class FoodOnceChallenge extends SettingModifier { public FoodOnceChallenge() { - super(MenuType.CHALLENGES, null, 2, new ItemStack(Material.COOKED_BEEF), "food-once-challenge"); + super(MenuType.CHALLENGES, null, 2, new ItemStack(Material.COOKED_BEEF), "food-once"); } // @NotNull @@ -28,9 +27,9 @@ public FoodOnceChallenge() { // public LegacyItemBuilder createSettingsItem() { // switch (getValue()) { // case 1: -// return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("item-food-once-challenge-player")); +// return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("challenge.food-once.player")); // case 2: -// return DefaultItem.create(Material.ENDER_CHEST, Message.forName("item-food-once-challenge-everyone")); +// return DefaultItem.create(Material.ENDER_CHEST, Message.forName("challenge.food-once.everyone")); // default: // return super.createSettingsItem(); // } @@ -38,7 +37,7 @@ public FoodOnceChallenge() { @Override public void playValueChangeTitle() { - ChallengeHelper.playChallengeValueTitle(this, getValue() == 1 ? Message.forName("item-food-once-challenge-player") : Message.forName("item-food-once-challenge-everyone")); + ChallengeHelper.playChallengeValueTitle(this, getValue() == 1 ? Message.forName("challenge.food-once.player") : Message.forName("challenge.food-once.everyone")); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @@ -48,14 +47,14 @@ public void onPlayerItemConsume(@NotNull PlayerItemConsumeEvent event) { Material type = event.getItem().getType(); if (hasEaten(event.getPlayer(), type)) { - Message.forName("food-once-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); + getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); ChallengeHelper.kill(event.getPlayer(), 1); } else { addFood(event.getPlayer(), type); if (teamFoodsActivated()) { - Message.forName("food-once-new-food-team").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); + getChallengeMessageKey("new-food-team").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); } else { - MessageKey.of("food-once-new-food").send(event.getPlayer(), Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); + getChallengeMessageKey("new-food").send(event.getPlayer(), Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java index 8a427506d..7fb510c51 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java @@ -18,7 +18,7 @@ public class InvertHealthChallenge extends TimedChallenge { public InvertHealthChallenge() { - super(MenuType.CHALLENGES, null, 1, 10, 5, false, new ItemStack(Material.POPPY), "invert-health-challenge"); + super(MenuType.CHALLENGES, null, 1, 10, 5, false, new ItemStack(Material.POPPY), "invert-health"); } public static void invertHealth(Player player) { @@ -49,7 +49,7 @@ protected int getSecondsUntilNextActivation() { @Override protected void onTimeActivation() { SoundSample.PLOP.broadcast(); - Message.forName("health-inverted").broadcast(Prefix.CHALLENGES); + getChallengeMessageKey("inverted").broadcast(Prefix.CHALLENGES); for (Player player : Bukkit.getOnlinePlayers()) { if (ignorePlayer(player)) continue; invertHealth(player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java index df72ff330..b094ba95f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/LowDropRateChallenge.java @@ -19,7 +19,7 @@ public class LowDropRateChallenge extends SettingModifier { private final Random random = new Random(); public LowDropRateChallenge() { - super(MenuType.CHALLENGES, null, 9, new ItemStack(Material.WOODEN_AXE), "low-drop-rate-challenge"); + super(MenuType.CHALLENGES, null, 9, new ItemStack(Material.WOODEN_AXE), "low-drop-rate"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java index 82735684a..e3b14bda8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java @@ -23,7 +23,7 @@ public void onExp(PlayerExpChangeEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (event.getAmount() <= 0) return; - Message.forName("exp-picked-up").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + getChallengeMessageKey("picked-up").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); ChallengeHelper.kill(event.getPlayer()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java index 2476d322c..a845f3a53 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoTradingChallenge.java @@ -15,7 +15,7 @@ public class NoTradingChallenge extends Setting { public NoTradingChallenge() { - super(MenuType.CHALLENGES, null, new ItemStack(Material.EMERALD), "no-trading-challenge"); + super(MenuType.CHALLENGES, null, new ItemStack(Material.EMERALD), "no-trading"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java index f960143ea..4c6caaeee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java @@ -17,7 +17,7 @@ public class OneDurabilityChallenge extends Setting { public OneDurabilityChallenge() { - super(MenuType.CHALLENGES, null, new ItemStack(Material.WOODEN_HOE), "one-durability-challenge"); + super(MenuType.CHALLENGES, null, new ItemStack(Material.WOODEN_HOE), "one-durability"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java index 837385c74..c8339d6b3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/AlwaysRunningChallenge.java @@ -15,7 +15,7 @@ public class AlwaysRunningChallenge extends Setting { public AlwaysRunningChallenge() { - super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, new ItemStack(Material.CARROT_ON_A_STICK), "always-running-challenge"); + super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, new ItemStack(Material.CARROT_ON_A_STICK), "always-running"); } @ScheduledTask(ticks = 1) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java index 2691d42bb..fba6ae032 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java @@ -46,7 +46,7 @@ protected void onEnable() { String time = "§e" + timeLeft + " §7" + (timeLeft == 1 ? Message.forName("second").asString() : Message.forName("seconds").asString()); - bossbar.setTitle(Message.forName("bossbar-dont-stop-running").asString(time)); + bossbar.setTitle(getChallengeMessageKey("bossbar"), time); }); bossbar.show(); } @@ -74,7 +74,7 @@ private void countUpOrKillEveryone() { broadcastFiltered(player -> { Integer count = playerStandingCount.getOrDefault(player, 0); if (count >= getValue()) { - Message.forName("stopped-moving").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + getChallengeMessageKey("stopped-moving").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); playerStandingCount.remove(player); ChallengeHelper.kill(player); return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java index 2723f38a9..4e5329dc0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/FiveHundredBlocksChallenge.java @@ -38,7 +38,7 @@ public class FiveHundredBlocksChallenge extends SettingModifier { private final Map blocksWalked = new HashMap<>(); public FiveHundredBlocksChallenge() { - super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, 1, 5, 5, new ItemStack(MinecraftNameWrapper.SIGN), "five-hundred-blocks-challenge"); + super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, 1, 5, 5, new ItemStack(MinecraftNameWrapper.SIGN), "five-hundred-blocks"); // Loot Generate Event was added in 1.15 try { @@ -64,7 +64,7 @@ public void onLootGenerate(LootGenerateEvent event) { protected void onEnable() { bossbar.setContent((bar, player) -> { int walked = blocksWalked.getOrDefault(player.getUniqueId(), 0); - bar.setTitle(Message.forName("bossbar-five-hundred-blocks").asString(walked, getBlocksToWalk())); + bar.setTitle(getChallengeMessageKey("bossbar"), walked, getBlocksToWalk()); }); bossbar.show(); } @@ -76,7 +76,7 @@ protected void onDisable() { @Override public void playValueChangeTitle() { - ChallengeHelper.playChallengeValueTitle(this, Message.forName("subtitle-blocks").asString(getBlocksToWalk())); + ChallengeHelper.playChallengeValueTitle(this, Message.forName("challenge.five-hundred-blocks.subtitle").asString(getBlocksToWalk())); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java index 4523605a7..5714f5f24 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/HigherJumpsChallenge.java @@ -14,7 +14,7 @@ public class HigherJumpsChallenge extends Setting { public HigherJumpsChallenge() { - super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, new ItemStack(Material.RABBIT_FOOT), "higher-jumps-challenge"); + super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, new ItemStack(Material.RABBIT_FOOT), "higher-jumps"); } @EventHandler(priority = EventPriority.NORMAL) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java index 7679c77ce..b2b9351d0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java @@ -63,7 +63,7 @@ public void onTick() { if (yaw != pair.getKey() || pitch != pair.getValue()) { Bukkit.getScheduler().runTask(plugin, () -> { if (player.getNoDamageTicks() > 0) return; - Message.forName("no-mouse-move-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); player.damage(getValue()); player.setNoDamageTicks(5); Bukkit.getScheduler().runTaskLater(plugin, () -> lastView.remove(player.getUniqueId()), 3); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java index 72c25fc61..09a186df3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java @@ -23,7 +23,7 @@ public class OnlyDirtChallenge extends Setting { public OnlyDirtChallenge() { - super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, new ItemStack(Material.DIRT), "only-dirt-challenge"); + super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, new ItemStack(Material.DIRT), "only-dirt"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @@ -35,7 +35,7 @@ public void onPlayerMove(@NotNull PlayerMoveEvent event) { Block blockBelow = BlockUtils.getBlockBelow(event.getTo()); if (blockBelow == null) return; if (blockBelow.getType() != Material.DIRT && !BukkitReflectionUtils.isAir(blockBelow.getType())) { - Message.forName("only-dirt-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); ChallengeHelper.kill(event.getPlayer()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java index 6be7f4fa6..c25897f97 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java @@ -18,7 +18,7 @@ public class OnlyDownChallenge extends Setting { public OnlyDownChallenge() { - super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, new ItemStack(Material.ACACIA_SLAB), "only-down-challenge"); + super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, new ItemStack(Material.ACACIA_SLAB), "only-down"); } @EventHandler @@ -27,7 +27,7 @@ public void onPlayerMove(@NotNull PlayerMoveEvent event) { if (ignorePlayer(event.getPlayer())) return; if (event.getTo() == null) return; if (event.getTo().getBlockY() <= event.getFrom().getBlockY()) return; - Message.forName("only-down-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); ChallengeHelper.kill(event.getPlayer()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java index e00999f87..7443db9a6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java @@ -28,7 +28,7 @@ public class TrafficLightChallenge extends TimedChallenge { private int state; public TrafficLightChallenge() { - super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, 1, 10, 5, new ItemStack(Material.LIME_STAINED_GLASS), "traffic-light-challenge"); + super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, 1, 10, 5, new ItemStack(Material.LIME_STAINED_GLASS), "traffic-light"); } // @Nullable @@ -110,7 +110,7 @@ public void onPlayerMove(@NotNull PlayerMoveEvent event) { restartTimer(); Player player = event.getPlayer(); - Message.forName("traffic-light-challenge-fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + getChallengeMessageKey("fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); ChallengeHelper.kill(player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index 53d28252a..94938b4e1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -80,11 +80,11 @@ protected void onEnable() { String time = "§e" + timeLeft + " §7" + (timeLeft == 1 ? Message.forName("second").asString() : Message.forName("seconds").asString()); if (currentQuestionedPlayer != player) { bossbar.setColor(BossBar.Color.GREEN); - bossbar.setTitle(Message.forName("bossbar-quiz-question-other").asString(time, NameHelper.getName(currentQuestionedPlayer))); + bossbar.setTitle(MessageKey.of("bossbar-quiz-question-other"), time, NameHelper.getName(currentQuestionedPlayer)); return; } bossbar.setColor(BossBar.Color.RED); - bossbar.setTitle(Message.forName("bossbar-quiz-question").asString(time)); + bossbar.setTitle(MessageKey.of("bossbar-quiz-question"), time); }); bossbar.show(); } @@ -107,9 +107,9 @@ protected int getSecondsUntilNextActivation() { private void broadcastMessage(@NotNull String questionedPlayerMessage, @NotNull String othersMessage, Object... args) { broadcast(player1 -> { if (currentQuestionedPlayer == player1) { - Message.forName(questionedPlayerMessage).send(player1, prefix, args); + MessageKey.of(questionedPlayerMessage).send(player1, prefix, args); } else { - Message.forName(othersMessage).send(player1, prefix, NameHelper.getName(currentQuestionedPlayer)); + MessageKey.of(othersMessage).send(player1, prefix, NameHelper.getName(currentQuestionedPlayer)); } }); } @@ -141,14 +141,14 @@ protected void onTimeActivation() { public void onSecond() { if (currentQuestion == null) return; if (!currentQuestionedPlayer.isOnline() || ignorePlayer(currentQuestionedPlayer)) { - Message.forName("quiz-cancel").broadcast(prefix); + MessageKey.of("quiz-cancel").broadcast(prefix); cancelQuestion(); } timeLeft--; if (timeLeft <= 0) { - Message.forName("quiz-time-up").broadcast(prefix); + MessageKey.of("quiz-time-up").broadcast(prefix); cancelQuestion(); } @@ -159,7 +159,7 @@ private void cancelQuestion() { restartTimer(); List rightAnswers = currentQuestion.getRightAnswers(); - Message.forName("quiz-right-answer-was" + (rightAnswers.size() != 1 ? "-multiple" : "")).send(currentQuestionedPlayer, prefix, StringUtils.getArrayAsString(rightAnswers.toArray(new String[0]), "§7, §e")); + MessageKey.of("quiz-right-answer-was" + (rightAnswers.size() != 1 ? "-multiple" : "")).send(currentQuestionedPlayer, prefix, StringUtils.getArrayAsString(rightAnswers.toArray(new String[0]), "§7, §e")); SoundSample.BREAK.play(currentQuestionedPlayer); currentQuestion = null; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java index 9a2657b9b..1c0462794 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/BlockRandomizerChallenge.java @@ -18,7 +18,7 @@ public class BlockRandomizerChallenge extends RandomizerSetting { public BlockRandomizerChallenge() { - super(MenuType.CHALLENGES, new ItemStack(Material.MINECART), "block-randomizer-challenge"); + super(MenuType.CHALLENGES, new ItemStack(Material.MINECART), "block-randomizer"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java index 441761194..62c8e4101 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/CraftingRandomizerChallenge.java @@ -19,7 +19,7 @@ public class CraftingRandomizerChallenge extends RandomizerSetting { protected final Map randomization = new HashMap<>(); public CraftingRandomizerChallenge() { - super(MenuType.CHALLENGES, new ItemStack(Material.CHEST_MINECART), "crafting-randomizer-challenge"); + super(MenuType.CHALLENGES, new ItemStack(Material.CHEST_MINECART), "crafting-randomizer"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java index dc01a095d..763e760a8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java @@ -33,7 +33,7 @@ public class EntityLootRandomizerChallenge extends RandomizerSetting implements protected Map randomization; public EntityLootRandomizerChallenge() { - super(MenuType.CHALLENGES, new ItemStack(Material.FURNACE_MINECART), "entity-loot-randomizer-challenge"); + super(MenuType.CHALLENGES, new ItemStack(Material.FURNACE_MINECART), "entity-loot-randomizer"); } @Override @@ -119,7 +119,7 @@ public Optional getEntityForLootTable(LootTable lootTable) { public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (!isEnabled()) { - MessageKey.of("command-searchloot-disabled").send(sender, Prefix.CHALLENGES); + getChallengeMessageKey("command-disabled").send(sender, Prefix.CHALLENGES); return; } @@ -152,9 +152,9 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr LootTable droppedLootTable = getLootTableForEntity(entityType); if (optionalEntity.isPresent()) { - MessageKey.of("command-searchloot-result").send(sender, Prefix.CHALLENGES, entityType, droppedLootTable, optionalEntity.get()); + getChallengeMessageKey("command-result").send(sender, Prefix.CHALLENGES, entityType, droppedLootTable, optionalEntity.get()); } else { - MessageKey.of("command-searchloot-nothing").send(sender, Prefix.CHALLENGES, entityType); + getChallengeMessageKey("command-nothing").send(sender, Prefix.CHALLENGES, entityType); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 0c7bf36eb..6ef84e5e4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -30,7 +30,7 @@ public class HotBarRandomizerChallenge extends TimedChallenge { public HotBarRandomizerChallenge() { - super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 10, 5, new ItemStack(Material.HOPPER_MINECART), "hotbar-randomizer-challenge"); + super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 10, 5, new ItemStack(Material.HOPPER_MINECART), "hotbar-randomizer"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java index eb402d913..cef9209fe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java @@ -79,7 +79,7 @@ public static class SpeedEvent implements Event { @NotNull @Override public Message getActivationMessage() { - return Message.forName("random-event-speed"); + return Message.forName("challenge.random-event.speed"); } @Override @@ -94,7 +94,7 @@ public static class HoleEvent implements Event { @NotNull @Override public Message getActivationMessage() { - return Message.forName("random-event-hole"); + return Message.forName("challenge.random-event.hole"); } @Override @@ -116,7 +116,7 @@ public static class FlyEvent implements Event { @NotNull @Override public Message getActivationMessage() { - return Message.forName("random-event-fly"); + return Message.forName("challenge.random-event.fly"); } @Override @@ -131,7 +131,7 @@ public static class ReplaceOresEvent implements Event { @NotNull @Override public Message getActivationMessage() { - return Message.forName("random-event-ores"); + return Message.forName("challenge.random-event.ores"); } @Override @@ -166,7 +166,7 @@ public static class SicknessEvent implements Event { @NotNull @Override public Message getActivationMessage() { - return Message.forName("random-event-sickness"); + return Message.forName("challenge.random-event.sickness"); } @Override @@ -182,7 +182,7 @@ public static class SpawnEntitiesEvent implements Event { @NotNull @Override public Message getActivationMessage() { - return Message.forName("random-event-entities"); + return Message.forName("challenge.random-event.entities"); } @Override @@ -206,7 +206,7 @@ public static class CobWebEvent implements Event { @NotNull @Override public Message getActivationMessage() { - return Message.forName("random-event-webs"); + return Message.forName("challenge.random-event.webs"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java index 4ea3287b9..56caa6a5c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java @@ -13,7 +13,7 @@ public class RandomItemChallenge extends TimedChallenge { public RandomItemChallenge() { - super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 60, 30, false, new ItemStack(Material.BEACON), "random-item-challenge"); + super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 60, 30, false, new ItemStack(Material.BEACON), "random-item"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java index 1b03e6a90..18bd8d480 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java @@ -18,7 +18,7 @@ public class RandomItemDroppingChallenge extends TimedChallenge { public RandomItemDroppingChallenge() { - super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 60, 5, new ItemStack(Material.DISPENSER), "random-dropping-challenge"); + super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 60, 5, new ItemStack(Material.DISPENSER), "random-dropping"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java index 92d9c54e8..a7196e700 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java @@ -15,7 +15,7 @@ public class RandomItemRemovingChallenge extends TimedChallenge { public RandomItemRemovingChallenge() { - super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 30, 30, new ItemStack(Material.DROPPER), "random-item-removing-challenge"); + super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 30, 30, new ItemStack(Material.DROPPER), "random-item-removing"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java index 27ff693b5..9bb578e91 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java @@ -3,7 +3,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; @@ -28,7 +27,7 @@ protected void onEnable() { bossbar.setContent((bossbar, player) -> { int currentTime = getCurrentTime(player); int maxTime = (getValue() * 60); - bossbar.setTitle(MessageKey.of("bossbar-biome-time-left"), getBiome(player), maxTime - currentTime); + bossbar.setTitle(getChallengeMessageKey("bossbar"), getBiome(player), maxTime - currentTime); bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(1 - ((float) currentTime / maxTime)); }); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java index 4ed019479..30bee71d8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java @@ -3,7 +3,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -22,7 +21,7 @@ public class MaxHeightTimeChallenge extends SettingModifier { public MaxHeightTimeChallenge() { - super(MenuType.CHALLENGES, SettingCategory.LIMITED_TIME, 3, 20, new ItemStack(Material.PARROT_SPAWN_EGG), "max-height-time-challenge"); + super(MenuType.CHALLENGES, SettingCategory.LIMITED_TIME, 3, 20, new ItemStack(Material.PARROT_SPAWN_EGG), "max-height-time"); } @Override @@ -30,7 +29,7 @@ protected void onEnable() { bossbar.setContent((bossbar, player) -> { int currentTime = getCurrentTime(player); int maxTime = (getValue() * 60); - bossbar.setTitle(MessageKey.of("bossbar-height-time-left"), player.getLocation().getBlockY(), maxTime - currentTime); + bossbar.setTitle(getChallengeMessageKey("bossbar"), player.getLocation().getBlockY(), maxTime - currentTime); bossbar.setColor(BossBar.Color.GREEN); bossbar.setProgress(1 - ((float) currentTime / maxTime)); }); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java index 663a6af4e..d33fcc44b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java @@ -28,7 +28,7 @@ public class AnvilRainChallenge extends MenuSetting { public AnvilRainChallenge() { // super(Message.forName("menu-anvil-rain-challenge-settings")); - super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.ANVIL), "anvil-rain-challenge"); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.ANVIL), "anvil-rain"); // registerSetting("time", new NumberSubSetting( // () -> new LegacyItemBuilder(Material.CLOCK, Message.forName("item-anvil-rain-time-challenge")), // value -> null, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java index 56628e1b0..6e96bd4fa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockPathChallenge.java @@ -16,7 +16,7 @@ public class BedrockPathChallenge extends Setting { public BedrockPathChallenge() { super(MenuType.CHALLENGES, SettingCategory.WORLD, new StandardItemBuilder.LeatherArmorBuilder(Material.LEATHER_BOOTS).setColor(Color.GRAY).build(), - "bedrock-path-challenge"); + "bedrock-path"); } @EventHandler diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java index ca30f50dc..0a4999c97 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlockFlyInAirChallenge.java @@ -19,7 +19,7 @@ public class BlockFlyInAirChallenge extends Setting { public BlockFlyInAirChallenge() { - super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.FERN), "blocks-fly-challenge"); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.FERN), "blocks-fly"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java index b8be62b6a..a21ca586a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java @@ -24,7 +24,7 @@ public class BlocksDisappearAfterTimeChallenge extends SettingModifier { private final Map tasks = new HashMap<>(); public BlocksDisappearAfterTimeChallenge() { - super(MenuType.CHALLENGES, SettingCategory.WORLD, 60, 300, new ItemStack(Material.STRING), "blocks-disappear-time-challenge"); + super(MenuType.CHALLENGES, SettingCategory.WORLD, 60, 300, new ItemStack(Material.STRING), "blocks-disappear-time"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java index 1133d99f0..897296e33 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java @@ -18,7 +18,7 @@ public class ChunkDeconstructionChallenge extends TimedChallenge { public ChunkDeconstructionChallenge() { - super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 60, 20, new ItemStack(Material.DIAMOND_PICKAXE), "chunk-deconstruction-challenge"); + super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 60, 20, new ItemStack(Material.DIAMOND_PICKAXE), "chunk-deconstruction"); } // @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java index 7b632b032..0e4a809bd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java @@ -26,7 +26,7 @@ public class ChunkDeletionChallenge extends SettingModifier { private final HashMap> chunks = new HashMap<>(); public ChunkDeletionChallenge() { - super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 120, 60, new ItemStack(Material.GOLDEN_PICKAXE), "setting-chunk-deletion-challenge"); + super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 120, 60, new ItemStack(Material.GOLDEN_PICKAXE), "chunk-deletion"); } // @Override @@ -37,7 +37,7 @@ public ChunkDeletionChallenge() { @Override protected void onEnable() { bossbar.setContent((bossbar, player) -> { - Message message = Message.forName("bossbar-chunk-deletion"); + Message message = Message.forName("challenge.chunk-deletion.bossbar"); bossbar.setColor(BossBar.Color.PINK); if (!checkIfAllowed(player)) { Tuple taskTuple = chunks.get(player.getLocation().getChunk()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java index fd5ad4654..6e7607724 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java @@ -16,7 +16,7 @@ public class FloorIsLavaChallenge extends SettingModifier { public FloorIsLavaChallenge() { - super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 60, 30, new ItemStack(Material.MAGMA_BLOCK), "floor-is-lava-challenge"); + super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 60, 30, new ItemStack(Material.MAGMA_BLOCK), "floor-is-lava"); } @EventHandler diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java index d7c2835f6..9be56df19 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java @@ -4,6 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; @@ -30,13 +31,13 @@ public class IceFloorChallenge extends Setting { private final List ignoredPlayers = new ArrayList<>(); public IceFloorChallenge() { - super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.PACKED_ICE), "ice-floor-challenge"); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.PACKED_ICE), "ice-floor"); } @Override protected void onEnable() { bossbar.setContent((bossbar, player) -> { - bossbar.setTitle(Message.forName("bossbar-ice-floor").asString(ignoreIce(player) ? Message.forName("disabled") : Message.forName("enabled"))); + bossbar.setTitle(getChallengeMessageKey("bossbar"), ignoreIce(player) ? MessageKey.of("disabled") : MessageKey.of("enabled")); bossbar.setColor(ignoreIce(player) ? BossBar.Color.RED : BossBar.Color.GREEN); }); bossbar.show(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java index dc9490c4c..ae94f3a74 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java @@ -46,7 +46,7 @@ public class LevelBorderChallenge extends Setting { private int bestPlayerLevel = 0; public LevelBorderChallenge() { - super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.ENCHANTING_TABLE), "level-border-challenge"); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.ENCHANTING_TABLE), "level-border"); } @Override @@ -60,7 +60,7 @@ protected void onEnable() { } bossbar.setContent((bar, player) -> { - bar.setTitle(Message.forName("bossbar-level-border").asString(bestPlayerLevel)); + bar.setTitle(getChallengeMessageKey("bossbar"), bestPlayerLevel); }); bossbar.show(); updateBorderSize(false); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index 98862406b..9ac40035d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -49,7 +49,7 @@ public class LoopChallenge extends Setting { private static final Map loops = new HashMap<>(); public LoopChallenge() { - super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.LEAD), "loop-challenge"); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.LEAD), "loop"); } @ScheduledTask(ticks = 1, async = false) @@ -75,7 +75,7 @@ public void onPause() { private void clearLoops() { if (loops.isEmpty()) return; broadcast(player -> new SoundSample().addSound(Sound.ENTITY_ITEM_BREAK, 0.5f).play(player)); - Message.forName("loops-cleared").broadcast(Prefix.CHALLENGES, loops.size()); + getChallengeMessageKey("cleared").broadcast(Prefix.CHALLENGES, loops.size()); loops.clear(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java index da1861adf..9808086cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/RepeatInChunkChallenge.java @@ -40,7 +40,7 @@ public class RepeatInChunkChallenge extends Setting { private final Set updatedChunks = new HashSet<>(); public RepeatInChunkChallenge() { - super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.GRASS_BLOCK), "repeat-in-chunk-challenge"); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.GRASS_BLOCK), "repeat-in-chunk"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index bedb5949a..3a6803057 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -30,7 +30,7 @@ public class SnakeChallenge extends Setting { private final ArrayList blocks = new ArrayList<>(); public SnakeChallenge() { - super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.BLUE_TERRACOTTA), "snake-challenge"); + super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.BLUE_TERRACOTTA), "snake"); } @Override @@ -70,7 +70,7 @@ public void onMove(@NotNull PlayerMoveEvent event) { } if (blocks.contains(to)) { - Message.forName("snake-failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); ChallengeHelper.kill(event.getPlayer()); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java index 07c0fe756..4c1d2fd7b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java @@ -18,7 +18,7 @@ public class SurfaceHoleChallenge extends SettingModifier { public SurfaceHoleChallenge() { - super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 60, 30, new ItemStack(Material.BARRIER), "item-surface-hole-challenge"); + super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 60, 30, new ItemStack(Material.BARRIER), "surface-hole"); } @EventHandler diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java index d3435aa78..76614efd7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java @@ -43,7 +43,7 @@ public class TsunamiChallenge extends TimedChallenge { private int waterHeight = Integer.MAX_VALUE, lavaHeight = 0; public TsunamiChallenge() { - super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 40, 4, new ItemStack(Material.ICE), "tsunami-challenge"); + super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 40, 4, new ItemStack(Material.ICE), "tsunami"); } // @Nullable @@ -72,10 +72,10 @@ protected void onEnable() { if (environment == Environment.NORMAL) { bossbar.setColor(BossBar.Color.BLUE); - bossbar.setTitle(Message.forName("bossbar-tsunami-water").asString(waterHeight)); + bossbar.setTitle(getChallengeMessageKey("bossbar-water"), waterHeight); } else if (environment == Environment.NETHER) { bossbar.setColor(BossBar.Color.RED); - bossbar.setTitle(Message.forName("bossbar-tsunami-lava").asString(lavaHeight)); + bossbar.setTitle(getChallengeMessageKey("bossbar-lava"), lavaHeight); } else { bossbar.setVisible(false); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java index 9f774fb35..601833d16 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java @@ -4,6 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; @@ -32,7 +33,7 @@ public class AllAdvancementGoal extends PointsGoal { private final int advancementCount; public AllAdvancementGoal() { - super(SettingCategory.SCORE_POINTS, new ItemStack(Material.BOOK), "all-advancements-goal"); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.BOOK), "all-advancements"); allAdvancements = new LinkedList<>(); Bukkit.getServer().advancementIterator().forEachRemaining(advancement -> { if (!advancement.getKey().toString().contains(":recipes/")) { @@ -46,8 +47,8 @@ public AllAdvancementGoal() { protected void onEnable() { updateAdvancements(); scoreboard.setContent(GoalHelper.createScoreboard(() -> - getPoints(new AtomicInteger(), true), player -> { - return Collections.singletonList(Message.forName("all-advancements-goal").asString(advancementCount)); + getPoints(new AtomicInteger(), true), _ -> { + return Collections.singletonList(MessageKey.of("all-advancements-goal").withArgs(advancementCount)); })); scoreboard.show(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index 29c69d305..076df42e3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -48,7 +48,7 @@ public class CollectAllItemsGoal extends SettingGoal implements SenderCommand { private Material currentItem; public CollectAllItemsGoal() { - super(null, new ItemStack(Material.GRASS_BLOCK), "collect-all-items-goal"); + super(null, new ItemStack(Material.GRASS_BLOCK), "collect-all-items"); random = new SeededRandomWrapper(); reloadItemsToFind(); totalItemsCount = itemsToFind.size(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java index 03531ab8d..0e5449e96 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectHorseAmorGoal.java @@ -15,7 +15,7 @@ public class CollectHorseAmorGoal extends ItemCollectionGoal { public CollectHorseAmorGoal() { - super(SettingCategory.FASTEST_TIME, new ItemStack(Material.DIAMOND_HORSE_ARMOR), "collect-horse-armor-goal"); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.DIAMOND_HORSE_ARMOR), "collect-horse-armor"); List targets = new ArrayList<>(Arrays.asList( Material.DIAMOND_HORSE_ARMOR, Material.GOLDEN_HORSE_ARMOR, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java index 70c50bd0a..d2545065d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectIceBlocksGoal.java @@ -10,7 +10,7 @@ public class CollectIceBlocksGoal extends ItemCollectionGoal { public CollectIceBlocksGoal() { - super(SettingCategory.FASTEST_TIME, new ItemStack(Material.PACKED_ICE), "collect-ice-goal", Material.ICE, Material.BLUE_ICE, Material.PACKED_ICE, Material.SNOW_BLOCK); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.PACKED_ICE), "collect-ice", Material.ICE, Material.BLUE_ICE, Material.PACKED_ICE, Material.SNOW_BLOCK); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java index afdd82d43..73d3cc08e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostDeathsGoal.java @@ -17,7 +17,7 @@ public class CollectMostDeathsGoal extends CollectionGoal { public CollectMostDeathsGoal() { - super(SettingCategory.SCORE_POINTS, new ItemStack(Material.LAVA_BUCKET), "most-deaths-goal", DamageCause.values()); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.LAVA_BUCKET), "most-deaths", DamageCause.values()); } @EventHandler diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java index 3d00c9c3c..f525e65de 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostExpGoal.java @@ -15,7 +15,7 @@ public class CollectMostExpGoal extends PointsGoal { public CollectMostExpGoal() { - super(SettingCategory.SCORE_POINTS, new ItemStack(Material.EXPERIENCE_BOTTLE), "most-xp-goal"); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.EXPERIENCE_BOTTLE), "most-xp"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java index 480d902fa..8c7f702ab 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectMostItemsGoal.java @@ -19,7 +19,7 @@ public class CollectMostItemsGoal extends CollectionGoal { public CollectMostItemsGoal() { - super(SettingCategory.SCORE_POINTS, new ItemStack(Material.STICK), "most-items-goal", ExperimentalUtils.getMaterials()); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.STICK), "most-items", ExperimentalUtils.getMaterials()); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java index d9d20fed6..6f2cb0d55 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectSwordsGoal.java @@ -15,7 +15,7 @@ public class CollectSwordsGoal extends ItemCollectionGoal { public CollectSwordsGoal() { - super(SettingCategory.FASTEST_TIME, new ItemStack(Material.DIAMOND_SWORD), "collect-swords-goal"); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.DIAMOND_SWORD), "collect-swords"); List targets = new ArrayList<>(Arrays.asList( Material.WOODEN_SWORD, Material.STONE_SWORD, Material.IRON_SWORD, Material.GOLDEN_SWORD, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java index ef0d52271..a6379ac49 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java @@ -27,7 +27,7 @@ public class CollectWoodGoal extends SettingModifierCollectionGoal { BOTH = 3; public CollectWoodGoal() { - super(SettingCategory.FASTEST_TIME, 1, newNether ? 3 : 1, new ItemStack(Material.GOLDEN_AXE), "collect-wood-goal"); + super(SettingCategory.FASTEST_TIME, 1, newNether ? 3 : 1, new ItemStack(Material.GOLDEN_AXE), "collect-wood"); } // @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java index 944f52475..e7a862cc7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWorkstationsGoal.java @@ -14,7 +14,7 @@ public class CollectWorkstationsGoal extends ItemCollectionGoal { public CollectWorkstationsGoal() { super( - SettingCategory.FASTEST_TIME, new ItemStack(Material.FLETCHING_TABLE), "collect-workstations-goal", + SettingCategory.FASTEST_TIME, new ItemStack(Material.FLETCHING_TABLE), "collect-workstations", Material.LECTERN, Material.COMPOSTER, Material.GRINDSTONE, Material.BLAST_FURNACE, Material.SMOKER, Material.FLETCHING_TABLE, Material.CARTOGRAPHY_TABLE, Material.BREWING_STAND, Material.SMITHING_TABLE, Material.CAULDRON, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java index 18b3e9758..0abb6dbb4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatCakeGoal.java @@ -21,7 +21,7 @@ public class EatCakeGoal extends SettingGoal { public EatCakeGoal() { - super(SettingCategory.FASTEST_TIME, new ItemStack(Material.CAKE), "eat-cake-goal"); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.CAKE), "eat-cake"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java index d0887cc03..0ab93d290 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/EatMostGoal.java @@ -16,7 +16,7 @@ public class EatMostGoal extends PointsGoal { public EatMostGoal() { - super(SettingCategory.SCORE_POINTS, new ItemStack(Material.COOKIE), "eat-most-goal"); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.COOKIE), "eat-most"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java index 1bcc48768..4276c67a8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FindElytraGoal.java @@ -10,7 +10,7 @@ public class FindElytraGoal extends FindItemGoal { public FindElytraGoal() { - super(SettingCategory.FASTEST_TIME, Material.ELYTRA, new ItemStack(Material.ELYTRA), "find-elytra-goal"); + super(SettingCategory.FASTEST_TIME, Material.ELYTRA, new ItemStack(Material.ELYTRA), "find-elytra"); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java index 994e19de7..e70a4b686 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FinishRaidGoal.java @@ -23,7 +23,7 @@ public class FinishRaidGoal extends SettingGoal { public FinishRaidGoal() { - super(SettingCategory.FASTEST_TIME, new ItemStack(Material.CROSSBOW), "finish-raid-goal"); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.CROSSBOW), "finish-raid"); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java index bd5a3e37d..a2238fa60 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/FirstOneToDieGoal.java @@ -21,7 +21,7 @@ public class FirstOneToDieGoal extends SettingGoal { private Player winner; public FirstOneToDieGoal() { - super(SettingCategory.FASTEST_TIME, new ItemStack(Material.STONE_SWORD), "first-one-to-die-goal"); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.STONE_SWORD), "first-one-to-die"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java index a8f6bae9c..919cfc464 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/GetFullHealthGoal.java @@ -27,7 +27,7 @@ public class GetFullHealthGoal extends SettingModifierGoal { public GetFullHealthGoal() { - super(MenuType.GOAL, SettingCategory.FASTEST_TIME, 1, 20, 20, new ItemStack(Material.AZURE_BLUET), "get-full-health-goal"); + super(MenuType.GOAL, SettingCategory.FASTEST_TIME, 1, 20, 20, new ItemStack(Material.AZURE_BLUET), "get-full-health"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java index ae596c6e8..54e5bee36 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMobsGoal.java @@ -16,7 +16,7 @@ public class KillAllMobsGoal extends KillMobsGoal { public KillAllMobsGoal() { - super(SettingCategory.KILL_ENTITY, getAllMobsToKill(), new ItemStack(Material.BOW), "all-mobs-goal"); + super(SettingCategory.KILL_ENTITY, getAllMobsToKill(), new ItemStack(Material.BOW), "all-mobs"); } static List getAllMobsToKill() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java index 7aa9481c6..f89930a75 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillAllMonsterGoal.java @@ -18,7 +18,7 @@ public class KillAllMonsterGoal extends KillMobsGoal { public KillAllMonsterGoal() { - super(SettingCategory.KILL_ENTITY, getAllMobsToKill(), new ItemStack(Material.ARROW), "all-monster-goal"); + super(SettingCategory.KILL_ENTITY, getAllMobsToKill(), new ItemStack(Material.ARROW), "all-monster"); } static List getAllMobsToKill() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java index cc4acbcff..06808a719 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillIronGolemGoal.java @@ -14,7 +14,7 @@ public class KillIronGolemGoal extends KillEntityGoal { public KillIronGolemGoal() { - super(SettingCategory.KILL_ENTITY, EntityType.IRON_GOLEM, new ItemStack(Material.IRON_INGOT), "iron-golem-goal"); + super(SettingCategory.KILL_ENTITY, EntityType.IRON_GOLEM, new ItemStack(Material.IRON_INGOT), "iron-golem"); this.killerNeeded = true; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java index 95cc99f9b..3ed448ddf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/KillSnowGolemGoal.java @@ -14,7 +14,7 @@ public class KillSnowGolemGoal extends KillEntityGoal { public KillSnowGolemGoal() { - super(SettingCategory.KILL_ENTITY, MinecraftNameWrapper.SNOW_GOLEM, new ItemStack(Material.SNOWBALL), "snow-golem-goal"); + super(SettingCategory.KILL_ENTITY, MinecraftNameWrapper.SNOW_GOLEM, new ItemStack(Material.SNOWBALL), "snow-golem"); this.killerNeeded = true; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java index fddcbbb2d..f561eac03 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/LastManStandingGoal.java @@ -23,7 +23,7 @@ public class LastManStandingGoal extends SettingGoal { private Player winner; public LastManStandingGoal() { - super(null, new ItemStack(Material.IRON_HELMET), "last-man-standing-goal"); + super(null, new ItemStack(Material.IRON_HELMET), "last-man-standing"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java index 2abfd0a72..59522b7bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MaxHeightGoal.java @@ -12,7 +12,7 @@ public class MaxHeightGoal extends FirstPlayerAtHeightGoal { public MaxHeightGoal() { - super(SettingCategory.FASTEST_TIME, new ItemStack(Material.FEATHER), "max-height-goal"); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.FEATHER), "max-height"); setHeightToGetTo(ChallengeAPI.getGameWorld(Environment.NORMAL).getMaxHeight()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java index d4f363a70..149ce62b9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MinHeightGoal.java @@ -13,7 +13,7 @@ public class MinHeightGoal extends FirstPlayerAtHeightGoal { public MinHeightGoal() { - super(SettingCategory.FASTEST_TIME, new ItemStack(Material.BEDROCK), "min-height-goal"); + super(SettingCategory.FASTEST_TIME, new ItemStack(Material.BEDROCK), "min-height"); setHeightToGetTo(BukkitReflectionUtils.getMinHeight(ChallengeAPI.getGameWorld(Environment.NORMAL)) + 1); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java index aa186835d..9063d2be9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MineMostBlocksGoal.java @@ -12,7 +12,7 @@ public class MineMostBlocksGoal extends PointsGoal { public MineMostBlocksGoal() { - super(SettingCategory.SCORE_POINTS, new ItemStack(Material.GOLDEN_PICKAXE), "mine-most-blocks-goal"); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.GOLDEN_PICKAXE), "mine-most-blocks"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java index 9c6e8e6bf..985152f89 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostEmeraldsGoal.java @@ -19,7 +19,7 @@ public class MostEmeraldsGoal extends PointsGoal { public MostEmeraldsGoal() { - super(SettingCategory.SCORE_POINTS, new ItemStack(Material.EMERALD), "most-emeralds-goal"); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.EMERALD), "most-emeralds"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java index 5b2e76173..1e90a4ee9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java @@ -18,7 +18,7 @@ public class MostOresGoal extends PointsGoal { public MostOresGoal() { - super(SettingCategory.SCORE_POINTS, new ItemStack(Material.COAL_ORE), "most-ores-goal"); + super(SettingCategory.SCORE_POINTS, new ItemStack(Material.COAL_ORE), "most-ores"); } private int getPointsForOre(Material material) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java index 7ea4574c6..911e7196c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java @@ -6,6 +6,7 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -42,7 +43,7 @@ public class RaceGoal extends SettingModifierGoal { private Location goal; public RaceGoal() { - super(MenuType.GOAL, SettingCategory.FASTEST_TIME, 1, 30, 5, new ItemStack(Material.STRUCTURE_VOID), "race-goal"); + super(MenuType.GOAL, SettingCategory.FASTEST_TIME, 1, 30, 5, new ItemStack(Material.STRUCTURE_VOID), "race"); } @Override @@ -121,7 +122,7 @@ public void onMove(PlayerMoveEvent event) { if (event.getTo().getWorld() != goal.getWorld()) return; if (event.getTo() == null) return; if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), goal)) { - Message.forName("race-goal-reached").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + MessageKey.of("race-goal-reached").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); ParticleUtils.spawnParticleCylinderAroundRadius(Challenges.getInstance(), event.getTo(), MinecraftNameWrapper.ENTITY_EFFECT, null, 0.75, 2); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java index 53da4a1ed..1c02e3c03 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java @@ -4,6 +4,8 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.*; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleDisplayGoal; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; @@ -36,7 +38,7 @@ public class ExtremeForceBattleGoal extends ForceBattleDisplayGoal new LegacyItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), @@ -136,24 +138,24 @@ public void setRandomTarget(Player player) { @Override protected void setScoreboardContent() { - scoreboard.setContent((board, player) -> { + scoreboard.setContent((board, _) -> { List ingamePlayers = ChallengeAPI.getIngamePlayers(); - int emptyLinesAvailable = 15 - ingamePlayers.size(); + int emptyLinesAvailable = board.getRemainingLines() - ingamePlayers.size(); if (emptyLinesAvailable > 0) { - board.addLine(""); + board.addEmptyLine(); emptyLinesAvailable--; } for (int i = 0; i < ingamePlayers.size() && i < 15; i++) { Player ingamePlayer = ingamePlayers.get(i); ForceTarget target = currentTarget.get(ingamePlayer.getUniqueId()); - String display = target == null ? Message.forName("none").asString() : (target.getScoreboardDisplayMessage().asString(getTargetName(target))); - board.addLine(NameHelper.getName(ingamePlayer) + " §8» §e" + display); + LocalizableMessage display = target == null ? MessageKey.of("none") : target.getScoreboardDisplayMessage().withArgs(getTargetName(target)); +// board.addLine(NameHelper.getName(ingamePlayer) + " §8» §e" + display); // TODO translation format } if (emptyLinesAvailable > 0) { - board.addLine(""); + board.addEmptyLine(); } }); } @@ -166,11 +168,9 @@ protected boolean shouldRegisterDupedTargetsSetting() { @Override public void handleJokerUse(Player player) { ForceTarget target = currentTarget.get(player.getUniqueId()); - if (giveItemOnSkip() && target instanceof ItemTarget) { - ItemTarget itemTarget = (ItemTarget) target; + if (giveItemOnSkip() && target instanceof ItemTarget itemTarget) { InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), itemTarget.getTarget()); - } else if (giveBlockOnSkip() && target instanceof BlockTarget) { - BlockTarget blockTarget = (BlockTarget) target; + } else if (giveBlockOnSkip() && target instanceof BlockTarget blockTarget) { InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), blockTarget.getTarget()); } super.handleJokerUse(player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java index 844a81597..a5e86db9c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java @@ -26,7 +26,7 @@ public class ForceAdvancementBattleGoal extends ForceBattleGoal { public ForceBiomeBattleGoal() { // super(Message.forName("menu-force-biome-battle-goal-settings")); - super(new ItemStack(Material.FILLED_MAP), "forice-biome-battle-goal"); + super(new ItemStack(Material.FILLED_MAP), "force-biome-battle"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java index 9d833b4ea..b7feb8341 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java @@ -20,7 +20,7 @@ public class ForceBlockBattleGoal extends ForceBattleDisplayGoal { public ForceBlockBattleGoal() { // super(Message.forName("menu-force-block-battle-goal-settings")); - super(new ItemStack(Material.CHEST), "force-block-battle-goal"); + super(new ItemStack(Material.CHEST), "force-block-battle"); // registerSetting("give-block", new BooleanSubSetting( // () -> new LegacyItemBuilder(Material.CHEST, Message.forName("item-force-block-battle-goal-give-block")), diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java index 47f0e6e24..99e812b57 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java @@ -20,7 +20,7 @@ public class ForceDamageBattleGoal extends ForceBattleGoal { public ForceDamageBattleGoal() { // super(Message.forName("menu-force-damage-battle-goal-settings")); - super(new ItemStack(Material.TOTEM_OF_UNDYING), "force-damange-battle-goal"); + super(new ItemStack(Material.TOTEM_OF_UNDYING), "force-damage-battle"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java index 9e37253f1..e00b26a4b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java @@ -19,7 +19,7 @@ public class ForceHeightBattleGoal extends ForceBattleGoal { public ForceHeightBattleGoal() { // super(Message.forName("menu-force-height-battle-goal-settings")); - super(new ItemStack(Material.RABBIT_FOOT), "force-height-battle-goal"); + super(new ItemStack(Material.RABBIT_FOOT), "force-height-battle"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java index bd047049d..bb63dfc6d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java @@ -22,7 +22,7 @@ public class ForceItemBattleGoal extends ForceBattleDisplayGoal { public ForceItemBattleGoal() { // super(Message.forName("menu-force-item-battle-goal-settings")); - super(new ItemStack(Material.ITEM_FRAME), "force-item-battle-goal"); + super(new ItemStack(Material.ITEM_FRAME), "force-item-battle"); // registerSetting("give-item", new BooleanSubSetting( // () -> new LegacyItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java index a229923e9..b7e9e24c3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java @@ -23,7 +23,7 @@ public class ForceMobBattleGoal extends ForceBattleDisplayGoal { public ForceMobBattleGoal() { // super(Message.forName("menu-force-mob-battle-goal-settings")); - super(new ItemStack(Material.BOW), "force-mob-battle-goal"); + super(new ItemStack(Material.BOW), "force-mob-battle"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java index ba518f7de..cf08a8a5b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java @@ -16,7 +16,7 @@ public class ForcePositionBattleGoal extends ForceBattleGoal { public ForcePositionBattleGoal() { // super(Message.forName("menu-force-position-battle-goal-settings")); - super(new ItemStack(Material.DIAMOND_BOOTS), "force-position-battle-goal"); + super(new ItemStack(Material.DIAMOND_BOOTS), "force-position-battle"); // registerSetting("radius", new NumberSubSetting( // () -> new LegacyItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-position-battle-radius")), // value -> null, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java index fe3986630..3603f6e90 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/AdvancementTarget.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import org.bukkit.Bukkit; import org.bukkit.advancement.Advancement; @@ -43,13 +43,13 @@ public String getName() { } @Override - public Message getNewTargetMessage() { - return Message.forName("force-advancement-battle-new-advancement"); + public MessageKey getNewTargetMessage() { + return MessageKey.of("force-advancement-battle-new-advancement"); } @Override - public Message getCompletedMessage() { - return Message.forName("force-advancement-battle-completed"); + public MessageKey getCompletedMessage() { + return MessageKey.of("force-advancement-battle-completed"); } @Override @@ -58,8 +58,8 @@ public ExtremeForceBattleGoal.TargetType getType() { } @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-advancement-target-display"); + public MessageKey getScoreboardDisplayMessage() { + return MessageKey.of("force-battle-advancement-target-display"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java index 4f3d71899..a6ad770a1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BiomeTarget.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import org.bukkit.block.Biome; import org.bukkit.entity.Player; @@ -39,13 +39,13 @@ public String getName() { } @Override - public Message getNewTargetMessage() { - return Message.forName("extreme-force-battle-new-biome"); + public MessageKey getNewTargetMessage() { + return MessageKey.of("extreme-force-battle-new-biome"); } @Override - public Message getCompletedMessage() { - return Message.forName("extreme-force-battle-found-biome"); + public MessageKey getCompletedMessage() { + return MessageKey.of("extreme-force-battle-found-biome"); } @Override @@ -54,8 +54,8 @@ public ExtremeForceBattleGoal.TargetType getType() { } @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-biome-target-display"); + public MessageKey getScoreboardDisplayMessage() { + return MessageKey.of("force-battle-biome-target-display"); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java index f7e1464c3..381d62ea2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/BlockTarget.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; @@ -41,13 +41,13 @@ public String getName() { } @Override - public Message getNewTargetMessage() { - return Message.forName("force-block-battle-new-block"); + public MessageKey getNewTargetMessage() { + return MessageKey.of("force-block-battle-new-block"); } @Override - public Message getCompletedMessage() { - return Message.forName("force-block-battle-found"); + public MessageKey getCompletedMessage() { + return MessageKey.of("force-block-battle-found"); } @Override @@ -56,8 +56,8 @@ public ExtremeForceBattleGoal.TargetType getType() { } @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-block-target-display"); + public MessageKey getScoreboardDisplayMessage() { + return MessageKey.of("force-battle-block-target-display"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java index c991be1be..0f552208a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/DamageTarget.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import org.bukkit.entity.Player; public class DamageTarget extends ForceTarget { @@ -26,13 +26,13 @@ public String getName() { } @Override - public Message getNewTargetMessage() { - return Message.forName("extreme-force-battle-new-damage"); + public MessageKey getNewTargetMessage() { + return MessageKey.of("extreme-force-battle-new-damage"); } @Override - public Message getCompletedMessage() { - return Message.forName("extreme-force-battle-took-damage"); + public MessageKey getCompletedMessage() { + return MessageKey.of("extreme-force-battle-took-damage"); } @Override @@ -41,8 +41,8 @@ public ExtremeForceBattleGoal.TargetType getType() { } @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-damage-target-display"); + public MessageKey getScoreboardDisplayMessage() { + return MessageKey.of("force-battle-damage-target-display"); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java index c4d99aabb..cf6b386a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java @@ -2,6 +2,7 @@ import lombok.Getter; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import org.bukkit.Material; import org.bukkit.entity.ArmorStand; @@ -25,13 +26,13 @@ protected ForceTarget(T target) { public abstract String getName(); - public abstract Message getNewTargetMessage(); + public abstract MessageKey getNewTargetMessage(); - public abstract Message getCompletedMessage(); + public abstract MessageKey getCompletedMessage(); public abstract ExtremeForceBattleGoal.TargetType getType(); - public abstract Message getScoreboardDisplayMessage(); + public abstract MessageKey getScoreboardDisplayMessage(); @Override public String toString() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java index d4f38e9de..187edc0fb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/HeightTarget.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import org.bukkit.entity.Player; public class HeightTarget extends ForceTarget { @@ -26,13 +26,13 @@ public String getName() { } @Override - public Message getNewTargetMessage() { - return Message.forName("extreme-force-battle-new-height"); + public MessageKey getNewTargetMessage() { + return MessageKey.of("extreme-force-battle-new-height"); } @Override - public Message getCompletedMessage() { - return Message.forName("extreme-force-battle-reached-height"); + public MessageKey getCompletedMessage() { + return MessageKey.of("extreme-force-battle-reached-height"); } @Override @@ -41,8 +41,8 @@ public ExtremeForceBattleGoal.TargetType getType() { } @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-height-target-display"); + public MessageKey getScoreboardDisplayMessage() { + return MessageKey.of("force-battle-height-target-display"); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java index f2b345c2c..875e68225 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ItemTarget.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.commons.bukkit.utils.item.ItemUtils; @@ -41,13 +41,13 @@ public String getName() { } @Override - public Message getNewTargetMessage() { - return Message.forName("force-item-battle-new-item"); + public MessageKey getNewTargetMessage() { + return MessageKey.of("force-item-battle-new-item"); } @Override - public Message getCompletedMessage() { - return Message.forName("force-item-battle-found"); + public MessageKey getCompletedMessage() { + return MessageKey.of("force-item-battle-found"); } @Override @@ -56,8 +56,8 @@ public ExtremeForceBattleGoal.TargetType getType() { } @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-item-target-display"); + public MessageKey getScoreboardDisplayMessage() { + return MessageKey.of("force-battle-item-target-display"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java index b0eb6d41e..eb8062a33 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/MobTarget.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; import net.codingarea.challenges.plugin.utils.misc.Utils; @@ -48,13 +48,13 @@ public String getName() { } @Override - public Message getNewTargetMessage() { - return Message.forName("force-mob-battle-new-mob"); + public MessageKey getNewTargetMessage() { + return MessageKey.of("force-mob-battle-new-mob"); } @Override - public Message getCompletedMessage() { - return Message.forName("force-mob-battle-killed"); + public MessageKey getCompletedMessage() { + return MessageKey.of("force-mob-battle-killed"); } @Override @@ -63,8 +63,8 @@ public ExtremeForceBattleGoal.TargetType getType() { } @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-mob-target-display"); + public MessageKey getScoreboardDisplayMessage() { + return MessageKey.of("force-battle-mob-target-display"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java index 3b6634bc9..242f29251 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/PositionTarget.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.collection.pair.Tuple; @@ -44,13 +45,13 @@ public String getName() { } @Override - public Message getNewTargetMessage() { - return Message.forName("extreme-force-battle-new-position"); + public MessageKey getNewTargetMessage() { + return MessageKey.of("extreme-force-battle-new-position"); } @Override - public Message getCompletedMessage() { - return Message.forName("extreme-force-battle-reached-position"); + public MessageKey getCompletedMessage() { + return MessageKey.of("extreme-force-battle-reached-position"); } @Override @@ -59,8 +60,8 @@ public ExtremeForceBattleGoal.TargetType getType() { } @Override - public Message getScoreboardDisplayMessage() { - return Message.forName("force-battle-position-target-display"); + public MessageKey getScoreboardDisplayMessage() { + return MessageKey.of("force-battle-position-target-display"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java index eee7396d2..db31f5179 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java @@ -35,7 +35,7 @@ public class BackpackSetting extends SettingModifier implements PlayerCommand { private final Inventory sharedBackpack; public BackpackSetting() { - super(MenuType.SETTINGS, null, 1, 2, SHARED, new ItemStack(Material.CHEST), "backpack-setting"); + super(MenuType.SETTINGS, null, 1, 2, SHARED, new ItemStack(Material.CHEST), "backpack"); size = Math.clamp(ChallengeConfigHelper.getSettingsDocument().getInt("backpack-size") * 9L, 9, 6 * 9); sharedBackpack = createInventory("§5Team Backpack"); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java index 3ce398337..0e3aa3050 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java @@ -33,7 +33,7 @@ public class CutCleanSetting extends MenuSetting { public CutCleanSetting() { - super(MenuType.SETTINGS, null, new ItemStack(Material.IRON_AXE), "menu-cut-clean-setting-settings"); + super(MenuType.SETTINGS, null, new ItemStack(Material.IRON_AXE), "cut-clean"); registerSetting("iron->iron_ingot", new ConvertDropSubSetting(() -> new LegacyItemBuilder(Material.IRON_INGOT, Message.forName("item-cut-clean-iron-setting")), true, Material.IRON_INGOT, "IRON_ORE", "DEEPSLATE_IRON_ORE")); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java index f58e2fbde..4050cd412 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java @@ -14,7 +14,7 @@ public class DamageMultiplierModifier extends Modifier { public DamageMultiplierModifier() { - super(MenuType.SETTINGS, null, 10, new ItemStack(Material.STONE_SWORD), "damage-multiplier-setting"); + super(MenuType.SETTINGS, null, 10, new ItemStack(Material.STONE_SWORD), "damage-multiplier"); } // @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java index e888b99d1..93a816afc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/EnderChestCommandSetting.java @@ -16,7 +16,7 @@ public class EnderChestCommandSetting extends Setting implements PlayerCommand { public EnderChestCommandSetting() { - super(MenuType.SETTINGS, null, new ItemStack(Material.ENDER_CHEST), "item-enderchest-command-setting"); + super(MenuType.SETTINGS, null, new ItemStack(Material.ENDER_CHEST), "enderchest-command"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java index 92514f061..9a6f4ce36 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java @@ -19,7 +19,7 @@ public class ImmediateRespawnSetting extends Setting { private boolean respawnWithEvent; public ImmediateRespawnSetting() { - super(MenuType.SETTINGS, null, new ItemStack(Material.GOLDEN_APPLE), "item-immediate-respawn-setting"); + super(MenuType.SETTINGS, null, new ItemStack(Material.GOLDEN_APPLE), "immediate-respawn"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java index ab9cb79bf..bf61ab083 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java @@ -80,6 +80,9 @@ public void handleClick(@NotNull ChallengeMenuClickInfo info) { } super.handleClick(info); + + String languageTag = VALUE_TO_TAG.get(getValue()); + getChallengeMessageKey("command-changing").send(info.getPlayer(), Prefix.CHALLENGES, languageTag); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index 3cfcfa797..0a5e3286a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -4,7 +4,6 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java index 572e1509f..1530f105b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/NoOffhandSetting.java @@ -17,7 +17,7 @@ public class NoOffhandSetting extends Setting { public NoOffhandSetting() { - super(MenuType.SETTINGS, null, new ItemStack(Material.SHIELD), "no-offhand-setting"); + super(MenuType.SETTINGS, null, new ItemStack(Material.SHIELD), "no-offhand"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java index 362d0004d..132be2419 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java @@ -35,7 +35,7 @@ public class PositionSetting extends Setting implements PlayerCommand, TabComple private final boolean particleLines; public PositionSetting() { - super(MenuType.SETTINGS, null, true, new ItemStack(Material.BLUE_BANNER), "position-setting"); + super(MenuType.SETTINGS, null, true, new ItemStack(Material.BLUE_BANNER), "position"); particleLines = ChallengeConfigHelper.getSettingsDocument().getBoolean("position-particle-lines"); Challenges.getInstance().registerCommand(new DelPosCommand(), "delposition"); Challenges.getInstance().registerCommand(new SetPosCommand(), "setposition"); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java index 08d1d2612..36438f1cb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PvPSetting.java @@ -12,7 +12,7 @@ public class PvPSetting extends Setting { public PvPSetting() { - super(MenuType.SETTINGS, null, true, new ItemStack(Material.STONE_SWORD), "pvp-setting"); + super(MenuType.SETTINGS, null, true, new ItemStack(Material.STONE_SWORD), "pvp"); } @EventHandler diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java index 587de479f..2c80a0594 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java @@ -24,7 +24,7 @@ public class RegenerationSetting extends Modifier { public RegenerationSetting() { super(MenuType.SETTINGS, null, 1, 3, ENABLED, - new StandardItemBuilder.PotionBuilder(Material.POTION).setColor(Color.RED).build(), "item-regeneration-setting"); + new StandardItemBuilder.PotionBuilder(Material.POTION).setColor(Color.RED).build(), "regeneration"); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java index cd7e4187d..36c5fa95e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; @@ -23,6 +24,8 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import java.util.Locale; + @Since("2.0") public class SlotLimitSetting extends Modifier { @@ -30,6 +33,12 @@ public SlotLimitSetting() { super(MenuType.SETTINGS, null, 1, 36, 36, new ItemStack(Material.BARRIER), "slot-limit"); } + @NotNull + @Override + public LocalizableMessage getSettingsName() { + return getChallengeMessageKey("settings").withArgs(getValue(), 36); + } + @Override protected void onValueChange() { update(); @@ -101,7 +110,7 @@ public void onPlayerInventoryClick(@NotNull PlayerInventoryClickEvent event) { if (!shouldExecuteEffect()) return; if (event.getClickedInventory() == null) return; if (event.getClickedInventory().getType() != InventoryType.PLAYER) return; - if (isBlocked(event.getSlot())) { + if (isBlocked(event.getSlot()) || event.getCurrentItem() != null && event.getCurrentItem().isSimilar(LegacyItemBuilder.BLOCKED_ITEM)) { event.setCancelled(true); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java index 624da0342..2333a2be4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SoupSetting.java @@ -16,7 +16,7 @@ public class SoupSetting extends Setting { public SoupSetting() { - super(MenuType.SETTINGS, null, new ItemStack(Material.MUSHROOM_STEW), "setting-soup"); + super(MenuType.SETTINGS, null, new ItemStack(Material.MUSHROOM_STEW), "soup"); } @EventHandler diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java index cabf73b6b..2c5ddf306 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SplitHealthSetting.java @@ -21,7 +21,7 @@ public class SplitHealthSetting extends Setting { public SplitHealthSetting() { - super(MenuType.SETTINGS, null, new StandardItemBuilder.PotionBuilder(Material.TIPPED_ARROW).setColor(Color.RED).build(), "item-split-health-setting"); + super(MenuType.SETTINGS, null, new StandardItemBuilder.PotionBuilder(Material.TIPPED_ARROW).setColor(Color.RED).build(), "split-health"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java index 90373de8c..bff77a10b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java @@ -28,7 +28,7 @@ public class TimberSetting extends SettingModifier { public static final int LOGS_LEAVES = 2; public TimberSetting() { - super(MenuType.SETTINGS, null, 2, new ItemStack(Material.DIAMOND_AXE), "item-timber-setting"); + super(MenuType.SETTINGS, null, 2, new ItemStack(Material.DIAMOND_AXE), "timber"); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java index 392170d65..ddb2a4b54 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TotemSaveDeathSetting.java @@ -15,7 +15,7 @@ public class TotemSaveDeathSetting extends Setting { public TotemSaveDeathSetting() { - super(MenuType.SETTINGS, null, new ItemStack(Material.TOTEM_OF_UNDYING), "setting-totem-save-death"); + super(MenuType.SETTINGS, null, new ItemStack(Material.TOTEM_OF_UNDYING), "totem-save-death"); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java index 938be2a03..6d86c20a2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java @@ -159,7 +159,7 @@ public ItemBuilder getSettingsItem(@NotNull Locale locale) { ItemStack preset = isEnabled() ? getSettingsItemPreset() : getDisabledSettingsItemPreset(); // apply formatting dynamically, to prevent duplicate format references ItemBuilder item = new ItemBuilder(locale, preset, MessageKey.of("challenge.settings-format"), - isEnabled() ? getSettingsName() : MessageKey.of("disabled")); // no need to override disabled name/item + isEnabled() ? getSettingsName() : MessageKey.of("generic.disabled")); // no need to override disabled name/item LocalizableMessage description = getSettingsDescription(); if (description != null && isEnabled()) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java index c7715f1e9..362ae62f3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java @@ -3,6 +3,7 @@ import lombok.Getter; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; @@ -30,7 +31,7 @@ public FirstPlayerAtHeightGoal(@Nullable SettingCategory category, @NotNull Item @Override protected void onEnable() { bossbar.setContent((bar, player) -> { - bar.setTitle(Message.forName("bossbar-first-at-height-goal").asString(getHeightToGetTo())); + bar.setTitle(MessageKey.of("bossbar-first-at-height-goal"), getHeightToGetTo()); }); bossbar.show(); } @@ -51,7 +52,7 @@ public void onMove(PlayerMoveEvent event) { if (ignorePlayer(event.getPlayer())) return; if (event.getTo().getBlockY() == event.getFrom().getBlockY()) return; if (event.getTo().getBlockY() == heightToGetTo) { - Message.forName("height-reached").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), getHeightToGetTo()); + MessageKey.of("height-reached").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), getHeightToGetTo()); ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java index 2aff1f67b..b780cd532 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java @@ -4,6 +4,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ForceTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.menu.MenuGoal; import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -227,11 +228,11 @@ protected T getRandomTarget(Player player) { return null; } - protected Message getNewTargetMessage(T newTarget) { + protected MessageKey getNewTargetMessage(T newTarget) { return newTarget.getNewTargetMessage(); } - protected Message getTargetCompletedMessage(T target) { + protected MessageKey getTargetCompletedMessage(T target) { return target.getCompletedMessage(); } @@ -276,7 +277,7 @@ public void getWinnersOnEnd(@NotNull List winners) { UUID uuid = entry.getKey(); OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); ChatColor color = getPlaceColor(place); - Message.forName("force-battle-leaderboard-entry") + MessageKey.of("force-battle-leaderboard-entry") .broadcast(Prefix.CHALLENGES, color, place, NameHelper.getName(offlinePlayer), entry.getValue().size()); } @@ -304,7 +305,7 @@ public void sendResult(@NotNull Player player) { UUID uuid = entry.getKey(); OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid); ChatColor color = getPlaceColor(place); - Message.forName("force-battle-leaderboard-entry") + MessageKey.of("force-battle-leaderboard-entry") .send(player, Prefix.CHALLENGES, color, place, NameHelper.getName(offlinePlayer), entry.getValue().size()); } @@ -348,7 +349,7 @@ protected void setScoreboardContent() { int emptyLinesAvailable = 15 - ingamePlayers.size(); if (emptyLinesAvailable > 0) { - board.addLine(""); + board.addEmptyLine(); emptyLinesAvailable--; } @@ -356,11 +357,11 @@ protected void setScoreboardContent() { Player ingamePlayer = ingamePlayers.get(i); T target = currentTarget.get(ingamePlayer.getUniqueId()); String display = target == null ? Message.forName("none").asString() : getTargetName(target); - board.addLine(NameHelper.getName(ingamePlayer) + " §8» §e" + display); +// board.addLine(NameHelper.getName(ingamePlayer) + " §8» §e" + display); // TODO format translation } if (emptyLinesAvailable > 0) { - board.addLine(""); + board.addEmptyLine(); } }); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java index 41c417acf..ea85e225c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ItemCollectionGoal.java @@ -1,9 +1,8 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; @@ -23,7 +22,7 @@ public abstract class ItemCollectionGoal extends CollectionGoal { public ItemCollectionGoal(@Nullable SettingCategory category, @NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey, @NotNull Material... target) { - super(category, displayItemPreset, nameMessageKey, target); + super(category, displayItemPreset, nameMessageKey, target); } public ItemCollectionGoal(@Nullable SettingCategory category, boolean enabledByDefault, @NotNull ItemStack displayItemPreset, @@ -41,7 +40,7 @@ protected void handleCollect(@NotNull Player player, @NotNull Material material) @Override protected void onEnable() { scoreboard.setContent(GoalHelper.createScoreboard(() -> getPoints(new AtomicInteger(), true), - player -> Collections.singletonList(Message.forName("items-to-collect").asString(target.length)))); + _ -> Collections.singletonList(MessageKey.of("items-to-collect").withArgs(target.length)))); scoreboard.show(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java index 179ea315f..33f605bbe 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; @@ -69,7 +70,7 @@ public void onDeath(@NotNull EntityDeathEvent event) { if (entitiesKilled.contains(event.getEntityType())) return; entitiesKilled.add(event.getEntityType()); if (entitiesToKill.contains(event.getEntityType())) { - Message.forName("mob-kill").broadcast(Prefix.CHALLENGES, event.getEntityType(), getEntitiesKilled().size(), entitiesToKill.size()); + MessageKey.of("mob-kill").broadcast(Prefix.CHALLENGES, event.getEntityType(), getEntitiesKilled().size(), entitiesToKill.size()); bossbar.update(); if (!getEntitiesLeftToKill().isEmpty()) return; resetEntitiesToKill(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java index 1e646ce97..ea5fe055e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java @@ -4,6 +4,8 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeScoreboard.ScoreboardInstance; import net.codingarea.challenges.plugin.utils.misc.NameHelper; @@ -82,18 +84,18 @@ public static int determinePosition(@NotNull SortedMap> map, @Not @NotNull public static BiConsumer createScoreboard(@NotNull Supplier> points) { - return createScoreboard(points, player -> new LinkedList<>()); + return createScoreboard(points, _ -> new LinkedList<>()); } @NotNull - public static BiConsumer createScoreboard(@NotNull Supplier> points, Function> additionalLines) { + public static BiConsumer createScoreboard(@NotNull Supplier> points, Function> additionalLines) { return (scoreboard, player) -> { SortedMap> leaderboard = GoalHelper.createLeaderboardFromPoints(points.get()); int playerPlace = GoalHelper.determinePosition(leaderboard, player); - scoreboard.addLine(""); - scoreboard.addLine(Message.forName("your-place").asString(playerPlace)); - scoreboard.addLine(""); + scoreboard.addEmptyLine(); + scoreboard.addLine(MessageKey.of("your-place"), playerPlace); + scoreboard.addEmptyLine(); { int place = 1; int displayed = 0; @@ -102,20 +104,20 @@ public static BiConsumer createScoreboard(@NotNull S for (Player current : players) { displayed++; if (displayed >= LEADERBOARD_SIZE) break; - scoreboard.addLine(Message.forName("scoreboard-leaderboard").asString(place, NameHelper.getName(current), NumberFormatter.MIDDLE_NUMBER.format(entry.getKey()))); + scoreboard.addLine(MessageKey.of("scoreboard-leaderboard"), place, current, NumberFormatter.MIDDLE_NUMBER.format(entry.getKey())); } if (displayed == LEADERBOARD_SIZE) break; place++; } } - scoreboard.addLine(""); + scoreboard.addEmptyLine(); - List lines = additionalLines.apply(player); + List lines = additionalLines.apply(player); if (!lines.isEmpty()) { - int linesThatCanBeAdded = 15 - scoreboard.getLines().size() - 1; + int linesThatCanBeAdded = scoreboard.getRemainingLines() - 1; for (int i = 0; i < lines.size() && linesThatCanBeAdded > 0; i++) { linesThatCanBeAdded--; - String line = lines.get(i); + LocalizableMessage line = lines.get(i); scoreboard.addLine(line); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java index 70e6a14f5..9b0ad8538 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java @@ -2,6 +2,7 @@ import lombok.RequiredArgsConstructor; import net.codingarea.commons.common.collection.NumberFormatter; +import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; @@ -40,8 +41,22 @@ public interface ArgumentFormat { return MessageKey.of("arg-format.hp").withArgs(hp, NumberFormatter.FLOATING_POINT.format(hearts)); }); - ArgumentFormat TIME = register(Integer.class, "seconds", arg -> { - return LocalizableMessage.from(_ -> NumberFormatter.TIME.format(arg)); + @SuppressWarnings({"unchecked", "rawtypes"}) + ArgumentFormat SECONDS_RANGE = register(Tuple.class, "minute_range", arg -> { + Tuple range = (Tuple) arg; + int seconds = range.getFirst(); + int secondsRange = range.getSecond(); + + if (seconds % 15 == 0) { + float minutes = seconds / 60f; + return MessageKey.of("arg-format.time-range").withArgs( + NumberFormatter.DEFAULT.format(minutes), MessageKey.pluralize("generic.minute", minutes), + NumberFormatter.DEFAULT.format(secondsRange), MessageKey.pluralize("generic.second", secondsRange)); + } + + return MessageKey.of("arg-format.time-range").withArgs( + NumberFormatter.DEFAULT.format(seconds), MessageKey.pluralize("generic.second", seconds), + NumberFormatter.DEFAULT.format(secondsRange), MessageKey.pluralize("generic.second", secondsRange)); }); ArgumentFormat DAMAGE_CAUSE = register(EntityDamageEvent.class, "damage_cause", event -> { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java index f63098469..1e5ebacfc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java @@ -88,6 +88,18 @@ static MessageKey of(@NotNull String id) { return i18n.getMessageKey(id); } + @NotNull + @CheckReturnValue + static MessageKey pluralize(@NotNull String singular, @NotNull String plural, @NotNull Number count) { + return of(count.intValue() == 1 ? singular : plural); + } + + @NotNull + @CheckReturnValue + static MessageKey pluralize(@NotNull String baseId, @NotNull Number count) { + return pluralize(baseId, baseId + "s", count); + } + @NotNull @CheckReturnValue @ApiStatus.Internal diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java index c6bcd4a56..7a3385367 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/loader/LanguageLoader.java @@ -197,6 +197,7 @@ private void migrateLanguageFileAndSave(@NotNull Document migratedLanguage, @Not @NotNull private List loadBundledLanguageNames() { try (InputStream in = getLanguageResourceStream("languages.json")) { + if (in == null) throw new IllegalStateException("Could not load bundled languages.json from jar"); return Document.parseJsonStringArray(IOUtils.toString(in)); } catch (Exception ex) { Logger.error("Could not load bundled languages", ex); @@ -206,7 +207,7 @@ private List loadBundledLanguageNames() { @Nullable private Document loadBundledLanguageDocument(@NotNull String languageName) { - try (InputStream in = getLanguageResourceStream("files/" + languageName + ".json")) { + try (InputStream in = getLanguageResourceStream("locales/" + languageName + ".json")) { if (in == null) return null; return Document.parseJson(in); } catch (Exception ex) { @@ -215,7 +216,8 @@ private Document loadBundledLanguageDocument(@NotNull String languageName) { } } - private InputStream getLanguageResourceStream(String path) { + @Nullable + private InputStream getLanguageResourceStream(@NotNull String path) { // no leading slash! return Challenges.getInstance().getResource("language/" + path); } @@ -236,7 +238,7 @@ private List fetchOnlineLanguages() { @Nullable private Document fetchOnlineLanguageDocument(@NotNull String languageName) { - String url = getGitHubUrl("language/files/" + languageName + ".json"); + String url = getGitHubUrl("language/locales/" + languageName + ".json"); try { return Document.parseJson(IOUtils.toString(url)); } catch (Exception ex) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java index a649397af..6a5cb33bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java @@ -57,7 +57,7 @@ public final void registerWithCommand(@NotNull Class class RequireVersion annotation = classOfChallenge.getAnnotation(RequireVersion.class); MinecraftVersion minVersion = annotation.value(); - if (!MinecraftVersion.current().isNewerOrEqualThan(minVersion)) { + if (MinecraftVersion.current().isOlderThan(minVersion)) { Logger.debug("Did not register challenge {}, requires version {}, server running on {}", classOfChallenge.getSimpleName(), minVersion, MinecraftVersion.current()); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java index fd5d50abe..e5b51864c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ChallengeEndCause.java @@ -1,27 +1,23 @@ package net.codingarea.challenges.plugin.management.server; import lombok.Getter; -import net.codingarea.challenges.plugin.content.legacy.Message; +import lombok.RequiredArgsConstructor; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; @Getter +@RequiredArgsConstructor public enum ChallengeEndCause { - TIMER_HIT_ZERO(Message.forName("challenge-end-timer-hit-zero"), Message.forName("challenge-end-timer-hit-zero-winner")), - GOAL_REACHED(Message.forName("challenge-end-goal-reached"), Message.forName("challenge-end-goal-reached-winner")), - GOAL_FAILED(Message.forName("challenge-end-goal-failed"), null); + TIMER_HIT_ZERO("challenge-end.timer-hit-zero", "challenge-end.timer-hit-zero-winner"), + GOAL_REACHED("challenge-end.goal-reached", "challenge-end.goal-reached-winner"), + GOAL_FAILED("challenge-end.goal-failed", null); - private final Message noWinnerMessage, winnerMessage; - - ChallengeEndCause(@NotNull Message noWinnerMessage, @Nullable Message winnerMessage) { - this.noWinnerMessage = noWinnerMessage; - this.winnerMessage = winnerMessage; - } + private final String noWinnerMessage, winnerMessage; @NotNull - public Message getMessage(boolean withWinner) { - return withWinner && winnerMessage != null ? winnerMessage : noWinnerMessage; + public MessageKey getMessage(boolean withWinner) { + return MessageKey.of(withWinner && winnerMessage != null ? winnerMessage : noWinnerMessage); } public boolean isWinnable() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java index 11a0423b2..749f203b0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java @@ -4,6 +4,7 @@ import lombok.Setter; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.bukkit.container.PlayerData; import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; @@ -85,9 +86,11 @@ public void prepareWorldReset(@Nullable CommandSender requestedBy, @Nullable Lon resetConfigs(seed); - String requester = requestedBy instanceof Player ? NameHelper.getName((Player) requestedBy) : "§4§lConsole"; - String kickMessage = Message.forName(restartOnReset ? "server-reset-restart" : "server-reset-stop").asString(requester); - Bukkit.getOnlinePlayers().forEach(player -> player.kickPlayer(kickMessage)); + Object requester = requestedBy instanceof Player ? requestedBy : "Console objectives = new ConcurrentHashMap<>(); - private BiConsumer content = (scoreboard, player) -> { + private BiConsumer content = (_, _) -> { }; public void setContent(@NotNull BiConsumer content) { @@ -55,15 +65,15 @@ public synchronized void update(@NotNull Player player) { ScoreboardInstance instance = new ScoreboardInstance(); content.accept(instance, player); - Collection lines = instance.getLines(); + LanguageProvider languageProvider = Challenges.getInstance().getTranslationManager().getLanguageProvider(); + Locale locale = languageProvider.getPlayerLanguage(player); + + ArrayList lines = instance.getLines(locale); if (lines.isEmpty()) { return; } Scoreboard scoreboard = player.getScoreboard(); - if (Bukkit.getScoreboardManager() == null) { - return; - } if (scoreboard == Bukkit.getScoreboardManager().getMainScoreboard()) { player.setScoreboard(scoreboard = Bukkit.getScoreboardManager().getNewScoreboard()); } @@ -75,12 +85,14 @@ public synchronized void update(@NotNull Player player) { unregister(oldObjective); } - Objective objective = registerDummyObjective(scoreboard, name, String.valueOf(instance.getTitle())); - int score = lines.size(); - for (String line : lines) { - if (line.isEmpty()) line = StringUtils.repeat(' ', score + 1); - score--; - objective.getScore(line).setScore(score); + Component title = instance.getTitle().getLocalizableKey().asComponent(player, instance.getTitle().getLocalizableArgs()); + Objective objective = registerDummyObjective(scoreboard, name, title); + for (int i = 0; i < lines.size(); i++) { + Component line = lines.get(i); + Score entry = objective.getScore(String.valueOf(i)); + entry.customName(line); + entry.setScore(MAX_LINES - i); + entry.numberFormat(NumberFormat.blank()); } objective.setDisplaySlot(DisplaySlot.SIDEBAR); @@ -115,49 +127,86 @@ private void unregister(@Nullable Objective objective) { @NotNull @SuppressWarnings("deprecation") - private Objective registerDummyObjective(@NotNull Scoreboard scoreboard, @NotNull String name, @NotNull String displayName) { -// try { -// return scoreboard.registerNewObjective(name, Criteria.DUMMY, displayName); -// } catch (Error ignored) { + private Objective registerDummyObjective(@NotNull Scoreboard scoreboard, @NotNull String name, @NotNull Component displayName) { + try { + return scoreboard.registerNewObjective(name, org.bukkit.scoreboard.Criteria.DUMMY, displayName); + } catch (Error ignored) { // replacement not yet available in this version, use deprecated method return scoreboard.registerNewObjective(name, "dummy", displayName); -// } + } } @ToString public static final class ScoreboardInstance { - private final String[] lines = new String[15]; + private final Object[] lines = new Object[MAX_LINES]; // either LocalizableMessage or Component @Getter - private String title = Message.forName("scoreboard-title").asString(); + private LocalizableMessage title = MessageKey.of("scoreboard.title"); private int linesIndex = 0; private ScoreboardInstance() { } @NotNull - public ScoreboardInstance addLine(@NotNull String text) { + public ScoreboardInstance addEmptyLine() { + return addLine(Component.empty()); + } + + public ScoreboardInstance addLine(@NotNull Component text) { + addLine((Object) text); + return this; + } + + @NotNull + public ScoreboardInstance addLine(@NotNull LocalizableMessage line) { + addLine((Object) line); + return this; + } + + @NotNull + public ScoreboardInstance addLine(@NotNull MessageKey line, @NotNull Object... args) { + if (args.length == 0) { + addLine((Object) line); + } else { + addLine((Object) line.withArgs(args)); + } + return this; + } + + private void addLine(@NotNull Object lineObj) { if (linesIndex >= lines.length) throw new IllegalStateException("All lines are already used! (" + lines.length + ")"); - lines[linesIndex++] = text; - return this; + lines[linesIndex++] = lineObj; } @NotNull - public Collection getLines() { - List list = new ArrayList<>(); - for (String line : lines) { + public ArrayList getLines(@NotNull Locale locale) { + ArrayList list = new ArrayList<>(lines.length); + for (Object line : lines) { if (line == null) continue; - list.add(line); + + if (line instanceof LocalizableMessage message) { + list.add(message.getLocalizableKey().asComponent(locale, message.getLocalizableArgs())); + } else { + list.add(ComponentArguments.convertToComponent(line)); + } } return list; } @NotNull - public ScoreboardInstance setTitle(@NotNull String title) { + public ScoreboardInstance setTitle(@NotNull LocalizableMessage title) { this.title = title; return this; } + + public int getRemainingLines() { + return MAX_LINES - linesIndex; + } + + public int getTotalLines() { + return linesIndex + 1; + } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java index 2952841d0..10737f73f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java @@ -55,7 +55,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc int countToTeleport = Math.min(list.size(), count); - Message.forName("command-back-teleported" + (countToTeleport > 1 ? "-multiple" : "")) + MessageKey.of("command-back-teleported" + (countToTeleport > 1 ? "-multiple" : "")) .send(player, Prefix.CHALLENGES, countToTeleport); Location location = list.get(countToTeleport - 1); inTeleport = true; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java index 26f0785db..df40dcf42 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java @@ -35,11 +35,11 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { if (confirmReset && (args.length < 1 || !args[0].equalsIgnoreCase("confirm")) || (args.length > 0 && !args[0].equalsIgnoreCase("confirm"))) { if (args.length > 0 && args[0].equalsIgnoreCase("settings")) { Challenges.getInstance().getChallengeManager().restoreDefaults(); - Message.forName("config-reset").broadcast(Prefix.CHALLENGES); + MessageKey.of("config-reset").broadcast(Prefix.CHALLENGES); return; } else if (args.length > 0 && args[0].equalsIgnoreCase("customs")) { Challenges.getInstance().getCustomChallengesLoader().resetChallenges(); - Message.forName("custom_challenges-reset").broadcast(Prefix.CHALLENGES); + MessageKey.of("custom_challenges-reset").broadcast(Prefix.CHALLENGES); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java index e49ac35c2..487ea614f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java @@ -34,8 +34,6 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr LocalizableMessage[] names = challenges.stream().map(IChallenge::getChallengeName).toArray(LocalizableMessage[]::new); MessageKey.of("command.skip-timer.done").broadcast(Prefix.CHALLENGES, LocalizableMessage.joinArray(names)); } - - MessageKey.of("test").send(sender, null, Material.MUSIC_DISC_13); } @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java index 894921e87..cedc43976 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/CheatListener.java @@ -1,9 +1,8 @@ package net.codingarea.challenges.plugin.spigot.listener; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.GameMode; @@ -13,11 +12,23 @@ import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent; -import org.bukkit.event.player.PlayerToggleSneakEvent; import org.jetbrains.annotations.NotNull; public class CheatListener implements Listener { + public static final String[] CHEAT_COMMANDS = { + "give", + "replaceitem", + "effect", + "i", + "summon", + "enchant", + "heal", + "kill", + "setblock", + "fill" + }; + public CheatListener() { Bukkit.getOnlinePlayers().stream() .filter(player -> player.getGameMode() == GameMode.CREATIVE) @@ -30,28 +41,8 @@ public void onGameModeChange(@NotNull PlayerGameModeChangeEvent event) { handleCheatsDetected(event.getPlayer()); } - @EventHandler(priority = EventPriority.MONITOR) - public void onSneak(PlayerToggleSneakEvent event) { - if (!event.isSneaking()) { - } -//// Structure structure = entry.getValue(); - - } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCommand(@NotNull PlayerCommandPreprocessEvent event) { - String[] commands = { - "give", - "replaceitem", - "effect", - "i", - "summon", - "enchant", - "heal", - "kill", - "setblock", - "fill" - }; String message = event.getMessage().toLowerCase(); if (message.isEmpty()) return; @@ -61,7 +52,7 @@ public void onCommand(@NotNull PlayerCommandPreprocessEvent event) { commandName = commandName.substring(commandName.indexOf(':') + 1); } - for (String command : commands) { + for (String command : CHEAT_COMMANDS) { if (!commandName.equalsIgnoreCase("/" + command)) continue; if (!hasPermission(event.getPlayer(), command)) continue; handleCheatsDetected(event.getPlayer()); @@ -90,7 +81,7 @@ private void handleCheatsDetected(@NotNull Player player) { if (!Challenges.getInstance().getStatsManager().isNoStatsAfterCheating()) return; Challenges.getInstance().getServerManager().setHasCheated(); Logger.info("Detected cheating: No more stats can be collected"); - Message.forName("cheats-detected").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + MessageKey.of("cheats-detected").broadcast(Prefix.CHALLENGES, player); } } diff --git a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java index 5d0d581dc..c5e25ee05 100644 --- a/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java +++ b/plugin/src/main/java/net/codingarea/commons/common/collection/pair/Pair.java @@ -1,5 +1,6 @@ package net.codingarea.commons.common.collection.pair; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; /** @@ -27,4 +28,22 @@ public interface Pair { */ boolean noneNull(); + @NotNull + @Contract(value = "_, _, -> new", pure = true) + static Tuple of(F first, S second) { + return Tuple.of(first, second); + } + + @NotNull + @Contract(value = "_, _, _ -> new", pure = true) + static Triple of(F first, S second, T third) { + return Triple.of(first, second, third); + } + + @NotNull + @Contract(value = "_, _, _, _ -> new", pure = true) + static Quadro of(F first, S second, T third, Q fourth) { + return Quadro.of(first, second, third, fourth); + } + } From 778ad2bf7b592a1a403be56e8988b9075f460095 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Tue, 7 Jul 2026 20:30:59 +0200 Subject: [PATCH 101/119] refactor: migrate custom menu generators (part 1) --- language/locales/de.json | 56 +++++- .../challenges/custom/CustomChallenge.java | 2 +- .../settings/sub/SubSettingsBuilder.java | 2 +- .../builder/ChooseItemSubSettingsBuilder.java | 4 +- .../ChooseMultipleItemSubSettingBuilder.java | 4 +- .../sub/builder/EmptySubSettingsBuilder.java | 2 +- .../builder/GeneratorSubSettingsBuilder.java | 2 +- .../builder/TextInputSubSettingsBuilder.java | 2 +- .../sub/builder/ValueSubSettingsBuilder.java | 4 +- .../type/helper/ChallengeHelper.java | 4 +- .../i18n/impl/format/ComponentSplitter.java | 5 +- .../challenges/ChallengeManager.java | 3 +- .../challenges/CustomChallengesLoader.java | 6 +- .../plugin/management/menu/MenuManager.java | 6 +- .../plugin/management/menu/MenuType.java | 4 +- .../menu/generator/AbstractMenuGenerator.java | 25 ++- .../generator/IChallengesMenuGenerator.java | 6 + .../generator/MultiPageMenuGenerator.java | 10 +- .../generator/SinglePageMenuGenerator.java | 17 +- .../UncachedMultiPageMenuGenerator.java | 155 +++++++++++++++++ .../challenge/ChallengeListMenuGenerator.java | 5 +- .../challenge/ChallengesMenuGenerator.java | 6 +- .../CustomChooseMaterialMenuGenerator.java | 84 +++++++++ .../impl/custom/CustomHomeMenuGenerator.java | 116 +++++++++++++ .../impl/custom/CustomListMenuGenerator.java | 64 +++++++ .../impl/custom/InfoMenuGenerator.java | 159 ++++++++++++++++++ .../implementation/SettingsMenuGenerator.java | 38 ----- .../generator/legacy/ChooseItemGenerator.java | 2 +- .../legacy/ChooseMultipleItemGenerator.java | 2 +- .../CustomMainSettingsMenuGenerator.java | 5 +- .../custom/IParentCustomGenerator.java | 7 +- .../custom/InfoMenuGenerator.java | 6 +- .../custom/MainCustomMenuGenerator.java | 3 +- .../custom/MaterialMenuGenerator.java | 3 +- .../custom/SubSettingChooseMenuGenerator.java | 2 +- ...SubSettingChooseMultipleMenuGenerator.java | 2 +- .../custom/SubSettingValueMenuGenerator.java | 2 +- .../utils/misc/MinecraftNameWrapper.java | 1 + .../utils/item/StandardItemBuilder.java | 35 ++-- .../bukkit/utils/menu/MenuPositionHolder.java | 2 +- .../utils/menu/MenuPositionListener.java | 6 + 41 files changed, 759 insertions(+), 110 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IChallengesMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/UncachedMultiPageMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChooseMaterialMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomHomeMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomListMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/InfoMenuGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{implementation => legacy}/custom/CustomMainSettingsMenuGenerator.java (94%) rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{implementation => legacy}/custom/IParentCustomGenerator.java (70%) rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{implementation => legacy}/custom/InfoMenuGenerator.java (98%) rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{implementation => legacy}/custom/MainCustomMenuGenerator.java (99%) rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{implementation => legacy}/custom/MaterialMenuGenerator.java (98%) rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{implementation => legacy}/custom/SubSettingChooseMenuGenerator.java (97%) rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{implementation => legacy}/custom/SubSettingChooseMultipleMenuGenerator.java (97%) rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{implementation => legacy}/custom/SubSettingValueMenuGenerator.java (97%) diff --git a/language/locales/de.json b/language/locales/de.json index b5b577e9b..89667da70 100644 --- a/language/locales/de.json +++ b/language/locales/de.json @@ -2,6 +2,7 @@ "generic": { "undefined": "undefiniert", "unknown": "unbekannt", + "none": "Nichts", "second": "Sekunde", "seconds": "Sekunden", "minute": "Minute", @@ -123,7 +124,60 @@ "name": "Einstellungen" }, "custom": { - "name": "Individuelle Challenges" + "name": "Individuelle Challenges", + "sub-name": "Individuell", + "selected-format": "Eingestellt {@symbol.circle} {0}", + "home": { + "item-view": "{@item-format('Challenges ansehen')}", + "item-create": "{@item-format('Challenge erstellen')}" + }, + "info": { + "name": "Info", + "item-save": [ + "{@item-format('Speichern')}" + ], + "item-delete": [ + "{@item-format('Löschen')}", + " ", + "Achtung diese Aktion kann nicht", + "rückgängig gemacht werden" + ], + "item-material": [ + "{@item-format('Anzeige Item')}", + " ", + "Klicke um das Anzeigeitem zu ändern", + " ", + "{@selected-format}" + ], + "item-trigger": [ + "{@item-format('Auslöser')}", + " ", + "Klicke um einzustellen, was passieren", + "muss, damit die Aktion ausgeführt wird", + " ", + "{@selected-format}" + ], + "item-action": [ + "{@item-format('Aktion')}", + " ", + "Klicke um einzustellen, was passieren", + "soll, wenn der Auslöser erfüllt ist", + " ", + "{@selected-format}" + ], + "item-name": [ + "{@item-format('Name')}", + " ", + "Klicke um den Namen über den Chat zu ändern", + "Maximale Zeichenanzahl: {1}", + " ", + "{@selected-format}" + ] + }, + "material": { + "name": "Anzeige", + "format": "{@item-format('{0}')}" + } } }, "category": { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index 752edd81d..9a11e4dfd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -9,7 +9,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.InfoMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.InfoMenuGenerator; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.common.config.Document; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java index 3907b45de..ec951b1f4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.*; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.legacy.MessageManager; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.entity.Player; import org.bukkit.event.player.AsyncPlayerChatEvent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java index 403d1274d..1f6c0d03d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java @@ -4,8 +4,8 @@ import lombok.Getter; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.SubSettingChooseMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.SubSettingChooseMenuGenerator; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java index d8a2686a9..5eae2ab64 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java @@ -5,8 +5,8 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.SubSettingChooseMultipleMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.SubSettingChooseMultipleMenuGenerator; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java index 4cd85ec7c..ad242fa7a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java @@ -2,7 +2,7 @@ import com.google.common.collect.Lists; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; import org.bukkit.entity.Player; import java.util.List; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java index 2974e6856..1880afd94 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; import org.bukkit.entity.Player; public abstract class GeneratorSubSettingsBuilder extends SubSettingsBuilder { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java index d9dc98472..49e928082 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java @@ -3,7 +3,7 @@ import com.google.common.collect.Lists; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.spigot.listener.ChatInputListener; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.misc.MapUtils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java index aef10415f..5611216fc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java @@ -9,8 +9,8 @@ import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.legacy.MessageManager; import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.IParentCustomGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.SubSettingValueMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.SubSettingValueMenuGenerator; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index 107057db1..c80f0b4d2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -9,7 +9,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengesMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.IChallengesMenuGenerator; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; @@ -69,7 +69,7 @@ public static void runSync(@NotNull Runnable task) { } public static void updateItems(@NotNull IChallenge challenge) { - challenge.getType().executeWithGenerator(ChallengesMenuGenerator.class, gen -> gen.updateElementDisplay(challenge)); + challenge.getType().executeWithGenerator(IChallengesMenuGenerator.class, gen -> gen.updateElementDisplay(challenge)); } public static void handleModifierClick(@NotNull MenuClickInfo info, @NotNull IModifier modifier) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSplitter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSplitter.java index 15205f4f2..30aace376 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSplitter.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSplitter.java @@ -6,6 +6,7 @@ import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @@ -72,7 +73,9 @@ public static List split(@NotNull Component self, @NotNull @RegExp St @NotNull private static List splitComponentContent(@NotNull Component component, @NotNull @RegExp String regex) { if (!(component instanceof TextComponent t)) { - return List.of(component); + List components = new ArrayList<>(1); + components.add(component); + return components; } String[] segments = t.content().split(regex); if (segments.length == 0) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java index 002644842..8cc176185 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java @@ -36,7 +36,8 @@ public void registerGameStateSaver(@NotNull GamestateSaveable savable) { } public void register(@NotNull IChallenge challenge) { - if (!challenge.getType().isUsable()) throw new IllegalArgumentException("Invalid MenuType"); + if (!challenge.getType().isUsable()) + throw new IllegalArgumentException("Invalid MenuType " + challenge.getType() + " for challenge " + challenge.getClass()); challenges.add(challenge); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java index c8b14d236..74c6e6b69 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java @@ -8,8 +8,8 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.IChallengeTrigger; import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.generator.IChallengesMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.IMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengesMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChallengeMenuGenerator; import net.codingarea.challenges.plugin.utils.misc.MapUtils; import net.codingarea.commons.common.config.Document; @@ -53,7 +53,7 @@ public void unregisterCustomChallenge(@NotNull UUID uuid) { public void loadCustomChallengesFrom(@NotNull Document document) { customChallenges.clear(); Challenges.getInstance().getChallengeManager().unregisterIf(iChallenge -> iChallenge.getType() == MenuType.CUSTOM); - ((ChallengesMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetCache(); + ((IChallengesMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetCache(); for (String key : document.keys()) { try { @@ -83,7 +83,7 @@ public void loadCustomChallengesFrom(@NotNull Document document) { public void resetChallenges() { customChallenges.clear(); Challenges.getInstance().getChallengeManager().unregisterIf(iChallenge -> iChallenge.getType() == MenuType.CUSTOM); - ((ChallengesMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetCache(); + ((IChallengesMenuGenerator) MenuType.CUSTOM.getMenuGenerator()).resetCache(); } private void generateCustomChallenge(CustomChallenge challenge, boolean deleted, boolean generate) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java index 611b5e84e..49478fcc4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuManager.java @@ -8,8 +8,8 @@ import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.management.menu.generator.AbstractMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.IChallengesMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.MainMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengesMenuGenerator; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; @@ -40,12 +40,12 @@ public MenuManager() { public void generateMenus() { for (MenuType value : MenuType.values()) { - value.executeWithGenerator(ChallengesMenuGenerator.class, ChallengesMenuGenerator::resetCache); + value.executeWithGenerator(IChallengesMenuGenerator.class, IChallengesMenuGenerator::resetCache); } for (IChallenge challenge : Challenges.getInstance().getChallengeManager().getChallenges()) { MenuType type = challenge.getType(); - type.executeWithGenerator(ChallengesMenuGenerator.class, gen -> gen.addToCache(challenge)); + type.executeWithGenerator(IChallengesMenuGenerator.class, gen -> gen.addToCache(challenge)); } Locale language = Challenges.getInstance().getLoaderRegistry().findLoaderByClassOrThrow(LanguageLoader.class).getConfigLanguage(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java index 190f95f07..14fc4f573 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/MenuType.java @@ -7,6 +7,7 @@ import net.codingarea.challenges.plugin.management.menu.generator.impl.TimerMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengeListMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.categorised.CategorisedMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.CustomHomeMenuGenerator; import org.bukkit.Material; import org.jetbrains.annotations.NotNull; @@ -21,8 +22,7 @@ public enum MenuType { ITEMS("items-blocks", Material.STICK, new ChallengeListMenuGenerator()), CHALLENGES("challenges", Material.BOOK, new CategorisedMenuGenerator()), SETTINGS("settings", Material.COMPARATOR, new ChallengeListMenuGenerator()), - CUSTOM("custom", Material.WRITABLE_BOOK, new ChallengeListMenuGenerator()); -// CUSTOM("custom", Material.WRITABLE_BOOK, new MainCustomMenuGenerator()); + CUSTOM("custom", Material.WRITABLE_BOOK, new CustomHomeMenuGenerator()); private final String key; @Getter diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java index ca209ab05..f8c0b8777 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java @@ -6,16 +6,21 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.i18n.LanguageProvider; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; import java.util.Locale; public abstract class AbstractMenuGenerator implements IMenuGenerator { @@ -41,10 +46,15 @@ public abstract class AbstractMenuGenerator implements IMenuGenerator { @NotNull public LocalizableMessage getMenuName() { if (menuType == null) - throw new IllegalStateException("MenuType not set, was it not initialized by MenuType directly?"); + throw new IllegalStateException("MenuType not set in " + this.getClass() + ", was it not initialized by MenuType directly?"); return menuType.getMenuName(); } + @NotNull + protected LocalizableMessage createSubMenuTitle(@NotNull Object menuNameArg, @NotNull Object subMenuNameArg) { + return MessageKey.of("menu.title-name-format-sub").withArgs(menuNameArg, subMenuNameArg); + } + @Override public void openMenu(@NotNull Player player, int page) { Locale locale = findLanguageProvider().getPlayerLanguage(player); @@ -82,6 +92,19 @@ protected LanguageProvider findLanguageProvider() { return Challenges.getInstance().getTranslationManager().getLanguageProvider(); } + @NotNull + public Collection retrieveViewers() { + List viewers = new ArrayList<>(); // default capacity: 10 + for (Player player : Bukkit.getOnlinePlayers()) { + MenuPosition position = MenuPosition.get(player); + if (position == null) continue; + if (position instanceof GeneratorMenuPosition generatorPosition && generatorPosition.getGenerator() == this) { + viewers.add(player); + } + } + return viewers; + } + @Getter @AllArgsConstructor public abstract class GeneratorMenuPosition implements MenuPosition { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IChallengesMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IChallengesMenuGenerator.java new file mode 100644 index 000000000..1b28a82d4 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IChallengesMenuGenerator.java @@ -0,0 +1,6 @@ +package net.codingarea.challenges.plugin.management.menu.generator; + +import net.codingarea.challenges.plugin.challenges.type.IChallenge; + +public interface IChallengesMenuGenerator extends IDynamicMenuGenerator { +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java index 4852ff211..02f203623 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java @@ -46,16 +46,12 @@ private MessageKey getMenuTitleKey() { return MessageKey.of("menu.title-format-page"); } - @NotNull - protected LocalizableMessage createSubMenuTitle(@NotNull Object menuNameArg, @NotNull Object subMenuNameArg) { - return MessageKey.of("menu.title-name-format-sub").withArgs(menuNameArg, subMenuNameArg); - } - @NotNull @CheckReturnValue protected final List generateInventories(@NotNull Locale locale) { - List inventories = new ArrayList<>(getPageCount()); - for (int page = 0; page < getPageCount(); page++) { + int pageCount = getPageCount(); + List inventories = new ArrayList<>(pageCount); + for (int page = 0; page < pageCount; page++) { Inventory inventory = createEmptyInventory(locale, page); setInventoryDecoration(inventory, page, locale); setNavigationItems(inventory, page, locale); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java index 504212b5f..7b00e4106 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/SinglePageMenuGenerator.java @@ -1,6 +1,8 @@ package net.codingarea.challenges.plugin.management.menu.generator; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -22,7 +24,9 @@ public abstract class SinglePageMenuGenerator extends AbstractMenuGenerator { @NotNull public abstract GeneratorMenuPosition createMenuPosition(@NotNull Player player); - public abstract void initInventoryDecoration(@NotNull Inventory inventory, @NotNull Locale locale); + public void setInventoryDecoration(@NotNull Inventory inventory, @NotNull Locale locale) { + InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); + } public abstract void updateInventoryContent(@NotNull Inventory inventory, @NotNull Locale locale); @@ -64,7 +68,7 @@ public void updateOrGeneratePages(@NotNull Locale locale) { @CheckReturnValue protected Inventory createAndInitInventory(@NotNull Locale locale) { Inventory inventory = createEmptyInventory(locale); - initInventoryDecoration(inventory, locale); + setInventoryDecoration(inventory, locale); setNavigationItems(inventory, 0, locale); updateInventoryContent(inventory, locale); return inventory; @@ -82,4 +86,13 @@ public void updatePage(int page) { public final int getPageCount() { return 1; } + + public abstract class SinglePageGeneratorMenuPosition extends GeneratorMenuPosition { + + public SinglePageGeneratorMenuPosition() { + super(0); + } + + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/UncachedMultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/UncachedMultiPageMenuGenerator.java new file mode 100644 index 000000000..3ca0a77b6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/UncachedMultiPageMenuGenerator.java @@ -0,0 +1,155 @@ +package net.codingarea.challenges.plugin.management.menu.generator; + +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.menu.MenuPosition; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; + +public abstract class UncachedMultiPageMenuGenerator extends AbstractMenuGenerator { + + public static int[] calcSlots(int rows, int cols, int size) { + if (rows * cols > size) throw new IllegalArgumentException("rows (" + rows + ") * cols (" + cols + ") must be <= size (" + size + ")"); + + final int sizeRows = size / 9; + final int rowOffset = Math.floorDiv(sizeRows - rows, 2); + final int colOffset = Math.floorDiv(9 - cols, 2); + + int[] slots = new int[rows * cols]; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + slots[i * cols + j] = (i + rowOffset) * 9 + (j + colOffset); + } + } + return slots; + } + + public static int[] calcSlots(int padding, int size) { + int rows = size / 9; + int cols = size / rows; + return calcSlots(rows - 2 * padding, cols - 2 * padding, size); + } + + protected final T[] elements; + + public UncachedMultiPageMenuGenerator(@NotNull T[] elements) { + this.elements = elements; + } + + @Override + public void updateOrGeneratePages(@NotNull Locale locale) { + // because pages are not cached, there is noting to update or pregenerate + } + + @Override + public void updatePages() { + // because pages are not cached, there is noting to update + } + + @Override + public void updatePage(int page) { + // because pages are not cached, there is noting to update + } + + @NotNull + @Override + public Inventory getOrInitInventory(@NotNull Locale locale, int page) { + Inventory inventory = createEmptyInventory(locale, page); + setInventoryDecoration(inventory, page, locale); + setNavigationItems(inventory, page, locale); + updateInventoryContent(inventory, page, locale); + return inventory; + } + + public void setInventoryDecoration(@NotNull Inventory inventory, int page, @NotNull Locale locale) { + InventoryUtils.fillInventory(inventory, ItemBuilder.FILL_ITEM); + } + + @NotNull + protected Inventory createEmptyInventory(@NotNull Locale locale, int page) { + return Bukkit.createInventory(MenuPosition.HOLDER, getInventorySize(), + getMenuTitleKey().asComponent(locale, getMenuName(), getMenuTitlePageArg(page))); + } + + @NotNull + protected Object getMenuTitlePageArg(int page) { + return page + 1; + } + + @NotNull + private MessageKey getMenuTitleKey() { + if (getPageCount() == 1) return MessageKey.of("menu.title-format"); + return MessageKey.of("menu.title-format-page"); + } + + @NotNull + @Override + public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { + return new UncachedMultiPageMenuPosition(page, player); + } + + public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Locale locale) { + int startIndex = page * getMaxEntriesPerPage(); + int endIndex = Math.min(startIndex + getMaxEntriesPerPage(), elements.length); + int[] slots = getSlots(); + for (int i = startIndex; i < endIndex; i++) { + T element = elements[i]; + setElementItemsAt(element, inventory, slots[i - startIndex], locale); + } + } + + protected void setElementItemsAt(@NotNull T element, @NotNull Inventory inventory, int slot, @NotNull Locale locale) { + ItemStack displayItem = createDisplayItem(element, locale); + inventory.setItem(slot, displayItem); + } + + public abstract void handleElementClick(@NotNull T element, @NotNull MenuClickInfo info); + + @NotNull + public abstract ItemStack createDisplayItem(@NotNull T element, @NotNull Locale locale); + + public abstract int[] getSlots(); + + @Override + public int getPageCount() { + return Math.ceilDiv(elements.length, getMaxEntriesPerPage()); + } + + public int getMaxEntriesPerPage() { + return getSlots().length; + } + + public class UncachedMultiPageMenuPosition extends HistoryAwareGeneratorMenuPosition { + + public UncachedMultiPageMenuPosition(int page, @NotNull Player player) { + super(page, player); + } + + @Override + public boolean handleMenuClick(@NotNull MenuClickInfo info) { + int[] slots = getSlots(); + for (int i = 0; i < slots.length; i++) { + if (info.getSlot() != slots[i]) continue; + + int elementIndex = getPage() * getMaxEntriesPerPage() + i; + if (elementIndex >= elements.length) return false; + + T element = elements[elementIndex]; + SoundSample.PLOP.play(info.getPlayer()); + handleElementClick(element, info); + return true; + } + + return false; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java index af1bdd335..b793c299b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java @@ -105,7 +105,7 @@ public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player * @param slotOffset See {@link #SLOT_OFFSETS} * @return Whether an action can be executed at this offset (otherwise fallback behavior/sound will be played) */ - public boolean executeChallengeAction(@NotNull IChallenge challenge, int slotOffset, @NotNull MenuClickInfo info) { + public boolean executeChallengeClickAction(@NotNull IChallenge challenge, int slotOffset, @NotNull MenuClickInfo info) { if (slotOffset == SLOT_OFFSET_DISPLAY || slotOffset == SLOT_OFFSET_SETTINGS) { challenge.handleClick(new ChallengeMenuClickInfo(info, slotOffset == SLOT_OFFSET_DISPLAY)); return true; @@ -152,7 +152,6 @@ protected void setChallengeUpdateItemsAt(@NotNull IChallenge challenge, @NotNull protected void setChallengeItemsAt(@NotNull IChallenge challenge, @NotNull Inventory inventory, int slotsIndex, @NotNull Locale locale) { inventory.setItem(DISPLAY_SLOTS[slotsIndex] + SLOT_OFFSET_DISPLAY, createChallengeDisplayItem(challenge, locale)); inventory.setItem(DISPLAY_SLOTS[slotsIndex] + SLOT_OFFSET_SETTINGS, createChallengeSettingsItem(challenge, locale)); - // TODO might need overrideable getter for settings slot } @NotNull @@ -276,7 +275,7 @@ public boolean handleMenuClick(@NotNull MenuClickInfo info) { if (challengeIndex >= assignedChallengesCache.size()) return false; // page not full IChallenge challenge = assignedChallengesCache.get(challengeIndex); // TODO slow LinkedList random access - return executeChallengeAction(challenge, offset, info); + return executeChallengeClickAction(challenge, offset, info); } return false; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengesMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengesMenuGenerator.java index 1ff44a06a..37634aa66 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengesMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengesMenuGenerator.java @@ -1,9 +1,10 @@ package net.codingarea.challenges.plugin.management.menu.generator.impl.challenge; import net.codingarea.challenges.plugin.challenges.type.IChallenge; -import net.codingarea.challenges.plugin.management.menu.generator.IDynamicMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.IChallengesMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.MultiPageMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.categorised.CategorisedMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.CustomListMenuGenerator; import org.jetbrains.annotations.NotNull; import java.util.Optional; @@ -11,8 +12,9 @@ /** * @see ChallengeListMenuGenerator * @see CategorisedMenuGenerator + * @see CustomListMenuGenerator */ -public abstract class ChallengesMenuGenerator extends MultiPageMenuGenerator implements IDynamicMenuGenerator { +public abstract class ChallengesMenuGenerator extends MultiPageMenuGenerator implements IChallengesMenuGenerator { public abstract boolean hasAnyNewChallenges(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChooseMaterialMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChooseMaterialMenuGenerator.java new file mode 100644 index 000000000..b4635926a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChooseMaterialMenuGenerator.java @@ -0,0 +1,84 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom; + +import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.generator.UncachedMultiPageMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.challenges.plugin.utils.misc.MapUtils; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NonNull; + +import java.util.ArrayList; +import java.util.Locale; + +public class CustomChooseMaterialMenuGenerator extends UncachedMultiPageMenuGenerator { + + public static final int SIZE = 5 * 9; + public static final int[] SLOTS = calcSlots(3, 7, SIZE); + public static final Material[] MATERIALS; + + static { + ArrayList materials = new ArrayList<>(); + for (Material material : ExperimentalUtils.getMaterials()) { + if (BukkitReflectionUtils.isAir(material)) continue; + if (!material.isItem()) continue; + materials.add(material); + } + MATERIALS = materials.toArray(new Material[0]); + } + + private final IParentCustomGenerator parent; + + public CustomChooseMaterialMenuGenerator(@NotNull IParentCustomGenerator parent) { + this(parent, MATERIALS); + } + + protected CustomChooseMaterialMenuGenerator(@NotNull IParentCustomGenerator parent, @NotNull Material[] elements) { + super(elements); + this.menuType = MenuType.CUSTOM; + this.parent = parent; + } + + @NotNull + @Override + public LocalizableMessage getMenuName() { + return createSubMenuTitle(MessageKey.of("menu.custom.sub-name"), MessageKey.of("menu.custom.material.name")); + } + + @Override + public void handleElementClick(@NonNull Material element, @NotNull MenuClickInfo info) { + parent.accept(info.getPlayer(), SettingType.MATERIAL, MapUtils.createStringArrayMap("material", element.name())); + } + + @NotNull + @Override + public ItemStack createDisplayItem(@NonNull Material element, @NotNull Locale locale) { + return new ItemBuilder(locale, element, MessageKey.of("menu.custom.material.format"), + element).build(); + } + + @Override + protected void handleNavigateOutOfMenu(@NotNull Player player) { + parent.decline(player); + } + + @Override + public int[] getSlots() { + return SLOTS; + } + + + @Override + public int getInventorySize() { + return SIZE; + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomHomeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomHomeMenuGenerator.java new file mode 100644 index 000000000..081315cb3 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomHomeMenuGenerator.java @@ -0,0 +1,116 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom; + +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.challenges.type.IChallenge; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.generator.IChallengesMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.SinglePageMenuGenerator; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NonNull; + +import java.util.Locale; + +public class CustomHomeMenuGenerator extends SinglePageMenuGenerator implements IChallengesMenuGenerator { + + public static final int VIEW_SLOT = 21; + public static final int CREATE_SLOT = 23; + public static final int SIZE = 5 * 9; + + private final CustomListMenuGenerator viewGenerator = new CustomListMenuGenerator(); + + @Override + public void setMenuType(MenuType menuType) { + // MenuType.CUSTOM instance not initialized when creating CustomListMenuGenerator + super.setMenuType(menuType); + viewGenerator.setMenuType(menuType); + } + + @NotNull + @Override + public GeneratorMenuPosition createMenuPosition(@NotNull Player player) { + return new CustomMainMenuPosition(); + } + + @Override + public void setInventoryDecoration(@NotNull Inventory inventory, @NotNull Locale locale) { + super.setInventoryDecoration(inventory, locale); // background fill items + for (int i : new int[]{1, 2, 6, 7, 9, 10, 16, 17, 27, 28, 34, 35, 37, 38, 39, 41, 42, 43}) { + inventory.setItem(i, ItemBuilder.FILL_ITEM_CONTRAST); + } + } + + @Override + public void updateInventoryContent(@NotNull Inventory inventory, @NotNull Locale locale) { + inventory.setItem(VIEW_SLOT, new ItemBuilder(locale, Material.BOOK, MessageKey.of("menu.custom.home.item-view")).build()); + inventory.setItem(CREATE_SLOT, new ItemBuilder(locale, Material.WRITABLE_BOOK, MessageKey.of("menu.custom.home.item-create")).build()); + } + + @Override + public int getInventorySize() { + return SIZE; + } + + @Override + public void addToCache(@NonNull IChallenge element) { + viewGenerator.addToCache(element); + } + + @Override + public void removeFromCache(@NonNull IChallenge element) { + viewGenerator.removeFromCache(element); + } + + @Override + public boolean isCached(@NonNull IChallenge element) { + return viewGenerator.isCached(element); + } + + @Override + public int getCachedCount() { + return viewGenerator.getCachedCount(); + } + + @Override + public void resetCache() { + viewGenerator.resetCache(); + } + + @Override + public void updateElementDisplay(@NonNull IChallenge element) { + viewGenerator.updateElementDisplay(element); + } + + public class CustomMainMenuPosition extends SinglePageGeneratorMenuPosition { + + @Override + public boolean handleMenuClick(@NotNull MenuClickInfo info) { + if (info.getSlot() == VIEW_SLOT) { + if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().isEmpty()) { + MessageKey.of("custom-not-loaded").send(info.getPlayer(), Prefix.CUSTOM); + SoundSample.BASS_OFF.play(info.getPlayer()); + return true; + } + viewGenerator.openMenu(info.getPlayer()); + SoundSample.PLOP.play(info.getPlayer()); + return true; + } else if (info.getSlot() == CREATE_SLOT) { + // TODO check permission, limit, abstract logic + InfoMenuGenerator generator = new InfoMenuGenerator(); + generator.openMenu(info.getPlayer()); + SoundSample.PLOP.play(info.getPlayer()); + return true; + } + + return false; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomListMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomListMenuGenerator.java new file mode 100644 index 000000000..076239359 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomListMenuGenerator.java @@ -0,0 +1,64 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom; + +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; +import net.codingarea.challenges.plugin.challenges.type.IChallenge; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengeListMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; + +public class CustomListMenuGenerator extends ChallengeListMenuGenerator { + + public static final int SIZE = CustomHomeMenuGenerator.SIZE; + + @Override + protected void handleNavigateOutOfMenu(@NotNull Player player) { + Challenges.getInstance().getMenuManager().openMenu(player, MenuType.CUSTOM, 0); + } + + @Override + public boolean executeChallengeClickAction(@NotNull IChallenge challenge, int slotOffset, @NotNull MenuClickInfo info) { + if (slotOffset == SLOT_OFFSET_DISPLAY || slotOffset == SLOT_OFFSET_LOWER) { + challenge.handleClick(new ChallengeMenuClickInfo(info, slotOffset == SLOT_OFFSET_LOWER)); + return true; + } else if (slotOffset == SLOT_OFFSET_SETTINGS && challenge instanceof CustomChallenge customChallenge) { + // TODO save & reuse? + InfoMenuGenerator generator = new InfoMenuGenerator(customChallenge); + generator.openMenu(info.getPlayer()); + SoundSample.CLICK.play(info.getPlayer()); + return true; + } + return false; + } + + @Override + protected void setChallengeItemsAt(@NotNull IChallenge challenge, @NotNull Inventory inventory, int slotsIndex, @NotNull Locale locale) { + inventory.setItem(DISPLAY_SLOTS[slotsIndex] + SLOT_OFFSET_DISPLAY, createChallengeDisplayItem(challenge, locale)); + inventory.setItem(DISPLAY_SLOTS[slotsIndex] + SLOT_OFFSET_SETTINGS, createChallengeCustomizeItem(challenge, locale)); + inventory.setItem(DISPLAY_SLOTS[slotsIndex] + SLOT_OFFSET_LOWER, createChallengeSettingsItem(challenge, locale)); + } + + @NotNull + protected ItemStack createChallengeCustomizeItem(@NotNull IChallenge challenge, @NotNull Locale locale) { + return DefaultItems.createCustomizePreset(); + } + + @Override + protected void setChallengeUpdateItemsAt(@NotNull IChallenge challenge, @NotNull Inventory inventory, int slotIndex, @NotNull Locale locale) { + // remove update/new indicator items as they would collide with display items and are not appropriate for custom challenges + } + + @Override + public int getInventorySize() { + return SIZE; + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/InfoMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/InfoMenuGenerator.java new file mode 100644 index 000000000..a705ba0c3 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/InfoMenuGenerator.java @@ -0,0 +1,159 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom; + +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; +import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; +import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; +import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.generator.SinglePageMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.common.collection.IRandom; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.jetbrains.annotations.NotNull; + +import java.util.*; + +// TODO rename to CustomChallengeMenuGenerator +public class InfoMenuGenerator extends SinglePageMenuGenerator implements IParentCustomGenerator { + + public static final int SIZE = 5 * 9; + + public static final int DELETE_SLOT = 19 + 9; + public static final int SAVE_SLOT = 25 + 9; + public static final int CONDITION_SLOT = 21 + 9; + public static final int ACTION_SLOT = 23 + 9; + public static final int MATERIAL_SLOT = 14; + public static final int NAME_SLOT = 12; + + private static final boolean savePlayerChallenges; + + // TODO + static { + savePlayerChallenges = Challenges.getInstance().getConfigDocument().getBoolean("save-player_challenges"); + } + + private final CustomChooseMaterialMenuGenerator chooseMaterialGenerator = new CustomChooseMaterialMenuGenerator(this); + + private final UUID uuid; + private String name; + private Material material; + private ChallengeTrigger trigger; + private Map subTriggers; + private ChallengeAction action; + private Map subActions; + + public InfoMenuGenerator(@NotNull CustomChallenge customChallenge) { + this.menuType = MenuType.CUSTOM; + this.uuid = customChallenge.getUniqueId(); + this.material = customChallenge.getMaterial(); + this.name = customChallenge.getDisplayName(); + this.trigger = customChallenge.getTrigger(); + this.subTriggers = customChallenge.getSubTriggers(); + this.action = customChallenge.getAction(); + this.subActions = customChallenge.getSubActions(); + } + + /** + * Default Settings for new Custom Challenges + */ + public InfoMenuGenerator() { + this.menuType = MenuType.CUSTOM; + this.trigger = null; + this.action = null; + this.subTriggers = new HashMap<>(); + this.subActions = new HashMap<>(); + this.uuid = UUID.randomUUID(); + this.material = IRandom.threadLocal().choose(CustomChooseMaterialMenuGenerator.MATERIALS); + this.name = "§7Custom §e#" + + (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() + 1); + } + + @NotNull + @Override + public LocalizableMessage getMenuName() { + return createSubMenuTitle(MessageKey.of("menu.custom.sub-name"), MessageKey.of("menu.custom.info.name")); + } + + @NotNull + @Override + public GeneratorMenuPosition createMenuPosition(@NotNull Player player) { + return new CustomChallengeMenuPosition(); + } + + @Override + public void updateInventoryContent(@NotNull Inventory inventory, @NotNull Locale locale) { + // Save / Delete Item + inventory.setItem(DELETE_SLOT, new ItemBuilder(locale, Material.BARRIER, MessageKey.of("menu.custom.info.item-delete")).build()); + inventory.setItem(SAVE_SLOT, new ItemBuilder(locale, Material.LIME_DYE, MessageKey.of("menu.custom.info.item-save")).build()); + + // Display Item + inventory.setItem(MATERIAL_SLOT, new ItemBuilder(locale, material == null ? Material.BARRIER : material, + MessageKey.of("menu.custom.info.item-material"), material != null ? material : MessageKey.of("generic.none")).build()); + + // Name Item + // TODO escape, format? + int maxNameLength = Challenges.getInstance().getCustomChallengesLoader().getMaxNameLength(); + inventory.setItem(NAME_SLOT, new ItemBuilder(locale, Material.NAME_TAG, MessageKey.of("menu.custom.info.item-name"), + name, maxNameLength).build()); + + // TODO TRIGGER; CONDITION; ACTION + } + + @Override + public int getInventorySize() { + return SIZE; + } + + @Override + public void accept(@NotNull Player player, @NotNull SettingType type, @NotNull Map data) { + openMenu(player); + + switch (type) { + case CONDITION: + trigger = Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(data.remove("trigger")[0]); + this.subTriggers = data; + break; + case ACTION: + action = Challenges.getInstance().getCustomSettingsLoader().getActionByName(data.remove("action")[0]); + this.subActions = data; + break; + case MATERIAL: + material = Material.valueOf(data.remove("material")[0]); + break; + } + + updatePages(); + } + + @Override + public void decline(@NotNull Player player) { + openMenu(player); + } + + public class CustomChallengeMenuPosition extends SinglePageGeneratorMenuPosition { + + @Override + public boolean handleMenuClick(@NotNull MenuClickInfo info) { + switch (info.getSlot()) { + case MATERIAL_SLOT -> { + chooseMaterialGenerator.openMenu(info.getPlayer()); + SoundSample.CLICK.play(info.getPlayer()); + return true; + } + } + + return false; + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java deleted file mode 100644 index aaf64d69d..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/SettingsMenuGenerator.java +++ /dev/null @@ -1,38 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.implementation; - -import net.codingarea.challenges.plugin.challenges.type.IChallenge; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChallengeMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import org.jetbrains.annotations.NotNull; - -public class SettingsMenuGenerator extends ChallengeMenuGenerator { - - public static final int[] SLOTS = {10, 11, 12, 13, 14, 15, 16}; - public static final int[] NAVIGATION_SLOTS = {27, 35}; - public static final int SIZE = 4 * 9; - - @Override - public int[] getSlots() { - return SLOTS; - } - - @Override - public int getSize() { - return SIZE; - } - - @Override - public int[] getNavigationSlots(int page) { - return NAVIGATION_SLOTS; - } - - @Override - public void executeClickAction(@NotNull IChallenge challenge, @NotNull MenuClickInfo info, int itemIndex) { - if (itemIndex <= 1) { - challenge.handleClick(new ChallengeMenuClickInfo(info, itemIndex == 0)); - } - - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseItemGenerator.java index d241f4286..e09288748 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseItemGenerator.java @@ -2,7 +2,7 @@ import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.MainCustomMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.MainCustomMenuGenerator; import net.codingarea.challenges.plugin.management.menu.position.LegacyGeneratorMenuPosition; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseMultipleItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseMultipleItemGenerator.java index 5ddc5c763..fb1ae68ec 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseMultipleItemGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseMultipleItemGenerator.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.implementation.custom.MainCustomMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.MainCustomMenuGenerator; import net.codingarea.challenges.plugin.management.menu.position.LegacyGeneratorMenuPosition; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/CustomMainSettingsMenuGenerator.java similarity index 94% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/CustomMainSettingsMenuGenerator.java index 480b9bd64..8c40e6967 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/CustomMainSettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/CustomMainSettingsMenuGenerator.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; +package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; import lombok.Getter; import net.codingarea.challenges.plugin.challenges.custom.settings.IChallengeSetting; @@ -8,6 +8,7 @@ import net.codingarea.challenges.plugin.utils.misc.MapUtils; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jspecify.annotations.NonNull; import java.util.HashMap; import java.util.LinkedHashMap; @@ -42,7 +43,7 @@ public String[] getSubTitles(int page) { } @Override - public void accept(Player player, SettingType type, Map data) { + public void accept(Player player, @NonNull SettingType type, @NonNull Map data) { subSettings.putAll(data); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/IParentCustomGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/IParentCustomGenerator.java similarity index 70% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/IParentCustomGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/IParentCustomGenerator.java index 47b13b20d..a3731939a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/IParentCustomGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/IParentCustomGenerator.java @@ -1,7 +1,8 @@ -package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; +package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -12,8 +13,8 @@ public interface IParentCustomGenerator { * @param type the type of the current setting. Only needed if parent is the first setting menu. * @param data a map that contains all the data of the settings */ - void accept(Player player, SettingType type, Map data); + void accept(@NotNull Player player, @NotNull SettingType type, @NotNull Map data); - void decline(Player player); + void decline(@NotNull Player player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/InfoMenuGenerator.java similarity index 98% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/InfoMenuGenerator.java index 2706bfc8e..455c19d43 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/InfoMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/InfoMenuGenerator.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; +package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; import lombok.Getter; import lombok.ToString; @@ -32,10 +32,12 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NonNull; import java.util.*; @ToString +@Deprecated public class InfoMenuGenerator extends MenuGenerator implements IParentCustomGenerator { public static final int DELETE_SLOT = 19 + 9, SAVE_SLOT = 25 + 9, CONDITION_SLOT = 21 + 9, ACTION_SLOT = 23 + 9, MATERIAL_SLOT = 14, NAME_SLOT = 12; @@ -154,7 +156,7 @@ public void open(@NotNull Player player, int page) { } @Override - public void accept(Player player, SettingType type, Map data) { + public void accept(Player player, @NonNull SettingType type, @NonNull Map data) { open(player, 0); switch (type) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/MainCustomMenuGenerator.java similarity index 99% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/MainCustomMenuGenerator.java index 020a2b596..5e26ca81e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MainCustomMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/MainCustomMenuGenerator.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; +package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; @@ -17,6 +17,7 @@ import org.bukkit.inventory.Inventory; import org.jetbrains.annotations.NotNull; +@Deprecated public class MainCustomMenuGenerator extends ChallengeMenuGenerator { public static final int[] SLOTS = {10, 11, 12, 13, 14, 15, 16}; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/MaterialMenuGenerator.java similarity index 98% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/MaterialMenuGenerator.java index 15906a42b..8c8705f84 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/MaterialMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/MaterialMenuGenerator.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; +package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChooseItemGenerator; @@ -11,6 +11,7 @@ import java.util.LinkedHashMap; +@Deprecated public class MaterialMenuGenerator extends ChooseItemGenerator { private final IParentCustomGenerator parent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingChooseMenuGenerator.java similarity index 97% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingChooseMenuGenerator.java index cba7b6bf6..7604465d1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingChooseMenuGenerator.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; +package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChooseItemGenerator; import net.codingarea.challenges.plugin.utils.misc.MapUtils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingChooseMultipleMenuGenerator.java similarity index 97% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingChooseMultipleMenuGenerator.java index d1d63b7be..734d40ede 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingChooseMultipleMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingChooseMultipleMenuGenerator.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; +package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChooseMultipleItemGenerator; import net.codingarea.challenges.plugin.utils.misc.MapUtils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingValueMenuGenerator.java similarity index 97% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingValueMenuGenerator.java index d7921816c..f6c8bf67f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/implementation/custom/SubSettingValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingValueMenuGenerator.java @@ -1,4 +1,4 @@ -package net.codingarea.challenges.plugin.management.menu.generator.implementation.custom; +package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.management.menu.generator.legacy.ValueMenuGenerator; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java index 19822a072..ba1738f22 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MinecraftNameWrapper.java @@ -40,6 +40,7 @@ public class MinecraftNameWrapper { public static final Attribute MAX_HEALTH = getAttributeByNames("GENERIC_MAX_HEALTH", "MAX_HEALTH"); public static final Attribute ATTACK_SPEED = getAttributeByNames("GENERIC_ATTACK_SPEED", "ATTACK_SPEED"); + public static final Attribute LUCK = getAttributeByNames("GENERIC_LUCK", "LUCK"); // replacement for wrapping via GameRule.getByName (marked for removal as of 1.21.11), // access via namespace key would be a viable alternative diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/StandardItemBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/StandardItemBuilder.java index 9db1d8348..418044534 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/StandardItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/StandardItemBuilder.java @@ -1,7 +1,7 @@ package net.codingarea.commons.bukkit.utils.item; import com.destroystokyo.paper.profile.PlayerProfile; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.commons.bukkit.core.BukkitModule; import net.codingarea.commons.common.config.Document; import org.bukkit.*; @@ -10,7 +10,6 @@ import org.bukkit.block.banner.Pattern; import org.bukkit.block.banner.PatternType; import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.*; @@ -150,22 +149,22 @@ public StandardItemBuilder hideAttributes() { @SuppressWarnings({"UnstableApiUsage"}) protected void applyDummyAttributeModifier() { -// try { -// // hacky fix to make paper hide damage attributes (only works with custom modifiers), "Vanilla behavior since 1.20.5" -// // see https://github.com/PaperMC/Paper/issues/11224 -// Attribute dummyAttribute = Attribute.LUCK; -// Collection modifiers = getItemMeta().getAttributeModifiers(dummyAttribute); -// -// if (modifiers == null || modifiers.isEmpty()) { -// meta.addAttributeModifier(dummyAttribute, new AttributeModifier( -// new NamespacedKey(BukkitModule.getFirstInstance(), "dummy"), -// 0, -// AttributeModifier.Operation.ADD_NUMBER, -// EquipmentSlotGroup.ANY -// )); -// } -// } catch (Throwable ignored) { // defend against experimental api changes -// } + try { + // hacky fix to make paper hide damage attributes (only works with custom modifiers), "Vanilla behavior since 1.20.5" + // see https://github.com/PaperMC/Paper/issues/11224 + Attribute dummyAttribute = MinecraftNameWrapper.LUCK; + Collection modifiers = getItemMeta().getAttributeModifiers(dummyAttribute); + + if (modifiers == null || modifiers.isEmpty()) { + meta.addAttributeModifier(dummyAttribute, new AttributeModifier( + new NamespacedKey(BukkitModule.getFirstInstance(), "dummy"), + 0, + AttributeModifier.Operation.ADD_NUMBER, + org.bukkit.inventory.EquipmentSlotGroup.ANY + )); + } + } catch (Throwable ignored) { // defend against experimental api changes + } } @NotNull diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java index 97ecff0cc..c571e44f7 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionHolder.java @@ -9,7 +9,7 @@ class MenuPositionHolder implements InventoryHolder { @NotNull @Override public Inventory getInventory() { - return null; + throw new UnsupportedOperationException("MenuPositionHolder does not hold an inventory"); } } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java index 0a670e584..e22f3e413 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java @@ -8,6 +8,7 @@ import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.Inventory; import org.jetbrains.annotations.NotNull; @@ -46,4 +47,9 @@ public void onClose(@NotNull InventoryCloseEvent event) { MenuPosition.remove(player); } + @EventHandler(priority = EventPriority.LOW) + public void onQuit(@NotNull PlayerQuitEvent event) { + MenuPosition.remove(event.getPlayer()); + } + } From 9aae18d1eb1cd1d05d02bc88673e1d9bca2bde28 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Wed, 8 Jul 2026 00:40:25 +0200 Subject: [PATCH 102/119] refactor: migrate custom menu generators (part 2) --- language/locales/de.json | 209 ++++++------ language/locales/en.json | 2 +- language/locales/global.json | 18 + .../challenges/custom/CustomChallenge.java | 59 ++-- .../custom/settings/ChallengeSetting.java | 18 +- .../custom/settings/CustomSettingsLoader.java | 6 +- .../custom/settings/IChallengeSetting.java | 19 +- .../settings/action/ChallengeAction.java | 16 +- .../settings/sub/SubSettingsBuilder.java | 17 +- .../builder/ChooseItemSubSettingsBuilder.java | 9 +- .../ChooseMultipleItemSubSettingBuilder.java | 9 +- .../sub/builder/EmptySubSettingsBuilder.java | 5 +- .../builder/GeneratorSubSettingsBuilder.java | 16 +- .../builder/TextInputSubSettingsBuilder.java | 5 +- .../sub/builder/ValueSubSettingsBuilder.java | 9 +- .../settings/trigger/ChallengeTrigger.java | 17 +- .../trigger/impl/IntervallTrigger.java | 2 + .../type/abstraction/AbstractChallenge.java | 3 +- .../type/abstraction/menu/MenuSetting.java | 5 +- .../i18n/impl/format/ComponentArguments.java | 8 + .../i18n/impl/format/ComponentSprites.java | 40 +++ .../challenges/CustomChallengesLoader.java | 33 +- .../UncachedMultiPageMenuGenerator.java | 3 +- .../generator/impl/MainMenuGenerator.java | 5 +- .../challenge/ChallengeListMenuGenerator.java | 5 +- .../categorised/CategorisedMenuGenerator.java | 9 +- .../custom/CustomChallengeMenuGenerator.java | 268 +++++++++++++++ .../impl/custom/CustomHomeMenuGenerator.java | 27 +- .../impl/custom/CustomListMenuGenerator.java | 7 +- .../CustomMainSettingsMenuGenerator.java | 100 ++++++ .../custom/IParentCustomGenerator.java | 5 +- .../impl/custom/InfoMenuGenerator.java | 159 --------- .../choose/CustomChooseItemMenuGenerator.java | 104 ++++++ .../CustomChooseMaterialMenuGenerator.java | 4 +- ...CustomChooseMultipleItemMenuGenerator.java | 125 +++++++ .../CustomChooseValueMenuGenerator.java | 125 +++++++ .../choose/SubSettingChooseMenuGenerator.java | 34 ++ ...SubSettingChooseMultipleMenuGenerator.java | 34 ++ .../choose}/SubSettingValueMenuGenerator.java | 26 +- .../generator/legacy/ChooseItemGenerator.java | 123 ------- .../legacy/ChooseMultipleItemGenerator.java | 154 --------- .../generator/legacy/ValueMenuGenerator.java | 120 ------- .../CustomMainSettingsMenuGenerator.java | 92 ------ .../legacy/custom/InfoMenuGenerator.java | 312 ------------------ .../custom/MainCustomMenuGenerator.java | 110 ------ .../legacy/custom/MaterialMenuGenerator.java | 51 --- .../custom/SubSettingChooseMenuGenerator.java | 38 --- ...SubSettingChooseMultipleMenuGenerator.java | 38 --- .../plugin/utils/item/DefaultItems.java | 17 + .../plugin/utils/item/ItemBuilder.java | 33 +- .../bukkit/utils/menu/MenuPosition.java | 13 +- .../utils/menu/MenuPositionListener.java | 2 +- 52 files changed, 1219 insertions(+), 1449 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSprites.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomMainSettingsMenuGenerator.java rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{legacy => impl}/custom/IParentCustomGenerator.java (77%) delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/InfoMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseItemMenuGenerator.java rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/{ => choose}/CustomChooseMaterialMenuGenerator.java (97%) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleItemMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMultipleMenuGenerator.java rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{legacy/custom => impl/custom/choose}/SubSettingValueMenuGenerator.java (53%) delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseItemGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseMultipleItemGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ValueMenuGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/CustomMainSettingsMenuGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/InfoMenuGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/MainCustomMenuGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/MaterialMenuGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingChooseMenuGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingChooseMultipleMenuGenerator.java diff --git a/language/locales/de.json b/language/locales/de.json index 89667da70..13acd432c 100644 --- a/language/locales/de.json +++ b/language/locales/de.json @@ -14,13 +14,17 @@ "time": "Zeit", "disabled": "Deaktiviert", "enabled": "Aktiviert", - "customized": "Anpassen", + "customize": "Anpassen", "console": "Konsole" }, "language": { "de": "Deutsch", "en": "Englisch" }, + "suffix": { + "new-challenge": "{@format('Neu!')}", + "updated-challenge": "{@format('Update!')}" + }, "timer": { "bar": { "up": "{@actionbar.format('Zeit: {0}')}", @@ -127,9 +131,11 @@ "name": "Individuelle Challenges", "sub-name": "Individuell", "selected-format": "Eingestellt {@symbol.circle} {0}", + "trigger-format": "Auslöser {@symbol.circle} {0}", + "action-format": "Aktion {@symbol.circle} {0}", "home": { "item-view": "{@item-format('Challenges ansehen')}", - "item-create": "{@item-format('Challenge erstellen')}" + "item-create": "{@item-format('Neue Challenge erstellen')}" }, "info": { "name": "Info", @@ -141,7 +147,7 @@ " ", "Achtung diese Aktion kann nicht", "rückgängig gemacht werden" - ], + ], "item-material": [ "{@item-format('Anzeige Item')}", " ", @@ -175,7 +181,7 @@ ] }, "material": { - "name": "Anzeige", + "name": "Anzeige-Item", "format": "{@item-format('{0}')}" } } @@ -1681,6 +1687,108 @@ " " ] }, + "custom": { + "trigger": { + "interval": { + "name": "*Intervall*" + }, + "jump": { + "name": "Spieler Springt" + }, + "sneak": { + "name": "Spieler Schleicht" + }, + "move_block": { + "name": "Spieler Läuft Einen Block" + }, + "death": [ + "Entity Stirbt" + ], + "item-custom-trigger-damage": [ + "Entity Erleidet Schaden" + ], + "item-custom-trigger-damage-any": [ + "Jeglicher Grund" + ], + "item-custom-trigger-damage_by_player": [ + "Entity Bekommt Schaden Von Spieler" + ], + "item-custom-trigger-intervall": [ + "Intervall" + ], + "item-custom-trigger-intervall-second": [ + "Jede Sekunde" + ], + "item-custom-trigger-intervall-seconds": [ + "Alle {0} Sekunden" + ], + "item-custom-trigger-intervall-minutes": [ + "Alle {0} Minuten" + ], + "item-custom-trigger-block_place": [ + "Block Platziert" + ], + "item-custom-trigger-block_break": [ + "Block Zerstört" + ], + "item-custom-trigger-consume_item": [ + "Item Konsumieren" + ], + "item-custom-trigger-pickup_item": [ + "Item Aufheben" + ], + "item-custom-trigger-drop_item": [ + "Spieler Droppt Item" + ], + "item-custom-trigger-advancement": [ + "Spieler Erhält Errungenschaft" + ], + "item-custom-trigger-hunger": [ + "Spieler Verliert Hunger" + ], + "item-custom-trigger-move_down": [ + "Block Nach Unten Bewegen" + ], + "item-custom-trigger-move_up": [ + "Block Nach Oben Bewegen" + ], + "item-custom-trigger-move_camera": [ + "Kamera Bewegen" + ], + "item-custom-trigger-stands_on_specific_block": [ + "Spieler Ist Auf Bestimmten Block" + ], + "item-custom-trigger-stands_not_on_specific_block": [ + "Spieler Ist Nicht Auf Bestimmten Block" + ], + "item-custom-trigger-gain_xp": [ + "Spieler Bekommt XP" + ], + "item-custom-trigger-level_up": [ + "Spieler Levelt Auf" + ], + "item-custom-trigger-item_craft": [ + "Spieler Craftet Item" + ], + "item-custom-trigger-in_liquid": [ + "Spieler In Flüssigkeit" + ], + "item-custom-trigger-get_item": [ + "Item bekommen", + "Aktion wird für *jedes* anklicken oder aufheben ausgeführt" + ] + }, + "action": { + "cancel": { + "name": "*Auslöser Abbrechen*", + "desc": [ + "Verhindert, dass der Auslöser ausgeführt wird.", + "Nicht abrechenbare Auslöser: *Springen*, *Sneaken*, *Töten*", + "*Advancement*, *Auf Leveln*, *In Flüssigkeit*" + ] + } + } + }, "syntax": "Bitte nutze /{0}", "reload": "Challenges Plugin wird neu geladen...", "reload-failed": "Ein Fehler ist während dem Reload aufgetreten", @@ -1709,8 +1817,6 @@ "Der Server kann nicht resettet werden", "Die Challenge wurde noch nicht gestartet" ], - "new-challenge-suffix": "{@challenge.suffix-format('Neu!')}", - "updated-challenge-suffix": "{@challenge.suffix-format('Update!')}", "feature-disabled": "Diese Funktion ist derzeit deaktiviert", "challenge-disabled": "Diese Challenge ist derzeit deaktiviert", "timer-not-started": "Der Timer wurde noch nicht gestartet", @@ -2248,97 +2354,6 @@ "custom-info-currently": "Eingestellt » ", "custom-info-trigger": "Auslöser", "custom-info-action": "Aktion", - "item-custom-trigger-jump": [ - "Spieler Springt" - ], - "item-custom-trigger-sneak": [ - "Spieler Schleicht" - ], - "item-custom-trigger-move_block": [ - "Spieler Läuft Einen Block" - ], - "item-custom-trigger-death": [ - "Entity Stirbt" - ], - "item-custom-trigger-damage": [ - "Entity Erleidet Schaden" - ], - "item-custom-trigger-damage-any": [ - "Jeglicher Grund" - ], - "item-custom-trigger-damage_by_player": [ - "Entity Bekommt Schaden Von Spieler" - ], - "item-custom-trigger-intervall": [ - "Intervall" - ], - "item-custom-trigger-intervall-second": [ - "Jede Sekunde" - ], - "item-custom-trigger-intervall-seconds": [ - "Alle {0} Sekunden" - ], - "item-custom-trigger-intervall-minutes": [ - "Alle {0} Minuten" - ], - "item-custom-trigger-block_place": [ - "Block Platziert" - ], - "item-custom-trigger-block_break": [ - "Block Zerstört" - ], - "item-custom-trigger-consume_item": [ - "Item Konsumieren" - ], - "item-custom-trigger-pickup_item": [ - "Item Aufheben" - ], - "item-custom-trigger-drop_item": [ - "Spieler Droppt Item" - ], - "item-custom-trigger-advancement": [ - "Spieler Erhält Errungenschaft" - ], - "item-custom-trigger-hunger": [ - "Spieler Verliert Hunger" - ], - "item-custom-trigger-move_down": [ - "Block Nach Unten Bewegen" - ], - "item-custom-trigger-move_up": [ - "Block Nach Oben Bewegen" - ], - "item-custom-trigger-move_camera": [ - "Kamera Bewegen" - ], - "item-custom-trigger-stands_on_specific_block": [ - "Spieler Ist Auf Bestimmten Block" - ], - "item-custom-trigger-stands_not_on_specific_block": [ - "Spieler Ist Nicht Auf Bestimmten Block" - ], - "item-custom-trigger-gain_xp": [ - "Spieler Bekommt XP" - ], - "item-custom-trigger-level_up": [ - "Spieler Levelt Auf" - ], - "item-custom-trigger-item_craft": [ - "Spieler Craftet Item" - ], - "item-custom-trigger-in_liquid": [ - "Spieler In Flüssigkeit" - ], - "item-custom-trigger-get_item": [ - "Item bekommen", - "Aktion wird für *jedes* anklicken oder aufheben ausgeführt" - ], - "item-custom-action-cancel": [ - "Auslöser Abbrechen", - "Verhindert, dass der Auslöser ausgeführt wird.", - "Nicht abrechenbare Auslöser: *Springen*, *Sneaken*, *Töten*", - "*Advancement*, *Auf Leveln*, *In Flüssigkeit*" - ], "item-custom-action-command": [ "Command Ausführen", "Lasse Spieler einen Command ausführen lassen", diff --git a/language/locales/en.json b/language/locales/en.json index 714a1746e..82d009c5b 100644 --- a/language/locales/en.json +++ b/language/locales/en.json @@ -4,7 +4,7 @@ "unknown": "unknown", "disabled": "Disabled", "enabled": "Enabled", - "customized": "Customize", + "customize": "Customize", "console": "Console" }, "language": { diff --git a/language/locales/global.json b/language/locales/global.json index df344bf81..d55708bb7 100644 --- a/language/locales/global.json +++ b/language/locales/global.json @@ -53,6 +53,11 @@ "title-format": "{@symbol.arrow} {0}", "title": "{@title-format('Challenges')}" }, + "suffix": { + "format": " {@symbol.vertical} {0}", + "selected": "{@format('{@symbol.check}')}", + "unselected": "{@format('{@symbol.x}')}" + }, "timer": { "bar": { "format": { @@ -699,5 +704,18 @@ "zero-hearts": { "*colorize*": "{0}" } + }, + "custom": { + "display-format": "{@symbol.arrow} {0}", + "trigger": { + "interval": { + "*colorize*": "{0}" + } + }, + "action": { + "cancel": { + "*colorize*": "{0}" + } + } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index 9a11e4dfd..2c31051f0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -5,16 +5,21 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.InfoMenuGenerator; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -37,7 +42,7 @@ public class CustomChallenge extends Setting { public CustomChallenge(MenuType menuType, UUID uuid, Material displayItem, String displayName, ChallengeTrigger trigger, Map subTriggers, ChallengeAction action, Map subActions) { - super(menuType, null, null, "custom-challenge"); + super(menuType, null, new ItemStack(displayItem), "custom-challenge"); this.uuid = uuid; this.material = displayItem; this.name = displayName; @@ -50,41 +55,35 @@ public CustomChallenge(MenuType menuType, UUID uuid, Material displayItem, Strin @NotNull @Override public ItemBuilder getDisplayItem(@NotNull Locale locale) { // TODO - String name = this.name; - if (name == null) { - name = "NULL"; - - } - Material material = this.material; - if (material == null) { - material = Material.BARRIER; - } - - LegacyItemBuilder builder = new LegacyItemBuilder(material, Message.forName("item-prefix").asString() + "§7" + name); + ItemBuilder item = new ItemBuilder(locale, displayItemPreset, MessageKey.of("custom.display-format"), name); // ADDING CONDITION INFO if (getTrigger() != null) { - builder.appendLore(" "); - List triggerDisplay = InfoMenuGenerator - .getSubSettingsDisplay(getTrigger().getSubSettingsBuilder(), getSubTriggers()); - - String triggerName = Message.forName(getTrigger().getMessage()).asItemDescription().getName(); - builder.appendLore(Message.forName("custom-info-trigger").asString() + " " + triggerName); - builder.appendLore(triggerDisplay); +// List triggerDisplay = SubSettingsBuilder +// .getSubSettingsDisplay(getTrigger().getSubSettingsBuilder(), getSubTriggers()); +// +// String triggerName = Message.forName(getTrigger().getMessageKey()).asItemDescription().getName(); +// builder.appendLore(Message.forName("custom-info-trigger").asString() + " " + triggerName); +// builder.appendLore(triggerDisplay); + + item.appendBlankLoreLine() + .appendLore(MessageKey.of("menu.custom.trigger-format"), getTrigger().getSettingName()); } // ADDING ACTION INFO if (getAction() != null) { - builder.appendLore(" "); - List actionDisplay = InfoMenuGenerator - .getSubSettingsDisplay(getAction().getSubSettingsBuilder(), getSubActions()); - - String actionName = Message.forName(getAction().getMessage()).asItemDescription().getName(); - builder.appendLore(Message.forName("custom-info-action").asString() + " " + actionName); - builder.appendLore(actionDisplay); +// builder.appendLore(" "); +// List actionDisplay = SubSettingsBuilder +// .getSubSettingsDisplay(getAction().getSubSettingsBuilder(), getSubActions()); +// +// String actionName = Message.forName(getAction().getMessageKey()).asItemDescription().getName(); +// builder.appendLore(Message.forName("custom-info-action").asString() + " " + actionName); +// builder.appendLore(actionDisplay); + + item.appendBlankLoreLine().appendLore(MessageKey.of("menu.custom.action-format"), getAction().getSettingName()); } - return new ItemBuilder(locale, builder.build()); + return item; } @Override @@ -98,9 +97,9 @@ public void writeSettings(@NotNull Document document) { document.set("material", material == null ? null : material.name()); document.set("name", name); - document.set("trigger", trigger == null ? null : trigger.getName()); + document.set("trigger", trigger == null ? null : trigger.getUniqueName()); document.set("subTrigger", subTriggers); - document.set("action", action == null ? null : action.getName()); + document.set("action", action == null ? null : action.getUniqueName()); document.set("subActions", subActions); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java index 6ba0be71f..f7d910679 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java @@ -1,7 +1,13 @@ package net.codingarea.challenges.plugin.challenges.custom.settings; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import java.util.Locale; import java.util.function.Supplier; public abstract class ChallengeSetting implements IChallengeSetting { @@ -22,17 +28,25 @@ public ChallengeSetting(String name, Supplier builderSupplie this(name, builderSupplier.get()); } - public String getMessageSuffix() { + public String getRelativeMessageKey() { return name.toLowerCase(); } + @NotNull + @Override + public ItemBuilder getDisplayItem(@NotNull Locale locale) { + return DefaultItems.createChallengeDisplayFormat(new ItemStack(getMaterial()), getSettingName(), getSettingDescription(), locale); + } + + @NotNull @Override public SubSettingsBuilder getSubSettingsBuilder() { return subSettingsBuilder; } + @NotNull @Override - public String getName() { + public String getUniqueName() { return name; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java index 458394d2e..aca2846e0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/CustomSettingsLoader.java @@ -39,7 +39,7 @@ public void enable() { private void loadTrigger() { registerTriggers( - new IntervallTrigger("intervall"), + new IntervallTrigger("interval"), new PlayerJumpTrigger("jump"), new PlayerSneakTrigger("sneak"), new MoveBlockTrigger("move_block"), @@ -118,7 +118,7 @@ public void registerTriggers(ChallengeTrigger... trigger) { fallbackTriggers.put(name, trigger1); } } - triggers.put(trigger1.getName(), trigger1); + triggers.put(trigger1.getUniqueName(), trigger1); Bukkit.getPluginManager().registerEvents(trigger1, Challenges.getInstance()); } } @@ -142,7 +142,7 @@ public void registerActions(ChallengeAction... action) { fallbackActions.put(name, action1); } } - actions.put(action1.getName(), action1); + actions.put(action1.getUniqueName(), action1); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java index 087837cca..ddd13fd69 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java @@ -1,16 +1,31 @@ package net.codingarea.challenges.plugin.challenges.custom.settings; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; public interface IChallengeSetting { + @NotNull SubSettingsBuilder getSubSettingsBuilder(); - String getName(); + @NotNull + String getUniqueName(); + @NotNull Material getMaterial(); - String getMessage(); + @NotNull + ItemBuilder getDisplayItem(@NotNull Locale locale); + + @NotNull + LocalizableMessage getSettingName(); + + @NotNull + LocalizableMessage getSettingDescription(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java index 5f328bd73..a10597f3f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java @@ -3,12 +3,16 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.common.collection.IRandom; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; import java.util.LinkedHashMap; +import java.util.Locale; import java.util.function.Supplier; public abstract class ChallengeAction extends ChallengeSetting implements IChallengeAction { @@ -31,15 +35,21 @@ public static LinkedHashMap getMenuItems() { LinkedHashMap map = new LinkedHashMap<>(); for (ChallengeAction value : Challenges.getInstance().getCustomSettingsLoader().getActions().values()) { - map.put(value.getName(), new LegacyItemBuilder(value.getMaterial(), Message.forName(value.getMessage())).hideAttributes().build()); + map.put(value.getUniqueName(), value.getDisplayItem(Locale.GERMAN).build()); // TODO } return map; } + @NotNull @Override - public final String getMessage() { - return "item-custom-action-" + getMessageSuffix(); + public LocalizableMessage getSettingName() { + return MessageKey.of("custom.action." + getRelativeMessageKey() + ".name"); } + @NotNull + @Override + public LocalizableMessage getSettingDescription() { + return MessageKey.of("custom.action." + getRelativeMessageKey() + ".desc"); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java index ec951b1f4..19dad9b99 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java @@ -2,9 +2,10 @@ import lombok.Getter; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.*; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.legacy.MessageManager; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.entity.Player; import org.bukkit.event.player.AsyncPlayerChatEvent; @@ -55,12 +56,24 @@ public static EmptySubSettingsBuilder createEmpty() { return new EmptySubSettingsBuilder(); } - public abstract boolean open(Player player, IParentCustomGenerator parentGenerator, String title); + public abstract boolean open(Player player, IParentCustomGenerator parentGenerator, LocalizableMessage title); public abstract List getDisplay(Map activated); public abstract boolean hasSettings(); + /** + * Collects the display lines of a builder and all of its children for the currently activated data. + * Relocated from the legacy custom {@code InfoMenuGenerator}. + */ + public static List getSubSettingsDisplay(SubSettingsBuilder builder, Map activated) { + List display = new LinkedList<>(); + for (SubSettingsBuilder child : builder.getAllChildren()) { + display.addAll(child.getDisplay(activated)); + } + return display; + } + public SubSettingsBuilder setParent(SubSettingsBuilder parent) { SubSettingsBuilder parentBuilder = getParent(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java index 1f6c0d03d..ab46c8742 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java @@ -3,9 +3,10 @@ import com.google.common.collect.Lists; import lombok.Getter; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.SubSettingChooseMenuGenerator; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.management.menu.generator.AbstractMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.SubSettingChooseMenuGenerator; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -30,7 +31,7 @@ public ChooseItemSubSettingsBuilder(String key, SubSettingsBuilder parent) { } @Override - public MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title) { + public AbstractMenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, LocalizableMessage title) { return new SubSettingChooseMenuGenerator(getKey(), parentGenerator, getSettings(), title); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java index 5eae2ab64..29838a9bd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java @@ -3,10 +3,11 @@ import com.google.common.collect.Lists; import lombok.Getter; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.SubSettingChooseMultipleMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.AbstractMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.SubSettingChooseMultipleMenuGenerator; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.entity.Player; @@ -32,7 +33,7 @@ public ChooseMultipleItemSubSettingBuilder(String key, SubSettingsBuilder parent } @Override - public MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title) { + public AbstractMenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, LocalizableMessage title) { return new SubSettingChooseMultipleMenuGenerator(getKey(), parentGenerator, getSettings(), title); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java index ad242fa7a..7230ed5d2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java @@ -2,7 +2,8 @@ import com.google.common.collect.Lists; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import org.bukkit.entity.Player; import java.util.List; @@ -25,7 +26,7 @@ public boolean hasSettings() { } @Override - public boolean open(Player player, IParentCustomGenerator parentGenerator, String title) { + public boolean open(Player player, IParentCustomGenerator parentGenerator, LocalizableMessage title) { return false; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java index 1880afd94..371b1dd37 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java @@ -1,9 +1,10 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.management.menu.generator.AbstractMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import org.bukkit.entity.Player; public abstract class GeneratorSubSettingsBuilder extends SubSettingsBuilder { @@ -16,18 +17,19 @@ public GeneratorSubSettingsBuilder(String key, SubSettingsBuilder parent) { super(key, parent); } - public boolean open(Player player, IParentCustomGenerator parentGenerator, String title) { + public boolean open(Player player, IParentCustomGenerator parentGenerator, LocalizableMessage title) { if (hasSettings()) { - MenuGenerator generator = getGenerator(player, parentGenerator, title + InventoryTitleManager.getTitleSplitter() + getKeyTranslation()); + LocalizableMessage subTitle = MessageKey.of("menu.title-name-format-sub").withArgs(title, getKeyTranslation()); + AbstractMenuGenerator generator = getGenerator(player, parentGenerator, subTitle); if (generator == null) return false; - generator.open(player, 0); + generator.openMenu(player); return true; } return false; } - public abstract MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title); + public abstract AbstractMenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, LocalizableMessage title); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java index 49e928082..bea1661c7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java @@ -3,7 +3,8 @@ import com.google.common.collect.Lists; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.spigot.listener.ChatInputListener; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.misc.MapUtils; @@ -49,7 +50,7 @@ public TextInputSubSettingsBuilder(String key, } @Override - public boolean open(Player player, IParentCustomGenerator parentGenerator, String title) { + public boolean open(Player player, IParentCustomGenerator parentGenerator, LocalizableMessage title) { player.closeInventory(); onOpen.accept(player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java index 5611216fc..5982e6ac4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java @@ -6,11 +6,12 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl.BooleanSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl.ModifierSetting; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.legacy.MessageManager; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.SubSettingValueMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.AbstractMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.SubSettingValueMenuGenerator; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.entity.Player; @@ -36,7 +37,7 @@ public ValueSubSettingsBuilder(SubSettingsBuilder parent) { } @Override - public MenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, String title) { + public AbstractMenuGenerator getGenerator(Player player, IParentCustomGenerator parentGenerator, LocalizableMessage title) { return new SubSettingValueMenuGenerator(parentGenerator, new LinkedHashMap<>(getDefaultSettings()), title); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java index f5dc512bf..619ecea42 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java @@ -3,11 +3,15 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; import java.util.LinkedHashMap; +import java.util.Locale; import java.util.function.Supplier; public abstract class ChallengeTrigger extends ChallengeSetting implements IChallengeTrigger { @@ -29,15 +33,22 @@ public static LinkedHashMap getMenuItems() { LinkedHashMap map = new LinkedHashMap<>(); for (ChallengeTrigger value : Challenges.getInstance().getCustomSettingsLoader().getTriggers().values()) { - map.put(value.getName(), new LegacyItemBuilder(value.getMaterial(), Message.forName(value.getMessage())).hideAttributes().build()); + map.put(value.getUniqueName(), value.getDisplayItem(Locale.GERMAN).build()); // TODO } return map; } + @NotNull @Override - public final String getMessage() { - return "item-custom-trigger-" + getMessageSuffix(); + public LocalizableMessage getSettingName() { + return MessageKey.of("custom.trigger." + getRelativeMessageKey() + ".name"); + } + + @NotNull + @Override + public LocalizableMessage getSettingDescription() { + return MessageKey.of("custom.trigger." + getRelativeMessageKey() + ".desc"); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java index 99f016c15..40389a7ac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.trigger.impl; import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.challenges.custom.settings.FallbackNames; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.content.legacy.Message; @@ -12,6 +13,7 @@ import java.util.LinkedList; import java.util.List; +@FallbackNames("intervall") public class IntervallTrigger extends ChallengeTrigger { public IntervallTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java index 6d86c20a2..1709c9005 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java @@ -126,8 +126,7 @@ protected final void updateItems() { @NotNull @Override public ItemBuilder getDisplayItem(@NotNull Locale locale) { - return new ItemBuilder(locale, displayItemPreset, MessageKey.of("challenge.display-format"), - getChallengeName(), getChallengeDescription()); + return DefaultItems.createChallengeDisplayFormat(displayItemPreset, getChallengeName(), getChallengeDescription(), locale); } /** diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java index 7c9542ad1..90081a3f8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java @@ -67,7 +67,7 @@ public ItemStack getSettingsItemPreset() { @NotNull @Override public LocalizableMessage getSettingsName() { - return MessageKey.of("customize"); + return MessageKey.of("generic.customize"); } @Override @@ -114,8 +114,7 @@ public final void updateItems() { @NotNull public ItemBuilder getDisplayItem(@NotNull Locale locale) { - return new ItemBuilder(locale, displayItemPreset, MessageKey.of("challenge.display-format"), - getDisplayName(), getDisplayDescription()); + return DefaultItems.createChallengeDisplayFormat(displayItemPreset, getDisplayName(), getDisplayDescription(), locale); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java index a408d13b2..eea20d7f9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java @@ -42,6 +42,14 @@ public static Component convertMessageHolderToComponent(@NotNull MessageHolder h public static Component getDetailedMaterialTranslatable(@NotNull Material material) { String key = material.translationKey(); // e.g., "item.minecraft.music_disc_strad" Component baseComponent = Component.translatable(key); + +// try { +// baseComponent = ComponentSprites.createSpriteComponent(material).appendSpace().append(baseComponent); +// } catch (Throwable ex) { +// ex.printStackTrace(); +// // sprites (and appendSpace) not available in this paper/adventure version +// } + String name = material.name(); if (name.startsWith("MUSIC_DISC_")) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSprites.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSprites.java new file mode 100644 index 000000000..4ae52f6c8 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSprites.java @@ -0,0 +1,40 @@ +package net.codingarea.challenges.plugin.content.i18n.impl.format; + +import net.kyori.adventure.key.Key; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.object.ObjectContents; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +final class ComponentSprites { + + private ComponentSprites() { + } + + @NotNull + static Component createSpriteComponent(@Nullable Material material) { + if (material == null || material.isAir() || !material.isItem()) { + return Component.empty(); + } + + // 2. Get the clean, lowercase vanilla key string (e.g., "diamond_sword" or "stone") + NamespacedKey namespaced = material.getKey(); + String materialKey = namespaced.getKey().toLowerCase(); + + // 3. Determine if the path should be prefixed with 'item/' or 'block/' + // Note: Some blocks (like STONE) use 'block/stone', while items use 'item/diamond_sword' + String prefix = material.isBlock() ? "block/" : "item/"; + + // 4. Create the resource path key inside the default atlas (minecraft:blocks) + Key spritePath = Key.key("minecraft", prefix + materialKey); + System.err.println("Creating sprite component for material: " + material + " with path: " + spritePath + " key: " + material.key() + " translatebleKey: " + material.translationKey()); + + // 5. Build and return the object component with an empty fallback + return Component.object(builder -> builder + .contents(ObjectContents.sprite(material.key())) // Defaults to the minecraft:blocks atlas + ); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java index 74c6e6b69..6a98ec569 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/CustomChallengesLoader.java @@ -10,7 +10,7 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.IChallengesMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.IMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChallengeMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.CustomHomeMenuGenerator; import net.codingarea.challenges.plugin.utils.misc.MapUtils; import net.codingarea.commons.common.config.Document; import org.bukkit.Material; @@ -87,21 +87,24 @@ public void resetChallenges() { } private void generateCustomChallenge(CustomChallenge challenge, boolean deleted, boolean generate) { - IMenuGenerator generator = challenge.getType().getMenuGenerator(); // TODO! - if (generator instanceof ChallengeMenuGenerator) { // TODO ! - ChallengeMenuGenerator menuGenerator = (ChallengeMenuGenerator) generator; - if (deleted) { - menuGenerator.removeChallengeFromCache(challenge); - if (generate) menuGenerator.generateInventories(); - } else { - if (!menuGenerator.isInChallengeCache(challenge)) { - menuGenerator.addChallengeToCache(challenge); - if (generate) menuGenerator.generateInventories(); - } else { - menuGenerator.updateItem(challenge); - } + IMenuGenerator generator = challenge.getType().getMenuGenerator(); + if (!(generator instanceof IChallengesMenuGenerator menuGenerator)) return; + + if (deleted) { + menuGenerator.removeFromCache(challenge); + if (generate) refreshCustomList(generator); + } else if (!menuGenerator.isCached(challenge)) { + menuGenerator.addToCache(challenge); + if (generate) refreshCustomList(generator); + } else { + menuGenerator.updateElementDisplay(challenge); + } + } - } + private void refreshCustomList(IMenuGenerator generator) { + // page count may have changed; regenerate the cached list pages for all known locales + if (generator instanceof CustomHomeMenuGenerator home) { + home.getListGenerator().updatePages(); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/UncachedMultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/UncachedMultiPageMenuGenerator.java index 3ca0a77b6..789db9680 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/UncachedMultiPageMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/UncachedMultiPageMenuGenerator.java @@ -17,7 +17,8 @@ public abstract class UncachedMultiPageMenuGenerator extends AbstractMenuGenerator { public static int[] calcSlots(int rows, int cols, int size) { - if (rows * cols > size) throw new IllegalArgumentException("rows (" + rows + ") * cols (" + cols + ") must be <= size (" + size + ")"); + if (rows * cols > size) + throw new IllegalArgumentException("rows (" + rows + ") * cols (" + cols + ") must be <= size (" + size + ")"); final int sizeRows = size / 9; final int rowOffset = Math.floorDiv(sizeRows - rows, 2); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java index 49c036ed6..bda6e8fa5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/MainMenuGenerator.java @@ -61,11 +61,12 @@ protected ItemBuilder createDisplayItem(@NotNull Locale locale, @NotNull MenuTyp ItemBuilder item = new ItemBuilder(locale, menuType.getDisplayItemMaterial(), MessageKey.of("menu.item-format"), menuType.getDisplayName()); + // TODO centralize suffix logic if (menuType.getMenuGenerator() instanceof ChallengesMenuGenerator generator) { if (generator.hasAnyNewChallenges()) { - item.appendName(MessageKey.of("new-challenge-suffix")); + item.appendName(MessageKey.of("suffix.new-challenge")); } else if (generator.hasAnyUpdatedChallenges()) { - item.appendName(MessageKey.of("updated-challenge-suffix")); + item.appendName(MessageKey.of("suffix.updated-challenge")); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java index b793c299b..57f0e98da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/ChallengeListMenuGenerator.java @@ -158,10 +158,11 @@ protected void setChallengeItemsAt(@NotNull IChallenge challenge, @NotNull Inven protected ItemStack createChallengeDisplayItem(@NotNull IChallenge challenge, @NotNull Locale locale) { ItemBuilder item = challenge.getDisplayItem(locale); + // TODO centralize suffix logic if (newSuffix && ChallengeAnnotations.isNew(challenge)) { - item.appendName(MessageKey.of("new-challenge-suffix")); + item.appendName(MessageKey.of("suffix.new-challenge")); } else if (updatedSuffix && ChallengeAnnotations.isUpdated(challenge)) { - item.appendName(MessageKey.of("updated-challenge-suffix")); + item.appendName(MessageKey.of("suffix.updated-challenge")); } return item.build(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java index 0637ea349..3eaaae1c0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/challenge/categorised/CategorisedMenuGenerator.java @@ -6,6 +6,7 @@ import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengeListMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengesMenuGenerator; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; @@ -140,15 +141,15 @@ private void setCategoryUpdateItemsAt(@NotNull SettingCategory category, @NotNul @NotNull protected ItemStack createCategoryDisplayItem(@NotNull Locale locale, @NotNull SettingCategory category) { - ItemBuilder item = new ItemBuilder(locale, category.getDisplayItemPreset(), MessageKey.of("challenge.display-format"), - category.getDisplayName(), category.getDescription()); + ItemBuilder item = DefaultItems.createChallengeDisplayFormat(category.getDisplayItemPreset(), category.getDisplayName(), category.getDescription(), locale); CategorisedListMenuGenerator generator = categoryGenerators.get(category); if (generator != null) { + // TODO centralize suffix logic if (generator.isNewSuffix() && generator.hasAnyNewChallenges()) { - item.appendName(MessageKey.of("new-challenge-suffix")); + item.appendName(MessageKey.of("suffix.new-challenge")); } else if (generator.isUpdatedSuffix() && generator.hasAnyUpdatedChallenges()) { - item.appendName(MessageKey.of("updated-challenge-suffix")); + item.appendName(MessageKey.of("suffix.updated-challenge")); } item.appendLore(category.getDescriptionInfo(), diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java new file mode 100644 index 000000000..a4549c600 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java @@ -0,0 +1,268 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom; + +import lombok.ToString; +import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; +import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; +import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; +import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.generator.SinglePageMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.CustomChooseMaterialMenuGenerator; +import net.codingarea.challenges.plugin.spigot.listener.ChatInputListener; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.common.collection.IRandom; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.jetbrains.annotations.NotNull; + +import java.util.*; + +@ToString +public class CustomChallengeMenuGenerator extends SinglePageMenuGenerator implements IParentCustomGenerator { + + public static final int SIZE = 5 * 9; + + public static final int DELETE_SLOT = 19 + 9; + public static final int SAVE_SLOT = 25 + 9; + public static final int CONDITION_SLOT = 21 + 9; + public static final int ACTION_SLOT = 23 + 9; + public static final int MATERIAL_SLOT = 14; + public static final int NAME_SLOT = 12; + + private static final boolean savePlayerChallenges; + + // TODO + static { + savePlayerChallenges = Challenges.getInstance().getConfigDocument().getBoolean("save-player_challenges"); + } + + private final CustomChooseMaterialMenuGenerator chooseMaterialGenerator = new CustomChooseMaterialMenuGenerator(this); + + private final UUID uuid; + private String name; + private Material material; + private ChallengeTrigger trigger; + private Map subTriggers; + private ChallengeAction action; + private Map subActions; + + public CustomChallengeMenuGenerator(@NotNull CustomChallenge customChallenge) { + this.menuType = MenuType.CUSTOM; + this.uuid = customChallenge.getUniqueId(); + this.material = customChallenge.getMaterial(); + this.name = customChallenge.getDisplayName(); + this.trigger = customChallenge.getTrigger(); + this.subTriggers = customChallenge.getSubTriggers(); + this.action = customChallenge.getAction(); + this.subActions = customChallenge.getSubActions(); + } + + /** + * Default Settings for new Custom Challenges + */ + public CustomChallengeMenuGenerator() { + this.menuType = MenuType.CUSTOM; + this.trigger = null; + this.action = null; + this.subTriggers = new HashMap<>(); + this.subActions = new HashMap<>(); + this.uuid = UUID.randomUUID(); + this.material = IRandom.threadLocal().choose(CustomChooseMaterialMenuGenerator.MATERIALS); + this.name = "§7Custom §e#" + + (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() + 1); + } + + @NotNull + @Override + public LocalizableMessage getMenuName() { + return createSubMenuTitle(MessageKey.of("menu.custom.sub-name"), MessageKey.of("menu.custom.info.name")); + } + + @NotNull + @Override + public GeneratorMenuPosition createMenuPosition(@NotNull Player player) { + return new CustomChallengeMenuPosition(); + } + + @Override + public void updateInventoryContent(@NotNull Inventory inventory, @NotNull Locale locale) { + // Save / Delete Item + inventory.setItem(DELETE_SLOT, new ItemBuilder(locale, Material.BARRIER, MessageKey.of("menu.custom.info.item-delete")).build()); + inventory.setItem(SAVE_SLOT, new ItemBuilder(locale, Material.LIME_DYE, MessageKey.of("menu.custom.info.item-save")).build()); + + // Trigger Item + LocalizableMessage triggerName = trigger == null ? MessageKey.of("generic.none") : trigger.getSettingName(); + ItemBuilder triggerItem = new ItemBuilder(locale, Material.WITHER_SKELETON_SKULL, MessageKey.of("menu.custom.info.item-trigger"), + triggerName); + if (trigger != null) { + List lines = SubSettingsBuilder.getSubSettingsDisplay(trigger.getSubSettingsBuilder(), subTriggers); + if (!lines.isEmpty()) triggerItem.appendLore(lines); + } + inventory.setItem(CONDITION_SLOT, triggerItem.build()); + + // Action Item + LocalizableMessage actionName = action == null ? MessageKey.of("generic.none") : action.getSettingName(); + ItemBuilder actionItem = new ItemBuilder(locale, Material.NETHER_STAR, MessageKey.of("menu.custom.info.item-action"), + actionName); + if (action != null) { + List lines = SubSettingsBuilder.getSubSettingsDisplay(action.getSubSettingsBuilder(), subActions); + if (!lines.isEmpty()) actionItem.appendLore(lines); + } + inventory.setItem(ACTION_SLOT, actionItem.build()); + + // Display Item + inventory.setItem(MATERIAL_SLOT, new ItemBuilder(locale, material == null ? Material.BARRIER : material, + MessageKey.of("menu.custom.info.item-material"), material != null ? material : MessageKey.of("generic.none")).build()); + + // Name Item + // TODO escape, format? + int maxNameLength = Challenges.getInstance().getCustomChallengesLoader().getMaxNameLength(); + inventory.setItem(NAME_SLOT, new ItemBuilder(locale, Material.NAME_TAG, MessageKey.of("menu.custom.info.item-name"), + name, maxNameLength).build()); + } + + @Override + public int getInventorySize() { + return SIZE; + } + + @Override + public void accept(@NotNull Player player, @NotNull SettingType type, @NotNull Map data) { + openMenu(player); + + switch (type) { + case CONDITION: + trigger = Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(data.remove("trigger")[0]); + this.subTriggers = data; + break; + case ACTION: + action = Challenges.getInstance().getCustomSettingsLoader().getActionByName(data.remove("action")[0]); + this.subActions = data; + break; + case MATERIAL: + material = Material.valueOf(data.remove("material")[0]); + break; + } + + updatePages(); + } + + @Override + public void decline(@NotNull Player player) { + openMenu(player); + } + + public void setName(@NotNull String name) { + this.name = name; + updatePages(); + } + + @NotNull + public CustomChallenge save() { + return Challenges.getInstance().getCustomChallengesLoader() + .registerCustomChallenge(uuid, material, name, trigger, subTriggers, action, subActions, true); + } + + private void navigateToChallengeList(@NotNull Player player) { + CustomHomeMenuGenerator home = (CustomHomeMenuGenerator) MenuType.CUSTOM.getMenuGenerator(); + CustomChallenge challenge = Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().get(uuid); + if (challenge == null) { + home.openMenu(player); + return; + } + CustomListMenuGenerator list = home.getListGenerator(); + int page = Math.max(0, Math.min(list.getPageOfChallenge(challenge), list.getPageCount() - 1)); + list.openMenu(player, page); + } + + public class CustomChallengeMenuPosition extends SinglePageGeneratorMenuPosition { + + @Override + public boolean handleMenuClick(@NotNull MenuClickInfo info) { + Player player = info.getPlayer(); + switch (info.getSlot()) { + case MATERIAL_SLOT -> { + chooseMaterialGenerator.openMenu(player); + SoundSample.CLICK.play(player); + return true; + } + case CONDITION_SLOT -> { + new CustomMainSettingsMenuGenerator(CustomChallengeMenuGenerator.this, SettingType.CONDITION, "trigger", + MessageKey.of("custom-title-trigger"), ChallengeTrigger.getMenuItems(), + key -> Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(key)) + .openMenu(player); + SoundSample.CLICK.play(player); + return true; + } + case ACTION_SLOT -> { + new CustomMainSettingsMenuGenerator(CustomChallengeMenuGenerator.this, SettingType.ACTION, "action", + MessageKey.of("custom-title-action"), ChallengeAction.getMenuItems(), + key -> Challenges.getInstance().getCustomSettingsLoader().getActionByName(key)) + .openMenu(player); + SoundSample.CLICK.play(player); + return true; + } + case NAME_SLOT -> { + MessageKey.of("custom-name-info").send(player, Prefix.CUSTOM); + player.closeInventory(); + ChatInputListener.setInputAction(player, event -> { + int maxNameLength = Challenges.getInstance().getCustomChallengesLoader().getMaxNameLength(); + if (event.getMessage().length() > maxNameLength) { + MessageKey.of("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxNameLength); + return; + } + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + setName(ChatColor.translateAlternateColorCodes('&', event.getMessage())); + openMenu(event.getPlayer()); + }); + }); + return true; + } + case DELETE_SLOT -> { + if (!Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().containsKey(uuid)) { + MessageKey.of("custom-not-deleted").send(player, Prefix.CUSTOM); + SoundSample.BASS_OFF.play(player); + return true; + } + navigateToChallengeList(player); + Challenges.getInstance().getCustomChallengesLoader().unregisterCustomChallenge(uuid); + new SoundSample().addSound(Sound.ENTITY_WITHER_BREAK_BLOCK, 0.4f).play(player); + return true; + } + case SAVE_SLOT -> { + String defaults = new CustomChallengeMenuGenerator().toString(); + String current = CustomChallengeMenuGenerator.this.toString(); + if (defaults.equals(current)) { + MessageKey.of("custom-no-changes").send(player, Prefix.CUSTOM); + SoundSample.BASS_OFF.play(player); + return true; + } + save(); + navigateToChallengeList(player); + MessageKey.of("custom-saved").send(player, Prefix.CUSTOM); + if (savePlayerChallenges) { + MessageKey.of("custom-saved-db").send(player, Prefix.CUSTOM); + } + SoundSample.LEVEL_UP.play(player); + return true; + } + } + + return false; + } + + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomHomeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomHomeMenuGenerator.java index 081315cb3..20ef007d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomHomeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomHomeMenuGenerator.java @@ -24,13 +24,18 @@ public class CustomHomeMenuGenerator extends SinglePageMenuGenerator implements public static final int CREATE_SLOT = 23; public static final int SIZE = 5 * 9; - private final CustomListMenuGenerator viewGenerator = new CustomListMenuGenerator(); + private final CustomListMenuGenerator listGenerator = new CustomListMenuGenerator(); + + @NotNull + public CustomListMenuGenerator getListGenerator() { + return listGenerator; + } @Override public void setMenuType(MenuType menuType) { // MenuType.CUSTOM instance not initialized when creating CustomListMenuGenerator super.setMenuType(menuType); - viewGenerator.setMenuType(menuType); + listGenerator.setMenuType(menuType); } @NotNull @@ -60,32 +65,32 @@ public int getInventorySize() { @Override public void addToCache(@NonNull IChallenge element) { - viewGenerator.addToCache(element); + listGenerator.addToCache(element); } @Override public void removeFromCache(@NonNull IChallenge element) { - viewGenerator.removeFromCache(element); + listGenerator.removeFromCache(element); } @Override public boolean isCached(@NonNull IChallenge element) { - return viewGenerator.isCached(element); + return listGenerator.isCached(element); } @Override public int getCachedCount() { - return viewGenerator.getCachedCount(); + return listGenerator.getCachedCount(); } @Override public void resetCache() { - viewGenerator.resetCache(); + listGenerator.resetCache(); } @Override public void updateElementDisplay(@NonNull IChallenge element) { - viewGenerator.updateElementDisplay(element); + listGenerator.updateElementDisplay(element); } public class CustomMainMenuPosition extends SinglePageGeneratorMenuPosition { @@ -98,14 +103,14 @@ public boolean handleMenuClick(@NotNull MenuClickInfo info) { SoundSample.BASS_OFF.play(info.getPlayer()); return true; } - viewGenerator.openMenu(info.getPlayer()); + listGenerator.openMenu(info.getPlayer()); SoundSample.PLOP.play(info.getPlayer()); return true; } else if (info.getSlot() == CREATE_SLOT) { // TODO check permission, limit, abstract logic - InfoMenuGenerator generator = new InfoMenuGenerator(); + CustomChallengeMenuGenerator generator = new CustomChallengeMenuGenerator(); generator.openMenu(info.getPlayer()); - SoundSample.PLOP.play(info.getPlayer()); + SoundSample.PLING.play(info.getPlayer()); return true; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomListMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomListMenuGenerator.java index 076239359..79d37e8f1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomListMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomListMenuGenerator.java @@ -3,10 +3,12 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; import net.codingarea.challenges.plugin.challenges.type.IChallenge; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.impl.challenge.ChallengeListMenuGenerator; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.challenges.plugin.utils.item.DefaultItems; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import org.bukkit.entity.Player; @@ -32,7 +34,7 @@ public boolean executeChallengeClickAction(@NotNull IChallenge challenge, int sl return true; } else if (slotOffset == SLOT_OFFSET_SETTINGS && challenge instanceof CustomChallenge customChallenge) { // TODO save & reuse? - InfoMenuGenerator generator = new InfoMenuGenerator(customChallenge); + CustomChallengeMenuGenerator generator = new CustomChallengeMenuGenerator(customChallenge); generator.openMenu(info.getPlayer()); SoundSample.CLICK.play(info.getPlayer()); return true; @@ -49,7 +51,8 @@ protected void setChallengeItemsAt(@NotNull IChallenge challenge, @NotNull Inven @NotNull protected ItemStack createChallengeCustomizeItem(@NotNull IChallenge challenge, @NotNull Locale locale) { - return DefaultItems.createCustomizePreset(); + return new ItemBuilder(locale, DefaultItems.createCustomizePreset(), MessageKey.of("challenge.settings-format"), + MessageKey.of("generic.customize")).build(); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomMainSettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomMainSettingsMenuGenerator.java new file mode 100644 index 000000000..2f664a17a --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomMainSettingsMenuGenerator.java @@ -0,0 +1,100 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom; + +import lombok.Getter; +import net.codingarea.challenges.plugin.challenges.custom.settings.IChallengeSetting; +import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.CustomChooseItemMenuGenerator; +import net.codingarea.challenges.plugin.utils.misc.MapUtils; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.Function; + +/** + * Lets the player choose a trigger or action, then walks its {@link SubSettingsBuilder} chain + * collecting the sub-setting data before handing it back to the parent generator. + * Replaces the legacy {@code custom.CustomMainSettingsMenuGenerator}. + */ +public class CustomMainSettingsMenuGenerator extends CustomChooseItemMenuGenerator implements IParentCustomGenerator { + + @Getter + private final IParentCustomGenerator parent; + private final SettingType type; + private final LocalizableMessage baseTitle; + private final String key; + private final Function instanceGetter; + private IChallengeSetting setting; + private SubSettingsBuilder subSettingsBuilder; + private Map subSettings; + + public CustomMainSettingsMenuGenerator(@NotNull IParentCustomGenerator parent, @NotNull SettingType type, + @NotNull String key, @NotNull LocalizableMessage baseTitle, + @NotNull LinkedHashMap items, + @NotNull Function instanceGetter) { + super(baseTitle, items); + this.parent = parent; + this.type = type; + this.baseTitle = baseTitle; + this.key = key; + this.instanceGetter = instanceGetter; + this.subSettings = new HashMap<>(); + } + + @NotNull + @Override + public LocalizableMessage getMenuName() { + return createSubMenuTitle(MessageKey.of("menu.custom.sub-name"), baseTitle); + } + + @Override + public void onItemClick(@NotNull Player player, @NotNull String itemKey) { + this.setting = instanceGetter.apply(itemKey); + this.subSettingsBuilder = setting.getSubSettingsBuilder(); + + subSettings.put(key, new String[]{setting.getUniqueName()}); + + if (!openSubSettingsMenu(player)) { + parent.accept(player, type, subSettings); + } + } + + @Override + public void accept(@NotNull Player player, @Nullable SettingType type, @NotNull Map data) { + subSettings.putAll(data); + + if (!openSubSettingsMenu(player)) { + parent.accept(player, this.type, subSettings); + } + } + + private boolean openSubSettingsMenu(@NotNull Player player) { + if (subSettingsBuilder != null && subSettingsBuilder.hasSettings()) { + subSettingsBuilder.open(player, this, baseTitle); + subSettingsBuilder = subSettingsBuilder.getChild(); + return true; + } + return false; + } + + @Override + protected void handleNavigateOutOfMenu(@NotNull Player player) { + parent.decline(player); + } + + @Override + public void decline(@NotNull Player player) { + if (setting != null) { + this.subSettings = MapUtils.createStringArrayMap(key, setting.getUniqueName()); + } + openMenu(player); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/IParentCustomGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/IParentCustomGenerator.java similarity index 77% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/IParentCustomGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/IParentCustomGenerator.java index a3731939a..3cc522735 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/IParentCustomGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/IParentCustomGenerator.java @@ -1,8 +1,9 @@ -package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Map; @@ -13,7 +14,7 @@ public interface IParentCustomGenerator { * @param type the type of the current setting. Only needed if parent is the first setting menu. * @param data a map that contains all the data of the settings */ - void accept(@NotNull Player player, @NotNull SettingType type, @NotNull Map data); + void accept(@NotNull Player player, @Nullable SettingType type, @NotNull Map data); void decline(@NotNull Player player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/InfoMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/InfoMenuGenerator.java deleted file mode 100644 index a705ba0c3..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/InfoMenuGenerator.java +++ /dev/null @@ -1,159 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.impl.custom; - -import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; -import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; -import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; -import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; -import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.SinglePageMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.common.collection.IRandom; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.jetbrains.annotations.NotNull; - -import java.util.*; - -// TODO rename to CustomChallengeMenuGenerator -public class InfoMenuGenerator extends SinglePageMenuGenerator implements IParentCustomGenerator { - - public static final int SIZE = 5 * 9; - - public static final int DELETE_SLOT = 19 + 9; - public static final int SAVE_SLOT = 25 + 9; - public static final int CONDITION_SLOT = 21 + 9; - public static final int ACTION_SLOT = 23 + 9; - public static final int MATERIAL_SLOT = 14; - public static final int NAME_SLOT = 12; - - private static final boolean savePlayerChallenges; - - // TODO - static { - savePlayerChallenges = Challenges.getInstance().getConfigDocument().getBoolean("save-player_challenges"); - } - - private final CustomChooseMaterialMenuGenerator chooseMaterialGenerator = new CustomChooseMaterialMenuGenerator(this); - - private final UUID uuid; - private String name; - private Material material; - private ChallengeTrigger trigger; - private Map subTriggers; - private ChallengeAction action; - private Map subActions; - - public InfoMenuGenerator(@NotNull CustomChallenge customChallenge) { - this.menuType = MenuType.CUSTOM; - this.uuid = customChallenge.getUniqueId(); - this.material = customChallenge.getMaterial(); - this.name = customChallenge.getDisplayName(); - this.trigger = customChallenge.getTrigger(); - this.subTriggers = customChallenge.getSubTriggers(); - this.action = customChallenge.getAction(); - this.subActions = customChallenge.getSubActions(); - } - - /** - * Default Settings for new Custom Challenges - */ - public InfoMenuGenerator() { - this.menuType = MenuType.CUSTOM; - this.trigger = null; - this.action = null; - this.subTriggers = new HashMap<>(); - this.subActions = new HashMap<>(); - this.uuid = UUID.randomUUID(); - this.material = IRandom.threadLocal().choose(CustomChooseMaterialMenuGenerator.MATERIALS); - this.name = "§7Custom §e#" + - (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() + 1); - } - - @NotNull - @Override - public LocalizableMessage getMenuName() { - return createSubMenuTitle(MessageKey.of("menu.custom.sub-name"), MessageKey.of("menu.custom.info.name")); - } - - @NotNull - @Override - public GeneratorMenuPosition createMenuPosition(@NotNull Player player) { - return new CustomChallengeMenuPosition(); - } - - @Override - public void updateInventoryContent(@NotNull Inventory inventory, @NotNull Locale locale) { - // Save / Delete Item - inventory.setItem(DELETE_SLOT, new ItemBuilder(locale, Material.BARRIER, MessageKey.of("menu.custom.info.item-delete")).build()); - inventory.setItem(SAVE_SLOT, new ItemBuilder(locale, Material.LIME_DYE, MessageKey.of("menu.custom.info.item-save")).build()); - - // Display Item - inventory.setItem(MATERIAL_SLOT, new ItemBuilder(locale, material == null ? Material.BARRIER : material, - MessageKey.of("menu.custom.info.item-material"), material != null ? material : MessageKey.of("generic.none")).build()); - - // Name Item - // TODO escape, format? - int maxNameLength = Challenges.getInstance().getCustomChallengesLoader().getMaxNameLength(); - inventory.setItem(NAME_SLOT, new ItemBuilder(locale, Material.NAME_TAG, MessageKey.of("menu.custom.info.item-name"), - name, maxNameLength).build()); - - // TODO TRIGGER; CONDITION; ACTION - } - - @Override - public int getInventorySize() { - return SIZE; - } - - @Override - public void accept(@NotNull Player player, @NotNull SettingType type, @NotNull Map data) { - openMenu(player); - - switch (type) { - case CONDITION: - trigger = Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(data.remove("trigger")[0]); - this.subTriggers = data; - break; - case ACTION: - action = Challenges.getInstance().getCustomSettingsLoader().getActionByName(data.remove("action")[0]); - this.subActions = data; - break; - case MATERIAL: - material = Material.valueOf(data.remove("material")[0]); - break; - } - - updatePages(); - } - - @Override - public void decline(@NotNull Player player) { - openMenu(player); - } - - public class CustomChallengeMenuPosition extends SinglePageGeneratorMenuPosition { - - @Override - public boolean handleMenuClick(@NotNull MenuClickInfo info) { - switch (info.getSlot()) { - case MATERIAL_SLOT -> { - chooseMaterialGenerator.openMenu(info.getPlayer()); - SoundSample.CLICK.play(info.getPlayer()); - return true; - } - } - - return false; - } - - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseItemMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseItemMenuGenerator.java new file mode 100644 index 000000000..67d0e91ce --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseItemMenuGenerator.java @@ -0,0 +1,104 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose; + +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.generator.UncachedMultiPageMenuGenerator; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; + +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; + +/** + * Displays a static, keyed set of pre-built {@link ItemStack}s to choose one from. + * Replaces the legacy {@code ChooseItemGenerator}. The item content is passed in pre-built, + * as its (legacy) localization happens outside this generator. + */ +public abstract class CustomChooseItemMenuGenerator extends UncachedMultiPageMenuGenerator { + + public static final int SIZE = 5 * 9; + public static final int[] SLOTS = calcSlots(3, 7, SIZE); + + private final LocalizableMessage menuName; + + protected CustomChooseItemMenuGenerator(@NotNull LocalizableMessage menuName, @NotNull LinkedHashMap items) { + super(toKeyedItems(items)); + this.menuType = MenuType.CUSTOM; + this.menuName = menuName; + } + + protected static KeyedItem[] toKeyedItems(@NotNull LinkedHashMap items) { + KeyedItem[] array = new KeyedItem[items.size()]; + int i = 0; + for (Map.Entry entry : items.entrySet()) { + array[i++] = new KeyedItem(entry.getKey(), entry.getValue()); + } + return array; + } + + @NotNull + @Override + public LocalizableMessage getMenuName() { + return menuName; + } + + public abstract void onItemClick(@NotNull Player player, @NotNull String key); + + @Override + public void handleElementClick(@NotNull KeyedItem element, @NotNull MenuClickInfo info) { + onItemClick(info.getPlayer(), element.key()); + } + + @NotNull + @Override + public ItemStack createDisplayItem(@NotNull KeyedItem element, @NotNull Locale locale) { + return element.item(); + } + + @Override + public int[] getSlots() { + return SLOTS; + } + + @Override + public int getInventorySize() { + return SIZE; + } + + @NotNull + @Override + public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { + return new ChooseItemMenuPosition(page); + } + + public class ChooseItemMenuPosition extends GeneratorMenuPosition { + + public ChooseItemMenuPosition(int page) { + super(page); + } + + @Override + public boolean handleMenuClick(@NotNull MenuClickInfo info) { + int[] slots = getSlots(); + for (int i = 0; i < slots.length; i++) { + if (info.getSlot() != slots[i]) continue; + + int index = getPage() * getMaxEntriesPerPage() + i; + if (index >= elements.length) return false; // page not full + + SoundSample.PLOP.play(info.getPlayer()); + onItemClick(info.getPlayer(), elements[index].key()); + return true; + } + return false; + } + } + + public record KeyedItem(@NotNull String key, @NotNull ItemStack item) { + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChooseMaterialMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMaterialMenuGenerator.java similarity index 97% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChooseMaterialMenuGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMaterialMenuGenerator.java index b4635926a..ecb1d417a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChooseMaterialMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMaterialMenuGenerator.java @@ -1,11 +1,11 @@ -package net.codingarea.challenges.plugin.management.menu.generator.impl.custom; +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.UncachedMultiPageMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.MapUtils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleItemMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleItemMenuGenerator.java new file mode 100644 index 000000000..1b3ad2203 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleItemMenuGenerator.java @@ -0,0 +1,125 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose; + +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.generator.UncachedMultiPageMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.CustomChooseItemMenuGenerator.KeyedItem; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; + +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; + +/** + * Choose multiple pre-built items; toggles a selection marker and confirms via a finish button. + * Replaces the legacy {@code ChooseMultipleItemGenerator}. + */ +public abstract class CustomChooseMultipleItemMenuGenerator extends UncachedMultiPageMenuGenerator { + + public static final int SIZE = 5 * 9; + public static final int[] SLOTS = calcSlots(3, 7, SIZE); + public static final int FINISH_SLOT = 40; + + private final LocalizableMessage menuName; + private final List selectedKeys = new LinkedList<>(); + + protected CustomChooseMultipleItemMenuGenerator(@NotNull LocalizableMessage menuName, @NotNull LinkedHashMap items) { + super(CustomChooseItemMenuGenerator.toKeyedItems(items)); + this.menuType = MenuType.CUSTOM; + this.menuName = menuName; + } + + @NotNull + @Override + public LocalizableMessage getMenuName() { + return menuName; + } + + public abstract void onItemClick(@NotNull Player player, @NotNull String[] keys); + + @Override + public void handleElementClick(@NotNull KeyedItem element, @NotNull MenuClickInfo info) { + // handled by the custom menu position (toggle instead of confirm) + } + + @NotNull + @Override + public ItemStack createDisplayItem(@NotNull KeyedItem element, @NotNull Locale locale) { + ItemBuilder builder = new ItemBuilder(locale, element.item().clone()).hideAttributes(); + if (selectedKeys.contains(element.key())) { + builder.addEnchantment(MinecraftNameWrapper.UNBREAKING, 1); + builder.appendName(" §8┃ §2§l✔"); + } else { + builder.appendName(" §8┃ §c✖"); + } + return builder.build(); + } + + @Override + public void setInventoryDecoration(@NotNull Inventory inventory, int page, @NotNull Locale locale) { + super.setInventoryDecoration(inventory, page, locale); + inventory.setItem(FINISH_SLOT, new ItemBuilder(locale, Material.LIME_DYE, MessageKey.of("custom-sub-finish")).build()); + } + + @Override + public int[] getSlots() { + return SLOTS; + } + + @Override + public int getInventorySize() { + return SIZE; + } + + @NotNull + @Override + public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { + return new ChooseMultipleMenuPosition(page); + } + + public class ChooseMultipleMenuPosition extends GeneratorMenuPosition { + + public ChooseMultipleMenuPosition(int page) { + super(page); + } + + @Override + public boolean handleMenuClick(@NotNull MenuClickInfo info) { + if (info.getSlot() == FINISH_SLOT) { + SoundSample.PLOP.play(info.getPlayer()); + onItemClick(info.getPlayer(), selectedKeys.toArray(new String[0])); + return true; + } + + int[] slots = getSlots(); + for (int i = 0; i < slots.length; i++) { + if (info.getSlot() != slots[i]) continue; + + int index = getPage() * getMaxEntriesPerPage() + i; + if (index >= elements.length) return false; // page not full + + String key = elements[index].key(); + if (selectedKeys.contains(key)) { + selectedKeys.remove(key); + } else { + selectedKeys.add(key); + } + SoundSample.LOW_PLOP.play(info.getPlayer()); + openMenu(info.getPlayer(), getPage()); // re-render selection markers + return true; + } + return false; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java new file mode 100644 index 000000000..889dd66b0 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java @@ -0,0 +1,125 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose; + +import lombok.Getter; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.generator.UncachedMultiPageMenuGenerator; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; +import java.util.Map; + +/** + * Displays adjustable {@link ValueSetting} rows with a finish button. + * Replaces the legacy {@code ValueMenuGenerator}. + */ +public abstract class CustomChooseValueMenuGenerator extends UncachedMultiPageMenuGenerator { + + public static final int SIZE = 4 * 9; + public static final int[] SLOTS = {10, 11, 12, 13}; // settings item at +9 each + public static final int FINISH_SLOT = 31; + + private final LocalizableMessage menuName; + + @Getter + private final Map settings; + + protected CustomChooseValueMenuGenerator(@NotNull LocalizableMessage menuName, @NotNull Map settings) { + super(settings.keySet().toArray(new ValueSetting[0])); + this.menuType = MenuType.CUSTOM; + this.menuName = menuName; + this.settings = settings; + } + + @NotNull + @Override + public LocalizableMessage getMenuName() { + return menuName; + } + + public abstract void onSaveItemClick(@NotNull Player player); + + @Override + protected void setElementItemsAt(@NotNull ValueSetting element, @NotNull Inventory inventory, int slot, @NotNull Locale locale) { + String value = settings.get(element); + inventory.setItem(slot, element.getDisplayItem(value).build()); + inventory.setItem(slot + 9, element.getSettingsItem(value).build()); + } + + @NotNull + @Override + public org.bukkit.inventory.ItemStack createDisplayItem(@NotNull ValueSetting element, @NotNull Locale locale) { + return element.getDisplayItem(settings.get(element)).build(); + } + + @Override + public void handleElementClick(@NotNull ValueSetting element, @NotNull MenuClickInfo info) { + // handled by the custom menu position (adjust value instead of confirm) + } + + @Override + public void setInventoryDecoration(@NotNull Inventory inventory, int page, @NotNull Locale locale) { + super.setInventoryDecoration(inventory, page, locale); + inventory.setItem(FINISH_SLOT, new ItemBuilder(locale, Material.LIME_DYE, MessageKey.of("custom-sub-finish")).build()); + } + + @Override + public int[] getSlots() { + return SLOTS; + } + + @Override + public int getInventorySize() { + return SIZE; + } + + @NotNull + @Override + public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { + return new ChooseValueMenuPosition(page); + } + + public class ChooseValueMenuPosition extends GeneratorMenuPosition { + + public ChooseValueMenuPosition(int page) { + super(page); + } + + @Override + public boolean handleMenuClick(@NotNull MenuClickInfo info) { + if (info.getSlot() == FINISH_SLOT) { + SoundSample.PLOP.play(info.getPlayer()); + onSaveItemClick(info.getPlayer()); + return true; + } + + int[] slots = getSlots(); + for (int i = 0; i < slots.length; i++) { + boolean isDisplaySlot = info.getSlot() == slots[i]; + boolean isSettingsSlot = info.getSlot() == slots[i] + 9; + if (!isDisplaySlot && !isSettingsSlot) continue; + + int index = getPage() * getMaxEntriesPerPage() + i; + if (index >= elements.length) return false; // page not full + + ValueSetting setting = elements[index]; + String oldValue = settings.get(setting); + String newValue = setting.onClick(info, oldValue, isSettingsSlot ? 1 : 0); + settings.put(setting, newValue); + SoundSample.CLICK.play(info.getPlayer()); + openMenu(info.getPlayer(), getPage()); // re-render adjusted value + return true; + } + return false; + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMenuGenerator.java new file mode 100644 index 000000000..257a0114c --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMenuGenerator.java @@ -0,0 +1,34 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose; + +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.utils.misc.MapUtils; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; + +import java.util.LinkedHashMap; + +public class SubSettingChooseMenuGenerator extends CustomChooseItemMenuGenerator { + + private final IParentCustomGenerator parent; + private final String key; + + public SubSettingChooseMenuGenerator(@NotNull String key, @NotNull IParentCustomGenerator parent, + @NotNull LinkedHashMap items, @NotNull LocalizableMessage title) { + super(title, items); + this.key = key; + this.parent = parent; + } + + @Override + public void onItemClick(@NotNull Player player, @NotNull String itemKey) { + parent.accept(player, null, MapUtils.createStringArrayMap(key, itemKey)); + } + + @Override + protected void handleNavigateOutOfMenu(@NotNull Player player) { + parent.decline(player); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMultipleMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMultipleMenuGenerator.java new file mode 100644 index 000000000..8f2e326e5 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMultipleMenuGenerator.java @@ -0,0 +1,34 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose; + +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; +import net.codingarea.challenges.plugin.utils.misc.MapUtils; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; + +import java.util.LinkedHashMap; + +public class SubSettingChooseMultipleMenuGenerator extends CustomChooseMultipleItemMenuGenerator { + + private final IParentCustomGenerator parent; + private final String key; + + public SubSettingChooseMultipleMenuGenerator(@NotNull String key, @NotNull IParentCustomGenerator parent, + @NotNull LinkedHashMap items, @NotNull LocalizableMessage title) { + super(title, items); + this.key = key; + this.parent = parent; + } + + @Override + public void onItemClick(@NotNull Player player, @NotNull String[] keys) { + parent.accept(player, null, MapUtils.createStringArrayMap(key, keys)); + } + + @Override + protected void handleNavigateOutOfMenu(@NotNull Player player) { + parent.decline(player); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingValueMenuGenerator.java similarity index 53% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingValueMenuGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingValueMenuGenerator.java index f6c8bf67f..072abfe55 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingValueMenuGenerator.java @@ -1,42 +1,36 @@ -package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.ValueMenuGenerator; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; -public class SubSettingValueMenuGenerator extends ValueMenuGenerator { +public class SubSettingValueMenuGenerator extends CustomChooseValueMenuGenerator { private final IParentCustomGenerator parent; - private final String title; - public SubSettingValueMenuGenerator(IParentCustomGenerator parent, Map settings, String title) { - super(settings); - this.title = title; + public SubSettingValueMenuGenerator(@NotNull IParentCustomGenerator parent, + @NotNull Map settings, @NotNull LocalizableMessage title) { + super(title, settings); this.parent = parent; } @Override - public String[] getSubTitles(int page) { - return new String[]{title}; - } - - @Override - public void onSaveItemClick(Player player) { - + public void onSaveItemClick(@NotNull Player player) { Map map = new HashMap<>(); for (Entry entry : getSettings().entrySet()) { map.put(entry.getKey().getKey(), new String[]{entry.getValue()}); } - parent.accept(player, null, map); } @Override - public void onBackToMenuItemClick(Player player) { + protected void handleNavigateOutOfMenu(@NotNull Player player) { parent.decline(player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseItemGenerator.java deleted file mode 100644 index e09288748..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseItemGenerator.java +++ /dev/null @@ -1,123 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.legacy; - -import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; -import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.MainCustomMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.position.LegacyGeneratorMenuPosition; -import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -import java.util.LinkedHashMap; - -public abstract class ChooseItemGenerator extends MultiPageMenuGenerator { - - private final LinkedHashMap items; - - public ChooseItemGenerator(LinkedHashMap items) { - this.items = items; - } - - private static int getNextMiddleSlot(int currentSlot) { - if (currentSlot >= 53) return currentSlot; - if (isSideSlot(currentSlot)) return getNextMiddleSlot(currentSlot + 1); - return currentSlot; - } - - private static boolean isSideSlot(int slot) { - return slot % 9 == 0 || slot % 9 == 8; - } - - private static boolean isTopOrBottomSlot(int slot) { - return slot < 9 || slot > 35; - } - - @Override - public MenuPosition createMenuPosition(int page) { - return new LegacyGeneratorMenuPosition(this, page) { - - @Override - public void handleClick(@NotNull MenuClickInfo info) { - - if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { - return; - } - - int slot = info.getSlot(); - int index = getItemsPerPage() * page + slot - 10; - - if (slot > 18) index -= 2; - if (slot > 27) index -= 2; - - if (index >= items.size()) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - String[] array = items.keySet().toArray(new String[0]); - - if (isSideSlot(slot) || isTopOrBottomSlot(slot)) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - String itemKey = array[index]; - - onItemClick(info.getPlayer(), itemKey); - SoundSample.PLOP.play(info.getPlayer()); - - } - }; - } - - @Override - public int getSize() { - return 5 * 9; - } - - @Override - public int getPagesCount() { - return (int) Math.ceil((float) items.size() / getItemsPerPage()); - } - - public int getItemsPerPage() { - return 3 * 7; - } - - @Override - public void generatePage(@NotNull Inventory inventory, int page) { - - int lastSlot = 10; - int startIndex = getItemsPerPage() * page; - for (int i = startIndex; i < startIndex + getItemsPerPage() && i < items.size(); i++) { - String key = items.keySet().toArray(new String[0])[i]; - ItemStack itemStack = items.get(key); - lastSlot = getNextMiddleSlot(lastSlot); - inventory.setItem(lastSlot, itemStack); - lastSlot++; - } - - } - - @Override - public int[] getNavigationSlots(int page) { - return MainCustomMenuGenerator.NAVIGATION_SLOTS; - } - - @Override - protected String getTitle(int page) { - return InventoryTitleManager.getTitle(MenuType.CUSTOM, getSubTitles(page)); - } - - public abstract String[] getSubTitles(int page); - - public abstract void onItemClick(Player player, String itemKey); - - public abstract void onBackToMenuItemClick(Player player); - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseMultipleItemGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseMultipleItemGenerator.java deleted file mode 100644 index fb1ae68ec..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChooseMultipleItemGenerator.java +++ /dev/null @@ -1,154 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.legacy; - -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; -import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.custom.MainCustomMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.position.LegacyGeneratorMenuPosition; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; -import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; - -public abstract class ChooseMultipleItemGenerator extends MultiPageMenuGenerator { - - public static final int FINISH_SLOT = 40; - - private final LinkedHashMap items; - private final List selectedKeys; - - public ChooseMultipleItemGenerator(LinkedHashMap items) { - this.items = items; - selectedKeys = new LinkedList<>(); - } - - private static int getNextMiddleSlot(int currentSlot) { - if (currentSlot >= 53) return currentSlot; - if (isSideSlot(currentSlot)) return getNextMiddleSlot(currentSlot + 1); - return currentSlot; - } - - private static boolean isSideSlot(int slot) { - return slot % 9 == 0 || slot % 9 == 8; - } - - private static boolean isTopOrBottomSlot(int slot) { - return slot < 9 || slot > 35; - } - - @Override - public MenuPosition createMenuPosition(int page) { - return new LegacyGeneratorMenuPosition(this, page) { - - @Override - public void handleClick(@NotNull MenuClickInfo info) { - - if (info.getSlot() == FINISH_SLOT) { - onItemClick(info.getPlayer(), selectedKeys.toArray(new String[0])); - SoundSample.PLOP.play(info.getPlayer()); - return; - } - - if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { - return; - } - - int slot = info.getSlot(); - int index = getItemsPerPage() * page + slot - 10; - - if (slot > 18) index -= 2; - if (slot > 27) index -= 2; - - if (index >= items.size()) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - String[] array = items.keySet().toArray(new String[0]); - - if (isSideSlot(slot) || isTopOrBottomSlot(slot)) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - String itemKey = array[index]; - - if (selectedKeys.contains(itemKey)) { - selectedKeys.remove(itemKey); - } else { - selectedKeys.add(itemKey); - } - generatePage(info.getInventory(), page); - SoundSample.LOW_PLOP.play(info.getPlayer()); - } - }; - } - - @Override - public int getSize() { - return 5 * 9; - } - - @Override - public int getPagesCount() { - return (items.size() / getItemsPerPage()) + 1; - } - - public int getItemsPerPage() { - return 3 * 7; - } - - @Override - public void generatePage(@NotNull Inventory inventory, int page) { - - int lastSlot = 10; - int startIndex = getItemsPerPage() * page; - for (int i = startIndex; i < startIndex + getItemsPerPage() && i < items.size(); i++) { - String key = items.keySet().toArray(new String[0])[i]; - LegacyItemBuilder itemBuilder = new LegacyItemBuilder(items.get(key)).clone(); - itemBuilder.hideAttributes(); - - if (selectedKeys.contains(key)) { - itemBuilder.addEnchantment(MinecraftNameWrapper.UNBREAKING, 1); - itemBuilder.appendName(" §8┃ §2§l✔"); - } else { - itemBuilder.appendName(" §8┃ §c✖"); - } - - lastSlot = getNextMiddleSlot(lastSlot); - inventory.setItem(lastSlot, itemBuilder.build()); - lastSlot++; - } - - inventory.setItem(FINISH_SLOT, DefaultItem.create(Material.LIME_DYE, Message.forName("custom-sub-finish")).build()); - } - - @Override - public int[] getNavigationSlots(int page) { - return MainCustomMenuGenerator.NAVIGATION_SLOTS; - } - - @Override - protected String getTitle(int page) { - return InventoryTitleManager.getTitle(MenuType.CUSTOM, getSubTitles(page)); - } - - public abstract String[] getSubTitles(int page); - - public abstract void onItemClick(Player player, String[] itemKeys); - - public abstract void onBackToMenuItemClick(Player player); - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ValueMenuGenerator.java deleted file mode 100644 index 68fb22c2e..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ValueMenuGenerator.java +++ /dev/null @@ -1,120 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.legacy; - -import lombok.Getter; -import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; -import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.position.LegacyGeneratorMenuPosition; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.jetbrains.annotations.NotNull; - -import java.util.Map; - -@Getter -public abstract class ValueMenuGenerator extends MultiPageMenuGenerator { - - public static final int FINISH_SLOT = 31; - - private final Map settings; - - public ValueMenuGenerator(Map settings) { - this.settings = settings; - } - - @Override - public MenuPosition createMenuPosition(int page) { - return new LegacyGeneratorMenuPosition(this, page) { - - @Override - public void handleClick(@NotNull MenuClickInfo info) { - - if (info.getSlot() == FINISH_SLOT) { - onSaveItemClick(info.getPlayer()); - SoundSample.PLOP.play(info.getPlayer()); - return; - } - - if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onBackToMenuItemClick(info.getPlayer()))) { - return; - } - - int slot = info.getSlot(); - - int index = getItemsPerPage() * page + slot - 10; - - if (slot > 18) index -= 9; - - if (index >= settings.size() || index < 0) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - ValueSetting[] array = settings.keySet().toArray(new ValueSetting[0]); - - ValueSetting key = array[index]; - String oldValue = settings.get(key); - - int itemIndex = slot >= 18 ? 1 : 0; - String newValue = key.onClick(info, oldValue, itemIndex); - settings.put(key, newValue); - SoundSample.CLICK.play(info.getPlayer()); - generatePage(info.getInventory(), page); - open(info.getPlayer(), page); - } - }; - } - - @Override - public int getSize() { - return 4 * 9; - } - - @Override - public int getPagesCount() { - return (settings.size() / getItemsPerPage()) + 1; - } - - public int getItemsPerPage() { - return 4; - } - - @Override - public void generatePage(@NotNull Inventory inventory, int page) { - - int startIndex = getItemsPerPage() * page; - for (int i = startIndex; i < startIndex + getItemsPerPage() && i < settings.size(); i++) { - int slot = i - (getItemsPerPage() * page) + 10; - ValueSetting key = settings.keySet().toArray(new ValueSetting[0])[i]; - String value = settings.get(key); - inventory.setItem(slot, key.getDisplayItem(value).build()); - inventory.setItem(slot + 9, key.getSettingsItem(value).build()); - } - - inventory.setItem(FINISH_SLOT, DefaultItem.create(Material.LIME_DYE, Message.forName("custom-sub-finish")).build()); - } - - @Override - public int[] getNavigationSlots(int page) { - return new int[]{27, 35}; - } - - @Override - protected String getTitle(int page) { - return InventoryTitleManager.getTitle(MenuType.CUSTOM, getSubTitles(page)); - } - - public abstract String[] getSubTitles(int page); - - public abstract void onSaveItemClick(Player player); - - public abstract void onBackToMenuItemClick(Player player); - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/CustomMainSettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/CustomMainSettingsMenuGenerator.java deleted file mode 100644 index 8c40e6967..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/CustomMainSettingsMenuGenerator.java +++ /dev/null @@ -1,92 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; - -import lombok.Getter; -import net.codingarea.challenges.plugin.challenges.custom.settings.IChallengeSetting; -import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; -import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChooseItemGenerator; -import net.codingarea.challenges.plugin.utils.misc.MapUtils; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.jspecify.annotations.NonNull; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.function.Function; - -public class CustomMainSettingsMenuGenerator extends ChooseItemGenerator implements IParentCustomGenerator { - - @Getter - private final IParentCustomGenerator parent; - private final SettingType type; - private final String title; - private final String key; - private final Function instanceGetter; - private IChallengeSetting setting; - private SubSettingsBuilder subSettingsBuilder; - private Map subSettings; - - public CustomMainSettingsMenuGenerator(IParentCustomGenerator parent, SettingType type, String key, String title, LinkedHashMap items, Function instanceGetter) { - super(items); - this.parent = parent; - this.type = type; - this.title = title; - this.key = key; - this.instanceGetter = instanceGetter; - this.subSettings = new HashMap<>(); - } - - @Override - public String[] getSubTitles(int page) { - return new String[]{title}; - } - - @Override - public void accept(Player player, @NonNull SettingType type, @NonNull Map data) { - - subSettings.putAll(data); - - if (!openSubSettingsMenu(player)) { - parent.accept(player, this.type, subSettings); - } - - } - - @Override - public void onItemClick(Player player, String itemKey) { - this.setting = instanceGetter.apply(itemKey); - this.subSettingsBuilder = setting.getSubSettingsBuilder(); - - subSettings.put(key, new String[]{setting.getName()}); - - if (!openSubSettingsMenu(player)) { - parent.accept(player, type, subSettings); - } - - } - - private boolean openSubSettingsMenu(Player player) { - - if (subSettingsBuilder != null && subSettingsBuilder.hasSettings()) { - subSettingsBuilder.open(player, this, title); - subSettingsBuilder = subSettingsBuilder.getChild(); - - return true; - } - return false; - } - - @Override - public void onBackToMenuItemClick(Player player) { - parent.decline(player); - } - - @Override - public void decline(Player player) { - if (setting != null) - this.subSettings = MapUtils.createStringArrayMap(key, setting.getName()); - open(player, 0); - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/InfoMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/InfoMenuGenerator.java deleted file mode 100644 index 455c19d43..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/InfoMenuGenerator.java +++ /dev/null @@ -1,312 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; - -import lombok.Getter; -import lombok.ToString; -import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; -import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; -import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; -import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; -import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChallengeMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; -import net.codingarea.challenges.plugin.spigot.listener.ChatInputListener; -import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; -import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; -import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.challenges.plugin.utils.misc.InventoryUtils.InventorySetter; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import net.codingarea.commons.common.collection.IRandom; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.Sound; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; - -import java.util.*; - -@ToString -@Deprecated -public class InfoMenuGenerator extends MenuGenerator implements IParentCustomGenerator { - - public static final int DELETE_SLOT = 19 + 9, SAVE_SLOT = 25 + 9, CONDITION_SLOT = 21 + 9, ACTION_SLOT = 23 + 9, MATERIAL_SLOT = 14, NAME_SLOT = 12; - - private static final Material[] defaultMaterials; - private static final boolean savePlayerChallenges; - - static { - savePlayerChallenges = Challenges.getInstance().getConfigDocument().getBoolean("save-player_challenges"); - ArrayList list = new ArrayList<>(Arrays.asList(ExperimentalUtils.getMaterials())); - list.removeIf(material1 -> !material1.isItem()); - defaultMaterials = list.toArray(new Material[0]); - } - - private final UUID uuid; - private String name; - private Material material; - private ChallengeTrigger trigger; - private Map subTriggers; - private ChallengeAction action; - private Map subActions; - private Inventory inventory; - - public InfoMenuGenerator(CustomChallenge customChallenge) { - this.uuid = customChallenge.getUniqueId(); - this.material = customChallenge.getMaterial(); - this.name = customChallenge.getDisplayName(); - this.trigger = customChallenge.getTrigger(); - this.subTriggers = customChallenge.getSubTriggers(); - this.action = customChallenge.getAction(); - this.subActions = customChallenge.getSubActions(); - } - - /** - * Default Settings for new Custom Challenges - */ - public InfoMenuGenerator() { - this.trigger = null; - this.action = null; - this.subTriggers = new HashMap<>(); - this.subActions = new HashMap<>(); - this.uuid = UUID.randomUUID(); - this.material = IRandom.threadLocal().choose(defaultMaterials); - this.name = "§7Custom §e#" + - (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() + 1); - } - - public static List getSubSettingsDisplay(SubSettingsBuilder builder, Map activated) { - List display = new LinkedList<>(); - for (SubSettingsBuilder child : builder.getAllChildren()) { - display.addAll(child.getDisplay(activated)); - } - return display; - } - - @Override - public void generateInventories() { - inventory = Bukkit.createInventory(MenuPosition.HOLDER, 6 * 9, InventoryTitleManager.getTitle(MenuType.CUSTOM, "Info")); - InventoryUtils.fillInventory(inventory, LegacyItemBuilder.FILL_ITEM); - - updateItems(); - - InventoryUtils.setNavigationItems(inventory, new int[]{36 + 9}, true, InventorySetter.INVENTORY, 0, 1); - } - - public void updateItems() { - String currently = Message.forName("custom-info-currently").asString(); - String none = Message.forName("none").asString(); - - // Save / Delete Item - inventory.setItem(DELETE_SLOT, new LegacyItemBuilder(Material.BARRIER, Message.forName("item-custom-info-delete")).build()); - inventory.setItem(SAVE_SLOT, new LegacyItemBuilder(Material.LIME_DYE, Message.forName("item-custom-info-save")).build()); - - // Trigger Item - LegacyItemBuilder triggerItem = new LegacyItemBuilder(Material.WITHER_SKELETON_SKULL, - Message.forName("item-custom-info-trigger")) - .appendLore( - currently + (trigger != null ? Message.forName(trigger.getMessage()) : none)); - if (trigger != null) { - triggerItem.appendLore(getSubSettingsDisplay(trigger.getSubSettingsBuilder(), subTriggers)); - } - inventory.setItem(CONDITION_SLOT, triggerItem.build()); - - // Action Item - LegacyItemBuilder actionItem = new LegacyItemBuilder(Material.NETHER_STAR, - Message.forName("item-custom-info-action")) - .appendLore(currently + (action != null ? Message.forName(action.getMessage()) : none)); - if (action != null) { - actionItem.appendLore(getSubSettingsDisplay(action.getSubSettingsBuilder(), subActions)); - } - inventory.setItem(ACTION_SLOT, actionItem.build()); - - // Display Item - inventory.setItem(MATERIAL_SLOT, new LegacyItemBuilder(material == null ? Material.BARRIER : material, Message.forName("item-custom-info-material")) - .appendLore(currently + (material != null ? BukkitStringUtils.getItemName(material).toPlainText() : none)).build()); - - // Name Item - inventory.setItem(NAME_SLOT, new LegacyItemBuilder(Material.NAME_TAG, Message.forName("item-custom-info-name")) - .appendLore(currently + "§7" + name).build()); - } - - @Override - public List getInventories() { - return Collections.singletonList(inventory); - } - - @Override - public MenuPosition createMenuPosition(int page) { - return new InfoMenuPosition(page, this); - } - - @Override - public void open(@NotNull Player player, int page) { - if (inventory == null) generateInventories(); - super.open(player, page); - } - - @Override - public void accept(Player player, @NonNull SettingType type, @NonNull Map data) { - open(player, 0); - - switch (type) { - case CONDITION: - trigger = Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(data.remove("trigger")[0]); - this.subTriggers = data; - break; - - case ACTION: - action = Challenges.getInstance().getCustomSettingsLoader().getActionByName(data.remove("action")[0]); - this.subActions = data; - break; - - case MATERIAL: - material = Material.valueOf(data.remove("material")[0]); - updateItems(); - break; - } - - updateItems(); - } - - public void setName(String name) { - this.name = name; - updateItems(); - } - - @Override - public void decline(Player player) { - open(player, 0); - } - - public CustomChallenge save() { - return Challenges.getInstance().getCustomChallengesLoader().registerCustomChallenge(uuid, material, name, - trigger, subTriggers, action, subActions, true); - } - - public void openChallengeMenu(Player player) { - CustomChallenge challenge = Challenges.getInstance().getCustomChallengesLoader() - .getCustomChallenges().get(uuid); - if (challenge == null) { - Challenges.getInstance().getMenuManager().openMenu(player, MenuType.CUSTOM, 0); - } else { - ChallengeMenuGenerator menuGenerator = (ChallengeMenuGenerator) MenuType.CUSTOM.getMenuGenerator(); - int page = menuGenerator.getPageOfChallenge(challenge) + 1; // +1 because the main and challenge menu are in the same generator - Challenges.getInstance().getMenuManager().openMenu(player, MenuType.CUSTOM, page); - } - } - - public class InfoMenuPosition implements MenuPosition { - - private final int page; - @Getter - private final InfoMenuGenerator generator; - - public InfoMenuPosition(int page, InfoMenuGenerator generator) { - this.page = page; - this.generator = generator; - } - - @Override - public void handleClick(@NotNull MenuClickInfo info) { - if (InventoryUtils.handleNavigationClicking(generator, new int[]{36 + 9}, page, info, () -> Challenges.getInstance().getMenuManager().openMenu(info.getPlayer(), MenuType.CUSTOM, 0))) { - return; - } - - if (ChallengeMenuGenerator.playNoPermissionsEffect(info.getPlayer())) { - info.getPlayer().closeInventory(); - return; - } - - Player player = info.getPlayer(); - - switch (info.getSlot()) { - case DELETE_SLOT: - if (!Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().containsKey(uuid)) { - MessageKey.of("custom-not-deleted").send(player, Prefix.CUSTOM); - SoundSample.BASS_OFF.play(player); - break; - } - openChallengeMenu(player); - Challenges.getInstance().getCustomChallengesLoader().unregisterCustomChallenge(uuid); - new SoundSample().addSound(Sound.ENTITY_WITHER_BREAK_BLOCK, 0.4f).play(player); - break; - case SAVE_SLOT: - - String defaults = new InfoMenuGenerator().toString(); - String current = InfoMenuGenerator.this.toString(); - if (defaults.equals(current)) { - MessageKey.of("custom-no-changes").send(player, Prefix.CUSTOM); - SoundSample.BASS_OFF.play(player); - return; - } - - save(); - openChallengeMenu(player); - MessageKey.of("custom-saved").send(player, Prefix.CUSTOM); - if (savePlayerChallenges) { - MessageKey.of("custom-saved-db").send(player, Prefix.CUSTOM); - } - SoundSample.LEVEL_UP.play(player); - break; - case CONDITION_SLOT: - new CustomMainSettingsMenuGenerator(generator, SettingType.CONDITION, - "trigger", Message.forName("custom-title-trigger").asString(), - ChallengeTrigger.getMenuItems(), - s -> Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(s)) - .open(player, 0); - SoundSample.CLICK.play(player); - break; - case ACTION_SLOT: - new CustomMainSettingsMenuGenerator(generator, SettingType.ACTION, - "action", Message.forName("custom-title-action").asString(), - ChallengeAction.getMenuItems(), - s -> Challenges.getInstance().getCustomSettingsLoader().getActionByName(s)) - .open(player, 0); - SoundSample.CLICK.play(player); - break; - case NAME_SLOT: - - MessageKey.of("custom-name-info").send(player, Prefix.CUSTOM); - player.closeInventory(); - - ChatInputListener.setInputAction(player, event -> { - int maxNameLength = Challenges.getInstance().getCustomChallengesLoader() - .getMaxNameLength(); - if (event.getMessage().length() > maxNameLength) { - MessageKey.of("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxNameLength); - return; - } - - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - setName(ChatColor.translateAlternateColorCodes('&', event.getMessage())); - open(event.getPlayer(), 0); - }); - - }); - - break; - case MATERIAL_SLOT: - MaterialMenuGenerator materialMenuGenerator = new MaterialMenuGenerator(generator); - materialMenuGenerator.open(player, 0); - SoundSample.CLICK.play(player); - break; - default: - SoundSample.CLICK.play(player); - break; - } - } - - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/MainCustomMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/MainCustomMenuGenerator.java deleted file mode 100644 index 5e26ca81e..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/MainCustomMenuGenerator.java +++ /dev/null @@ -1,110 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; - -import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; -import net.codingarea.challenges.plugin.challenges.type.IChallenge; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChallengeMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import org.bukkit.Material; -import org.bukkit.inventory.Inventory; -import org.jetbrains.annotations.NotNull; - -@Deprecated -public class MainCustomMenuGenerator extends ChallengeMenuGenerator { - - public static final int[] SLOTS = {10, 11, 12, 13, 14, 15, 16}; - public static final int[] NAVIGATION_SLOTS = {36, 44}; - public static final int SIZE = 5 * 9; - private static final int VIEW_SLOT = 21; - private static final int CREATE_SLOT = 23; - - private static final int maxCustomChallenges; - - static { - maxCustomChallenges = Challenges.getInstance().getConfigDocument().getInt("custom-challenge-settings.max-challenges"); - } - - public MainCustomMenuGenerator() { - super(1); - } - - @Override - protected String getTitle(int page) { - return page != 0 ? InventoryTitleManager.getTitle(getMenuType(), - Message.forName("custom-title-view").asString(), String.valueOf(page)) : - InventoryTitleManager.getTitle(getMenuType(), "Menu"); - } - - @Override - public void executeClickAction(@NotNull IChallenge challenge, @NotNull MenuClickInfo info, int itemIndex) { - if (itemIndex == 0 || itemIndex == 2) { - challenge.handleClick(new ChallengeMenuClickInfo(info, itemIndex == 0)); - } else if (challenge instanceof CustomChallenge) { - InfoMenuGenerator infoMenuGenerator = new InfoMenuGenerator((CustomChallenge) challenge); - infoMenuGenerator.open(info.getPlayer(), 0); - SoundSample.CLICK.play(info.getPlayer()); - } - } - - @Override - public void generatePage(@NotNull Inventory inventory, int page) { - if (page == 0) { - inventory.setItem(VIEW_SLOT, new LegacyItemBuilder(Material.BOOK, Message.forName("custom-main-view-challenges")).build()); - inventory.setItem(CREATE_SLOT, new LegacyItemBuilder(Material.WRITABLE_BOOK, Message.forName("custom-main-create-challenge")).build()); - } - } - - @Override - public void onPreChallengePageClicking(@NotNull MenuClickInfo info, int page) { - if (info.getSlot() == VIEW_SLOT) { - if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().isEmpty()) { - MessageKey.of("custom-not-loaded").send(info.getPlayer(), Prefix.CUSTOM); - return; - } - open(info.getPlayer(), 1); - SoundSample.PLOP.play(info.getPlayer()); - } else if (info.getSlot() == CREATE_SLOT) { - if (ChallengeMenuGenerator.playNoPermissionsEffect(info.getPlayer())) { - return; - } - if (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() > maxCustomChallenges) { - MessageKey.of("custom-limit").send(info.getPlayer(), Prefix.CUSTOM, maxCustomChallenges); - SoundSample.BASS_OFF.play(info.getPlayer()); - return; - } - new InfoMenuGenerator().open(info.getPlayer(), 0); - SoundSample.PLING.play(info.getPlayer()); - } - } - - @Override - public void setSettingsItems(@NotNull Inventory inventory, @NotNull IChallenge challenge, int topSlot) { - inventory.setItem(getSlots()[topSlot], getDisplayItemBuilder(challenge).build()); - inventory.setItem(getSlots()[topSlot] + 9, DefaultItem.customize().build()); - inventory.setItem(getSlots()[topSlot] + 18, getSettingsItem(challenge)); - } - - @Override - public int[] getSlots() { - return SLOTS; - } - - @Override - public int getSize() { - return SIZE; - } - - @Override - public int[] getNavigationSlots(int page) { - return page == 0 ? new int[]{NAVIGATION_SLOTS[0]} : NAVIGATION_SLOTS; - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/MaterialMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/MaterialMenuGenerator.java deleted file mode 100644 index 8c8705f84..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/MaterialMenuGenerator.java +++ /dev/null @@ -1,51 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; - -import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChooseItemGenerator; -import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; -import net.codingarea.challenges.plugin.utils.misc.MapUtils; -import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import java.util.LinkedHashMap; - -@Deprecated -public class MaterialMenuGenerator extends ChooseItemGenerator { - - private final IParentCustomGenerator parent; - - public MaterialMenuGenerator(IParentCustomGenerator parent) { - super(createMaterialsMap()); - this.parent = parent; - } - - public static LinkedHashMap createMaterialsMap() { - LinkedHashMap map = new LinkedHashMap<>(); - - for (Material material : ExperimentalUtils.getMaterials()) { - if (BukkitReflectionUtils.isAir(material)) continue; - if (!material.isItem()) continue; - map.put(material.name(), new ItemStack(material)); - } - - return map; - } - - @Override - public String[] getSubTitles(int page) { - return new String[]{"Material"}; - } - - @Override - public void onItemClick(Player player, String itemKey) { - parent.accept(player, SettingType.MATERIAL, MapUtils.createStringArrayMap("material", itemKey)); - } - - @Override - public void onBackToMenuItemClick(Player player) { - parent.decline(player); - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingChooseMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingChooseMenuGenerator.java deleted file mode 100644 index 7604465d1..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingChooseMenuGenerator.java +++ /dev/null @@ -1,38 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; - -import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChooseItemGenerator; -import net.codingarea.challenges.plugin.utils.misc.MapUtils; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import java.util.LinkedHashMap; - -public class SubSettingChooseMenuGenerator extends ChooseItemGenerator { - - private final IParentCustomGenerator parent; - private final String key; - private final String title; - - public SubSettingChooseMenuGenerator(String key, IParentCustomGenerator parent, LinkedHashMap map, String title) { - super(map); - this.key = key; - this.title = title; - this.parent = parent; - } - - @Override - public String[] getSubTitles(int page) { - return new String[]{title}; - } - - @Override - public void onItemClick(Player player, String itemKey) { - parent.accept(player, null, MapUtils.createStringArrayMap(key, itemKey)); - } - - @Override - public void onBackToMenuItemClick(Player player) { - parent.decline(player); - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingChooseMultipleMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingChooseMultipleMenuGenerator.java deleted file mode 100644 index 734d40ede..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/custom/SubSettingChooseMultipleMenuGenerator.java +++ /dev/null @@ -1,38 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.legacy.custom; - -import net.codingarea.challenges.plugin.management.menu.generator.legacy.ChooseMultipleItemGenerator; -import net.codingarea.challenges.plugin.utils.misc.MapUtils; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import java.util.LinkedHashMap; - -public class SubSettingChooseMultipleMenuGenerator extends ChooseMultipleItemGenerator { - - private final IParentCustomGenerator parent; - private final String key; - private final String title; - - public SubSettingChooseMultipleMenuGenerator(String key, IParentCustomGenerator parent, LinkedHashMap map, String title) { - super(map); - this.key = key; - this.title = title; - this.parent = parent; - } - - @Override - public String[] getSubTitles(int page) { - return new String[]{title}; - } - - @Override - public void onItemClick(Player player, String[] itemKeys) { - parent.accept(player, null, MapUtils.createStringArrayMap(key, itemKeys)); - } - - @Override - public void onBackToMenuItemClick(Player player) { - parent.decline(player); - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java index 8eaf942ff..0dc640aad 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java @@ -2,10 +2,12 @@ import lombok.AccessLevel; import lombok.NoArgsConstructor; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import java.util.Locale; @@ -22,34 +24,49 @@ public static final class SkullTextures { RED_ARROW_DOWN = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTM4NTJiZjYxNmYzMWVkNjdjMzdkZTRiMGJhYTJjNWY4ZDhmY2E4MmU3MmRiY2FmY2JhNjY5NTZhODFjNCJ9fX0="; } + @Contract("_ -> new") public static ItemBuilder createNavigateNext(@NotNull Locale locale) { return new ItemBuilder.SkullBuilder(locale, MessageKey.of("navigate-next")).setBase64Texture(DefaultItem.SkullTextures.ARROW_RIGHT); } + @Contract("_ -> new") public static ItemBuilder createNavigateBack(@NotNull Locale locale) { return new ItemBuilder.SkullBuilder(locale, MessageKey.of("navigate-back")).setBase64Texture(SkullTextures.ARROW_LEFT); } + @Contract("_ -> new") public static ItemBuilder createNavigateBackMainMenu(@NotNull Locale locale) { return new ItemBuilder(locale, Material.DARK_OAK_DOOR, MessageKey.of("navigate-back")); } + @Contract("_, _, _, _ -> new") + public static ItemBuilder createChallengeDisplayFormat(@NotNull ItemStack displayItemPreset, @NotNull LocalizableMessage name, + @NotNull LocalizableMessage desc, @NotNull Locale locale) { + return new ItemBuilder(locale, displayItemPreset, MessageKey.of("challenge.display-format"), + name, desc); + } + + @Contract("-> new") public static ItemStack createEnabledPreset() { return new ItemStack(Material.LIME_DYE); } + @Contract("_ -> new") public static ItemStack createEnabledValuePreset(int amount) { return new ItemStack(Material.LIME_DYE, amount); } + @Contract("-> new") public static ItemStack createDisabledPreset() { return new ItemStack(MinecraftNameWrapper.RED_DYE); } + @Contract("_ -> new") public static ItemStack createValuePreset(int value) { return new ItemStack(Material.STONE_BUTTON, Math.max(value, 1)); } + @Contract("-> new") public static ItemStack createCustomizePreset() { return new ItemStack(MinecraftNameWrapper.SIGN); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index 550d69458..db115c0de 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -106,16 +106,8 @@ public ItemBuilder setLore(@NotNull MessageKey key, @NotNull Object... args) { @NotNull public ItemBuilder appendLore(@NotNull MessageKey key, @NotNull Object... args) { - ItemMeta meta = getItemMeta(); - List existingLore = meta.lore(); List loreComponents = key.asComponents(locale, args); - if (existingLore == null) { - meta.lore(loreComponents); - return this; - } - - existingLore.addAll(loreComponents); // modifiable copy - meta.lore(existingLore); + addToLore(loreComponents); return this; } @@ -125,21 +117,20 @@ public ItemBuilder appendLore(@NotNull LocalizableMessage localizable) { } @NotNull - public ItemBuilder appendLoreWithEmptyLine(@NotNull MessageKey key, @NotNull Object... args) { + public ItemBuilder appendBlankLoreLine() { + addToLore(List.of(Component.space())); + return this; + } + + protected void addToLore(@NotNull Collection components) { ItemMeta meta = getItemMeta(); - List lore = meta.lore(); - if (lore != null) { - lore.add(Component.empty()); + List existingLore = meta.lore(); + if (existingLore != null) { + existingLore.addAll(components); + meta.lore(existingLore); } else { - meta.lore(List.of(Component.empty())); + meta.lore(List.copyOf(components)); } - - return this.appendLore(key, args); - } - - @NotNull - public ItemBuilder appendLoreWithEmptyLine(@NotNull LocalizableMessage localizable) { - return this.appendLoreWithEmptyLine(localizable.getLocalizableKey(), localizable.getLocalizableArgs()); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java index 6ad64ff3e..463c74379 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java @@ -24,11 +24,17 @@ private Holder() { InventoryHolder HOLDER = new MenuPositionHolder(); static void set(@NotNull Player player, @Nullable MenuPosition position) { - Holder.positions.put(player, position); + MenuPosition prev = Holder.positions.put(player, position); + if (prev != null) { + prev.handleClose(player); + } } static void remove(@NotNull Player player) { - Holder.positions.remove(player); + MenuPosition prev = Holder.positions.remove(player); + if (prev != null) { + prev.handleClose(player); + } } @Nullable @@ -42,4 +48,7 @@ static void setEmpty(@NotNull Player player) { void handleClick(@NotNull MenuClickInfo info); + default void handleClose(@NotNull Player player) { + } + } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java index e22f3e413..14de90f78 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java @@ -42,7 +42,7 @@ public void onClick(@NotNull InventoryClickEvent event) { @EventHandler(priority = EventPriority.LOW) public void onClose(@NotNull InventoryCloseEvent event) { if (!(event.getPlayer() instanceof Player player)) return; - if (event.getReason() == InventoryCloseEvent.Reason.OPEN_NEW) return; + if (event.getReason() == InventoryCloseEvent.Reason.OPEN_NEW) return; // New menu inventory if (event.getInventory().getHolder() != MenuPosition.HOLDER) return; // No menu inventory MenuPosition.remove(player); } From b7ff68ea169c7ef005a6d9ffd52157d063b6c980 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Wed, 8 Jul 2026 01:13:16 +0200 Subject: [PATCH 103/119] refactor: minor cleanup --- .../setting/DifficultySetting.java | 4 +- .../utils/item/StandardItemBuilder.java | 3 +- .../bukkit/utils/menu/MenuClickInfo.java | 42 ++++--------------- 3 files changed, 12 insertions(+), 37 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java index 1c18390e4..7d28de2a0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java @@ -38,8 +38,8 @@ public DifficultySetting() { @Override public ItemStack getSettingsItemPreset() { return switch (getDifficultyByValue(getValue())) { - case PEACEFUL -> new ItemStack(Material.LIME_DYE); - case EASY -> new ItemStack(MinecraftNameWrapper.GREEN_DYE); + case PEACEFUL -> new ItemStack(MinecraftNameWrapper.GREEN_DYE); + case EASY -> new ItemStack(Material.LIME_DYE); case NORMAL -> new ItemStack(Material.ORANGE_DYE); case HARD -> new ItemStack(MinecraftNameWrapper.RED_DYE); }; diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/StandardItemBuilder.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/StandardItemBuilder.java index 418044534..9142e5f9f 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/StandardItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/StandardItemBuilder.java @@ -34,7 +34,8 @@ public class StandardItemBuilder { protected ItemMeta meta; public StandardItemBuilder(@NotNull ItemStack item) { - this(item, item.getItemMeta()); + ItemStack cloned = item.clone(); + this(cloned, cloned.getItemMeta()); } public StandardItemBuilder(@NotNull ItemStack item, @Nullable ItemMeta meta) { diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java index 5b172a784..487c5cea6 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuClickInfo.java @@ -1,5 +1,8 @@ package net.codingarea.commons.bukkit.utils.menu; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.ToString; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; @@ -7,6 +10,9 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +@Getter +@ToString +@EqualsAndHashCode public class MenuClickInfo { protected final Player player; @@ -23,32 +29,10 @@ public MenuClickInfo(@NotNull Player player, @NotNull Inventory inventory, boole this.slot = slot; } - @NotNull - public Player getPlayer() { - return player; - } - - @NotNull - public Inventory getInventory() { - return inventory; - } - - public boolean isRightClick() { - return rightClick; - } - public boolean isLeftClick() { return !rightClick; } - public boolean isShiftClick() { - return shiftClick; - } - - public int getSlot() { - return slot; - } - @Nullable public ItemStack getClickedItem() { return inventory.getItem(slot); @@ -56,18 +40,8 @@ public ItemStack getClickedItem() { @NotNull public Material getClickedMaterial() { - return getClickedItem() == null ? Material.AIR : getClickedItem().getType(); - } - - @Override - public String toString() { - return "MenuClickInfo{" + - "player=" + player + - ", inventory=" + inventory + - ", shiftClick=" + shiftClick + - ", rightClick=" + rightClick + - ", slot=" + slot + - '}'; + ItemStack item = getClickedItem(); + return item == null ? Material.AIR : item.getType(); } } From fc2837a503094e0730eafe4b101a88740595fc6b Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Fri, 10 Jul 2026 00:08:54 +0200 Subject: [PATCH 104/119] refactor: migrate custom menu generators (part 3) --- language/locales/de.json | 60 ++-- language/locales/global.json | 18 +- .../challenges/custom/CustomChallenge.java | 3 +- .../custom/settings/ChallengeSetting.java | 11 + .../custom/settings/IChallengeSetting.java | 7 +- .../settings/action/ChallengeAction.java | 10 +- .../settings/action/EntityTargetAction.java | 3 +- .../action/impl/DamageEntityAction.java | 9 +- .../action/impl/HealEntityAction.java | 17 +- .../action/impl/HungerPlayerAction.java | 10 +- .../custom/settings/sub/SelectableKey.java | 89 +++++ .../settings/sub/SubSettingsBuilder.java | 42 +-- .../builder/ChooseItemSubSettingsBuilder.java | 47 +-- .../ChooseMultipleItemSubSettingBuilder.java | 65 +--- .../sub/builder/EmptySubSettingsBuilder.java | 9 +- .../builder/GeneratorSubSettingsBuilder.java | 2 +- .../builder/TextInputSubSettingsBuilder.java | 25 +- .../sub/builder/ValueSubSettingsBuilder.java | 34 +- .../settings/trigger/ChallengeTrigger.java | 14 +- .../trigger/impl/ConsumeItemTrigger.java | 6 +- .../trigger/impl/EntityDamageTrigger.java | 19 +- .../trigger/impl/InLiquidTrigger.java | 8 +- .../trigger/impl/IntervallTrigger.java | 28 +- .../impl/StandsOnSpecificBlockTrigger.java | 5 +- .../goal/CollectAllItemsGoal.java | 12 +- .../setting/TopCommandSetting.java | 2 +- .../abstraction/FirstPlayerAtHeightGoal.java | 7 + .../type/abstraction/menu/MenuSetting.java | 2 +- .../type/helper/SubSettingsHelper.java | 71 ++-- .../content/i18n/LocalizableMessage.java | 69 +++- .../plugin/content/i18n/MessageHolder.java | 11 +- .../plugin/content/i18n/MessageKey.java | 19 +- .../content/i18n/impl/JoinedMessageImpl.java | 52 --- .../i18n/impl/LocalizableMessageImpl.java | 7 + .../content/i18n/impl/MessageKeyImpl.java | 22 +- .../DynamicMessageImpl.java} | 17 +- .../i18n/impl/dynamic/JoinedMessageImpl.java | 74 ++++ .../impl/dynamic/WrappedObjMessageImpl.java | 56 +++ .../i18n/impl/format/ComponentArguments.java | 22 +- .../i18n/impl/format/ComponentFormatter.java | 2 +- .../i18n/impl/format/ComponentSplitter.java | 193 +++++++--- .../i18n/impl/format/ComponentSprites.java | 40 --- .../content/i18n/impl/format/ItemSprites.java | 333 ++++++++++++++++++ .../menu/generator/AbstractMenuGenerator.java | 1 - ...UncachedMultiPageSelectMenuGenerator.java} | 16 +- .../custom/CustomChallengeMenuGenerator.java | 14 +- .../choose/CustomChooseItemMenuGenerator.java | 104 ------ .../CustomChooseMaterialMenuGenerator.java | 8 +- ...CustomChooseMultipleItemMenuGenerator.java | 125 ------- ...tomChooseMultipleOptionsMenuGenerator.java | 93 +++++ .../CustomChooseOptionMenuGenerator.java | 57 +++ .../CustomChooseValueMenuGenerator.java | 11 +- .../CustomMainSettingsMenuGenerator.java | 11 +- .../choose/SubSettingChooseMenuGenerator.java | 6 +- ...SubSettingChooseMultipleMenuGenerator.java | 10 +- .../server/scoreboard/ChallengeActionBar.java | 4 +- .../scoreboard/ChallengeScoreboard.java | 2 +- .../spigot/command/SkipTimerCommand.java | 2 + .../plugin/utils/item/DefaultItem.java | 1 + .../plugin/utils/item/DefaultItems.java | 5 + .../plugin/utils/item/ItemBuilder.java | 25 +- .../commons/bukkit/utils/item/ItemUtils.java | 6 +- 62 files changed, 1296 insertions(+), 757 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/JoinedMessageImpl.java rename plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/{DynamicLocalizableMessageImpl.java => dynamic/DynamicMessageImpl.java} (68%) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/JoinedMessageImpl.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/WrappedObjMessageImpl.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSprites.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ItemSprites.java rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/{UncachedMultiPageMenuGenerator.java => UncachedMultiPageSelectMenuGenerator.java} (96%) delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseItemMenuGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleItemMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleOptionsMenuGenerator.java create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseOptionMenuGenerator.java rename plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/{ => choose}/CustomMainSettingsMenuGenerator.java (92%) diff --git a/language/locales/de.json b/language/locales/de.json index 13acd432c..5454c2b34 100644 --- a/language/locales/de.json +++ b/language/locales/de.json @@ -130,9 +130,9 @@ "custom": { "name": "Individuelle Challenges", "sub-name": "Individuell", - "selected-format": "Eingestellt {@symbol.circle} {0}", - "trigger-format": "Auslöser {@symbol.circle} {0}", - "action-format": "Aktion {@symbol.circle} {0}", + "selected-format": "{@subsetting-format('Eingestellt', '{0}')}", + "trigger-format": "{@subsetting-format('Auslöser', '{0}')}", + "action-format": "{@subsetting-format('Aktion', '{0}')}", "home": { "item-view": "{@item-format('Challenges ansehen')}", "item-create": "{@item-format('Neue Challenge erstellen')}" @@ -408,6 +408,12 @@ "*Spieler* sind durch die *Wand* sichtbar" ] }, + "no-hunger": { + "name": "*Kein Hunger*", + "desc": [ + "Du bekommst keinen *Hunger*" + ] + }, "no-item-damage": { "name": "*Kein Itemschaden*", "desc": [ @@ -459,6 +465,14 @@ "kannst du *sofort* wieder Schaden *bekommen*" ] }, + "top-command": { + "name": "*Top Command*", + "desc": [ + "Mit */top* kannst du dich", + "zur *Oberfläche* oder in", + "die *Overworld* teleportieren" + ] + }, "max-health": { "name": "*Maximale Herzen*", "desc": [ @@ -479,6 +493,20 @@ "das *Farmen* von Items *einfacher* machen" ] }, + "fortress-spawn": { + "name": "*Festungs Spawn*", + "desc": [ + "Wenn du in den *Nether* gehst,", + "spawnst du immer in einer *Festung*" + ] + }, + "bastion-spawn": { + "name": "*Bastions Spawn*", + "desc": [ + "Wenn du in den *Nether* gehst,", + "spawnst du immer in einer *Bastion*" + ] + }, "no-offhand": { "name": "*Keine Offhand*", "desc": [ @@ -1574,7 +1602,9 @@ "name": "*Alle Items*", "desc": [ "Finde *alle Items*, die es *in Minecraft gibt*" - ] + ], + "bossbar-current": "{@bossbar.format-arg('{3}{0}', '{1} / {2}')}", + "bossbar-finished": "{@bossbar.format('Alle Items gefunden')}" }, "damage-teleport": { "name": "*Schaden Random Teleport*", @@ -2031,8 +2061,6 @@ "quiz-verb-dropped": "gedropped", "quiz-verb-suffered": "erlitten", "bossbar-timer-paused": "» Der Timer ist pausiert", - "bossbar-all-items-current-max": "» {0} {1} / {2}", - "bossbar-all-items-finished": "» Alle Items gefunden", "bossbar-race-goal-info": "» Ziel X: {0} / Z: {1} {2} Blöcke", "bossbar-race-goal": "» Ziel X: {0} / Z: {1}", "bossbar-first-at-height-goal": "» Ziel Y: {0}", @@ -2151,28 +2179,8 @@ "Gebratenes Essen", "*Rohes Fleisch* wird direkt zu *gebratenem Fleisch*" ], - "no-hunger-setting": [ - "Kein Hunger", - "Du bekommst keinen *Hunger*" - ], "item-timber-setting-logs": "Baumstämme", "item-timber-setting-logs-and-leaves": "Baumstämme und Blätter", - "top-command-setting": [ - "Top Command", - "Mit */top* kannst du dich", - "zur *Oberfläche* oder in", - "die *Overworld* teleportieren" - ], - "item-fortress-spawn-setting": [ - "Festungs Spawn", - "Wenn du in den *Nether* gehst,", - "spawnst du immer in einer *Festung*" - ], - "item-bastion-spawn-setting": [ - "Bastions Spawn", - "Wenn du in den *Nether* gehst,", - "spawnst du immer in einer *Bastion*" - ], "item-regeneration-setting-not_natural": "Nicht natürlich", "menu-all-blocks-disappear-challenge-settings": "Alle Blöcke verschwinden", "item-all-blocks-disappear-break-challenge": [ diff --git a/language/locales/global.json b/language/locales/global.json index d55708bb7..949fb811e 100644 --- a/language/locales/global.json +++ b/language/locales/global.json @@ -19,9 +19,10 @@ "plus-minus": "±" }, "generic": { - "delimiter": ", " }, "arg-format": { + "delimiter": ", ", + "remaining": " +{0}", "hp": "{0} HP ({1} {@symbol.heart})", "hearts": "{0} {@symbol.heart}", "damage-cause": "{0}", @@ -96,7 +97,8 @@ "display": "{@name}" }, "custom": { - "display": "{@name}" + "display": "{@name}", + "subsetting-format": "{0} {@symbol.circle} {1}" } }, "category": { @@ -239,6 +241,9 @@ "glow": { "*colorize*": "{0}" }, + "no-hunger": { + "*colorize*": "{0}" + }, "no-item-damage": { "*colorize*": "{0}" }, @@ -263,6 +268,9 @@ "no-hit-delay": { "*colorize*": "{0}" }, + "top-command": { + "*colorize*": "{0}" + }, "max-health": { "*colorize*": "{0}" }, @@ -272,6 +280,12 @@ "cut-clean": { "*colorize*": "{0}" }, + "fortress-spawn": { + "*colorize*": "{0}" + }, + "bastion-spawn": { + "*colorize*": "{0}" + }, "no-offhand": { "*colorize*": "{0}" }, diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index 2c31051f0..abcdcb6c8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -80,7 +80,8 @@ public ItemBuilder getDisplayItem(@NotNull Locale locale) { // TODO // builder.appendLore(Message.forName("custom-info-action").asString() + " " + actionName); // builder.appendLore(actionDisplay); - item.appendBlankLoreLine().appendLore(MessageKey.of("menu.custom.action-format"), getAction().getSettingName()); + item.appendBlankLoreLine() + .appendLore(MessageKey.of("menu.custom.action-format"), getAction().getSettingName()); } return item; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java index f7d910679..df8f4a544 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java @@ -4,6 +4,7 @@ import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @@ -28,6 +29,10 @@ public ChallengeSetting(String name, Supplier builderSupplie this(name, builderSupplier.get()); } + @NotNull + public abstract Material getMaterial(); + + @NotNull public String getRelativeMessageKey() { return name.toLowerCase(); } @@ -38,6 +43,12 @@ public ItemBuilder getDisplayItem(@NotNull Locale locale) { return DefaultItems.createChallengeDisplayFormat(new ItemStack(getMaterial()), getSettingName(), getSettingDescription(), locale); } + @NotNull + @Override + public final String getKey() { + return this.getUniqueName(); + } + @NotNull @Override public SubSettingsBuilder getSubSettingsBuilder() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java index ddd13fd69..c8f68bb01 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/IChallengeSetting.java @@ -1,14 +1,14 @@ package net.codingarea.challenges.plugin.challenges.custom.settings; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import org.bukkit.Material; import org.jetbrains.annotations.NotNull; import java.util.Locale; -public interface IChallengeSetting { +public interface IChallengeSetting extends SelectableKey { @NotNull SubSettingsBuilder getSubSettingsBuilder(); @@ -16,9 +16,6 @@ public interface IChallengeSetting { @NotNull String getUniqueName(); - @NotNull - Material getMaterial(); - @NotNull ItemBuilder getDisplayItem(@NotNull Locale locale); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java index a10597f3f..0c5a79c8f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java @@ -2,13 +2,11 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeSetting; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.common.collection.IRandom; -import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.LinkedHashMap; @@ -31,11 +29,11 @@ public ChallengeAction(String name, Supplier builderSupplier super(name, builderSupplier); } - public static LinkedHashMap getMenuItems() { - LinkedHashMap map = new LinkedHashMap<>(); + public static LinkedHashMap getMenuItems() { + LinkedHashMap map = new LinkedHashMap<>(); for (ChallengeAction value : Challenges.getInstance().getCustomSettingsLoader().getActions().values()) { - map.put(value.getUniqueName(), value.getDisplayItem(Locale.GERMAN).build()); // TODO + map.put(value.getUniqueName(), value); } return map; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java index f57c55daf..1d9f2f915 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/EntityTargetAction.java @@ -6,8 +6,7 @@ public abstract class EntityTargetAction extends ChallengeAction implements IEntityTargetAction { - public EntityTargetAction(String name, - SubSettingsBuilder subSettingsBuilder) { + public EntityTargetAction(String name, SubSettingsBuilder subSettingsBuilder) { super(name, subSettingsBuilder); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java index e6434aade..31157213f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java @@ -1,12 +1,13 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; +import org.bukkit.inventory.ItemStack; import java.util.Map; @@ -14,10 +15,8 @@ public class DamageEntityAction extends EntityTargetAction { public DamageEntityAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createChooseItemChild("amount").fill(builder -> { - String prefix = DefaultItem.getItemPrefix(); for (int i = 1; i < 21; i++) { - builder.addSetting( - String.valueOf(i), new LegacyItemBuilder(Material.FERMENTED_SPIDER_EYE, prefix + "§7" + (i / 2f) + " §c❤").setAmount(i).build()); + builder.addSetting(SelectableKey.of(String.valueOf(i), new ItemStack(Material.FERMENTED_SPIDER_EYE, i), ArgumentFormat.HEARTS.apply(i))); } })); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java index 4018053ae..239073fdd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java @@ -1,26 +1,25 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; +import org.bukkit.inventory.ItemStack; import java.util.Map; public class HealEntityAction extends EntityTargetAction { public HealEntityAction(String name) { + // TODO centralize with DamageEntityAction / value chooser super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createChooseItemChild("amount").fill(builder -> { - String prefix = DefaultItem.getItemPrefix(); for (int i = 1; i < 21; i++) { - builder.addSetting( - String.valueOf(i), new LegacyItemBuilder( - MinecraftNameWrapper.RED_DYE, prefix + "§7" + (i / 2f) + " §c❤").setAmount(i).build()); + builder.addSetting(SelectableKey.of(String.valueOf(i), new ItemStack(Material.FERMENTED_SPIDER_EYE, i), ArgumentFormat.HEARTS.apply(i))); } })); } @@ -28,13 +27,11 @@ public HealEntityAction(String name) { @Override public void executeFor(Entity entity, Map subActions) { int amount = Integer.parseInt(subActions.get("amount")[0]); - if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; + if (entity instanceof LivingEntity livingEntity) { AttributeInstance attribute = livingEntity.getAttribute(MinecraftNameWrapper.MAX_HEALTH); if (attribute == null) return; - double newHealth = Math.min(livingEntity.getHealth() + amount, - attribute.getBaseValue()); + double newHealth = Math.min(livingEntity.getHealth() + amount, attribute.getBaseValue()); livingEntity.setHealth(newHealth); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java index 732eb774c..f09445d23 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java @@ -1,11 +1,12 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; import net.codingarea.challenges.plugin.challenges.custom.settings.action.PlayerTargetAction; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import java.util.Map; @@ -14,11 +15,10 @@ public class HungerPlayerAction extends PlayerTargetAction { public HungerPlayerAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true) .createChooseItemChild("amount").fill(builder -> { - String prefix = DefaultItem.getItemPrefix(); for (int i = 1; i < 21; i++) { - builder.addSetting( - String.valueOf(i), new LegacyItemBuilder(Material.ROTTEN_FLESH, prefix + "§7" + i).setAmount(i).build()); + // TODO correct formatting + builder.addSetting(SelectableKey.of(String.valueOf(i), new ItemStack(Material.ROTTEN_FLESH, i), LocalizableMessage.wrap(i))); } })); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java new file mode 100644 index 000000000..db767eaf6 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java @@ -0,0 +1,89 @@ +package net.codingarea.challenges.plugin.challenges.custom.settings.sub; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.translation.Translatable; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; + +/** + * @see Option + * @see ValueSetting + */ +public interface SelectableKey { + + @NotNull + String getKey(); + + @NotNull + ItemBuilder getDisplayItem(@NotNull Locale locale); + + // TODO rename factories to represent args + + @Contract(pure = true) + static SelectableKey.Option of(@NotNull String key, @NotNull Material displayMaterial, @NotNull LocalizableMessage name) { + return new SelectableKey.Option(key, new ItemStack(displayMaterial), name); + } + + @Contract(pure = true) + static SelectableKey.Option of(@NotNull String key, @NotNull Material displayMaterial, @NotNull Translatable name) { + return new SelectableKey.Option(key, new ItemStack(displayMaterial), name); + } + + @Contract(pure = true) + static SelectableKey.Option of(@NotNull String key, @NotNull Material displayMaterial, @NotNull Component name) { + return new SelectableKey.Option(key, new ItemStack(displayMaterial), name); + } + + @Contract(pure = true) + static SelectableKey.Option of(@NotNull String key, @NotNull Material displayMaterial, @NotNull String nameKey, @NotNull Object... nameArgs) { + return of(key, displayMaterial, LocalizableMessage.of(nameKey, nameArgs)); + } + + @Contract(pure = true) + static SelectableKey.Option of(@NotNull String key, @NotNull ItemStack displayPreset, @NotNull LocalizableMessage name) { + return new SelectableKey.Option(key, displayPreset, name); + } + + @Contract(pure = true) + static SelectableKey.Option of(@NotNull String key, @NotNull ItemStack displayPreset, @NotNull Translatable name) { + return new SelectableKey.Option(key, displayPreset, name); + } + + @Contract(pure = true) + static SelectableKey.Option of(@NotNull String key, @NotNull ItemStack displayPreset, @NotNull Component name) { + return new SelectableKey.Option(key, displayPreset, name); + } + + @Contract(pure = true) + static SelectableKey.Option of(@NotNull String key, @NotNull ItemStack displayPreset, @NotNull String nameKey, @NotNull Object... nameArgs) { + return of(key, displayPreset, LocalizableMessage.of(nameKey, nameArgs)); + } + + @Getter + @RequiredArgsConstructor(access = AccessLevel.PRIVATE) + class Option implements SelectableKey { + + // TODO DESCRIPTION? + + private final String key; + private final ItemStack displayItemPreset; + private final Object localizableNameArg; + + @NotNull + @Override + public ItemBuilder getDisplayItem(@NotNull Locale locale) { + return DefaultItems.createMenuDisplayFormat(displayItemPreset, localizableNameArg, locale); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java index 19dad9b99..9c4d0f146 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java @@ -3,17 +3,14 @@ import lombok.Getter; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.*; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.content.legacy.MessageManager; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.entity.Player; import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.jetbrains.annotations.NotNull; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; @@ -58,18 +55,16 @@ public static EmptySubSettingsBuilder createEmpty() { public abstract boolean open(Player player, IParentCustomGenerator parentGenerator, LocalizableMessage title); - public abstract List getDisplay(Map activated); + @NotNull + public abstract Collection getCurrentDisplayFor(@NotNull Map activated); public abstract boolean hasSettings(); - /** - * Collects the display lines of a builder and all of its children for the currently activated data. - * Relocated from the legacy custom {@code InfoMenuGenerator}. - */ - public static List getSubSettingsDisplay(SubSettingsBuilder builder, Map activated) { - List display = new LinkedList<>(); - for (SubSettingsBuilder child : builder.getAllChildren()) { - display.addAll(child.getDisplay(activated)); + @NotNull + public final Collection collectCurrentDisplayFor(@NotNull Map activated) { + List display = new LinkedList<>(); + for (SubSettingsBuilder setting : getAllChildren()) { + display.addAll(setting.getCurrentDisplayFor(activated)); } return display; } @@ -91,10 +86,13 @@ public SubSettingsBuilder setKey(String key) { return this; } - public String getKeyTranslation() { - String messageName = "custom-subsetting-" + key; - return MessageManager.hasMessageInCache(messageName) - ? Message.forName(messageName).asString() : StringUtils.getEnumName(key); + @NotNull + protected static LocalizableMessage getKeyTranslation(@NotNull String key) { + // TODO ported legacy logic to new translation system; please overhaul this + MessageKey nameKey = MessageKey.of("custom-subsetting-" + key); + if (nameKey.exists()) return nameKey; + // TODO remove fallback, everything should be translated! + return LocalizableMessage.wrap(StringUtils.getEnumName(key)); } public List getAllChildren() { @@ -149,8 +147,7 @@ public ChooseMultipleItemSubSettingBuilder createChooseMultipleChild(String key) return builder; } - public TextInputSubSettingsBuilder createTextInputChild(String key, - Consumer onOpen, + public TextInputSubSettingsBuilder createTextInputChild(String key, Consumer onOpen, Predicate isValid) { TextInputSubSettingsBuilder builder = new TextInputSubSettingsBuilder(key, this, onOpen, isValid); @@ -158,4 +155,7 @@ public TextInputSubSettingsBuilder createTextInputChild(String key, return builder; } + public record SubSettingDisplay(@NotNull LocalizableMessage keyName, @NotNull LocalizableMessage valueFormatted) { + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java index ab46c8742..0e510f1ac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java @@ -1,26 +1,22 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder; -import com.google.common.collect.Lists; import lombok.Getter; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.generator.AbstractMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.SubSettingChooseMenuGenerator; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; +import java.util.*; import java.util.function.Consumer; @Getter public class ChooseItemSubSettingsBuilder extends GeneratorSubSettingsBuilder { - protected final LinkedHashMap settings = new LinkedHashMap<>(); + protected final LinkedHashMap settings = new LinkedHashMap<>(); public ChooseItemSubSettingsBuilder(String key) { super(key); @@ -35,36 +31,29 @@ public AbstractMenuGenerator getGenerator(Player player, IParentCustomGenerator return new SubSettingChooseMenuGenerator(getKey(), parentGenerator, getSettings(), title); } + @NotNull @Override - public List getDisplay(Map activated) { - List display = Lists.newLinkedList(); + public Collection getCurrentDisplayFor(@NotNull Map activated) { + String[] values = activated.get(getKey()); + if (values == null) return Collections.emptyList(); - for (Entry entry : activated.entrySet()) { - if (entry.getKey().equals(getKey())) { - for (String value : entry.getValue()) { - ItemStack itemStack = getSettings().get(value); - if (itemStack != null) { - if (itemStack.getItemMeta() == null) continue; - display.add("§7" + getKeyTranslation() + " " + itemStack.getItemMeta().getDisplayName()); - } - } - } + // overkill; there should only be ever a single value/setting selected! + List valueNameArgs = new ArrayList<>(values.length); + for (String value : values) { + SelectableKey.Option option = settings.get(value); + if (option != null) valueNameArgs.add(option.getLocalizableNameArg()); } - return display; + SubSettingDisplay display = new SubSettingDisplay(getKeyTranslation(this.getKey()), LocalizableMessage.joinList(2, valueNameArgs)); + return List.of(display); } - public ChooseItemSubSettingsBuilder addSetting(String key, ItemStack value) { - settings.put(key, value); + public ChooseItemSubSettingsBuilder addSetting(@NotNull SelectableKey.Option value) { + settings.put(value.getKey(), value); return this; } - public ChooseItemSubSettingsBuilder addSetting(String key, LegacyItemBuilder value) { - settings.put(key, value.hideAttributes().build()); - return this; - } - - public ChooseItemSubSettingsBuilder fill(Consumer actions) { + public ChooseItemSubSettingsBuilder fill(@NotNull Consumer actions) { actions.accept(this); return this; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java index 29838a9bd..3b03355c9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java @@ -1,28 +1,22 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder; -import com.google.common.collect.Lists; import lombok.Getter; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.generator.AbstractMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.SubSettingChooseMultipleMenuGenerator; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; +import java.util.*; import java.util.function.Consumer; @Getter public class ChooseMultipleItemSubSettingBuilder extends GeneratorSubSettingsBuilder { - protected final LinkedHashMap settings = new LinkedHashMap<>(); + protected final LinkedHashMap settings = new LinkedHashMap<>(); public ChooseMultipleItemSubSettingBuilder(String key) { super(key); @@ -37,49 +31,24 @@ public AbstractMenuGenerator getGenerator(Player player, IParentCustomGenerator return new SubSettingChooseMultipleMenuGenerator(getKey(), parentGenerator, getSettings(), title); } + @NotNull @Override - public List getDisplay(Map activated) { - List display = Lists.newLinkedList(); - - for (Entry entry : activated.entrySet()) { - if (entry.getKey().equals(getKey())) { - - int count = 0; - String firstDisplay = null; - - for (String value : entry.getValue()) { - ItemStack itemStack = getSettings().get(value); - if (itemStack != null) { - if (firstDisplay == null) { - if (itemStack.getItemMeta() == null) continue; - firstDisplay = "§7" + getKeyTranslation() + " " + itemStack.getItemMeta().getDisplayName(); - } else { - count++; - } - - } - } - - if (firstDisplay != null) { - String suffix = count == 0 ? "" : " §7+" + count; - display.add(firstDisplay + suffix); - } else { - display.add("§7" + getKeyTranslation() + " " + DefaultItem.getItemPrefix() + Message.forName("none").asString()); - } - - } + public Collection getCurrentDisplayFor(@NotNull Map activated) { + String[] values = activated.get(getKey()); + if (values == null) return Collections.emptyList(); + + List valueNameArgs = new ArrayList<>(values.length); + for (String value : values) { + SelectableKey.Option option = settings.get(value); + if (option != null) valueNameArgs.add(option.getLocalizableNameArg()); } - return display; - } - - public ChooseMultipleItemSubSettingBuilder addSetting(String key, ItemStack value) { - settings.put(key, value); - return this; + SubSettingDisplay display = new SubSettingDisplay(getKeyTranslation(this.getKey()), LocalizableMessage.joinList(2, valueNameArgs)); + return List.of(display); } - public ChooseMultipleItemSubSettingBuilder addSetting(String key, LegacyItemBuilder value) { - settings.put(key, value.hideAttributes().build()); + public ChooseMultipleItemSubSettingBuilder addSetting(@NotNull SelectableKey.Option value) { + settings.put(value.getKey(), value); return this; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java index 7230ed5d2..9587b22db 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/EmptySubSettingsBuilder.java @@ -1,12 +1,13 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder; -import com.google.common.collect.Lists; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; -import java.util.List; +import java.util.Collection; +import java.util.Collections; import java.util.Map; public class EmptySubSettingsBuilder extends SubSettingsBuilder { @@ -16,8 +17,8 @@ public EmptySubSettingsBuilder() { } @Override - public List getDisplay(Map activated) { - return Lists.newLinkedList(); + public @NotNull Collection getCurrentDisplayFor(@NotNull Map activated) { + return Collections.emptyList(); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java index 371b1dd37..724167097 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/GeneratorSubSettingsBuilder.java @@ -20,7 +20,7 @@ public GeneratorSubSettingsBuilder(String key, SubSettingsBuilder parent) { public boolean open(Player player, IParentCustomGenerator parentGenerator, LocalizableMessage title) { if (hasSettings()) { - LocalizableMessage subTitle = MessageKey.of("menu.title-name-format-sub").withArgs(title, getKeyTranslation()); + LocalizableMessage subTitle = MessageKey.of("menu.title-name-format-sub").withArgs(title, getKeyTranslation(this.getKey())); AbstractMenuGenerator generator = getGenerator(player, parentGenerator, subTitle); if (generator == null) return false; generator.openMenu(player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java index bea1661c7..699b9bc5e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java @@ -1,20 +1,17 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder; -import com.google.common.collect.Lists; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.spigot.listener.ChatInputListener; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.misc.MapUtils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.jetbrains.annotations.NotNull; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; +import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; @@ -69,16 +66,16 @@ public boolean open(Player player, IParentCustomGenerator parentGenerator, Local return true; } + @NotNull @Override - public List getDisplay(Map activated) { - List display = Lists.newLinkedList(); - - for (Entry entry : activated.entrySet()) { - if (entry.getKey().equals(getKey())) { - for (String value : entry.getValue()) { - display.add("§7" + getKeyTranslation() + " " + DefaultItem.getItemPrefix() + value); - } - } + public Collection getCurrentDisplayFor(@NotNull Map activated) { + // TODO ported logic from legacy code; needs optimization / complete impl overhaul + String[] values = activated.get(this.getKey()); + if (values == null) return Collections.emptyList(); + + List display = new ArrayList<>(values.length); + for (String value : values) { + display.add(new SubSettingDisplay(getKeyTranslation(this.getKey()), LocalizableMessage.wrap(value))); } return display; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java index 5982e6ac4..d24b1959c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java @@ -15,7 +15,9 @@ import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -41,37 +43,25 @@ public AbstractMenuGenerator getGenerator(Player player, IParentCustomGenerator return new SubSettingValueMenuGenerator(parentGenerator, new LinkedHashMap<>(getDefaultSettings()), title); } + @NotNull @Override - public List getDisplay(Map activated) { - List display = Lists.newLinkedList(); + public Collection getCurrentDisplayFor(@NotNull Map activated) { + List display = Lists.newLinkedList(); - for (Entry entry : activated.entrySet()) { + // TODO logic ported from legacy code; overhaul system + for (ValueSetting setting : defaultSettings.keySet()) { + String[] values = activated.get(setting.getKey()); + if (values == null || values.length == 0) continue; - for (ValueSetting setting : defaultSettings.keySet()) { - - if (entry.getKey().equals(setting.getKey())) { - - LegacyItemBuilder builder = setting.getSettingsItem(entry.getValue()[0]); - if (builder != null) { - display.add("§7" + getKeyTranslation(entry.getKey()) + " " + builder.getName()); - - } - - } - - } + String value = values[0]; + // TODO get setting value formatted name + display.add(new SubSettingDisplay(getKeyTranslation(setting.getKey()), LocalizableMessage.wrap(setting.getSettingsItem(value).getName()))); } return display; } - public String getKeyTranslation(String key) { - String messageName = "custom-subsetting-" + key; - return MessageManager.hasMessageInCache(messageName) - ? Message.forName(messageName).asString() : StringUtils.getEnumName(key); - } - public ValueSubSettingsBuilder addBooleanSetting(String key, LegacyItemBuilder displayItem, boolean defaultValue) { defaultSettings.put(new BooleanSetting(key, displayItem), diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java index 619ecea42..ca8ce46f2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java @@ -2,22 +2,18 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeSetting; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; -import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.LinkedHashMap; -import java.util.Locale; import java.util.function.Supplier; public abstract class ChallengeTrigger extends ChallengeSetting implements IChallengeTrigger { - public ChallengeTrigger(String name, - SubSettingsBuilder subSettingsBuilder) { + public ChallengeTrigger(String name, SubSettingsBuilder subSettingsBuilder) { super(name, subSettingsBuilder); } @@ -29,11 +25,11 @@ public ChallengeTrigger(String name, Supplier builderSupplie super(name, builderSupplier); } - public static LinkedHashMap getMenuItems() { - LinkedHashMap map = new LinkedHashMap<>(); + public static LinkedHashMap getMenuItems() { + LinkedHashMap map = new LinkedHashMap<>(); for (ChallengeTrigger value : Challenges.getInstance().getCustomSettingsLoader().getTriggers().values()) { - map.put(value.getUniqueName(), value.getDisplayItem(Locale.GERMAN).build()); // TODO + map.put(value.getUniqueName(), value); // TODO } return map; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java index 0af34725a..bd05cdbcb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java @@ -1,11 +1,9 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.trigger.impl; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; @@ -18,7 +16,7 @@ public ConsumeItemTrigger(String name) { super(name, SubSettingsBuilder.createChooseMultipleItem(SubSettingsHelper.ITEM).fill(builder -> { for (Material material : ExperimentalUtils.getMaterials()) { if (material.isEdible()) { - builder.addSetting(material.name(), new LegacyItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemComponent(material).toPlainText()).build()); + builder.addSetting(SelectableKey.of(material.name(), material, material)); } } })); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java index a3350862e..f558b3402 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java @@ -1,17 +1,17 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.trigger.impl; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; -import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder.PotionBuilder; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; @@ -26,19 +26,16 @@ public EntityDamageTrigger(String name) { Arrays.asList(PotionEffectType.values())); Collections.shuffle(types, new Random(1)); - builder.addSetting(SubSettingsHelper.ANY, new LegacyItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-trigger-damage-any"))); + builder.addSetting(SelectableKey.of(SubSettingsHelper.ANY, Material.NETHER_STAR, "item-custom-trigger-damange-any")); DamageCause[] values = DamageCause.values(); for (int i = 0; i < values.length; i++) { DamageCause cause = values[i]; PotionEffectType effectType = types.get(i); - builder.addSetting(cause.name(), - new PotionBuilder(Material.TIPPED_ARROW, - DefaultItem.getItemPrefix() + StringUtils.getEnumName(cause)) - .color(effectType.getColor()) - .build()); - + ItemStack displayItemPreset = new StandardItemBuilder.PotionBuilder(Material.TIPPED_ARROW).color(effectType.getColor()).build(); + // TODO correct formatting + builder.addSetting(SelectableKey.of(cause.name(), displayItemPreset, LocalizableMessage.wrap(StringUtils.getEnumName(cause)))); } })); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java index 4c1c4b0a1..0723a0108 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java @@ -1,12 +1,12 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.trigger.impl; import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -19,8 +19,8 @@ public class InLiquidTrigger extends ChallengeTrigger { public InLiquidTrigger(String name) { super(name, SubSettingsBuilder.createChooseMultipleItem(SubSettingsHelper.LIQUID).fill(builder -> { - builder.addSetting("LAVA", new LegacyItemBuilder(Material.LAVA_BUCKET, DefaultItem.getItemPrefix() + "§cLava")); - builder.addSetting("WATER", new LegacyItemBuilder(Material.WATER_BUCKET, DefaultItem.getItemPrefix() + "§9Water")); + builder.addSetting(SelectableKey.of("LAVA", Material.LAVA_BUCKET, LocalizableMessage.wrap("§cLava"))); + builder.addSetting(SelectableKey.of("WATER", Material.WATER_BUCKET, LocalizableMessage.wrap("§9Water"))); })); Challenges.getInstance().getScheduler().register(this); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java index 40389a7ac..afced1462 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java @@ -3,12 +3,12 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.FallbackNames; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.PlayerCountPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.Material; +import org.jetbrains.annotations.NotNull; import java.util.LinkedList; import java.util.List; @@ -16,21 +16,21 @@ @FallbackNames("intervall") public class IntervallTrigger extends ChallengeTrigger { - public IntervallTrigger(String name) { + public IntervallTrigger(@NotNull String name) { super(name, SubSettingsBuilder.createChooseItem("time").fill(builder -> { - builder.addSetting("1", new LegacyItemBuilder(Material.MUSIC_DISC_13, Message.forName("item-custom-trigger-intervall-second"), "1").build()); + builder.addSetting(SelectableKey.of("1", Material.MUSIC_DISC_13, "item-custom-trigger-intervall-second", "1")); String seconds = "item-custom-trigger-intervall-seconds"; - builder.addSetting("2", new LegacyItemBuilder(Material.MUSIC_DISC_CAT, Message.forName(seconds), "2")); - builder.addSetting("5", new LegacyItemBuilder(Material.MUSIC_DISC_BLOCKS, Message.forName(seconds), "5")); - builder.addSetting("10", new LegacyItemBuilder(Material.MUSIC_DISC_CHIRP, Message.forName(seconds), "10")); - builder.addSetting("20", new LegacyItemBuilder(Material.MUSIC_DISC_FAR, Message.forName(seconds), "20")); - builder.addSetting("30", new LegacyItemBuilder(Material.MUSIC_DISC_MALL, Message.forName(seconds), "30")); - builder.addSetting("60", new LegacyItemBuilder(Material.MUSIC_DISC_MELLOHI, Message.forName(seconds), "60")); + builder.addSetting(SelectableKey.of("2", Material.MUSIC_DISC_CAT, seconds, "2")); + builder.addSetting(SelectableKey.of("5", Material.MUSIC_DISC_BLOCKS, seconds, "5")); + builder.addSetting(SelectableKey.of("10", Material.MUSIC_DISC_CHIRP, seconds, "10")); + builder.addSetting(SelectableKey.of("20", Material.MUSIC_DISC_FAR, seconds, "20")); + builder.addSetting(SelectableKey.of("30", Material.MUSIC_DISC_MALL, seconds, "30")); + builder.addSetting(SelectableKey.of("60", Material.MUSIC_DISC_MELLOHI, seconds, "60")); String minutes = "item-custom-trigger-intervall-minutes"; - builder.addSetting("120", new LegacyItemBuilder(Material.MUSIC_DISC_STAL, Message.forName(minutes), "2")); - builder.addSetting("180", new LegacyItemBuilder(Material.MUSIC_DISC_STRAD, Message.forName(minutes), "3")); - builder.addSetting("240", new LegacyItemBuilder(Material.MUSIC_DISC_WARD, Message.forName(minutes), "4")); - builder.addSetting("300", new LegacyItemBuilder(Material.MUSIC_DISC_11, Message.forName(minutes), "5")); + builder.addSetting(SelectableKey.of("120", Material.MUSIC_DISC_STAL, minutes, "2")); + builder.addSetting(SelectableKey.of("180", Material.MUSIC_DISC_STRAD, minutes, "3")); + builder.addSetting(SelectableKey.of("240", Material.MUSIC_DISC_WARD, minutes, "4")); + builder.addSetting(SelectableKey.of("300", Material.MUSIC_DISC_11, minutes, "5")); })); Challenges.getInstance().getScheduler().register(this); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java index 38606ffcd..e279ce321 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java @@ -8,6 +8,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; +import org.jetbrains.annotations.NotNull; import java.util.Objects; @@ -17,6 +18,7 @@ public StandsOnSpecificBlockTrigger(String name) { super(name, SubSettingsHelper.createBlockSettingsBuilder()); } + @NotNull @Override public Material getMaterial() { return Material.PACKED_ICE; @@ -25,8 +27,7 @@ public Material getMaterial() { @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onMove(PlayerMoveEvent event) { if (BlockUtils.isSameBlockLocation(event.getTo(), event.getFrom())) return; - Block blockBelow = BlockUtils.getBlockBelow( - Objects.requireNonNull(event.getTo())); + Block blockBelow = BlockUtils.getBlockBelow(event.getTo()); if (blockBelow == null) return; createData() diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index 076df42e3..2d391bc11 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -4,15 +4,15 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; +import net.codingarea.challenges.plugin.challenges.type.annotation.Updated; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.impl.format.ComponentArguments; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.item.ItemUtils; import net.codingarea.commons.common.collection.SeededRandomWrapper; @@ -35,6 +35,7 @@ import java.util.List; @Since("2.0") +@Updated("2.4") public class CollectAllItemsGoal extends SettingGoal implements SenderCommand { @Getter @@ -71,19 +72,20 @@ private void nextItem() { ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED); return; } - currentItem = itemsToFind.remove(0); + currentItem = itemsToFind.removeFirst(); } @Override protected void onEnable() { bossbar.setContent((bossbar, player) -> { if (currentItem == null) { - bossbar.setTitle(MessageKey.of("bossbar-all-items-finished")); + bossbar.setTitle(getChallengeMessageKey("bossbar-finished")); bossbar.setColor(BossBar.Color.GREEN); return; } int foundItemsCount = totalItemsCount - itemsToFind.size() + 1; - bossbar.setTitle(MessageKey.of("bossbar-all-items-current-max"), currentItem, foundItemsCount, totalItemsCount); + bossbar.setTitle(getChallengeMessageKey("bossbar-current"), + currentItem, foundItemsCount, totalItemsCount, new ItemStack(currentItem)); }); bossbar.show(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java index 882b1e602..cfef40251 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TopCommandSetting.java @@ -18,7 +18,7 @@ public class TopCommandSetting extends Setting implements PlayerCommand { public TopCommandSetting() { - super(MenuType.SETTINGS, null, new ItemStack(Material.MAGENTA_GLAZED_TERRACOTTA), "top-command-setting"); + super(MenuType.SETTINGS, null, new ItemStack(Material.MAGENTA_GLAZED_TERRACOTTA), "top-command"); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java index 362ae62f3..5237147b9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java @@ -2,6 +2,7 @@ import lombok.Getter; import net.codingarea.challenges.plugin.ChallengeAPI; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; @@ -57,6 +58,12 @@ public void onMove(PlayerMoveEvent event) { } } + @NotNull + @Override + public LocalizableMessage getChallengeDescription() { + return super.getChallengeDescription().withArgs(heightToGetTo); + } + protected void setHeightToGetTo(int heightToGetTo) { this.heightToGetTo = heightToGetTo; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java index 90081a3f8..f38e53edf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java @@ -122,7 +122,7 @@ public ItemBuilder getSettingsItem(@NotNull Locale locale) { ItemStack preset = isEnabled() ? getSettingsItemPreset() : DefaultItems.createDisabledPreset(); // apply formatting dynamically, to prevent duplicate format references ItemBuilder item = new ItemBuilder(locale, preset, MessageKey.of("challenge.subsettings-format"), - isEnabled() ? getSettingsName() : MessageKey.of("disabled")); // no need to override disabled name/item + isEnabled() ? getSettingsName() : MessageKey.of("generic.disabled")); // no need to override disabled name/item LocalizableMessage description = getSettingsDescription(); if (description != null && isEnabled()) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java index 5d2edccd3..6071891de 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java @@ -1,20 +1,21 @@ package net.codingarea.challenges.plugin.challenges.type.helper; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.ChooseItemSubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.ChooseMultipleItemSubSettingBuilder; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.StructureUtils; -import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder.PotionBuilder; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Material; import org.bukkit.StructureType; import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffectType; public class SubSettingsHelper { @@ -32,32 +33,31 @@ public static ChooseMultipleItemSubSettingBuilder createEntityTypeSettingsBuilde return SubSettingsBuilder.createChooseMultipleItem(ENTITY_TYPE).fill(builder -> { if (any) { - builder.addSetting(ANY, new LegacyItemBuilder( - Material.NETHER_STAR, Message.forName("item-custom-setting-entity_type-any")).build()); + builder.addSetting(SelectableKey.of(ANY, Material.NETHER_STAR, "item-custom-setting-entity_type-any")); } if (player) { - builder.addSetting("PLAYER", new LegacyItemBuilder(Material.PLAYER_HEAD, Message.forName("item-custom-setting-entity_type-player")).build()); + builder.addSetting(SelectableKey.of("PLAYER", Material.PLAYER_HEAD, "item-custom-setting-entity_type-player")); } for (EntityType type : EntityType.values()) { if (!type.isSpawnable() || !type.isAlive()) continue; + Material displayMaterial; try { - Material spawnEgg = Material.valueOf(type.name() + "_SPAWN_EGG"); - builder.addSetting(type.name(), new LegacyItemBuilder(spawnEgg, - DefaultItem.getItemPrefix() + BukkitStringUtils.getEntityName(type).toPlainText()).build()); + displayMaterial = Material.valueOf(type.name() + "_SPAWN_EGG"); } catch (Exception ex) { - builder.addSetting(type.name(), new LegacyItemBuilder(Material.STRUCTURE_VOID, - DefaultItem.getItemPrefix() + BukkitStringUtils.getEntityName(type).toPlainText())); + displayMaterial = Material.STRUCTURE_VOID; } + + builder.addSetting(SelectableKey.of(type.name(), displayMaterial, type)); } }); } public static ChooseMultipleItemSubSettingBuilder createBlockSettingsBuilder() { return SubSettingsBuilder.createChooseMultipleItem(BLOCK).fill(builder -> { - builder.addSetting(ANY, new LegacyItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-setting-block-any")).build()); + builder.addSetting(SelectableKey.of(ANY, Material.NETHER_STAR, "item-custom-setting-block-any")); for (Material material : ExperimentalUtils.getMaterials()) { if (material.isBlock() && material.isItem() && !BukkitReflectionUtils.isAir(material)) { - builder.addSetting(material.name(), new LegacyItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); + builder.addSetting(SelectableKey.of(material.name(), material, material)); } } }); @@ -65,10 +65,10 @@ public static ChooseMultipleItemSubSettingBuilder createBlockSettingsBuilder() { public static ChooseMultipleItemSubSettingBuilder createItemSettingsBuilder() { return SubSettingsBuilder.createChooseMultipleItem(ITEM).fill(builder -> { - builder.addSetting(ANY, new LegacyItemBuilder(Material.NETHER_STAR, Message.forName("item-custom-setting-item-any")).build()); + builder.addSetting(SelectableKey.of(ANY, Material.NETHER_STAR, "item-custom-setting-item-any")); for (Material material : ExperimentalUtils.getMaterials()) { if (material.isItem() && !BukkitReflectionUtils.isAir(material)) { - builder.addSetting(material.name(), new LegacyItemBuilder(material, DefaultItem.getItemPrefix() + BukkitStringUtils.getItemName(material).toPlainText()).build()); + builder.addSetting(SelectableKey.of(material.name(), material, material)); } } }); @@ -86,37 +86,30 @@ public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean every ChooseItemSubSettingsBuilder builder = SubSettingsBuilder.createChooseItem(TARGET_ENTITY); if (console) { - builder.addSetting("console", new LegacyItemBuilder(Material.COMMAND_BLOCK_MINECART, Message.forName("item-custom-setting-target-console"))); + // TODO generic translation; constant keys? + builder.addSetting(SelectableKey.of("console", Material.COMMAND_BLOCK_MINECART, "item-custom-setting-target-console")); } if (!onlyPlayer) { - builder.addSetting("current", new LegacyItemBuilder(Material.DRAGON_HEAD, - Message.forName("item-custom-setting-target-current"))); + builder.addSetting(SelectableKey.of("current", Material.DRAGON_HEAD, "item-custom-setting-target-current")); } - builder.addSetting("current_player", new LegacyItemBuilder(Material.PLAYER_HEAD, - Message.forName("item-custom-setting-target-current_player"))); - builder.addSetting("random_player", new LegacyItemBuilder(Material.ZOMBIE_HEAD, - Message.forName("item-custom-setting-target-random_player"))); - builder.addSetting("every_player", new LegacyItemBuilder(Material.PLAYER_HEAD, - Message.forName("item-custom-setting-target-every_player"))); + builder.addSetting(SelectableKey.of("current_player", Material.PLAYER_HEAD, "item-custom-setting-target-current_player")); + builder.addSetting(SelectableKey.of("random_player", Material.ZOMBIE_HEAD, "item-custom-setting-target-random_player")); + builder.addSetting(SelectableKey.of("every_player", Material.PLAYER_HEAD, "item-custom-setting-target-every_player")); if (everyMob && !onlyPlayer) { - builder.addSetting("every_mob", new LegacyItemBuilder(Material.WITHER_SKELETON_SKULL, - Message.forName("item-custom-setting-target-every_mob"))); - builder.addSetting("every_mob_except_current", new LegacyItemBuilder(Material.SKELETON_SKULL, - Message.forName("item-custom-setting-target-every_mob_except_current"))); - builder.addSetting("every_mob_except_players", new LegacyItemBuilder(Material.SKELETON_SKULL, - Message.forName("item-custom-setting-target-every_mob_except_players"))); + builder.addSetting(SelectableKey.of("every_mob", Material.WITHER_SKELETON_SKULL, "item-custom-setting-target-every_mob")); + builder.addSetting(SelectableKey.of("every_mob_except_current", Material.SKELETON_SKULL, "item-custom-setting-target-every_mob_except_current")); + builder.addSetting(SelectableKey.of("every_mob_except_players", Material.SKELETON_SKULL, "item-custom-setting-target-every_mob_except_players")); } return builder; } - public static SubSettingsBuilder createPotionSettingsBuilder(boolean potionType, - boolean potionTime) { - + public static SubSettingsBuilder createPotionSettingsBuilder(boolean potionType, boolean potionTime) { SubSettingsBuilder potionSettings = SubSettingsBuilder.createValueItem().fill(builder -> { + // TODO also port if (potionTime) { builder.addModifierSetting("length", new LegacyItemBuilder(Material.CLOCK, Message.forName("item-random-effect-length-challenge")), @@ -134,10 +127,12 @@ public static SubSettingsBuilder createPotionSettingsBuilder(boolean potionType, if (potionType) { potionSettings = potionSettings.createChooseItemChild("potion_type").fill(builder -> { for (PotionEffectType effectType : PotionEffectType.values()) { - builder.addSetting(effectType.getName(), new PotionBuilder(Material.POTION, - DefaultItem.getItemPrefix() + StringUtils.getEnumName(effectType.getName())) + ItemStack displayItemPreset = new StandardItemBuilder.PotionBuilder(Material.POTION) .addEffect(effectType.createEffect(1, 0)) - .color(effectType.getColor()).build()); + .color(effectType.getColor()).build(); + + // TODO custom centralized translation? + builder.addSetting(SelectableKey.of(effectType.getName(), displayItemPreset, LocalizableMessage.wrap(StringUtils.getEnumName(effectType.getName())))); } }); } @@ -148,9 +143,9 @@ public static SubSettingsBuilder createPotionSettingsBuilder(boolean potionType, public static SubSettingsBuilder createStructureSettingsBuilder() { return SubSettingsBuilder.createChooseItem(STRUCTURE).fill(builder -> { - builder.addSetting("random_structure", new LegacyItemBuilder(Material.STRUCTURE_BLOCK, Message.forName("item-custom-action-place_structure-random")).build()); + builder.addSetting(SelectableKey.of("random_structure", Material.STRUCTURE_BLOCK, "item-custom-action-place_structure-random")); for (StructureType structure : StructureType.getStructureTypes().values()) { - builder.addSetting(structure.getName(), new LegacyItemBuilder(StructureUtils.getStructureIcon(structure), DefaultItem.getItemPrefix() + StringUtils.getEnumName(structure.getName())).build()); + builder.addSetting(SelectableKey.of(structure.getName(), StructureUtils.getStructureIcon(structure), StringUtils.getEnumName(structure.getName()))); } }); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java index 9414f0cd0..7e73d899a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java @@ -1,13 +1,12 @@ package net.codingarea.challenges.plugin.content.i18n; -import net.codingarea.challenges.plugin.content.i18n.impl.DynamicLocalizableMessageImpl; -import net.codingarea.challenges.plugin.content.i18n.impl.JoinedMessageImpl; +import net.codingarea.challenges.plugin.content.i18n.impl.dynamic.DynamicMessageImpl; +import net.codingarea.challenges.plugin.content.i18n.impl.dynamic.JoinedMessageImpl; +import net.codingarea.challenges.plugin.content.i18n.impl.dynamic.WrappedObjMessageImpl; import org.bukkit.entity.Player; -import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.CheckReturnValue; -import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.*; -import java.util.List; +import java.util.Collection; import java.util.Locale; import java.util.function.Function; @@ -19,14 +18,28 @@ */ public interface LocalizableMessage { + // TODO add LocalizableMessage helper methods (same as in MessageKey without args!) + @NotNull + @CheckReturnValue MessageHolder localize(@NotNull Locale locale); @NotNull + @CheckReturnValue MessageHolder localize(@NotNull Player playerLocale); + /** + * @return a new {@link LocalizableMessage} instance with the same {@link MessageKey} but with the new provided arguments. + */ @NotNull - @ApiStatus.Internal + @Contract(pure = true) + LocalizableMessage withArgs(@NotNull Object... args); + + /** + * @return the {@link MessageKey} of this {@link LocalizableMessage} + * or {@code null} if this is a dynamic message that does not have a key. + */ + @Nullable MessageKey getLocalizableKey(); @NotNull @@ -41,22 +54,46 @@ static LocalizableMessage of(@NotNull String messageKey, @NotNull Object[] args) @NotNull @CheckReturnValue - static LocalizableMessage join(@NotNull MessageKey delimiter, @NotNull Object... elements) { - return new JoinedMessageImpl(delimiter, elements); + static LocalizableMessage join(@NotNull MessageKey delimiter, @NotNull MessageKey remainingPlaceholder, int limit, @NotNull Object... elements) { + return new JoinedMessageImpl(delimiter, remainingPlaceholder, limit, elements); + } + + @NotNull + @CheckReturnValue + static LocalizableMessage join(int limit, @NotNull Object... elements) { + return join(MessageKey.of("arg-format.delimiter"), MessageKey.of("arg-format.remaining"), limit, elements); + } + + @NotNull + @CheckReturnValue + static LocalizableMessage joinArray(int limit, @NotNull Object[] elements) { + return join(limit, elements); } @NotNull @CheckReturnValue static LocalizableMessage joinArray(@NotNull Object[] elements) { - return join(MessageKey.of("generic.delimiter"), elements); + return join(elements.length, elements); } @NotNull @CheckReturnValue - static LocalizableMessage joinList(@NotNull List elements) { + static LocalizableMessage joinList(int limit, @NotNull Collection elements) { + return joinArray(limit, elements.toArray()); + } + + @NotNull + @CheckReturnValue + static LocalizableMessage joinList(@NotNull Collection elements) { return joinArray(elements.toArray()); } + @NotNull + @CheckReturnValue + static LocalizableMessage joinArgsLimited(int limit, @NotNull Object... elements) { // prevents ambiguous var-args + return joinArray(limit, elements); + } + @NotNull @CheckReturnValue static LocalizableMessage joinArgs(@NotNull Object... elements) { // prevents ambiguous var-args @@ -66,7 +103,7 @@ static LocalizableMessage joinArgs(@NotNull Object... elements) { // prevents am @NotNull @CheckReturnValue static LocalizableMessage fromLines(@NotNull Function valueFunction, @NotNull Object... args) { - return new DynamicLocalizableMessageImpl(valueFunction, args); + return new DynamicMessageImpl(valueFunction, args); } @NotNull @@ -75,4 +112,12 @@ static LocalizableMessage from(@NotNull Function valueFunction, return fromLines(valueFunction.andThen((string) -> new String[]{string}), args); } + @NotNull + @CheckReturnValue + @ApiStatus.Internal + @ApiStatus.Experimental + static LocalizableMessage wrap(@NotNull Object arg) { + return new WrappedObjMessageImpl(arg); + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageHolder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageHolder.java index ec262844d..8ab0d157a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageHolder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageHolder.java @@ -1,8 +1,9 @@ package net.codingarea.challenges.plugin.content.i18n; - import org.jetbrains.annotations.NotNull; +import java.util.Arrays; + /** * Represents a localized message with arguments. * @@ -12,4 +13,12 @@ public record MessageHolder(@NotNull String[] rawValue, @NotNull Object[] positi public static final Object[] EMPTY_ARGS = new Object[0]; + @NotNull + @Override + public String toString() { + return "MessageHolder{" + + "raw=" + Arrays.toString(rawValue) + + ", args=" + Arrays.toString(positionalArgs) + + '}'; + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java index 1e5ebacfc..2feb5ed66 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java @@ -7,10 +7,7 @@ import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.CheckReturnValue; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.*; import java.util.List; import java.util.Locale; @@ -90,14 +87,14 @@ static MessageKey of(@NotNull String id) { @NotNull @CheckReturnValue - static MessageKey pluralize(@NotNull String singular, @NotNull String plural, @NotNull Number count) { - return of(count.intValue() == 1 ? singular : plural); + static MessageKey pluralize(@NotNull String singularKey, @NotNull String pluralKey, @NotNull Number count) { + return of(count.intValue() == 1 ? singularKey : pluralKey); } @NotNull @CheckReturnValue - static MessageKey pluralize(@NotNull String baseId, @NotNull Number count) { - return pluralize(baseId, baseId + "s", count); + static MessageKey pluralize(@NotNull String baseKey, @NotNull Number count) { + return pluralize(baseKey, baseKey + "s", count); } @NotNull @@ -120,6 +117,11 @@ default MessageKey getChildKey(@NotNull String child) { @NotNull String getKey(); + /** + * @return whether this key exists in any language + */ + boolean exists(); + boolean isCached(@NotNull Locale locale); void removeValue(@NotNull Locale locale); @@ -143,6 +145,7 @@ default MessageKey getChildKey(@NotNull String child) { String localizeRawValueAsSingleLine(@NotNull Locale locale); @NotNull + @Contract(pure = true) LocalizableMessage withArgs(@NotNull Object... args); // Helpers diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/JoinedMessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/JoinedMessageImpl.java deleted file mode 100644 index 57b36fa64..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/JoinedMessageImpl.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.codingarea.challenges.plugin.content.i18n.impl; - -import lombok.RequiredArgsConstructor; -import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.content.i18n.MessageHolder; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.content.i18n.impl.format.MessageFormatter; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - -import java.util.Locale; - -@RequiredArgsConstructor -public class JoinedMessageImpl implements LocalizableMessage { - - public static final MessageKey KEY = MessageKey.empty(""); - - private final MessageKey delimiter; - private final Object[] elements; - - @NotNull - @Override - public MessageHolder localize(@NotNull Locale locale) { - StringBuilder raw = new StringBuilder(); - String localizedDelimiter = delimiter.localizeRawValueAsSingleLine(locale); - for (int i = 0; i < elements.length; i++) { - raw.append(MessageFormatter.START_ARG_CHAR).append(i).append(MessageFormatter.END_ARG_CHAR); - if (i != elements.length - 1) raw.append(localizedDelimiter); - } - - Object[] args = MessageKeyImpl.localizeArgsAsCopy(locale, elements); - return new MessageHolder(new String[]{raw.toString()}, args); - } - - @NotNull - @Override - public MessageHolder localize(@NotNull Player playerLocale) { - return localize(MessageKeyImpl.getPlayerLocale(playerLocale)); - } - - @NotNull - @Override - public MessageKey getLocalizableKey() { - return KEY; - } - - @NotNull - @Override - public Object[] getLocalizableArgs() { - return elements; - } -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java index 465916ef5..44209c7ee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java @@ -6,6 +6,7 @@ import net.codingarea.challenges.plugin.content.i18n.MessageKey; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NonNull; import java.util.Locale; @@ -27,6 +28,12 @@ public MessageHolder localize(@NotNull Player playerLocale) { return localize(MessageKeyImpl.getPlayerLocale(playerLocale)); } + @NotNull + @Override + public LocalizableMessage withArgs(@NotNull Object... args) { + return new LocalizableMessageImpl(messageKey, args); + } + @NotNull @Override public MessageKey getLocalizableKey() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java index 9b7964aa3..6a4054832 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java @@ -47,6 +47,11 @@ public void removeValue(@NotNull Locale locale) { values.remove(locale); } + @Override + public boolean exists() { + return !values.isEmpty(); + } + @Override public boolean isCached(@NotNull Locale locale) { return values.containsKey(locale); @@ -57,7 +62,7 @@ public boolean isCached(@NotNull Locale locale) { public String[] localizeRawValue(@NotNull Locale locale) { String[] value = values.get(locale); if (value != null && value.length != 0) return value; - return new String[]{MessageKey.formatMissingTranslation(key, locale)}; + return arrayOf(MessageKey.formatMissingTranslation(key, locale)); } @NotNull @@ -127,11 +132,11 @@ protected String localizePrefix(@NotNull Locale locale, @Nullable Prefix prefix) } @NotNull - protected static Locale getPlayerLocale(@NotNull Player player) { + public static Locale getPlayerLocale(@NotNull Player player) { return Challenges.getInstance().getTranslationManager().getLanguageProvider().getPlayerLanguage(player); } - protected static void localizeArgs(@NotNull Locale locale, @NotNull Object[] args) { + public static void localizeArgs(@NotNull Locale locale, @NotNull Object[] args) { for (int i = 0; i < args.length; i++) { if (args[i] instanceof LocalizableMessage message) { args[i] = message.localize(locale); @@ -141,7 +146,7 @@ protected static void localizeArgs(@NotNull Locale locale, @NotNull Object[] arg @NotNull @CheckReturnValue - protected static Object[] localizeArgsAsCopy(@NotNull Locale locale, @NotNull Object[] args) { + public static Object[] localizeArgsAsCopy(@NotNull Locale locale, @NotNull Object[] args) { if (args.length == 0) return args; // avoid mutating original array & ensure args array is really of type Object, so MessageHolder can be stored Object[] localizedArgs = new Object[args.length]; @@ -150,6 +155,11 @@ protected static Object[] localizeArgsAsCopy(@NotNull Locale locale, @NotNull Ob return localizedArgs; } + @NotNull + public static String[] arrayOf(@NotNull String single) { + return new String[]{single}; + } + // Action Implementations @Override @@ -174,7 +184,7 @@ public void sendRandom(@NotNull Player target, @Nullable Prefix prefix, @NotNull Locale locale = getPlayerLocale(target); localizeArgs(locale, args); String raw = random.choose(localizeRawValue(locale)); - target.sendMessage(ComponentFormatter.deserializeLinesWithArgs(localizePrefix(locale, prefix), new String[]{raw}, args)); + target.sendMessage(ComponentFormatter.deserializeLinesWithArgs(localizePrefix(locale, prefix), arrayOf(raw), args)); } @Override @@ -186,7 +196,7 @@ public void broadcast(@Nullable Prefix prefix, @NotNull Object... args) { public void broadcastRandom(@Nullable Prefix prefix, @NotNull Object... args) { int index = random.nextInt(getMinValueLengthIncludingFallback()); doBroadcast0(Player::sendMessage, locale -> - ComponentFormatter.deserializeLinesWithArgs(localizePrefix(locale, prefix), new String[]{localizeRawValue(locale)[index]}, localizeArgsAsCopy(locale, args))); + ComponentFormatter.deserializeLinesWithArgs(localizePrefix(locale, prefix), arrayOf(localizeRawValue(locale)[index]), localizeArgsAsCopy(locale, args))); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/DynamicLocalizableMessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/DynamicMessageImpl.java similarity index 68% rename from plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/DynamicLocalizableMessageImpl.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/DynamicMessageImpl.java index 795f866cb..f4d5e1a99 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/DynamicLocalizableMessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/DynamicMessageImpl.java @@ -1,19 +1,20 @@ -package net.codingarea.challenges.plugin.content.i18n.impl; +package net.codingarea.challenges.plugin.content.i18n.impl.dynamic; import lombok.RequiredArgsConstructor; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageHolder; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.impl.MessageKeyImpl; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NonNull; import java.util.Locale; import java.util.function.Function; @RequiredArgsConstructor -public class DynamicLocalizableMessageImpl implements LocalizableMessage { - - public static final MessageKey KEY = MessageKey.empty(""); +public class DynamicMessageImpl implements LocalizableMessage { private final Function valueFunction; private final Object[] args; @@ -32,8 +33,14 @@ public MessageHolder localize(@NotNull Player playerLocale) { @NotNull @Override + public LocalizableMessage withArgs(@NonNull @NotNull Object... args) { + return new DynamicMessageImpl(valueFunction, args); + } + + @Nullable + @Override public MessageKey getLocalizableKey() { - return KEY; + return null; } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/JoinedMessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/JoinedMessageImpl.java new file mode 100644 index 000000000..1117246f3 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/JoinedMessageImpl.java @@ -0,0 +1,74 @@ +package net.codingarea.challenges.plugin.content.i18n.impl.dynamic; + +import lombok.RequiredArgsConstructor; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageHolder; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.impl.MessageKeyImpl; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jspecify.annotations.NonNull; + +import java.util.Locale; + +import static net.codingarea.challenges.plugin.content.i18n.impl.MessageKeyImpl.arrayOf; +import static net.codingarea.challenges.plugin.content.i18n.impl.format.MessageFormatter.END_ARG_CHAR; +import static net.codingarea.challenges.plugin.content.i18n.impl.format.MessageFormatter.START_ARG_CHAR; + +@RequiredArgsConstructor +public class JoinedMessageImpl implements LocalizableMessage { + + private final MessageKey delimiter; + private final MessageKey remainingPlaceholder; + private final int limit; + private final Object[] elements; + + @NotNull + @Override + public MessageHolder localize(@NotNull Locale locale) { + String localizedDelimiter = delimiter.localizeRawValueAsSingleLine(locale); + int shown = Math.min(elements.length, limit); + int remaining = elements.length - shown; + + StringBuilder raw = new StringBuilder(); + for (int i = 0; i < shown; i++) { + if (i > 0) raw.append(localizedDelimiter); + raw.append(START_ARG_CHAR).append(i).append(END_ARG_CHAR); + } + + Object[] args = new Object[shown + (remaining > 0 ? 1 : 0)]; + System.arraycopy(elements, 0, args, 0, shown); + if (remaining > 0) { + raw.append(START_ARG_CHAR).append(shown).append(END_ARG_CHAR); + args[shown] = remainingPlaceholder.withArgs(remaining); + } + + MessageKeyImpl.localizeArgs(locale, args); + return new MessageHolder(arrayOf(raw.toString()), args); + } + + @NotNull + @Override + public MessageHolder localize(@NotNull Player playerLocale) { + return localize(MessageKeyImpl.getPlayerLocale(playerLocale)); + } + + @NotNull + @Override + public LocalizableMessage withArgs(@NonNull @NotNull Object... args) { + return new JoinedMessageImpl(delimiter, remainingPlaceholder, limit, args); + } + + @Nullable + @Override + public MessageKey getLocalizableKey() { + return null; + } + + @NotNull + @Override + public Object[] getLocalizableArgs() { + return elements; + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/WrappedObjMessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/WrappedObjMessageImpl.java new file mode 100644 index 000000000..3fff8c2d7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/WrappedObjMessageImpl.java @@ -0,0 +1,56 @@ +package net.codingarea.challenges.plugin.content.i18n.impl.dynamic; + +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageHolder; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.impl.MessageKeyImpl; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Locale; + +@ApiStatus.Internal +@ApiStatus.Experimental +public class WrappedObjMessageImpl implements LocalizableMessage { + // TODO REMOVE: this class introduced unnecessary overhead, impacting performance + + public static final String[] VALUE = new String[]{"{0}"}; + + public WrappedObjMessageImpl(@NotNull Object wrappedArray) { + this.wrappedArray = new Object[]{wrappedArray}; + } + + private final Object[] wrappedArray; + + @NotNull + @Override + public MessageHolder localize(@NotNull Locale locale) { + return new MessageHolder(VALUE, wrappedArray); + } + + @NotNull + @Override + public MessageHolder localize(@NotNull Player playerLocale) { + return localize(MessageKeyImpl.getPlayerLocale(playerLocale)); + } + + @NotNull + @Override + public LocalizableMessage withArgs(@NotNull Object... args) { + if (args.length != 1) throw new IllegalArgumentException("WrappedObjMessageImpl must wrap a single object, but got " + args.length + " arguments."); + return new WrappedObjMessageImpl(args); + } + + @Nullable + @Override + public MessageKey getLocalizableKey() { + return null; + } + + @Override + public @NotNull Object[] getLocalizableArgs() { + return new Object[0]; + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java index eea20d7f9..0757b446a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java @@ -7,6 +7,7 @@ import net.kyori.adventure.translation.Translatable; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -23,6 +24,7 @@ public static Component convertToComponent(@Nullable Object obj) { case ComponentLike like -> like.asComponent(); case MessageHolder holder -> convertMessageHolderToComponent(holder); case Material material -> getDetailedMaterialTranslatable(material); + case ItemStack item -> getItemSpriteOrEmpty(item); case Translatable translatable -> // net.kyori.adventure.translation.Translatable Component.translatable(translatable); case Player player -> player.displayName(); @@ -38,18 +40,22 @@ public static Component convertMessageHolderToComponent(@NotNull MessageHolder h return ComponentFormatter.deserializeLinesWithArgs(null, holder.rawValue(), holder.positionalArgs()); } + @NotNull + public static Component getItemSpriteOrEmpty(@NotNull ItemStack item) { + try { + Component sprite = ItemSprites.sprite(item); + if (sprite.equals(Component.empty())) return sprite; // don't append space + return sprite.appendSpace(); + } catch (Throwable ignored) { + // not yet available in this version + return Component.empty(); + } + } + @NotNull public static Component getDetailedMaterialTranslatable(@NotNull Material material) { String key = material.translationKey(); // e.g., "item.minecraft.music_disc_strad" Component baseComponent = Component.translatable(key); - -// try { -// baseComponent = ComponentSprites.createSpriteComponent(material).appendSpace().append(baseComponent); -// } catch (Throwable ex) { -// ex.printStackTrace(); -// // sprites (and appendSpace) not available in this paper/adventure version -// } - String name = material.name(); if (name.startsWith("MUSIC_DISC_")) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java index 7b9e7b535..a1983a558 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java @@ -110,7 +110,7 @@ public static List replacePositionalArgsAsList(@NotNull Component com } Component replaced = replacePositionalArgs(component, positionalArgs); - return ComponentSplitter.split(replaced, ComponentSplitter.NEW_LINE); + return ComponentSplitter.split(replaced); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSplitter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSplitter.java index 30aace376..c0abb4d7a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSplitter.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSplitter.java @@ -2,90 +2,171 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; -import org.intellij.lang.annotations.RegExp; +import net.kyori.adventure.text.format.Style; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; -import java.util.Arrays; +import java.util.Collections; import java.util.List; -import java.util.stream.Collectors; +/** + * Splits an Adventure {@link Component} into multiple components by newline + * characters ({@code \n}), while preserving all styling (colors, decorations, + * click/hover events, fonts, etc.). + *

    + * Designed for frequent calls: no regex, no component builders, no redundant + * allocations, and a zero-copy fast path for components without newlines. + */ public final class ComponentSplitter { - @RegExp - public static final String NEW_LINE = "\\n"; - private ComponentSplitter() { } /** - * Splits a component and the underlying component tree by a regex. Styles are being preserved, so - * splitting {@code line1\nline2} by the regex "\n" will produce two components - * with {@link net.kyori.adventure.text.format.TextColor} green. It matches the regex for all - * components and their content but not for a pattern that goes beyond one component. - * {@code line1abcline2} can therefore not be split with the regex "abc", because - * only "ab" or "c" would match. + * Splits the given component at every {@code \n} into separate components. + * Styles are resolved against their parents before splitting, so each + * resulting line renders exactly like the corresponding part of the input. + *

    + * A trailing newline produces a trailing empty line; an input without any + * newline is returned unchanged as a single-element list. * - * @param self A component to split at a regex. - * @param separator A regex to split the TextComponent content at. - * @return A list of new components + * @param component the component to split + * @return the line components (never empty); the list is freshly allocated + * and owned by the caller, except for the newline-free fast path + * which returns an immutable singleton */ @NotNull @Contract(pure = true) - public static List split(@NotNull Component self, @NotNull @RegExp String separator) { - // First split component content - List lines = splitComponentContent(self, separator); + public static List split(@NotNull Component component) { + // Fast path: nothing to split -> return the original instance untouched. + if (!containsNewline(component)) { + return Collections.singletonList(component); + } + + final SplitState state = new SplitState(); + visit(component, Style.empty(), state); + state.finishLine(); // flush the last line + return state.lines; + } - if (self.children().isEmpty()) { - return lines; + private static boolean containsNewline(final Component component) { + if (component instanceof TextComponent + && ((TextComponent) component).content().indexOf('\n') >= 0) { + return true; + } + for (final Component child : component.children()) { + if (containsNewline(child)) { + return true; + } + } + return false; + } + + private static void visit(final Component component, final Style parentStyle, final SplitState state) { + // Resolve the effective style like vanilla rendering does, but skip the + // merge entirely when one side cannot contribute anything. + final Style own = component.style(); + final Style style; + if (parentStyle.isEmpty()) { + style = own; + } else if (own.isEmpty()) { + style = parentStyle; + } else { + style = own.merge(parentStyle, Style.Merge.Strategy.IF_ABSENT_ON_TARGET); } - // Extract last split, which will contain all children of the same line - Component parent = lines.removeLast(); + if (component instanceof TextComponent) { + final String content = ((TextComponent) component).content(); + final int firstNewline = content.indexOf('\n'); - // Process each child in order - for (Component child : self.children()) { - // Split child to List - List childSegments = split(child, separator); + if (firstNewline < 0) { + if (!content.isEmpty()) { + // Reuse the original component when it already carries the + // resolved style and has no children; otherwise re-wrap. + if (style == own && component.children().isEmpty()) { + state.append(component); + } else { + state.append(Component.text(content, style)); + } + } + } else { + // Manual scan instead of String#split: no regex, no String[]. + int start = 0; + int newline = firstNewline; + do { + if (newline > start) { + state.append(Component.text(content.substring(start, newline), style)); + } + state.finishLine(); + start = newline + 1; + } while ((newline = content.indexOf('\n', start)) >= 0); - // each split will be a new row, except the first which will stick to the parent - parent = parent.append(childSegments.get(0)); - for (int i = 1; i < childSegments.size(); i++) { - lines.add(parent); - parent = Component.empty().style(parent.style()); - parent = parent.append(childSegments.get(i)); + if (start < content.length()) { + state.append(Component.text(content.substring(start), style)); + } + } + } else { + // Non-text components (translatable, keybind, score, selector, ...) + // cannot be split internally. Append them with the resolved style + // and without children - those are visited separately below so + // newlines inside them are still handled. + if (style == own && component.children().isEmpty()) { + state.append(component); + } else { + state.append(component.children(Collections.emptyList()).style(style)); } } - lines.add(parent); - return lines; + + for (final Component child : component.children()) { + visit(child, style, state); + } } /** - * Splits a {@link TextComponent} by a regex. - * - * @param component A {@link TextComponent} to split. If the provided Component is no instance of - * TextComponent, a list with only the component is returned. - * @param regex A regex that splits the content of the TextComponent, similar to - * {@link String#split(String)} - * @return A list of TextComponents that contain the string segments of the original content. + * Mutable state used while walking the component tree. Lines are assembled + * without component builders: a single-part line is used as-is, and + * multi-part lines are attached as children of an empty root via + * {@link Component#children(List)}. */ - @NotNull - private static List splitComponentContent(@NotNull Component component, @NotNull @RegExp String regex) { - if (!(component instanceof TextComponent t)) { - List components = new ArrayList<>(1); - components.add(component); - return components; + private static final class SplitState { + private final List lines = new ArrayList<>(); + + /** + * The only part of the current line, while it has exactly one. + */ + private Component single; + /** + * All parts of the current line, once it has two or more. + */ + private List parts; + + void append(final Component part) { + if (this.parts != null) { + this.parts.add(part); + return; + } + if (this.single == null) { + this.single = part; + return; + } + // Second part arrived: promote to a list. + this.parts = new ArrayList<>(8); + this.parts.add(this.single); + this.parts.add(part); + this.single = null; } - String[] segments = t.content().split(regex); - if (segments.length == 0) { - // Special case if the split regex is equals to the content. - segments = new String[]{"", ""}; + + void finishLine() { + if (this.parts != null) { + this.lines.add(Component.empty().children(this.parts)); + this.parts = null; + } else if (this.single != null) { + this.lines.add(this.single); + this.single = null; + } else { + this.lines.add(Component.empty()); + } } - return Arrays.stream(segments) - .map(s -> Component.text(s).style(t.style())) - .map(c -> (Component) c) - .collect(Collectors.toList()); } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSprites.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSprites.java deleted file mode 100644 index 4ae52f6c8..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentSprites.java +++ /dev/null @@ -1,40 +0,0 @@ -package net.codingarea.challenges.plugin.content.i18n.impl.format; - -import net.kyori.adventure.key.Key; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.object.ObjectContents; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -final class ComponentSprites { - - private ComponentSprites() { - } - - @NotNull - static Component createSpriteComponent(@Nullable Material material) { - if (material == null || material.isAir() || !material.isItem()) { - return Component.empty(); - } - - // 2. Get the clean, lowercase vanilla key string (e.g., "diamond_sword" or "stone") - NamespacedKey namespaced = material.getKey(); - String materialKey = namespaced.getKey().toLowerCase(); - - // 3. Determine if the path should be prefixed with 'item/' or 'block/' - // Note: Some blocks (like STONE) use 'block/stone', while items use 'item/diamond_sword' - String prefix = material.isBlock() ? "block/" : "item/"; - - // 4. Create the resource path key inside the default atlas (minecraft:blocks) - Key spritePath = Key.key("minecraft", prefix + materialKey); - System.err.println("Creating sprite component for material: " + material + " with path: " + spritePath + " key: " + material.key() + " translatebleKey: " + material.translationKey()); - - // 5. Build and return the object component with an empty fallback - return Component.object(builder -> builder - .contents(ObjectContents.sprite(material.key())) // Defaults to the minecraft:blocks atlas - ); - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ItemSprites.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ItemSprites.java new file mode 100644 index 000000000..2fc2565ea --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ItemSprites.java @@ -0,0 +1,333 @@ +package net.codingarea.challenges.plugin.content.i18n.impl.format; + +import io.papermc.paper.datacomponent.DataComponentTypes; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.object.ObjectContents; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.Tag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; + +/** + * Resolves a {@link Material} / {@link ItemStack} to an Adventure sprite {@link Component} + * for boss bars, action bars, tab lists, etc. (MC 1.21.9+ object components). + * + *

    Fully self-contained: no config files, no asset extraction. The override tables below + * were machine-validated against the complete vanilla item registry and texture lists of + * both 26.1.2 and the 26.3 snapshots (0 unresolved sprites on either). Materials that + * don't exist on the running server version are skipped automatically, so this compiles + * and runs across API versions.

    + */ +final class ItemSprites { + + private ItemSprites() { + } + + // ------------------------------------------------------------------ atlases + + private static final Key BLOCKS_ATLAS = Key.key("minecraft", "blocks"); + + /** + * Items lived in the blocks atlas only on 1.21.9/1.21.10; minecraft:items ever since. + */ + private static final Key ITEMS_ATLAS = switch (Bukkit.getMinecraftVersion()) { + case "1.21.9", "1.21.10" -> BLOCKS_ATLAS; + default -> Key.key("minecraft", "items"); + }; + + private static final Map CACHE = new ConcurrentHashMap<>(); + + // ------------------------------------------------------- irregular item sprites + // Items whose sprite name differs from their registry key (animated / layered / absent). + + private static final Map ITEM_OVERRIDES = materialMap(Map.of( + "clock", "clock_00", // per-frame since the item-model split + "compass", "compass_16", // frame 16 = the classic "north" look + "recovery_compass", "recovery_compass_16", + "crossbow", "crossbow_standby", + "debug_stick", "stick", // has no texture of its own + "tipped_arrow", "tipped_arrow_base", // tint layer can't render; base only + "enchanted_golden_apple", "golden_apple", // glint-only variant, no own texture + "light", "light_15" // plain "light" removed in 26.3+ + )); + + // ------------------------------------------------- blocks with flat ITEM sprites + // Their block form has no matching texture, but item/ exists. + + private static final Set ITEM_SPRITE_BLOCKS = materialSet( + "wheat", "nether_wart", "sugar_cane", "bamboo", "cake", "cauldron", "bell", + "hopper", "repeater", "comparator", "brewing_stand", "flower_pot", + "campfire", "soul_campfire", "lantern", "soul_lantern", "kelp", "seagrass", + "sea_pickle", "pointed_dripstone", "pink_petals", "wildflowers", "leaf_litter", + "firefly_bush", "mangrove_propagule", "pitcher_plant", "nether_sprouts", + "barrier", "structure_void", "sniffer_egg", "sulfur_spike"); + + /** + * Tag/suffix driven so future colors, wood types & oxidation states just work. + */ + private static boolean usesItemSprite(Material m, String key) { + return ITEM_SPRITE_BLOCKS.contains(m) + || Tag.DOORS.isTagged(m) + || Tag.ALL_SIGNS.isTagged(m) // signs + hanging signs + || Tag.CANDLES.isTagged(m) + || key.endsWith("_chain") || key.equals("iron_chain") + || key.endsWith("copper_lantern"); // (waxed_ already stripped by caller) + } + + // ------------------------------------------------------------ sprite-less items + // Rendered as 3D block-entity models in inventory; their textures exist only as + // unwrapped UV sheets in dedicated atlases (minecraft:chest, shulker_boxes, ...) + // which look wrong drawn flat, so we substitute (beds, player heads) or stay empty. + + private static boolean hasNoSprite(Material m, String key) { + return key.endsWith("chest") // chest, trapped/ender, copper chests + || key.endsWith("_banner") + || key.contains("golem_statue") // 26.x copper golem statues + || m == Material.CONDUIT || m == Material.DECORATED_POT || m == Material.SHIELD; + } + + private static boolean isSkull(String key) { + return key.endsWith("_head") || key.endsWith("_skull"); + } + + // ------------------------------------------------ irregular block texture names + // Multi-face / animated / renamed blocks. Every entry verified to exist in both + // 26.1.2 and 26.3 assets (e.g. purpur_pillar_top, because the plain purpur_pillar + // texture was renamed to purpur_pillar_side in 26.2+). + + private static final Map BLOCK_OVERRIDES = materialMap(Map.ofEntries( + Map.entry("grass_block", "grass_block_side"), + Map.entry("mycelium", "mycelium_side"), + Map.entry("podzol", "podzol_side"), + Map.entry("dirt_path", "dirt_path_top"), + Map.entry("crafting_table", "crafting_table_front"), + Map.entry("furnace", "furnace_front"), + Map.entry("blast_furnace", "blast_furnace_front"), + Map.entry("smoker", "smoker_front"), + Map.entry("loom", "loom_front"), + Map.entry("smithing_table", "smithing_table_front"), + Map.entry("fletching_table", "fletching_table_front"), + Map.entry("cartography_table", "cartography_table_side3"), + Map.entry("grindstone", "grindstone_side"), + Map.entry("stonecutter", "stonecutter_side"), + Map.entry("lectern", "lectern_front"), + Map.entry("enchanting_table", "enchanting_table_side"), + Map.entry("jukebox", "jukebox_side"), + Map.entry("tnt", "tnt_side"), + Map.entry("cactus", "cactus_side"), + Map.entry("melon", "melon_side"), + Map.entry("pumpkin", "pumpkin_side"), + Map.entry("hay_block", "hay_block_side"), + Map.entry("dried_kelp_block", "dried_kelp_side"), + Map.entry("bone_block", "bone_block_side"), + Map.entry("snow_block", "snow"), + Map.entry("barrel", "barrel_side"), + Map.entry("composter", "composter_side"), + Map.entry("dispenser", "dispenser_front"), + Map.entry("dropper", "dropper_front"), + Map.entry("observer", "observer_front"), + Map.entry("crafter", "crafter_north"), + Map.entry("piston", "piston_side"), + Map.entry("sticky_piston", "piston_side"), + Map.entry("daylight_detector", "daylight_detector_top"), + Map.entry("target", "target_side"), + Map.entry("bee_nest", "bee_nest_front"), + Map.entry("beehive", "beehive_front"), + Map.entry("honey_block", "honey_block_side"), + Map.entry("bookshelf", "bookshelf"), + Map.entry("chiseled_bookshelf", "chiseled_bookshelf_occupied"), + Map.entry("magma_block", "magma"), + Map.entry("basalt", "basalt_side"), + Map.entry("polished_basalt", "polished_basalt_side"), + Map.entry("quartz_block", "quartz_block_side"), + Map.entry("smooth_quartz", "quartz_block_bottom"), + Map.entry("quartz_pillar", "quartz_pillar_top"), + Map.entry("purpur_pillar", "purpur_pillar_top"), + Map.entry("smooth_sandstone", "sandstone_top"), + Map.entry("smooth_red_sandstone", "red_sandstone_top"), + Map.entry("lodestone", "lodestone_side"), + Map.entry("respawn_anchor", "respawn_anchor_side0"), + Map.entry("ancient_debris", "ancient_debris_side"), + Map.entry("reinforced_deepslate", "reinforced_deepslate_side"), + Map.entry("sculk_sensor", "sculk_sensor_top"), + Map.entry("calibrated_sculk_sensor", "calibrated_sculk_sensor_top"), + Map.entry("sculk_catalyst", "sculk_catalyst_side"), + Map.entry("sculk_shrieker", "sculk_shrieker_side"), + Map.entry("suspicious_sand", "suspicious_sand_0"), + Map.entry("suspicious_gravel", "suspicious_gravel_0"), + Map.entry("vault", "vault_front_off"), + Map.entry("trial_spawner", "trial_spawner_side_inactive"), + Map.entry("command_block", "command_block_front"), + Map.entry("chain_command_block", "chain_command_block_front"), + Map.entry("repeating_command_block", "repeating_command_block_front"), + Map.entry("jigsaw", "jigsaw_side"), + Map.entry("test_block", "test_block_start"), + Map.entry("end_portal_frame", "end_portal_frame_side"), + Map.entry("scaffolding", "scaffolding_side"), + Map.entry("heavy_weighted_pressure_plate", "iron_block"), + Map.entry("light_weighted_pressure_plate", "gold_block"), + Map.entry("petrified_oak_slab", "oak_planks"), + Map.entry("bamboo_fence", "bamboo_fence"), + Map.entry("bamboo_fence_gate", "bamboo_fence_gate"), + Map.entry("bamboo_stairs", "bamboo_planks"), + Map.entry("bamboo_slab", "bamboo_planks"), + Map.entry("bamboo_button", "bamboo_planks"), + Map.entry("bamboo_pressure_plate", "bamboo_planks"), + Map.entry("anvil", "anvil"), + Map.entry("chipped_anvil", "chipped_anvil_top"), + Map.entry("damaged_anvil", "damaged_anvil_top"), + Map.entry("azalea", "azalea_top"), + Map.entry("flowering_azalea", "flowering_azalea_top"), + Map.entry("big_dripleaf", "big_dripleaf_top"), + Map.entry("small_dripleaf", "small_dripleaf_top"), + Map.entry("mangrove_roots", "mangrove_roots_side"), + Map.entry("muddy_mangrove_roots", "muddy_mangrove_roots_side"), + Map.entry("sniffer_egg", "sniffer_egg_not_cracked_north"), // fallback; item sprite preferred + Map.entry("dried_ghast", "dried_ghast_hydration_0_north"), + Map.entry("shelf_mushroom", "shelf_mushroom_stage1"), + Map.entry("sunflower", "sunflower_front"), + Map.entry("lilac", "lilac_top"), + Map.entry("rose_bush", "rose_bush_top"), + Map.entry("peony", "peony_top"), + Map.entry("tall_grass", "tall_grass_top"), + Map.entry("large_fern", "large_fern_top"), + Map.entry("straw_bed", "straw_bed") // unlike colored beds, has a flat texture + )); + + // ==================================================================== public API + + /** + * Sprite for an item stack. Prefer this over {@link #sprite(Material)}: it renders + * real player heads and skips stacks whose item model was customized by a + * datapack/plugin (a vanilla-derived sprite would be misleading for those). + */ + public static @NotNull Component sprite(@Nullable ItemStack stack) { + if (stack == null || stack.isEmpty()) return Component.empty(); + + Key model = stack.getData(DataComponentTypes.ITEM_MODEL); + if (model != null && !model.equals(stack.getType().getKey())) return Component.empty(); + + if (stack.getType() == Material.PLAYER_HEAD + && stack.getItemMeta() instanceof SkullMeta skull + && skull.getOwningPlayer() != null) { + return Component.object(ObjectContents.playerHead(skull.getOwningPlayer().getUniqueId())); + } + return sprite(stack.getType()); + } + + /** + * Sprite for a material, or {@link Component#empty()} if nothing usable exists. + */ + public static @NotNull Component sprite(@Nullable Material material) { + if (material == null || material.isAir() || !material.isItem()) return Component.empty(); + return CACHE.computeIfAbsent(material, ItemSprites::resolve); + } + + // ==================================================================== resolution + + private static Component resolve(Material m) { + // waxed_/infested_ blocks are pure state variants sharing the base's textures + // AND item sprites — strip before anything else (fixes waxed copper doors etc.) + String key = stripAliasPrefix(m.getKey().getKey()); + + String itemOverride = ITEM_OVERRIDES.get(m); + if (itemOverride != null) return item(itemOverride); + if (isSkull(key)) return Component.empty(); // (player heads via ItemStack overload) + if (hasNoSprite(m, key)) return Component.empty(); + if (Tag.SHULKER_BOXES.isTagged(m)) return Component.empty(); + + String blockOverride = BLOCK_OVERRIDES.get(m); + if (blockOverride != null) return block(blockOverride); + + // colored beds have no flat sprite anywhere -> wool substitute + if (Tag.BEDS.isTagged(m) && key.endsWith("_bed")) { + return block(key.substring(0, key.length() - 4) + "_wool"); + } + + if (!m.isBlock() || usesItemSprite(m, key)) return item(key); + return block(deriveBlockTexture(key)); + } + + /** + * Shaped blocks (stairs, slabs, walls, fences, panes, buttons, plates, carpets), + * wood/hyphae and froglights have no textures of their own — derive the block + * they borrow from, then apply that base's override if it has one. + */ + private static String deriveBlockTexture(String key) { + if (key.endsWith("froglight")) return key + "_side"; + if (key.endsWith("_wood")) return key.substring(0, key.length() - 5) + "_log"; + if (key.endsWith("_hyphae")) return key.substring(0, key.length() - 7) + "_stem"; + + String base = null; + for (String suffix : new String[]{"_stairs", "_slab", "_wall", "_fence_gate", + "_fence", "_button", "_pressure_plate", "_pane", "_carpet"}) { + if (key.endsWith(suffix)) { + base = key.substring(0, key.length() - suffix.length()); + break; + } + } + if (base == null) return key; // full block with its own texture + + // resolve the borrowed base: oak_stairs -> oak_planks, nether_brick_fence -> + // nether_bricks, purpur_stairs -> purpur_block, moss_carpet -> moss_block, + // white_carpet -> white_wool, smooth_sandstone_slab -> (override) sandstone_top + for (String candidate : List.of(base, base + "_planks", base + "s", + base + "_block", base + "_wool")) { + Material bm = Material.matchMaterial(candidate); + if (bm != null && bm.isBlock()) { + String o = BLOCK_OVERRIDES.get(bm); + return o != null ? o : candidate; + } + } + return key; // graceful worst case for future unknown blocks + } + + private static String stripAliasPrefix(String key) { + for (String prefix : new String[]{"waxed_", "infested_"}) { + if (key.startsWith(prefix)) { + String stripped = key.substring(prefix.length()); + if (Material.matchMaterial(stripped) != null) return stripped; + } + } + return key; + } + + // ==================================================================== components + + private static Component item(String name) { + return Component.object(ObjectContents.sprite(ITEMS_ATLAS, Key.key("minecraft", "item/" + name))); + } + + private static Component block(String name) { + return Component.object(ObjectContents.sprite(BLOCKS_ATLAS, Key.key("minecraft", "block/" + name))); + } + + // -------------------------------------------------- version-safe table builders + // Built from key strings via matchMaterial so entries for materials that don't + // exist on this server/API version are silently skipped (compiles everywhere, + // and 26.2+/26.3 entries like sulfur_spike are inert on 26.1.x). + + private static Set materialSet(String... keys) { + return Arrays.stream(keys) + .map(Material::matchMaterial) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(() -> EnumSet.noneOf(Material.class))); + } + + private static Map materialMap(Map byKey) { + Map out = new EnumMap<>(Material.class); + byKey.forEach((k, v) -> { + Material m = Material.matchMaterial(k); + if (m != null) out.put(m, v); + }); + return out; + } +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java index f8c0b8777..f9ba99d7f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java @@ -97,7 +97,6 @@ public Collection retrieveViewers() { List viewers = new ArrayList<>(); // default capacity: 10 for (Player player : Bukkit.getOnlinePlayers()) { MenuPosition position = MenuPosition.get(player); - if (position == null) continue; if (position instanceof GeneratorMenuPosition generatorPosition && generatorPosition.getGenerator() == this) { viewers.add(player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/UncachedMultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/UncachedMultiPageSelectMenuGenerator.java similarity index 96% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/UncachedMultiPageMenuGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/UncachedMultiPageSelectMenuGenerator.java index 789db9680..aa6b91cf9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/UncachedMultiPageMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/UncachedMultiPageSelectMenuGenerator.java @@ -14,7 +14,7 @@ import java.util.Locale; -public abstract class UncachedMultiPageMenuGenerator extends AbstractMenuGenerator { +public abstract class UncachedMultiPageSelectMenuGenerator extends AbstractMenuGenerator { public static int[] calcSlots(int rows, int cols, int size) { if (rows * cols > size) @@ -41,7 +41,7 @@ public static int[] calcSlots(int padding, int size) { protected final T[] elements; - public UncachedMultiPageMenuGenerator(@NotNull T[] elements) { + public UncachedMultiPageSelectMenuGenerator(@NotNull T[] elements) { this.elements = elements; } @@ -60,6 +60,12 @@ public void updatePage(int page) { // because pages are not cached, there is noting to update } + @NotNull + @Override + public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { + return new UncachedMultiPageMenuPosition(page, player); + } + @NotNull @Override public Inventory getOrInitInventory(@NotNull Locale locale, int page) { @@ -91,12 +97,6 @@ private MessageKey getMenuTitleKey() { return MessageKey.of("menu.title-format-page"); } - @NotNull - @Override - public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { - return new UncachedMultiPageMenuPosition(page, player); - } - public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotNull Locale locale) { int startIndex = page * getMaxEntriesPerPage(); int endIndex = Math.min(startIndex + getMaxEntriesPerPage(), elements.length); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java index a4549c600..c29d11b12 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java @@ -10,10 +10,10 @@ import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.SinglePageMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.CustomChooseMaterialMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.CustomMainSettingsMenuGenerator; import net.codingarea.challenges.plugin.spigot.listener.ChatInputListener; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -107,8 +107,7 @@ public void updateInventoryContent(@NotNull Inventory inventory, @NotNull Locale ItemBuilder triggerItem = new ItemBuilder(locale, Material.WITHER_SKELETON_SKULL, MessageKey.of("menu.custom.info.item-trigger"), triggerName); if (trigger != null) { - List lines = SubSettingsBuilder.getSubSettingsDisplay(trigger.getSubSettingsBuilder(), subTriggers); - if (!lines.isEmpty()) triggerItem.appendLore(lines); + appendSubSettingDisplay(triggerItem, trigger.getSubSettingsBuilder().getCurrentDisplayFor(subTriggers)); } inventory.setItem(CONDITION_SLOT, triggerItem.build()); @@ -117,8 +116,7 @@ public void updateInventoryContent(@NotNull Inventory inventory, @NotNull Locale ItemBuilder actionItem = new ItemBuilder(locale, Material.NETHER_STAR, MessageKey.of("menu.custom.info.item-action"), actionName); if (action != null) { - List lines = SubSettingsBuilder.getSubSettingsDisplay(action.getSubSettingsBuilder(), subActions); - if (!lines.isEmpty()) actionItem.appendLore(lines); + appendSubSettingDisplay(actionItem, action.getSubSettingsBuilder().getCurrentDisplayFor(subActions)); } inventory.setItem(ACTION_SLOT, actionItem.build()); @@ -133,6 +131,12 @@ public void updateInventoryContent(@NotNull Inventory inventory, @NotNull Locale name, maxNameLength).build()); } + protected void appendSubSettingDisplay(@NotNull ItemBuilder item, @NotNull Collection display) { + for (SubSettingsBuilder.SubSettingDisplay settingDisplay : display) { + item.appendLore(MessageKey.of("menu.custom.subsetting-format"), settingDisplay.keyName(), settingDisplay.valueFormatted()); + } + } + @Override public int getInventorySize() { return SIZE; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseItemMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseItemMenuGenerator.java deleted file mode 100644 index 67d0e91ce..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseItemMenuGenerator.java +++ /dev/null @@ -1,104 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose; - -import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.UncachedMultiPageMenuGenerator; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; - -/** - * Displays a static, keyed set of pre-built {@link ItemStack}s to choose one from. - * Replaces the legacy {@code ChooseItemGenerator}. The item content is passed in pre-built, - * as its (legacy) localization happens outside this generator. - */ -public abstract class CustomChooseItemMenuGenerator extends UncachedMultiPageMenuGenerator { - - public static final int SIZE = 5 * 9; - public static final int[] SLOTS = calcSlots(3, 7, SIZE); - - private final LocalizableMessage menuName; - - protected CustomChooseItemMenuGenerator(@NotNull LocalizableMessage menuName, @NotNull LinkedHashMap items) { - super(toKeyedItems(items)); - this.menuType = MenuType.CUSTOM; - this.menuName = menuName; - } - - protected static KeyedItem[] toKeyedItems(@NotNull LinkedHashMap items) { - KeyedItem[] array = new KeyedItem[items.size()]; - int i = 0; - for (Map.Entry entry : items.entrySet()) { - array[i++] = new KeyedItem(entry.getKey(), entry.getValue()); - } - return array; - } - - @NotNull - @Override - public LocalizableMessage getMenuName() { - return menuName; - } - - public abstract void onItemClick(@NotNull Player player, @NotNull String key); - - @Override - public void handleElementClick(@NotNull KeyedItem element, @NotNull MenuClickInfo info) { - onItemClick(info.getPlayer(), element.key()); - } - - @NotNull - @Override - public ItemStack createDisplayItem(@NotNull KeyedItem element, @NotNull Locale locale) { - return element.item(); - } - - @Override - public int[] getSlots() { - return SLOTS; - } - - @Override - public int getInventorySize() { - return SIZE; - } - - @NotNull - @Override - public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { - return new ChooseItemMenuPosition(page); - } - - public class ChooseItemMenuPosition extends GeneratorMenuPosition { - - public ChooseItemMenuPosition(int page) { - super(page); - } - - @Override - public boolean handleMenuClick(@NotNull MenuClickInfo info) { - int[] slots = getSlots(); - for (int i = 0; i < slots.length; i++) { - if (info.getSlot() != slots[i]) continue; - - int index = getPage() * getMaxEntriesPerPage() + i; - if (index >= elements.length) return false; // page not full - - SoundSample.PLOP.play(info.getPlayer()); - onItemClick(info.getPlayer(), elements[index].key()); - return true; - } - return false; - } - } - - public record KeyedItem(@NotNull String key, @NotNull ItemStack item) { - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMaterialMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMaterialMenuGenerator.java index ecb1d417a..d4a16226e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMaterialMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMaterialMenuGenerator.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.UncachedMultiPageMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.UncachedMultiPageSelectMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; @@ -20,10 +20,10 @@ import java.util.ArrayList; import java.util.Locale; -public class CustomChooseMaterialMenuGenerator extends UncachedMultiPageMenuGenerator { +public class CustomChooseMaterialMenuGenerator extends UncachedMultiPageSelectMenuGenerator { - public static final int SIZE = 5 * 9; - public static final int[] SLOTS = calcSlots(3, 7, SIZE); + public static final int SIZE = CustomChooseOptionMenuGenerator.SIZE; + public static final int[] SLOTS = CustomChooseOptionMenuGenerator.SLOTS; public static final Material[] MATERIALS; static { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleItemMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleItemMenuGenerator.java deleted file mode 100644 index 1b3ad2203..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleItemMenuGenerator.java +++ /dev/null @@ -1,125 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose; - -import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.UncachedMultiPageMenuGenerator; -import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.CustomChooseItemMenuGenerator.KeyedItem; -import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; - -/** - * Choose multiple pre-built items; toggles a selection marker and confirms via a finish button. - * Replaces the legacy {@code ChooseMultipleItemGenerator}. - */ -public abstract class CustomChooseMultipleItemMenuGenerator extends UncachedMultiPageMenuGenerator { - - public static final int SIZE = 5 * 9; - public static final int[] SLOTS = calcSlots(3, 7, SIZE); - public static final int FINISH_SLOT = 40; - - private final LocalizableMessage menuName; - private final List selectedKeys = new LinkedList<>(); - - protected CustomChooseMultipleItemMenuGenerator(@NotNull LocalizableMessage menuName, @NotNull LinkedHashMap items) { - super(CustomChooseItemMenuGenerator.toKeyedItems(items)); - this.menuType = MenuType.CUSTOM; - this.menuName = menuName; - } - - @NotNull - @Override - public LocalizableMessage getMenuName() { - return menuName; - } - - public abstract void onItemClick(@NotNull Player player, @NotNull String[] keys); - - @Override - public void handleElementClick(@NotNull KeyedItem element, @NotNull MenuClickInfo info) { - // handled by the custom menu position (toggle instead of confirm) - } - - @NotNull - @Override - public ItemStack createDisplayItem(@NotNull KeyedItem element, @NotNull Locale locale) { - ItemBuilder builder = new ItemBuilder(locale, element.item().clone()).hideAttributes(); - if (selectedKeys.contains(element.key())) { - builder.addEnchantment(MinecraftNameWrapper.UNBREAKING, 1); - builder.appendName(" §8┃ §2§l✔"); - } else { - builder.appendName(" §8┃ §c✖"); - } - return builder.build(); - } - - @Override - public void setInventoryDecoration(@NotNull Inventory inventory, int page, @NotNull Locale locale) { - super.setInventoryDecoration(inventory, page, locale); - inventory.setItem(FINISH_SLOT, new ItemBuilder(locale, Material.LIME_DYE, MessageKey.of("custom-sub-finish")).build()); - } - - @Override - public int[] getSlots() { - return SLOTS; - } - - @Override - public int getInventorySize() { - return SIZE; - } - - @NotNull - @Override - public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { - return new ChooseMultipleMenuPosition(page); - } - - public class ChooseMultipleMenuPosition extends GeneratorMenuPosition { - - public ChooseMultipleMenuPosition(int page) { - super(page); - } - - @Override - public boolean handleMenuClick(@NotNull MenuClickInfo info) { - if (info.getSlot() == FINISH_SLOT) { - SoundSample.PLOP.play(info.getPlayer()); - onItemClick(info.getPlayer(), selectedKeys.toArray(new String[0])); - return true; - } - - int[] slots = getSlots(); - for (int i = 0; i < slots.length; i++) { - if (info.getSlot() != slots[i]) continue; - - int index = getPage() * getMaxEntriesPerPage() + i; - if (index >= elements.length) return false; // page not full - - String key = elements[index].key(); - if (selectedKeys.contains(key)) { - selectedKeys.remove(key); - } else { - selectedKeys.add(key); - } - SoundSample.LOW_PLOP.play(info.getPlayer()); - openMenu(info.getPlayer(), getPage()); // re-render selection markers - return true; - } - return false; - } - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleOptionsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleOptionsMenuGenerator.java new file mode 100644 index 000000000..29d83855f --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMultipleOptionsMenuGenerator.java @@ -0,0 +1,93 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose; + +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; +import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Locale; +import java.util.Map; + +public abstract class CustomChooseMultipleOptionsMenuGenerator extends CustomChooseOptionMenuGenerator { + + public static final int FINISH_SLOT = 40; + + private final Collection selectedKeys = new HashSet<>(); + + protected CustomChooseMultipleOptionsMenuGenerator(@NotNull LocalizableMessage menuName, @NotNull Map items) { + super(menuName, items); + } + + public abstract void onSaveClick(@NotNull Player player, @NotNull String[] keys); + + @Override + public void onItemClick(@NotNull Player player, @NotNull String key) { + if (selectedKeys.contains(key)) { + selectedKeys.remove(key); + } else { + selectedKeys.add(key); + } + } + + @Override + public void handleElementClick(@NotNull SelectableKey element, @NotNull MenuClickInfo info) { + super.handleElementClick(element, info); + + // re-render element + setElementItemsAt(element, info.getInventory(), info.getSlot(), findLanguageProvider().getPlayerLanguage(info.getPlayer())); + } + + @NotNull + @Override + public ItemStack createDisplayItem(@NotNull SelectableKey element, @NotNull Locale locale) { + ItemBuilder item = element.getDisplayItem(locale); + if (selectedKeys.contains(element.getKey())) { + item.addEnchantment(MinecraftNameWrapper.UNBREAKING, 1); + item.appendName(MessageKey.of("suffix.selected")); + } else { + item.appendName(MessageKey.of("suffix.unselected")); + } + return item.build(); + } + + @Override + public void setInventoryDecoration(@NotNull Inventory inventory, int page, @NotNull Locale locale) { + super.setInventoryDecoration(inventory, page, locale); + inventory.setItem(FINISH_SLOT, new ItemBuilder(locale, Material.LIME_DYE, MessageKey.of("custom-sub-finish")).build()); + } + + @NotNull + @Override + public GeneratorMenuPosition createMenuPosition(int page, @NotNull Player player) { + return new CustomChooseMultipleOptionsMenuPosition(page, player); + } + + public class CustomChooseMultipleOptionsMenuPosition extends UncachedMultiPageMenuPosition { + + public CustomChooseMultipleOptionsMenuPosition(int page, @NotNull Player player) { + super(page, player); + } + + @Override + public boolean handleMenuClick(@NotNull MenuClickInfo info) { + if (info.getSlot() == FINISH_SLOT) { + SoundSample.PLOP.play(info.getPlayer()); + onSaveClick(info.getPlayer(), selectedKeys.toArray(new String[0])); + return true; + } + + return super.handleMenuClick(info); + } + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseOptionMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseOptionMenuGenerator.java new file mode 100644 index 000000000..70b7f1d70 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseOptionMenuGenerator.java @@ -0,0 +1,57 @@ +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose; + +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.management.menu.MenuType; +import net.codingarea.challenges.plugin.management.menu.generator.UncachedMultiPageSelectMenuGenerator; +import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; + +import java.util.Locale; +import java.util.Map; + +public abstract class CustomChooseOptionMenuGenerator extends UncachedMultiPageSelectMenuGenerator { + + public static final int SIZE = 5 * 9; + public static final int[] SLOTS = calcSlots(3, 7, SIZE); + + private final LocalizableMessage menuName; + + protected CustomChooseOptionMenuGenerator(@NotNull LocalizableMessage menuName, @NotNull Map items) { + super(items.values().toArray(new SelectableKey[0])); + this.menuType = MenuType.CUSTOM; + this.menuName = menuName; + } + + @NotNull + @Override + public LocalizableMessage getMenuName() { + return menuName; + } + + public abstract void onItemClick(@NotNull Player player, @NotNull String key); + + @Override + public void handleElementClick(@NotNull SelectableKey element, @NotNull MenuClickInfo info) { + onItemClick(info.getPlayer(), element.getKey()); + } + + @NotNull + @Override + public ItemStack createDisplayItem(@NotNull SelectableKey element, @NotNull Locale locale) { + return element.getDisplayItem(locale).build(); + } + + @Override + public int[] getSlots() { + return SLOTS; + } + + @Override + public int getInventorySize() { + return SIZE; + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java index 889dd66b0..1a7486c39 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java @@ -5,13 +5,14 @@ import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.generator.UncachedMultiPageMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.UncachedMultiPageSelectMenuGenerator; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.Locale; @@ -21,11 +22,11 @@ * Displays adjustable {@link ValueSetting} rows with a finish button. * Replaces the legacy {@code ValueMenuGenerator}. */ -public abstract class CustomChooseValueMenuGenerator extends UncachedMultiPageMenuGenerator { +public abstract class CustomChooseValueMenuGenerator extends UncachedMultiPageSelectMenuGenerator { - public static final int SIZE = 4 * 9; + public static final int SIZE = 5 * 9; public static final int[] SLOTS = {10, 11, 12, 13}; // settings item at +9 each - public static final int FINISH_SLOT = 31; + public static final int FINISH_SLOT = 40; private final LocalizableMessage menuName; @@ -56,7 +57,7 @@ protected void setElementItemsAt(@NotNull ValueSetting element, @NotNull Invento @NotNull @Override - public org.bukkit.inventory.ItemStack createDisplayItem(@NotNull ValueSetting element, @NotNull Locale locale) { + public ItemStack createDisplayItem(@NotNull ValueSetting element, @NotNull Locale locale) { return element.getDisplayItem(settings.get(element)).build(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomMainSettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomMainSettingsMenuGenerator.java similarity index 92% rename from plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomMainSettingsMenuGenerator.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomMainSettingsMenuGenerator.java index 2f664a17a..10ad8c792 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomMainSettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomMainSettingsMenuGenerator.java @@ -1,20 +1,19 @@ -package net.codingarea.challenges.plugin.management.menu.generator.impl.custom; +package net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose; import lombok.Getter; import net.codingarea.challenges.plugin.challenges.custom.settings.IChallengeSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.CustomChooseItemMenuGenerator; +import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.utils.misc.MapUtils; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; -import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Function; @@ -23,7 +22,7 @@ * collecting the sub-setting data before handing it back to the parent generator. * Replaces the legacy {@code custom.CustomMainSettingsMenuGenerator}. */ -public class CustomMainSettingsMenuGenerator extends CustomChooseItemMenuGenerator implements IParentCustomGenerator { +public class CustomMainSettingsMenuGenerator extends CustomChooseOptionMenuGenerator implements IParentCustomGenerator { @Getter private final IParentCustomGenerator parent; @@ -37,7 +36,7 @@ public class CustomMainSettingsMenuGenerator extends CustomChooseItemMenuGenerat public CustomMainSettingsMenuGenerator(@NotNull IParentCustomGenerator parent, @NotNull SettingType type, @NotNull String key, @NotNull LocalizableMessage baseTitle, - @NotNull LinkedHashMap items, + @NotNull Map items, @NotNull Function instanceGetter) { super(baseTitle, items); this.parent = parent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMenuGenerator.java index 257a0114c..24f2114d8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMenuGenerator.java @@ -1,21 +1,21 @@ package net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.utils.misc.MapUtils; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.LinkedHashMap; -public class SubSettingChooseMenuGenerator extends CustomChooseItemMenuGenerator { +public class SubSettingChooseMenuGenerator extends CustomChooseOptionMenuGenerator { private final IParentCustomGenerator parent; private final String key; public SubSettingChooseMenuGenerator(@NotNull String key, @NotNull IParentCustomGenerator parent, - @NotNull LinkedHashMap items, @NotNull LocalizableMessage title) { + @NotNull LinkedHashMap items, @NotNull LocalizableMessage title) { super(title, items); this.key = key; this.parent = parent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMultipleMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMultipleMenuGenerator.java index 8f2e326e5..4115f9240 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMultipleMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/SubSettingChooseMultipleMenuGenerator.java @@ -1,28 +1,28 @@ package net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.utils.misc.MapUtils; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.LinkedHashMap; +import java.util.Map; -public class SubSettingChooseMultipleMenuGenerator extends CustomChooseMultipleItemMenuGenerator { +public class SubSettingChooseMultipleMenuGenerator extends CustomChooseMultipleOptionsMenuGenerator { private final IParentCustomGenerator parent; private final String key; public SubSettingChooseMultipleMenuGenerator(@NotNull String key, @NotNull IParentCustomGenerator parent, - @NotNull LinkedHashMap items, @NotNull LocalizableMessage title) { + @NotNull Map items, @NotNull LocalizableMessage title) { super(title, items); this.key = key; this.parent = parent; } @Override - public void onItemClick(@NotNull Player player, @NotNull String[] keys) { + public void onSaveClick(@NotNull Player player, @NotNull String[] keys) { parent.accept(player, null, MapUtils.createStringArrayMap(key, keys)); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeActionBar.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeActionBar.java index 1f3b47293..e6dfcae9c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeActionBar.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeActionBar.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.impl.format.ComponentArguments; import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -29,7 +30,8 @@ public void send(@NotNull Player player) { try { LocalizableMessage actionbar = content.apply(player); - actionbar.getLocalizableKey().sendActionBar(player, actionbar.getLocalizableArgs()); + // TODO add LocalizableMessage helper methods (same as in MessageKey without args!) + player.sendActionBar(ComponentArguments.convertMessageHolderToComponent(actionbar.localize(player))); } catch (Exception ex) { Logger.error("Unable to update actionbar for player '{}'", player.getName(), ex); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java index e6ba91537..0f29c0aa6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeScoreboard.java @@ -186,7 +186,7 @@ public ArrayList getLines(@NotNull Locale locale) { if (line == null) continue; if (line instanceof LocalizableMessage message) { - list.add(message.getLocalizableKey().asComponent(locale, message.getLocalizableArgs())); + list.add(ComponentArguments.convertMessageHolderToComponent(message.localize(locale))); } else { list.add(ComponentArguments.convertToComponent(line)); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java index 487ea614f..2202dc7b9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java @@ -6,10 +6,12 @@ import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.impl.format.ComponentArguments; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import org.bukkit.Material; import org.bukkit.command.CommandSender; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java index 331cc8841..9b664f916 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItem.java @@ -6,6 +6,7 @@ import org.bukkit.Material; import org.jetbrains.annotations.NotNull; +@Deprecated public final class DefaultItem { public static final class SkullTextures { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java index 0dc640aad..3e3fccf4c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java @@ -46,6 +46,11 @@ public static ItemBuilder createChallengeDisplayFormat(@NotNull ItemStack displa name, desc); } + @Contract("_, _, _ -> new") + public static ItemBuilder createMenuDisplayFormat(@NotNull ItemStack displayItemPreset, @NotNull Object nameArg, @NotNull Locale locale) { + return new ItemBuilder(locale, displayItemPreset, MessageKey.of("menu.item-format"), nameArg); + } + @Contract("-> new") public static ItemStack createEnabledPreset() { return new ItemStack(Material.LIME_DYE); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index db115c0de..ede60f40e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -6,6 +6,8 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.impl.format.ComponentFormatter; +import net.codingarea.challenges.plugin.content.i18n.impl.format.MessageFormatter; import net.codingarea.commons.bukkit.utils.item.BannerPattern; import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import net.kyori.adventure.text.Component; @@ -21,10 +23,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Collection; -import java.util.List; -import java.util.Locale; -import java.util.UUID; +import java.util.*; public class ItemBuilder extends StandardItemBuilder { @@ -106,8 +105,14 @@ public ItemBuilder setLore(@NotNull MessageKey key, @NotNull Object... args) { @NotNull public ItemBuilder appendLore(@NotNull MessageKey key, @NotNull Object... args) { - List loreComponents = key.asComponents(locale, args); - addToLore(loreComponents); + List components = key.asComponents(locale, args); + addToLore(components); + System.out.println(key.withArgs(args).localize(locale)); + System.out.println(key.getKey()); + System.out.println(components.size()); + for (Component component : components) { + System.out.println(ComponentFormatter.MINI_MESSAGE.serialize(component)); + } return this; } @@ -116,6 +121,14 @@ public ItemBuilder appendLore(@NotNull LocalizableMessage localizable) { return this.appendLore(localizable.getLocalizableKey(), localizable.getLocalizableArgs()); } + @NotNull + public ItemBuilder appendLoreList(@NotNull Collection lines) { + for (LocalizableMessage line : lines) { + appendLore(line); + } + return this; + } + @NotNull public ItemBuilder appendBlankLoreLine() { addToLore(List.of(Component.space())); diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java index dbc743da2..439bb7ca2 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/item/ItemUtils.java @@ -63,10 +63,8 @@ public static boolean isObtainableInSurvival(@NotNull Material material) { case "SUSPICIOUS_GRAVEL": case "SUSPICIOUS_SAND": return false; - } - - if (MinecraftVersion.current().isOlderThan(MinecraftVersion.V1_19)) { - return !name.equals("SCULK_SENSOR"); + case "SCULK_SENSOR": + return MinecraftVersion.currentExact().isNewerOrEqualThan(MinecraftVersion.V1_19); } return true; From 34b3f667931dcac996aa140c9dd92269d5c75ca7 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Fri, 10 Jul 2026 00:44:38 +0200 Subject: [PATCH 105/119] fix: menu gen history stack --- .../menu/generator/AbstractMenuGenerator.java | 26 ++++++++++++++----- .../plugin/utils/item/ItemBuilder.java | 9 +------ 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java index f9ba99d7f..df222545a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/AbstractMenuGenerator.java @@ -57,9 +57,13 @@ protected LocalizableMessage createSubMenuTitle(@NotNull Object menuNameArg, @No @Override public void openMenu(@NotNull Player player, int page) { + openMenuWithPositionOverwrite(player, page, createMenuPosition(page, player)); + } + + private void openMenuWithPositionOverwrite(@NotNull Player player, int page, @NotNull GeneratorMenuPosition menuPosition) { Locale locale = findLanguageProvider().getPlayerLanguage(player); Inventory inventory = getOrInitInventory(locale, page); - MenuPosition.set(player, createMenuPosition(page, player)); + MenuPosition.set(player, menuPosition); player.openInventory(inventory); } @@ -163,6 +167,7 @@ public AbstractMenuGenerator getGenerator() { public abstract class HistoryAwareGeneratorMenuPosition extends GeneratorMenuPosition { private final GeneratorMenuPosition previousPosition; + private volatile boolean forgotten = false; public HistoryAwareGeneratorMenuPosition(int page, @Nullable GeneratorMenuPosition previousPosition) { super(page); @@ -172,10 +177,8 @@ public HistoryAwareGeneratorMenuPosition(int page, @Nullable GeneratorMenuPositi public HistoryAwareGeneratorMenuPosition(int page, @NotNull Player player) { super(page); if (MenuPosition.get(player) instanceof GeneratorMenuPosition prevPosition) { - // skip other pages of same menu (we only care about the menu before!) - while (prevPosition.getGenerator() == AbstractMenuGenerator.this - && prevPosition instanceof HistoryAwareGeneratorMenuPosition historyAwarePosition - && historyAwarePosition.getPreviousPosition() != null) { + while (prevPosition instanceof HistoryAwareGeneratorMenuPosition historyAwarePosition + && shouldSkipPreviousPosition(historyAwarePosition)) { prevPosition = historyAwarePosition.getPreviousPosition(); } this.previousPosition = prevPosition; @@ -184,8 +187,17 @@ public HistoryAwareGeneratorMenuPosition(int page, @NotNull Player player) { } } + protected boolean shouldSkipPreviousPosition(@NotNull HistoryAwareGeneratorMenuPosition prevPosition) { + // skip other pages of same menu (we only care about the menu before!) + skip all forgotten positions + return prevPosition.isForgotten() + || prevPosition.getGenerator() == AbstractMenuGenerator.this + && prevPosition.getPreviousPosition() != null; + } + @Override protected void handleNavigateOutOfMenu(@NotNull Player player) { + this.forgotten = true; + if (previousPosition == null) { super.handleNavigateOutOfMenu(player); return; @@ -195,9 +207,9 @@ protected void handleNavigateOutOfMenu(@NotNull Player player) { int previousPage = previousPosition.getPage(); int previousMenuPageCount = previousMenu.getPageCount(); if (previousPage < previousMenuPageCount) { // dynamic page count might have changed - previousMenu.openMenu(player, previousPage); + previousMenu.openMenuWithPositionOverwrite(player, previousPage, previousPosition); } else { - previousMenu.openMenu(player, previousMenuPageCount - 1); + previousMenu.openMenuWithPositionOverwrite(player, previousMenuPageCount - 1, previousPosition); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index ede60f40e..4d2b9d449 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -105,14 +105,7 @@ public ItemBuilder setLore(@NotNull MessageKey key, @NotNull Object... args) { @NotNull public ItemBuilder appendLore(@NotNull MessageKey key, @NotNull Object... args) { - List components = key.asComponents(locale, args); - addToLore(components); - System.out.println(key.withArgs(args).localize(locale)); - System.out.println(key.getKey()); - System.out.println(components.size()); - for (Component component : components) { - System.out.println(ComponentFormatter.MINI_MESSAGE.serialize(component)); - } + addToLore(key.asComponents(locale, args)); return this; } From ad331a7bfa2083fdaf84730723e19d3b445026cc Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Fri, 10 Jul 2026 15:17:43 +0200 Subject: [PATCH 106/119] refactor: migrate menu generators (part 4) --- language/locales/de.json | 67 ++--- language/locales/global.json | 26 +- .../settings/action/ChallengeAction.java | 15 +- .../settings/trigger/ChallengeTrigger.java | 14 +- .../challenge/world/AnvilRainChallenge.java | 3 +- .../setting/CutCleanSetting.java | 77 +++--- .../type/abstraction/ForceBattleGoal.java | 34 ++- .../type/abstraction/menu/MenuSetting.java | 94 +++---- .../menu/SubSettingsMenuGenerator.java | 15 +- .../type/helper/SubSettingsHelper.java | 5 +- .../CustomMainSettingsMenuGenerator.java | 4 +- .../legacy/ChallengeMenuGenerator.java | 258 ------------------ .../menu/generator/legacy/MenuGenerator.java | 63 ----- .../legacy/MultiPageMenuGenerator.java | 70 ----- .../position/LegacyGeneratorMenuPosition.java | 18 -- .../plugin/utils/item/DefaultItems.java | 7 +- .../plugin/utils/misc/InventoryUtils.java | 30 -- 17 files changed, 184 insertions(+), 616 deletions(-) delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChallengeMenuGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/MenuGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/MultiPageMenuGenerator.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/LegacyGeneratorMenuPosition.java diff --git a/language/locales/de.json b/language/locales/de.json index 5454c2b34..d938c387a 100644 --- a/language/locales/de.json +++ b/language/locales/de.json @@ -487,11 +487,45 @@ ] }, "cut-clean": { - "name": "*CutClean*", + "name": "*{@menu}*", "desc": [ "Verschiedene *Einstellungen*, die", "das *Farmen* von Items *einfacher* machen" - ] + ], + "menu": "CutClean", + "sub": { + "iron": { + "name": "*Eisen*", + "desc": "*Eisenerz* wird direkt zu *Eisenbarren*" + }, + "gold": { + "name": "*Gold*", + "desc": "*Golderz* wird direkt zu *Goldbarren*" + }, + "coal": { + "name": "*Kohle*", + "desc": "*Kohleerz* wird direkt zu *Fackeln*" + }, + "flint": { + "name": "*Kies*", + "desc": "*Kies* wird direkt zu *Feuerstein*" + }, + "vein": { + "name": "*Erzvenen*", + "desc": "*Erzvenen* werden direkt *komplett abgebaut*" + }, + "inventory": { + "name": "*Direkt ins Inventar*", + "desc": [ + "*Items* werden, *anstatt gedroppt* zu werden,", + "*direkt* ins *Inventar* hinzugefügt" + ] + }, + "food": { + "name": "*Gebratenes Essen*", + "desc": "*Rohes Fleisch* wird direkt zu *gebratenem Fleisch*" + } + } }, "fortress-spawn": { "name": "*Festungs Spawn*", @@ -2150,35 +2184,6 @@ "item-backpack-setting-team": "Team", "item-backpack-setting-player": "Player", "menu-cut-clean-setting-settings": "CutClean", - "item-cut-clean-gold-setting": [ - "Gold", - "*Golderz* wird direkt zu *Goldbarren*" - ], - "item-cut-clean-iron-setting": [ - "Iron", - "*Eisenerz* wird direkt zu *Eisenbarren*" - ], - "item-cut-clean-coal-setting": [ - "Coal", - "*Kohleerz* wird direkt zu *Fackeln*" - ], - "item-cut-clean-flint-setting": [ - "Flint", - "*Gravel* droppt immer *Flint*" - ], - "item-cut-clean-vein-setting": [ - "Ore Veins", - "*Erz Venen* werden direkt abgebaut" - ], - "item-cut-clean-inventory-setting": [ - "Direkt ins Inventar", - "*Items* werden, *anstatt gedroppt* zu werden,", - "*direkt* ins *Inventar* hinzugefügt" - ], - "item-cut-clean-food-setting": [ - "Gebratenes Essen", - "*Rohes Fleisch* wird direkt zu *gebratenem Fleisch*" - ], "item-timber-setting-logs": "Baumstämme", "item-timber-setting-logs-and-leaves": "Baumstämme und Blätter", "item-regeneration-setting-not_natural": "Nicht natürlich", diff --git a/language/locales/global.json b/language/locales/global.json index 949fb811e..05e8deae6 100644 --- a/language/locales/global.json +++ b/language/locales/global.json @@ -187,7 +187,7 @@ }, "challenge": { "display-format": [ - "{@symbol.arrow} {0}", + "{@menu.item-format}", " ", "{1}" ], @@ -269,7 +269,7 @@ "*colorize*": "{0}" }, "top-command": { - "*colorize*": "{0}" + "*colorize*": "{0}" }, "max-health": { "*colorize*": "{0}" @@ -278,7 +278,27 @@ "*colorize*": "{0}" }, "cut-clean": { - "*colorize*": "{0}" + "*colorize*": "{0}", + "sub": { + "iron": { + "*colorize*": "{0}" + }, + "gold": { + "*colorize*": "{0}" + }, + "coal": { + "*colorize*": "{0}" + }, + "flint": { + "*colorize*": "{0}" + }, + "vein": { + "*colorize*": "{0}" + }, + "inventory": { + "*colorize*": "{0}" + } + } }, "fortress-spawn": { "*colorize*": "{0}" diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java index 0c5a79c8f..b9013ff88 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java @@ -9,8 +9,8 @@ import net.codingarea.commons.common.collection.IRandom; import org.jetbrains.annotations.NotNull; -import java.util.LinkedHashMap; -import java.util.Locale; +import java.util.Collections; +import java.util.Map; import java.util.function.Supplier; public abstract class ChallengeAction extends ChallengeSetting implements IChallengeAction { @@ -29,14 +29,9 @@ public ChallengeAction(String name, Supplier builderSupplier super(name, builderSupplier); } - public static LinkedHashMap getMenuItems() { - LinkedHashMap map = new LinkedHashMap<>(); - - for (ChallengeAction value : Challenges.getInstance().getCustomSettingsLoader().getActions().values()) { - map.put(value.getUniqueName(), value); - } - - return map; + @NotNull + public static Map getMenuItems() { + return Collections.unmodifiableMap(Challenges.getInstance().getCustomSettingsLoader().getActions()); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java index ca8ce46f2..60039ac6b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java @@ -8,7 +8,8 @@ import net.codingarea.challenges.plugin.content.i18n.MessageKey; import org.jetbrains.annotations.NotNull; -import java.util.LinkedHashMap; +import java.util.Collections; +import java.util.Map; import java.util.function.Supplier; public abstract class ChallengeTrigger extends ChallengeSetting implements IChallengeTrigger { @@ -25,14 +26,9 @@ public ChallengeTrigger(String name, Supplier builderSupplie super(name, builderSupplier); } - public static LinkedHashMap getMenuItems() { - LinkedHashMap map = new LinkedHashMap<>(); - - for (ChallengeTrigger value : Challenges.getInstance().getCustomSettingsLoader().getTriggers().values()) { - map.put(value.getUniqueName(), value); // TODO - } - - return map; + @NotNull + public static Map getMenuItems() { + return Collections.unmodifiableMap(Challenges.getInstance().getCustomSettingsLoader().getTriggers()); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java index d33fcc44b..af4decef3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java @@ -196,8 +196,7 @@ public void destroyRandomBlocks(@NotNull Location origin) { public void applyDamageToNearEntities(@NotNull Location location) { if (location.getWorld() == null) return; for (Entity entity : location.getWorld().getNearbyEntities(location, 0.25, 0.25, 0.25)) { - if (!(entity instanceof LivingEntity)) continue; - LivingEntity livingEntity = (LivingEntity) entity; + if (!(entity instanceof LivingEntity livingEntity)) continue; livingEntity.damage(getDamage()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java index 0e3aa3050..904c8ce2b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/CutCleanSetting.java @@ -4,10 +4,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.menu.MenuSetting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.DropPriority; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.challenges.plugin.utils.misc.Utils; @@ -27,31 +26,40 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Supplier; @Since("2.0") public class CutCleanSetting extends MenuSetting { public CutCleanSetting() { super(MenuType.SETTINGS, null, new ItemStack(Material.IRON_AXE), "cut-clean"); - registerSetting("iron->iron_ingot", - new ConvertDropSubSetting(() -> new LegacyItemBuilder(Material.IRON_INGOT, Message.forName("item-cut-clean-iron-setting")), true, - Material.IRON_INGOT, "IRON_ORE", "DEEPSLATE_IRON_ORE")); - registerSetting("gold->gold_ingot", - new ConvertDropSubSetting(() -> new LegacyItemBuilder(Material.GOLD_INGOT, Message.forName("item-cut-clean-gold-setting")), true, - Material.GOLD_INGOT, "GOLD_ORE", "DEEPSLATE_GOLD_ORE")); - registerSetting("coal->torch", - new ConvertDropSubSetting(() -> new LegacyItemBuilder(Material.COAL, Message.forName("item-cut-clean-coal-setting")), false, - Material.TORCH, "COAL_ORE", "DEEPSLATE_COAL_ORE")); - registerSetting("gravel->flint", - new ConvertDropSubSetting(() -> new LegacyItemBuilder(Material.FLINT, Message.forName("item-cut-clean-flint-setting")), false, - Material.FLINT, "GRAVEL")); - registerSetting("ore->veins", - new BreakOreVeinsSubSetting(() -> new LegacyItemBuilder(Material.GOLDEN_PICKAXE, Message.forName("item-cut-clean-vein-setting")), 1, 10)); - registerSetting("items->inventory", - new DirectIntoInventorySubSetting(() -> new LegacyItemBuilder(Material.CHEST, Message.forName("item-cut-clean-inventory-setting")))); - registerSetting("row->cooked", - new CookFoodSubSetting(() -> new LegacyItemBuilder(Material.COOKED_BEEF, Message.forName("item-cut-clean-food-setting")), true)); + registerSetting("iron->iron_ingot", new ConvertDropSubSetting( + new ItemStack(Material.IRON_INGOT), getChallengeMessageKey("sub.iron"), + true, Material.IRON_INGOT, "IRON_ORE", "DEEPSLATE_IRON_ORE" + )); + registerSetting("gold->gold_ingot", new ConvertDropSubSetting( + new ItemStack(Material.GOLD_INGOT), getChallengeMessageKey("sub.gold"), + true, Material.GOLD_INGOT, "GOLD_ORE", "DEEPSLATE_GOLD_ORE" + )); + registerSetting("coal->torch", new ConvertDropSubSetting( + new ItemStack(Material.COAL), getChallengeMessageKey("sub.coal"), + false, Material.TORCH, "COAL_ORE", "DEEPSLATE_COAL_ORE" + )); + registerSetting("gravel->flint", new ConvertDropSubSetting( + new ItemStack(Material.FLINT), getChallengeMessageKey("sub.flint"), + false, Material.FLINT, "GRAVEL" + )); + registerSetting("ore->veins", new BreakOreVeinsSubSetting( + new ItemStack(Material.GOLDEN_PICKAXE), getChallengeMessageKey("sub.vein"), + 1, 10, 3 + )); + registerSetting("items->inventory", new DirectIntoInventorySubSetting( + new ItemStack(Material.CHEST), getChallengeMessageKey("sub.inventory"), + false + )); + registerSetting("row->cooked", new CookFoodSubSetting( + new ItemStack(Material.COOKED_BEEF), getChallengeMessageKey("sub.food"), + true + )); } protected boolean directIntoInventory() { @@ -60,14 +68,8 @@ protected boolean directIntoInventory() { private class DirectIntoInventorySubSetting extends BooleanSubSetting { - public DirectIntoInventorySubSetting(@NotNull Supplier item) { - super(item.get().build()); - } - - @NotNull - @Override - public BooleanSubSetting setEnabled(boolean enabled) { - return super.setEnabled(enabled); + public DirectIntoInventorySubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, boolean enabledByDefault) { + super(displayItemPreset, nameMessageKeySpace, enabledByDefault); } } @@ -77,9 +79,9 @@ private class ConvertDropSubSetting extends BooleanSubSetting { protected final Material[] from; protected final Material to; - public ConvertDropSubSetting(@NotNull Supplier item, boolean enabledByDefault, - @NotNull Material to, @NotNull String... from) { - super(item.get().build(), enabledByDefault); + public ConvertDropSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, + boolean enabledByDefault, @NotNull Material to, @NotNull String... from) { + super(displayItemPreset, nameMessageKeySpace, enabledByDefault); List materials = new ArrayList<>(); for (String s : from) { @@ -130,8 +132,9 @@ public void onBlockBreak(@NotNull BlockBreakEvent event) { private class BreakOreVeinsSubSetting extends NumberAndBooleanSubSetting { - public BreakOreVeinsSubSetting(@NotNull Supplier item, int min, int max) { - super(item.get().build(), min, max); // TODO + public BreakOreVeinsSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, + int min, int max, int defaultValue) { + super(displayItemPreset, nameMessageKeySpace, min, max, defaultValue); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @@ -205,14 +208,14 @@ private boolean canBeBroken(@NotNull Block block, @NotNull ItemStack tool) { private class CookFoodSubSetting extends BooleanSubSetting { - public CookFoodSubSetting(@NotNull Supplier item, boolean enabledByDefault) { - super(item.get().toItem(), enabledByDefault); + public CookFoodSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, boolean enabledByDefault) { + super(displayItemPreset, nameMessageKeySpace, enabledByDefault); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onEntityKill(@NotNull EntityDeathEvent event) { if (!isEnabled()) return; - event.getDrops().replaceAll(item -> new LegacyItemBuilder(ItemUtils.convertFoodToCookedFood(item.getType())).setAmount(item.getAmount()).build()); + event.getDrops().replaceAll(item -> new ItemStack(ItemUtils.convertFoodToCookedFood(item.getType()), item.getAmount())); Player killer = event.getEntity().getKiller(); if (killer != null && directIntoInventory()) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java index b780cd532..9f21d80d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java @@ -51,24 +51,22 @@ public ForceBattleGoal(@NotNull ItemStack displayItemPreset, @NotNull String nam super(MenuType.GOAL, SettingCategory.FORCE_BATTLE, displayItemPreset, nameMessageKey); // TODO ! -// registerSetting("jokers", new NumberSubSetting( -// () -> new LegacyItemBuilder(Material.BARRIER, Message.forName("item-force-battle-goal-jokers")), -// value -> null, -// value -> "§e" + value, -// 1, -// 32, -// 5 -// )); -// registerSetting("showScoreboard", new BooleanSubSetting( -// () -> new LegacyItemBuilder(Material.BOOK, Message.forName("item-force-battle-show-scoreboard")), -// true -// )); -// if (shouldRegisterDupedTargetsSetting()) { -// registerSetting("dupedTargets", new BooleanSubSetting( -// () -> new LegacyItemBuilder(Material.PAPER, Message.forName("item-force-battle-duped-targets")), -// true -// )); -// } + registerSetting("jokers", new NumberSubSetting( + new ItemStack(Material.BARRIER), MessageKey.of("challenge.force-battle.sub.goal-jokers"), + 1, + 32, + 5 + )); + registerSetting("showScoreboard", new BooleanSubSetting( + new ItemStack(Material.BOOK), MessageKey.of("challenge.force-battle.sub.scoreboard"), + true + )); + if (shouldRegisterDupedTargetsSetting()) { + registerSetting("dupedTargets", new BooleanSubSetting( + new ItemStack(Material.PAPER), MessageKey.of("challenge.force-battle.sub.duped-targets"), + true + )); + } } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java index f38e53edf..498e09d38 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction.menu; +import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import net.codingarea.challenges.plugin.Challenges; @@ -34,11 +35,13 @@ public MenuSetting(@NotNull MenuType menu, @Nullable SettingCategory category, this.menuGenerator = new SubSettingsMenuGenerator(this); } - protected final void registerSetting(@NotNull String name, @NotNull SubSetting setting) { + @NotNull + protected final T registerSetting(@NotNull String name, @NotNull T setting) { if (name.equals("enabled")) throw new IllegalArgumentException("SubSetting name 'enabled' is reserved"); settings.put(name, setting); menuGenerator.addToCache(setting); Challenges.getInstance().registerListener(setting); + return setting; } public final SubSetting getSetting(@NotNull String name) { @@ -98,14 +101,13 @@ public void restoreDefaults() { // TODO extract duplicate logic with AbstractChallenge public abstract class SubSetting implements Listener { - @Setter - @Getter - private int page = -1, slot = -1; + private final MessageKey nameMessageKeySpace; // TODO this is might not be an really elegant solution... protected final ItemStack displayItemPreset; - public SubSetting(@NotNull ItemStack displayItemPreset) { + public SubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace) { this.displayItemPreset = displayItemPreset; + this.nameMessageKeySpace = nameMessageKeySpace; } public final void updateItems() { @@ -119,6 +121,7 @@ public ItemBuilder getDisplayItem(@NotNull Locale locale) { @NotNull public ItemBuilder getSettingsItem(@NotNull Locale locale) { + // TODO abstract duplicate logic with AbstractChallenge! ItemStack preset = isEnabled() ? getSettingsItemPreset() : DefaultItems.createDisabledPreset(); // apply formatting dynamically, to prevent duplicate format references ItemBuilder item = new ItemBuilder(locale, preset, MessageKey.of("challenge.subsettings-format"), @@ -132,14 +135,23 @@ public ItemBuilder getSettingsItem(@NotNull Locale locale) { return item; } + /** + * @implNote Only used if {@link #isEnabled()}. + * Name/Lore will be overwritten by formatting. + * Set name in {@link #getSettingsName()} and lore in {@link #getSettingsDescription()} + */ @NotNull public abstract ItemStack getSettingsItemPreset(); @NotNull - protected abstract LocalizableMessage getDisplayName(); + public LocalizableMessage getDisplayName() { + return nameMessageKeySpace.getChildKey("name"); + } @NotNull - protected abstract LocalizableMessage getDisplayDescription(); + public LocalizableMessage getDisplayDescription() { + return nameMessageKeySpace.getChildKey("desc"); + } @NotNull protected LocalizableMessage getSettingsName() { @@ -174,12 +186,12 @@ public class BooleanSubSetting extends SubSetting { private final boolean enabledByDefault; private boolean enabled; - public BooleanSubSetting(@NotNull ItemStack displayItemPreset) { - this(displayItemPreset, false); + public BooleanSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace) { + this(displayItemPreset, nameMessageKeySpace, false); } - public BooleanSubSetting(@NotNull ItemStack displayItemPreset, boolean enabledByDefault) { - super(displayItemPreset); + public BooleanSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, boolean enabledByDefault) { + super(displayItemPreset, nameMessageKeySpace); this.enabledByDefault = enabledByDefault; this.setEnabled(enabledByDefault); } @@ -190,18 +202,6 @@ public ItemStack getSettingsItemPreset() { return DefaultItems.createEnabledPreset(); } - @NotNull - @Override - protected LocalizableMessage getDisplayName() { - return null; // TODO - } - - @NotNull - @Override - protected LocalizableMessage getDisplayDescription() { - return null; // TODO - } - @Override public int getAsInt() { return enabled ? 1 : 0; @@ -255,26 +255,25 @@ protected void onDisable() { public class NumberSubSetting extends SubSetting { - // TODO name, desc private final int max, min; private final int defaultValue; @Getter private int value; - public NumberSubSetting(@NotNull ItemStack displayItemPreset) { - this(displayItemPreset, 64); + public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace) { + this(displayItemPreset, nameMessageKeySpace, 64); } - public NumberSubSetting(@NotNull ItemStack displayItemPreset, int max) { - this(displayItemPreset, max, 1); + public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int max) { + this(displayItemPreset, nameMessageKeySpace, max, 1); } - public NumberSubSetting(@NotNull ItemStack displayItemPreset, int min, int max) { - this(displayItemPreset, min, max, min); + public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int min, int max) { + this(displayItemPreset, nameMessageKeySpace, min, max, min); } - public NumberSubSetting(@NotNull ItemStack displayItemPreset, int min, int max, int defaultValue) { - super(displayItemPreset); + public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int min, int max, int defaultValue) { + super(displayItemPreset, nameMessageKeySpace); if (max <= min) throw new IllegalArgumentException("max <= min"); if (min < 0) throw new IllegalArgumentException("min < 0"); if (defaultValue > max) throw new IllegalArgumentException("defaultValue > max"); @@ -285,8 +284,9 @@ public NumberSubSetting(@NotNull ItemStack displayItemPreset, int min, int max, this.min = min; } + @NotNull @Override - public @NotNull ItemStack getSettingsItemPreset() { + public ItemStack getSettingsItemPreset() { return DefaultItems.createValuePreset(value); } @@ -303,18 +303,6 @@ public void setValue(int value) { onValueChange(); } - @NotNull - @Override - protected LocalizableMessage getDisplayName() { - return null; // TODO - } - - @NotNull - @Override - protected LocalizableMessage getDisplayDescription() { - return null; // TODO - } - @Override public int getAsInt() { @@ -365,20 +353,20 @@ public class NumberAndBooleanSubSetting extends NumberSubSetting { private final boolean enabledByDefault = false; // Implement in future private boolean enabled; - public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset) { - super(displayItemPreset); + public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace) { + super(displayItemPreset, nameMessageKeySpace); } - public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset, int max) { - super(displayItemPreset, max); + public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int max) { + super(displayItemPreset, nameMessageKeySpace, max); } - public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset, int min, int max) { - super(displayItemPreset, min, max); + public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int min, int max) { + super(displayItemPreset, nameMessageKeySpace, min, max); } - public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset, int min, int max, int defaultValue) { - super(displayItemPreset, min, max, defaultValue); + public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int min, int max, int defaultValue) { + super(displayItemPreset, nameMessageKeySpace, min, max, defaultValue); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/SubSettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/SubSettingsMenuGenerator.java index e117f9279..5aabf96b2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/SubSettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/SubSettingsMenuGenerator.java @@ -77,8 +77,6 @@ public void updateInventoryContent(@NotNull Inventory inventory, int page, @NotN int i = 0; for (MenuSetting.SubSetting setting : settings) { - setting.setPage(page); - setting.setSlot(slots[i]); setSubSettingItemsAt(setting, inventory, slots[i], locale); i++; } @@ -91,7 +89,7 @@ public void updateElementDisplay(@NotNull MenuSetting.SubSetting setting) { int page = getPageOfSubSetting(settingsIndex); int settingsOnPage = getSubSettingsCountForPage(page); - int slotIndex = settingsIndex % settingsOnPage; + int slotIndex = settingsIndex % MAX_SLOTS_PER_PAGE; // don't use settingsOnPage here; pages before might have more int displaySlot = getSlots(settingsOnPage)[slotIndex]; updatePage(page, (inventory, locale) -> setSubSettingItemsAt(setting, inventory, displaySlot, locale)); @@ -144,11 +142,12 @@ public SubSettingsMenuPosition(int page, @NotNull Player player) { @Override public boolean handleMenuClick(@NotNull MenuClickInfo info) { List settings = getSubSettingsForPage(page); - for (MenuSetting.SubSetting setting : settings) { - int settingsSlot = setting.getSlot(); // TODO - if (info.getSlot() != settingsSlot && info.getSlot() != settingsSlot + 9) continue; - - setting.handleClick(new ChallengeMenuClickInfo(info, info.getSlot() == settingsSlot)); + int[] slots = getSlots(settings.size()); + for (int i = 0; i < settings.size() && i < slots.length; i++) { + int slot = slots[i]; + if (info.getSlot() != slot && info.getSlot() != slot + 9) continue; + MenuSetting.SubSetting setting = settings.get(i); + setting.handleClick(new ChallengeMenuClickInfo(info, info.getSlot() == slot)); return true; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java index 6071891de..bdc24296d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java @@ -18,7 +18,10 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffectType; -public class SubSettingsHelper { +public final class SubSettingsHelper { + + private SubSettingsHelper() { + } public static final String ENTITY_TYPE = "entity_type", diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomMainSettingsMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomMainSettingsMenuGenerator.java index 10ad8c792..5da09dad9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomMainSettingsMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomMainSettingsMenuGenerator.java @@ -3,8 +3,8 @@ import lombok.Getter; import net.codingarea.challenges.plugin.challenges.custom.settings.IChallengeSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.SettingType; -import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; @@ -36,7 +36,7 @@ public class CustomMainSettingsMenuGenerator extends CustomChooseOptionMenuGener public CustomMainSettingsMenuGenerator(@NotNull IParentCustomGenerator parent, @NotNull SettingType type, @NotNull String key, @NotNull LocalizableMessage baseTitle, - @NotNull Map items, + @NotNull Map items, @NotNull Function instanceGetter) { super(baseTitle, items); this.parent = parent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChallengeMenuGenerator.java deleted file mode 100644 index 966bf9f66..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/ChallengeMenuGenerator.java +++ /dev/null @@ -1,258 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.legacy; - -import com.google.common.collect.ImmutableList; -import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.challenges.type.IChallenge; -import net.codingarea.challenges.plugin.challenges.type.annotation.ChallengeAnnotations; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.management.menu.MenuManager; -import net.codingarea.challenges.plugin.management.menu.position.LegacyGeneratorMenuPosition; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; -import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.logging.Logger; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import net.codingarea.commons.common.config.Document; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -import java.util.LinkedList; -import java.util.List; -import java.util.function.Consumer; - -public abstract class ChallengeMenuGenerator extends MultiPageMenuGenerator { - - protected final List challenges = new LinkedList<>(); - protected final boolean newSuffix; - protected final boolean updatedSuffix; - - private final int startPage; - protected Consumer onLeaveClick; - - public ChallengeMenuGenerator(int startPage, Consumer onLeaveClick) { - Document config = Challenges.getInstance().getConfigDocument(); - this.newSuffix = config.getBoolean("challenge-updates.new.suffix"); - this.updatedSuffix = config.getBoolean("challenge-updates.updated.suffix"); - this.startPage = startPage; - this.onLeaveClick = onLeaveClick; - } - - public ChallengeMenuGenerator(int startPage) { - this(startPage, player -> Challenges.getInstance().getMenuManager().openMainMenuInstantly(player)); - } - - public ChallengeMenuGenerator() { - this(0); - } - - public static boolean playNoPermissionsEffect(@NotNull Player player) { - MenuManager menuManager = Challenges.getInstance().getMenuManager(); - if (!menuManager.permissionToManageGUI()) return false; - if (mayManageSettings(player)) return false; - menuManager.playNoPermissionsEffect(player); - return true; - } - - private static boolean mayManageSettings(@NotNull Player player) { - return player.hasPermission(MenuManager.MANAGE_GUI_PERMISSION); - } - - @Override - public MenuPosition createMenuPosition(int page) { - return new ChallengeMenuPositionLegacyGenerator(this, page); - } - - @Override - public int getPagesCount() { - return (int) (Math.ceil((double) challenges.size() / getSlots().length) + startPage); - } - - @Override - public void generatePage(@NotNull Inventory inventory, int page) { - - } - - @Override - public void generateInventories() { - super.generateInventories(); - - for (IChallenge challenge : challenges) { - updateItem(challenge); - } - - } - - public void updateItem(IChallenge challenge) { - - int index = challenges.indexOf(challenge); - if (index == -1) return; // Challenge not registered or menus not loaded - - int page = (index / getSlots().length); - if (page >= getInventories().size()) return; // This should never happen - - int slot = index - getSlots().length * page; - - Inventory inventory = getInventories().get(page + startPage); - setSettingsItems(inventory, challenge, slot); - - if (newSuffix && ChallengeAnnotations.isNew(challenge)) { - inventory.setItem(slot + 1, new LegacyItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); - inventory.setItem(slot + 28, new LegacyItemBuilder(Material.LIME_STAINED_GLASS_PANE, "§0").build()); - } else if (updatedSuffix && ChallengeAnnotations.isUpdated(challenge)) { - inventory.setItem(slot + 1, new LegacyItemBuilder(Material.YELLOW_STAINED_GLASS_PANE, "§0").build()); - inventory.setItem(slot + 28, new LegacyItemBuilder(Material.YELLOW_STAINED_GLASS_PANE, "§0").build()); - } - } - - public int getPageOfChallenge(IChallenge challenge) { - int index = challenges.indexOf(challenge); - if (index == -1) return -1; // Challenge not registered or menus not loaded - - int page = (index / getSlots().length); - if (page >= getInventories().size()) return -1; // This should never happen - - return page; - } - - public void setSettingsItems(@NotNull Inventory inventory, @NotNull IChallenge challenge, int topSlot) { - inventory.setItem(getSlots()[topSlot], getDisplayItem(challenge)); - inventory.setItem(getSlots()[topSlot] + 9, getSettingsItem(challenge)); - } - - public void resetChallengeCache() { - this.challenges.clear(); - } - - public boolean isInChallengeCache(@NotNull IChallenge challenge) { - return challenges.contains(challenge); - } - - public void addChallengeToCache(@NotNull IChallenge challenge) { - if (ChallengeAnnotations.isNew(challenge) && Challenges.getInstance().getMenuManager().isDisplayNewInFront()) { - challenges.add(countNewChallenges(), challenge); - } else { - challenges.add(challenge); - } - } - - public void removeChallengeFromCache(@NotNull IChallenge challenge) { - challenges.remove(challenge); - } - - protected ItemStack getDisplayItem(@NotNull IChallenge challenge) { - return getDisplayItemBuilder(challenge).build(); - } - - protected LegacyItemBuilder getDisplayItemBuilder(@NotNull IChallenge challenge) { - try { - LegacyItemBuilder item = new LegacyItemBuilder(challenge.getDisplayItem(null).build()).hideAttributes(); - if (newSuffix && ChallengeAnnotations.isNew(challenge)) { - return item.appendName(" " + Message.forName("new-challenge")); - } else if (updatedSuffix && ChallengeAnnotations.isUpdated(challenge)) { - return item.appendName(" " + Message.forName("updated-challenge")); - } else { - return item; - } - } catch (Exception ex) { - Logger.error("Error while generating challenge display item for challenge {}", challenge.getClass().getSimpleName(), ex); - return new LegacyItemBuilder(); - } - } - - protected ItemStack getSettingsItem(@NotNull IChallenge challenge) { - try { - LegacyItemBuilder item = new LegacyItemBuilder(challenge.getSettingsItem(null).build()).hideAttributes(); - return item.build(); - } catch (Exception ex) { - Logger.error("Error while generating challenge settings item for challenge {}", challenge.getClass().getSimpleName(), ex); - return new LegacyItemBuilder().build(); - } - } - - protected int countNewChallenges() { - return (int) challenges.stream().filter(ChallengeAnnotations::isNew).count(); - } - - public abstract int[] getSlots(); - - public abstract void executeClickAction(@NotNull IChallenge challenge, @NotNull MenuClickInfo info, int itemIndex); - - public void onPreChallengePageClicking(@NotNull MenuClickInfo clickInfo, int page) { - - } - - public List getChallenges() { - return ImmutableList.copyOf(challenges); - } - - private class ChallengeMenuPositionLegacyGenerator extends LegacyGeneratorMenuPosition { - - public ChallengeMenuPositionLegacyGenerator(MenuGenerator generator, int page) { - super(generator, page); - } - - @Override - public void handleClick(@NotNull MenuClickInfo info) { - - if (InventoryUtils.handleNavigationClicking(generator, getNavigationSlots(page), page, info, () -> onLeaveClick.accept(info.getPlayer()))) { - return; - } - - - if (page < startPage) { - onPreChallengePageClicking(info, page); - return; - } - - int itemIndex = 0; - int index = 0; - for (int i : getSlots()) { - if (i == info.getSlot()) break; - if ((i + 9) == info.getSlot()) { - itemIndex = 1; - break; - } else if ((i + 18) == info.getSlot()) { - itemIndex = 2; - break; - } - index++; - } - - if (itemIndex == 2) { - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - if (index == getSlots().length) { // No possible bound slot was clicked - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - int offset = (page - startPage) * getSlots().length; - index += offset; - - if (index >= challenges.size()) { // No bound slot was clicked - SoundSample.CLICK.play(info.getPlayer()); - return; - } - - IChallenge challenge = challenges.get(index); - - if (playNoPermissionsEffect(info.getPlayer())) return; - - try { - executeClickAction(challenge, info, itemIndex); - updateItem(challenge); - } catch (Exception ex) { - Logger.error("An exception occurred while handling click on {}", challenge.getClass().getName(), ex); - } - - } - - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/MenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/MenuGenerator.java deleted file mode 100644 index 6884e41c3..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/MenuGenerator.java +++ /dev/null @@ -1,63 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.legacy; - -import lombok.Getter; -import lombok.Setter; -import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.management.menu.position.LegacyGeneratorMenuPosition; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; -import org.jetbrains.annotations.NotNull; - -import java.util.List; - -@Getter -@Setter -public abstract class MenuGenerator { - - // ONLY MODIFY IF YOU KNOW WHAT YOU ARE DOING - private MenuType menuType; - - public abstract void generateInventories(); - - public abstract List getInventories(); - - @NotNull - public abstract MenuPosition createMenuPosition(int page); - - public boolean hasInventoryOpen(Player player) { - MenuPosition menuPosition = MenuPosition.get(player); - return menuPosition instanceof LegacyGeneratorMenuPosition - && CompatibilityUtils.getTopInventory(player).getType() != InventoryType.CRAFTING - && ((LegacyGeneratorMenuPosition) menuPosition).getGenerator() == this; - } - - public int getPage(Player player) { - MenuPosition menuPosition = MenuPosition.get(player); - if (menuPosition instanceof LegacyGeneratorMenuPosition) - return ((LegacyGeneratorMenuPosition) menuPosition).getPage(); - return 0; - } - - public void reopenInventoryForPlayers() { - for (Player player : Bukkit.getOnlinePlayers()) { - if (hasInventoryOpen(player)) { - open(player, getPage(player)); - } - } - } - - public void open(@NotNull Player player, int page) { - List inventories = getInventories(); - if (inventories == null || inventories.isEmpty()) generateInventories(); - if (inventories == null || inventories.isEmpty()) return; - if (page >= inventories.size()) page = inventories.size() - 1; - Inventory inventory = inventories.get(page); - MenuPosition.set(player, createMenuPosition(page)); - player.openInventory(inventory); - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/MultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/MultiPageMenuGenerator.java deleted file mode 100644 index c7bcd3490..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/legacy/MultiPageMenuGenerator.java +++ /dev/null @@ -1,70 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.generator.legacy; - -import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; -import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.challenges.plugin.utils.misc.InventoryUtils.InventorySetter; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; -import org.bukkit.Bukkit; -import org.bukkit.inventory.Inventory; -import org.jetbrains.annotations.NotNull; - -import java.util.ArrayList; -import java.util.List; - -public abstract class MultiPageMenuGenerator extends MenuGenerator { - - protected final List inventories = new ArrayList<>(); - - @NotNull - protected Inventory createNewInventory(int page) { - Inventory inventory = Bukkit.createInventory(MenuPosition.HOLDER, getSize(), getTitle(page)); - InventoryUtils.fillInventory(inventory, LegacyItemBuilder.FILL_ITEM); - inventories.add(inventory); - return inventory; - } - - protected String getTitle(int page) { - return InventoryTitleManager.getTitle(getMenuType(), page); - } - - public abstract int getSize(); - - public abstract int getPagesCount(); - - public abstract void generatePage(@NotNull Inventory inventory, int page); - - public abstract int[] getNavigationSlots(int page); - - @Override - public void generateInventories() { - inventories.clear(); - - for (int page = 0; page < getPagesCount(); page++) { - Inventory inventory = createNewInventory(page); - generatePage(inventory, page); - } - - for (int i = 0; i < inventories.size(); i++) { - addNavigationItems(inventories.get(i), i); - } - - reopenInventoryForPlayers(); - - } - - @Override - public List getInventories() { - return inventories; - } - - public void addNavigationItems(@NotNull Inventory inventory, int page) { - InventoryUtils.setNavigationItems(inventory, - getNavigationSlots(page), true, - InventorySetter.INVENTORY, page, inventories.size(), - DefaultItem.navigateBack().clone().setLore("", "§7Shift §8» §7-5"), - DefaultItem.navigateNext().clone().setLore("", "§7Shift §8» §7+5")); - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/LegacyGeneratorMenuPosition.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/LegacyGeneratorMenuPosition.java deleted file mode 100644 index 3875ca0ee..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/position/LegacyGeneratorMenuPosition.java +++ /dev/null @@ -1,18 +0,0 @@ -package net.codingarea.challenges.plugin.management.menu.position; - -import lombok.Getter; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; -import net.codingarea.commons.bukkit.utils.menu.MenuPosition; - -@Getter -public abstract class LegacyGeneratorMenuPosition implements MenuPosition { - - protected final MenuGenerator generator; - protected final int page; - - public LegacyGeneratorMenuPosition(MenuGenerator generator, int page) { - this.generator = generator; - this.page = page; - } - -} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java index 3e3fccf4c..4133da0c9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java @@ -9,6 +9,7 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Locale; @@ -41,9 +42,9 @@ public static ItemBuilder createNavigateBackMainMenu(@NotNull Locale locale) { @Contract("_, _, _, _ -> new") public static ItemBuilder createChallengeDisplayFormat(@NotNull ItemStack displayItemPreset, @NotNull LocalizableMessage name, - @NotNull LocalizableMessage desc, @NotNull Locale locale) { - return new ItemBuilder(locale, displayItemPreset, MessageKey.of("challenge.display-format"), - name, desc); + @Nullable LocalizableMessage desc, @NotNull Locale locale) { + if (desc == null) return createMenuDisplayFormat(displayItemPreset, name, locale); + return new ItemBuilder(locale, displayItemPreset, MessageKey.of("challenge.display-format"), name, desc); } @Contract("_, _, _ -> new") diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java index 7cc322ba1..868401c27 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java @@ -1,7 +1,6 @@ package net.codingarea.challenges.plugin.utils.misc; import net.codingarea.challenges.plugin.ChallengeAPI; -import net.codingarea.challenges.plugin.management.menu.generator.legacy.MenuGenerator; import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.AnimationFrame; @@ -183,35 +182,6 @@ public static ItemStack getRandomItem(boolean onlyOne, boolean respectMaxStackSi return new ItemStack(material, stackSize); } - /** - * @return if a navigation item was clicked - */ - public static boolean handleNavigationClicking(MenuGenerator generator, int[] navigationSlots, int page, MenuClickInfo info, Runnable onDoorClick) { - int pagesSwitching = info.isShiftClick() ? 5 : 1; - if (navigationSlots.length >= 1 && info.getSlot() == navigationSlots[0]) { - if (page <= 0) { - if (page == 0) { - onDoorClick.run(); - } else { - SoundSample.CLICK.play(info.getPlayer()); - } - return page == 0; - } else { - SoundSample.CLICK.play(info.getPlayer()); - generator.open(info.getPlayer(), Math.max(page - pagesSwitching, 0)); - return true; - } - } else if (navigationSlots.length >= 2 && info.getSlot() == navigationSlots[1]) { - SoundSample.CLICK.play(info.getPlayer()); - if (page < (generator.getInventories().size())) { - generator.open(info.getPlayer(), Math.min(page + pagesSwitching, generator.getInventories().size())); - return true; - } - return false; - } - return false; - } - @FunctionalInterface public interface InventorySetter { From 39abc27f21276fe7ce85db43f9b0c6df1988e7ab Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Fri, 10 Jul 2026 18:27:50 +0200 Subject: [PATCH 107/119] refactor: migrate localization usage (part 5) refactor: optimize imports --- language/locales/de.json | 252 +++++++++++++----- language/locales/en.json | 5 - language/locales/global.json | 91 ++++++- .../challenges/custom/CustomChallenge.java | 5 - .../custom/settings/ChallengeSetting.java | 1 - .../action/impl/ExecuteCommandAction.java | 2 +- .../action/impl/PlaceStructureAction.java | 2 +- .../custom/settings/sub/SelectableKey.java | 5 +- .../sub/builder/ValueSubSettingsBuilder.java | 4 - .../trigger/impl/IntervallTrigger.java | 2 +- .../impl/StandsOnSpecificBlockTrigger.java | 2 - .../challenge/ZeroHeartsChallenge.java | 3 - .../damage/DelayDamageChallenge.java | 12 +- .../challenge/damage/FreezeChallenge.java | 10 +- .../challenge/damage/JumpDamageChallenge.java | 2 - .../damage/SneakDamageChallenge.java | 1 - .../PermanentEffectOnDamageChallenge.java | 2 +- .../entities/MobTransformationChallenge.java | 2 - .../entities/MobsRespawnInEndChallenge.java | 2 - .../extraworld/JumpAndRunChallenge.java | 16 +- .../extraworld/WaterMLGChallenge.java | 19 +- .../challenge/force/ForceBiomeChallenge.java | 20 +- .../challenge/force/ForceBlockChallenge.java | 13 +- .../challenge/force/ForceHeightChallenge.java | 14 +- .../challenge/force/ForceItemChallenge.java | 15 +- .../challenge/force/ForceMobChallenge.java | 15 +- .../inventory/MissingItemsChallenge.java | 13 +- .../inventory/UncraftItemsChallenge.java | 11 +- .../miscellaneous/EnderGamesChallenge.java | 11 +- .../miscellaneous/FoodOnceChallenge.java | 2 +- .../miscellaneous/InvertHealthChallenge.java | 20 +- .../miscellaneous/NoExpChallenge.java | 1 - .../movement/DontStopRunningChallenge.java | 3 +- .../challenge/movement/MoveMouseDamage.java | 1 - .../challenge/movement/OnlyDirtChallenge.java | 1 - .../challenge/movement/OnlyDownChallenge.java | 1 - .../movement/TrafficLightChallenge.java | 13 +- .../challenge/quiz/QuizChallenge.java | 3 +- .../randomizer/HotBarRandomizerChallenge.java | 16 +- .../randomizer/RandomChallengeChallenge.java | 11 +- .../randomizer/RandomEventChallenge.java | 17 +- .../randomizer/RandomItemChallenge.java | 11 +- .../RandomItemDroppingChallenge.java | 15 +- .../RandomItemRemovingChallenge.java | 13 +- .../RandomItemSwappingChallenge.java | 15 +- .../randomizer/RandomizedHPChallenge.java | 22 +- .../challenge/time/MaxBiomeTimeChallenge.java | 17 +- .../time/MaxHeightTimeChallenge.java | 19 +- .../challenge/world/BedrockWallChallenge.java | 13 +- .../BlocksDisappearAfterTimeChallenge.java | 11 +- .../world/ChunkDeconstructionChallenge.java | 11 +- .../world/ChunkDeletionChallenge.java | 11 +- .../challenge/world/FloorIsLavaChallenge.java | 13 +- .../challenge/world/IceFloorChallenge.java | 2 - .../challenge/world/LevelBorderChallenge.java | 1 - .../challenge/world/LoopChallenge.java | 1 - .../challenge/world/SnakeChallenge.java | 1 - .../challenge/world/SurfaceHoleChallenge.java | 13 +- .../challenge/world/TsunamiChallenge.java | 13 +- .../damage/DamageRuleSetting.java | 15 +- .../goal/AllAdvancementGoal.java | 1 - .../goal/CollectAllItemsGoal.java | 1 - .../implementation/goal/CollectWoodGoal.java | 2 +- .../implementation/goal/MostOresGoal.java | 2 +- .../implementation/goal/RaceGoal.java | 2 +- .../forcebattle/ExtremeForceBattleGoal.java | 3 +- .../goal/forcebattle/targets/ForceTarget.java | 1 - .../material/BlockMaterialSetting.java | 40 ++- .../setting/BackpackSetting.java | 36 +-- .../setting/DamageDisplaySetting.java | 5 +- .../setting/DamageMultiplierModifier.java | 11 +- .../setting/DeathMessageSetting.java | 32 ++- .../setting/HardcoreHeartsSetting.java | 1 + .../setting/KeepInventorySetting.java | 5 +- .../setting/MaxHealthSetting.java | 5 - .../setting/PositionSetting.java | 3 +- .../setting/RegenerationSetting.java | 2 +- .../setting/SlotLimitSetting.java | 2 - .../implementation/setting/TimberSetting.java | 9 +- .../type/abstraction/AbstractChallenge.java | 8 +- .../abstraction/FirstPlayerAtHeightGoal.java | 1 - .../type/abstraction/ForceBattleGoal.java | 2 +- .../type/abstraction/KillMobsGoal.java | 3 +- .../abstraction/NetherPortalSpawnSetting.java | 2 +- .../type/abstraction/SettingModifier.java | 6 + .../SettingModifierCollectionGoal.java | 2 - .../type/abstraction/TimedChallenge.java | 5 + .../type/abstraction/menu/MenuSetting.java | 11 +- .../type/helper/ChallengeHelper.java | 59 +++- .../challenges/type/helper/GoalHelper.java | 2 - .../plugin/content/i18n/ArgumentFormat.java | 31 ++- .../content/i18n/CustomTranslatable.java | 23 ++ .../content/i18n/LocalizableMessage.java | 6 - .../i18n/impl/LocalizableMessageImpl.java | 1 - .../impl/dynamic/WrappedObjMessageImpl.java | 3 +- .../i18n/impl/format/ComponentFormatter.java | 1 - .../i18n/impl/format/MessageFormatter.java | 36 ++- .../plugin/content/legacy/MessageImpl.java | 4 - .../challenges/ChallengeLoader.java | 34 ++- .../challenges/ChallengeManager.java | 3 +- .../challenges/ModuleChallengeLoader.java | 23 +- .../inventory/PlayerInventoryManager.java | 2 +- .../menu/generator/IMenuGenerator.java | 2 +- .../generator/MultiPageMenuGenerator.java | 1 - .../scheduler/timer/TimerFormat.java | 18 +- .../management/server/TitleManager.java | 2 +- .../management/server/WorldManager.java | 2 - .../server/scoreboard/ChallengeBossBar.java | 1 - .../plugin/spigot/command/BackCommand.java | 3 +- .../spigot/command/ChallengesCommand.java | 2 +- .../spigot/command/DatabaseCommand.java | 2 +- .../plugin/spigot/command/FeedCommand.java | 2 +- .../plugin/spigot/command/FlyCommand.java | 2 +- .../spigot/command/GamemodeCommand.java | 2 +- .../spigot/command/GamestateCommand.java | 2 +- .../plugin/spigot/command/GodModeCommand.java | 2 +- .../plugin/spigot/command/HealCommand.java | 2 +- .../plugin/spigot/command/InvseeCommand.java | 5 +- .../spigot/command/LeaderboardCommand.java | 4 +- .../plugin/spigot/command/ResetCommand.java | 3 +- .../plugin/spigot/command/ResultCommand.java | 2 +- .../plugin/spigot/command/SearchCommand.java | 2 +- .../spigot/command/SkipTimerCommand.java | 3 - .../plugin/spigot/command/StatsCommand.java | 4 +- .../plugin/spigot/command/TimeCommand.java | 4 +- .../plugin/spigot/command/TimerCommand.java | 2 +- .../plugin/spigot/command/VillageCommand.java | 2 +- .../plugin/spigot/command/WeatherCommand.java | 2 +- .../plugin/spigot/command/WorldCommand.java | 2 +- .../plugin/spigot/listener/HelpListener.java | 2 - .../listener/PlayerConnectionListener.java | 2 +- .../utils/bukkit/command/PlayerCommand.java | 2 +- .../plugin/utils/item/ItemBuilder.java | 7 +- .../plugin/utils/misc/ArmorUtils.java | 26 ++ .../plugin/utils/misc/InventoryUtils.java | 2 - 135 files changed, 773 insertions(+), 637 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/CustomTranslatable.java diff --git a/language/locales/de.json b/language/locales/de.json index d938c387a..ef873b231 100644 --- a/language/locales/de.json +++ b/language/locales/de.json @@ -12,6 +12,7 @@ "day": "Tag", "days": "Tage", "time": "Zeit", + "interval": "Intervall", "disabled": "Deaktiviert", "enabled": "Aktiviert", "customize": "Anpassen", @@ -311,6 +312,7 @@ } }, "challenge": { + "settings-modifier-max-health": "Maximale Leben: {0}", "difficulty": { "name": "*Schwierigkeit*", "desc": [ @@ -351,7 +353,8 @@ "desc": [ "Es wird im Chat angezeigt,", "wenn jemand *Schaden* bekommt" - ] + ], + "message": "{0} nahm {1} Schaden durch {2}" }, "language": { "name": "*Sprache*", @@ -379,7 +382,10 @@ "name": "*Todesnachrichten*", "desc": [ "Schaltet *Todesnachrichten* ein/aus" - ] + ], + "vanilla": "Vanilla", + "message": "{0} ist gestorben", + "message-cause": "{0} ist durch {1} gestorben" }, "health-display": { "name": "*Health Display*", @@ -452,11 +458,18 @@ "desc": [ "Du kannst einen *Baum* zerstören,", "indem du *einen Block* des Baumes abbaust" - ] + ], + "settings": { + "logs": "Baumstämme", + "logs-leaves": "Baumstämme und Blätter" + } }, "pvp": { "name": "*PvP*", - "desc": [] + "desc": [ + "Du kannst anderen Spielern *Schaden*", + "*direkt zufügen* und umgekehrt" + ] }, "no-hit-delay": { "name": "*NoHitDelay*", @@ -1654,6 +1667,137 @@ "dauerhaft Absorption bekommen" ], "bossbar": "{@symbol.arrow} Schutzzeit {@symbol.vertical} {0}s" + }, + "damage-rule": { + "desc-format": [ + "Stellt ein, ob du Schaden durch", + "{0} bekommen kannst", + " ", + "Dazu zählt: *{1}*" + ], + "none": { + "name": "*Genereller Schaden*", + "desc": [ + "Stellt ein, ob du Schaden bekommen kannst", + "Du kannst *weiterhin* Schaden durch *Challenges* bekommen" + ] + }, + "fire": { + "name": "*Feuer Schaden*", + "desc": "{@desc-format('*Lava* und *Feuer*', '{0}')}" + }, + "attack": { + "name": "*Angriff Schaden*", + "desc": "{@desc-format('*Nahkampfangriffe von Kreaturen*', '{0}')}" + }, + "projectile": { + "name": "*Projektil Schaden*", + "desc": "{@desc-format('*Projektile*', '{0}')}" + }, + "fall": { + "name": "*Fallschaden*", + "desc": "{@desc-format('*Fallschaden*', '{0}')}" + }, + "explosion": { + "name": "*Explosions Schaden*", + "desc": "{@desc-format('*Explosionen*', '{0}')}" + }, + "drowning": { + "name": "*Ertrink Schaden*", + "desc": "{@desc-format('*Ertrinken*', '{0}')}" + }, + "block": { + "name": "*Block Schaden*", + "desc": "{@desc-format('*Blöcke*', '{0}')}" + }, + "magic": { + "name": "*Magie Schaden*", + "desc": "{@desc-format('*Gift*, *Wither* oder andere *Tränke*', '{0}')}" + }, + "freeze": { + "name": "*Frost Schaden*", + "desc": "{@desc-format('*Frost*', '{0}')}" + } + }, + "material-rule": { + "desc-format": [ + "Stellt ein, ob *{0}*", + "benutzt werden kann", + " ", + "Dazu zählt: *{1}*" + ], + "armor": { + "name": "*Rüstung*", + "desc": "{@desc-format('Rüstung', '{0}')}" + }, + "golden_apple": { + "name": "*Goldener Apfel*", + "desc": "{@desc-format('Goldener Apfel', '{0}')}" + }, + "crafting_table": { + "name": "*Werkbank*", + "desc": "{@desc-format('Werkbank', '{0}')}" + }, + "chest": { + "name": "*Truhe*", + "desc": "{@desc-format('Truhe', '{0}')}" + }, + "furnace": { + "name": "*Ofen*", + "desc": "{@desc-format('Ofen', '{0}')}" + }, + "enchant": { + "name": "*Verzauberungstisch*", + "desc": "{@desc-format('Verzauberungstisch', '{0}')}" + }, + "anvil": { + "name": "*Amboss*", + "desc": "{@desc-format('Amboss', '{0}')}" + }, + "brewing_stand": { + "name": "*Braustand*", + "desc": "{@desc-format('Braustand', '{0}')}" + }, + "bow": { + "name": "*Bogen*", + "desc": "{@desc-format('Bogen', '{0}')}" + }, + "throwable": { + "name": "*Wurfprojektile*", + "desc": "{@desc-format('Wurfprojektile', '{0}')}" + }, + "flint_and_steel": { + "name": "*Feuerzeug*", + "desc": "{@desc-format('Feuerzeug', '{0}')}" + }, + "bucket": { + "name": "*Eimer*", + "desc": "{@desc-format('Eimer', '{0}')}" + }, + "sword": { + "name": "*Schwert*", + "desc": "{@desc-format('Schwert', '{0}')}" + }, + "pickaxe": { + "name": "*Spitzhacke*", + "desc": "{@desc-format('Spitzhacke', '{0}')}" + }, + "elytra": { + "name": "*Elytra*", + "desc": "{@desc-format('Elytra', '{0}')}" + }, + "shield": { + "name": "*Schild*", + "desc": "{@desc-format('Schild', '{0}')}" + }, + "totem": { + "name": "*Totem*", + "desc": "{@desc-format('Totem', '{0}')}" + }, + "ender_pearl": { + "name": "*Enderperle*", + "desc": "{@desc-format('Enderperle', '{0}')}" + } } }, "title": { @@ -1689,7 +1833,7 @@ "command": { "skip-timer": { "none": "Es ist keine Challenge aktiviert, dessen Timer übersprungen werden könnte", - "done": "Die Timer folgender Challenges wurden übersprungen: {0}" + "done": "Die Timer folgender Challenges wurden übersprungen: {0}" } }, "challenge-end": { @@ -1859,9 +2003,6 @@ "reload-success": "Challenges Plugin wurde erfolgreich neu geladen", "player-command": "Dazu musst du ein Spieler sein!", "no-permission": "Dazu hast du keine Rechte", - "enabled": "Aktiviert", - "disabled": "Deaktiviert", - "customize": "Anpassen", "navigate-back": "« Zurück", "navigate-next": "» Weiter", "seconds": "Sekunden", @@ -2015,9 +2156,6 @@ "command-god-mode-enabled": "Du bist nun im God-Mode", "command-god-mode-disabled": "Du bist nun nicht mehr im God-Mode", "command-god-mode-toggled-others": "{0} Spieler sind jetzt im God-Mode", - "player-damage-display": "{0} nahm {1} Schaden durch {2}", - "death-message": "{0} ist gestorben", - "death-message-cause": "{0} ist durch {1} gestorben", "unable-to-find-fortress": "Es konnte keine Festung gefunden werden", "unable-to-find-bastion": "Es konnte keine Bastion gefunden werden", "death-collected": "Todesgrund {0} wurde registriert", @@ -2145,9 +2283,6 @@ "lore-category-activated-count": "Aktiviert » {0}/{1}", "lore-category-activated": "Aktiviert » Ja", "lore-category-deactivated": "Aktiviert » Nein", - "item-time-seconds-description": "» Zeit: {0} Sekunden", - "item-time-seconds-range-description": "» Zeit: {0}-{1} Sekunden", - "item-time-minutes-description": "» Zeit: {0} Minuten", "item-heart-damage-description": "» Schaden: {0} ", "item-heart-start-description": "» Start: {0} ", "item-max-health-description": "» Maximale Leben: {0} ", @@ -2180,12 +2315,9 @@ ], "item-language-setting-german": "Deutsch", "item-language-setting-english": "English", - "item-death-message-setting-vanilla": "Vanilla", "item-backpack-setting-team": "Team", "item-backpack-setting-player": "Player", "menu-cut-clean-setting-settings": "CutClean", - "item-timber-setting-logs": "Baumstämme", - "item-timber-setting-logs-and-leaves": "Baumstämme und Blätter", "item-regeneration-setting-not_natural": "Nicht natürlich", "menu-all-blocks-disappear-challenge-settings": "Alle Blöcke verschwinden", "item-all-blocks-disappear-break-challenge": [ @@ -2257,53 +2389,6 @@ "menu-force-height-battle-goal-settings": "Force Height Battle", "menu-force-position-battle-goal-settings": "Force Position Battle", "menu-extreme-force-battle-goal-settings": "Extreme Force Battle", - "item-damage-rule-none": [ - "Genereller Schaden", - "Stellt ein, ob du Schaden bekommen kannst" - ], - "item-damage-rule-fire": [ - "Feuer Schaden", - "Stellt ein, ob du Schaden durch", - "*Lava* und *Feuer* bekommen kannst" - ], - "item-damage-rule-attack": [ - "Angriff Schaden", - "Stellt ein, ob du Schaden durch", - "*Nahkampfangriffe von Entities* bekommen kannst" - ], - "item-damage-rule-projectile": [ - "Projektil Schaden", - "Stellt ein, ob du Schaden durch", - "*Projektile* bekommen kannst" - ], - "item-damage-rule-fall": [ - "Fallschaden", - "Stellt ein, ob du *Fallschaden* bekommen kannst" - ], - "item-damage-rule-explosion": [ - "Explosions Schaden", - "Stellt ein, ob du *Explosions Schaden* bekommen kannst" - ], - "item-damage-rule-drowning": [ - "Ertrink Schaden", - "Stellt ein, ob du Schaden durch", - "*Ertrinken* bekommen kannst" - ], - "item-damage-rule-block": [ - "Block Schaden", - "Stellt ein, ob du Schaden durch", - "*Fallende Blöcke* bekommen kannst" - ], - "item-damage-rule-magic": [ - "Magie Schaden", - "Stellt ein, ob du Schaden durch", - "*Gift*, *Wither* und andere *Tränke* bekommen kannst" - ], - "item-damage-rule-freeze": [ - "Frost Schaden", - "Stellt ein, ob du Schaden durch", - "*Frost* bekommen kannst" - ], "item-block-material": [ "{0}", "Stellt ein, ob *{1}*", @@ -2546,5 +2631,42 @@ "custom-subsetting-length": "Länge", "custom-subsetting-amplifier": "Stärke", "custom-subsetting-change": "Veränderung", - "custom-subsetting-swap_targets": "Tausch Ziele" + "custom-subsetting-swap_targets": "Tausch Ziele", + "translatable": { + "damage-cause": { + "kill": "Kill", + "world_border": "Weltbarriere", + "contact": "Kontakt", + "entity_attack": "Angriff", + "entity_sweep_attack": "Schwungangriff", + "projectile": "Projektil", + "suffocation": "Ersticken", + "fall": "Fall", + "fire": "Feuer", + "fire_tick": "Verbrennen", + "melting": "Schmelzen", + "lava": "Lava", + "drowning": "Ertrinken", + "block_explosion": "Blockexplosion", + "entity_explosion": "Kreaturenexplosion", + "void": "Leere", + "lightning": "Blitzeinschlag", + "suicide": "Selbstmord", + "starvation": "Verhungern", + "poison": "Gift", + "magic": "Magie", + "wither": "Wither", + "falling_block": "Fallender Block", + "thorns": "Dornen", + "dragon_breath": "Drachenatem", + "fly_into_wall": "kinetische Energie", + "hot_floor": "Heißen Boden", + "campfire": "Lagerfeuer", + "cramming": "Überfüllung", + "dried_out": "Austrocknen", + "freeze": "Erfrieren", + "sonic_boom": "Schallknall", + "custom": "unbekannte Ursache" + } + } } diff --git a/language/locales/en.json b/language/locales/en.json index 82d009c5b..e84a6e6c2 100644 --- a/language/locales/en.json +++ b/language/locales/en.json @@ -1197,9 +1197,6 @@ "reload-success": "Challenges Plugin successfully reloaded", "player-command": "You must be a player!", "no-permission": "You don't have permissions to do this", - "enabled": "Activated", - "disabled": "Deactivated", - "customize": "Customize", "navigate-back": "« Back", "navigate-next": "» Next", "seconds": "seconds", @@ -1618,8 +1615,6 @@ " ", "The player with the *most points* wins." ], - "item-time-seconds-description": "» Time: {0} seconds", - "item-time-seconds-range-description": "» Time: {0}-{1} Sekunden", "item-time-minutes-description": "» Time: {0} minutes", "item-heart-damage-description": "» Damage: {0} ", "item-heart-start-description": "» Start: {0} ", diff --git a/language/locales/global.json b/language/locales/global.json index 05e8deae6..75061e1bc 100644 --- a/language/locales/global.json +++ b/language/locales/global.json @@ -28,7 +28,7 @@ "damage-cause": "{0}", "damage-cause-source": "{0} ({1})", "time": "{0} {1}", - "time-range": "{@time} {@symbol.plus-minus} {2} {3}" + "time-range": "{@time} {@symbol.plus-minus} {@time('{2}', '{3}')}" }, "prefix": { "format": "{@symbol.vertical} {0} {@symbol.vertical} ", @@ -202,6 +202,7 @@ "settings-modifier-value": "{0}", "settings-modifier-multiplier": "{0}x", "settings-modifier-time": "{@generic.time}: {0}", + "settings-modifier-interval": "{@generic.interval}: {0}", "difficulty": { "*colorize*": "{0}" }, @@ -737,6 +738,94 @@ }, "zero-hearts": { "*colorize*": "{0}" + }, + "damage-rule": { + "none": { + "*colorize*": "{0}" + }, + "fire": { + "*colorize*": "{0}" + }, + "attack": { + "*colorize*": "{0}" + }, + "projectile": { + "*colorize*": "{0}" + }, + "fall": { + "*colorize*": "{0}" + }, + "explosion": { + "*colorize*": "{0}" + }, + "drowning": { + "*colorize*": "{0}" + }, + "block": { + "*colorize*": "{0}" + }, + "magic": { + "*colorize*": "{0}" + }, + "freeze": { + "*colorize*": "{0}" + } + }, + "material-rule": { + "armor": { + "*colorize*": "{0}" + }, + "golden_apple": { + "*colorize*": "{0}" + }, + "crafting_table": { + "*colorize*": "{0}" + }, + "chest": { + "*colorize*": "{0}" + }, + "furnace": { + "*colorize*": "{0}" + }, + "enchant": { + "*colorize*": "{0}" + }, + "anvil": { + "*colorize*": "{0}" + }, + "brewing_stand": { + "*colorize*": "{0}" + }, + "bow": { + "*colorize*": "{0}" + }, + "throwable": { + "*colorize*": "{0}" + }, + "flint_and_steel": { + "*colorize*": "{0}" + }, + "bucket": { + "*colorize*": "{0}" + }, + "sword": { + "*colorize*": "{0}" + }, + "pickaxe": { + "*colorize*": "{0}" + }, + "elytra": { + "*colorize*": "{0}" + }, + "shield": { + "*colorize*": "{0}" + }, + "totem": { + "*colorize*": "{0}" + }, + "ender_pearl": { + "*colorize*": "{0}" + } } }, "custom": { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index abcdcb6c8..a1a76170b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -5,21 +5,16 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; -import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; -import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import java.util.List; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java index df8f4a544..eed425f66 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/ChallengeSetting.java @@ -1,7 +1,6 @@ package net.codingarea.challenges.plugin.challenges.custom.settings; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java index 7611300dc..62228925f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java @@ -3,8 +3,8 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.action.PlayerTargetAction; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.command.CommandSender; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java index da5e0eb08..afae8f853 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java @@ -2,8 +2,8 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.FallbackNames; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; -import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.challenges.plugin.challenges.type.annotation.RequireVersion; +import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.codingarea.commons.common.collection.IRandom; import org.bukkit.*; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java index db767eaf6..743cfa385 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java @@ -4,6 +4,7 @@ import lombok.Getter; import lombok.RequiredArgsConstructor; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.kyori.adventure.text.Component; @@ -46,7 +47,7 @@ static SelectableKey.Option of(@NotNull String key, @NotNull Material displayMat @Contract(pure = true) static SelectableKey.Option of(@NotNull String key, @NotNull Material displayMaterial, @NotNull String nameKey, @NotNull Object... nameArgs) { - return of(key, displayMaterial, LocalizableMessage.of(nameKey, nameArgs)); + return of(key, displayMaterial, MessageKey.of(nameKey).withArgs(nameArgs)); } @Contract(pure = true) @@ -66,7 +67,7 @@ static SelectableKey.Option of(@NotNull String key, @NotNull ItemStack displayPr @Contract(pure = true) static SelectableKey.Option of(@NotNull String key, @NotNull ItemStack displayPreset, @NotNull String nameKey, @NotNull Object... nameArgs) { - return of(key, displayPreset, LocalizableMessage.of(nameKey, nameArgs)); + return of(key, displayPreset, MessageKey.of(nameKey).withArgs(nameArgs)); } @Getter diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java index d24b1959c..fbafc5d1f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java @@ -7,13 +7,10 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl.BooleanSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl.ModifierSetting; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.content.legacy.MessageManager; import net.codingarea.challenges.plugin.management.menu.generator.AbstractMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.SubSettingValueMenuGenerator; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; -import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -21,7 +18,6 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.function.Consumer; import java.util.function.Function; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java index afced1462..e6d5fd20d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java @@ -2,8 +2,8 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.FallbackNames; -import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SelectableKey; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.management.scheduler.policy.PlayerCountPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java index e279ce321..9a393591e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/StandsOnSpecificBlockTrigger.java @@ -10,8 +10,6 @@ import org.bukkit.event.player.PlayerMoveEvent; import org.jetbrains.annotations.NotNull; -import java.util.Objects; - public class StandsOnSpecificBlockTrigger extends ChallengeTrigger { public StandsOnSpecificBlockTrigger(String name) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java index bf63cff0d..578484b5c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/ZeroHeartsChallenge.java @@ -5,18 +5,15 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; -import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java index 7479054f6..4c0c9b891 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DelayDamageChallenge.java @@ -2,7 +2,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -29,11 +30,10 @@ public DelayDamageChallenge() { super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 64, 4, false, new ItemStack(Material.REDSTONE), "delay-damage"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue() * 30); -// } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSeconds(getValue() * 30); + } @Override protected int getSecondsUntilNextActivation() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java index 9c06711df..fed88f0d2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/FreezeChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; @@ -24,11 +25,10 @@ public FreezeChallenge() { super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 5, 60, 20, new ItemStack(Material.BLUE_ICE), "freeze"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue()); -// } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSeconds(getValue()); + } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onDamage(@NotNull EntityDamageEvent event) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java index e48a33450..69ced2d66 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java @@ -3,12 +3,10 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import org.bukkit.Color; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java index 61bc8fb34..bc7ac00d1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java @@ -2,7 +2,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java index 612b5cd45..55f64b71d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/PermanentEffectOnDamageChallenge.java @@ -3,8 +3,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java index ee52a92a2..d94e95721 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobTransformationChallenge.java @@ -2,13 +2,11 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDamageByPlayerEvent; import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; -import org.bukkit.boss.BarColor; import org.bukkit.entity.EnderDragon; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java index 9b88deb03..97721b9cd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobsRespawnInEndChallenge.java @@ -4,7 +4,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.spigot.events.EntityDeathByPlayerEvent; @@ -14,7 +13,6 @@ import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; -import org.bukkit.boss.BarColor; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java index cc0acd0b7..a0e40909f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java @@ -5,9 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.WorldDependentChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Updated; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.policy.ExtraWorldPolicy; @@ -19,7 +17,6 @@ import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.common.collection.pair.Tuple; import net.codingarea.commons.common.config.Document; import org.bukkit.*; import org.bukkit.block.Block; @@ -53,20 +50,9 @@ public JumpAndRunChallenge() { super(MenuType.CHALLENGES, 1, 10, 5, new ItemStack(Material.ACACIA_STAIRS), "jump-and-run"); } - @NotNull - @Override - public LocalizableMessage getSettingsName() { - return MessageKey.of("generic.enabled"); - } - @Override public LocalizableMessage getSettingsDescription() { - return MessageKey.of("challenge.settings-modifier-time").withArgs(ArgumentFormat.SECONDS_RANGE.apply(Tuple.of(getValue() * 60, 30))); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + return ChallengeHelper.getSettingsDescriptionIntervalSecondsRange(getValue() * 60, 30); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java index 488ef3c6b..e90af1cd9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/WaterMLGChallenge.java @@ -4,11 +4,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.WorldDependentChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.commons.common.collection.pair.Tuple; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; @@ -26,20 +23,9 @@ public WaterMLGChallenge() { super(MenuType.CHALLENGES, 1, 10, 5, new ItemStack(Material.WATER_BUCKET), "water-mlg"); } - @NotNull - @Override - public LocalizableMessage getSettingsName() { - return MessageKey.of("generic.enabled"); - } - @Override public LocalizableMessage getSettingsDescription() { - return MessageKey.of("challenge.settings-modifier-time").withArgs(ArgumentFormat.SECONDS_RANGE.apply(Tuple.of(getValue() * 60, 10))); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 10, getValue() * 60 + 10); + return ChallengeHelper.getSettingsDescriptionIntervalSecondsRange(getValue() * 60, 10); } @Override @@ -79,13 +65,12 @@ public void onPlayerBucketEmpty(@NotNull PlayerBucketEmptyEvent event) { @EventHandler(priority = EventPriority.HIGH) public void onEntityDamage(@NotNull EntityDamageEvent event) { - if (!(event.getEntity() instanceof Player)) return; + if (!(event.getEntity() instanceof Player player)) return; if (!isInExtraWorld()) return; if (AbstractChallenge.getFirstInstance(OneTeamLifeSetting.class).isEnabled()) { teleportBack(); } else { - Player player = (Player) event.getEntity(); teleportBack(player); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java index b00adc30e..1bcd7ff01 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBiomeChallenge.java @@ -5,20 +5,18 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; -import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.commons.common.config.Document; import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; import org.bukkit.NamespacedKey; import org.bukkit.Registry; import org.bukkit.block.Biome; -import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -40,15 +38,15 @@ public ForceBiomeChallenge() { super(MenuType.CHALLENGES, SettingCategory.FORCE, 2, 20, 5, new ItemStack(Material.CHAINMAIL_BOOTS), "force-biome"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return ChallengeHelper.getTimeRangeSettingsDescription(this, 60 * 3, 60); -// } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSecondsRange(getValue() * 60 * 3, 60); + } + @NotNull @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 * 3 - 60, getValue() * 60 * 3 + 60); + public ItemStack getSettingsItemPreset() { + return DefaultItems.createEnabledValuePreset(getValue() * 3); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java index bac8444e8..945ede90f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -16,7 +16,6 @@ import net.codingarea.commons.common.config.Document; import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; -import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @@ -33,15 +32,9 @@ public ForceBlockChallenge() { super(MenuType.CHALLENGES, SettingCategory.FORCE, 2, 15, new ItemStack(Material.GOLDEN_BOOTS), "force-block"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSecondsRange(getValue() * 60, 30); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java index 3c1a99ed2..beac0f299 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceHeightChallenge.java @@ -4,19 +4,17 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.EndingForceChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.commons.common.config.Document; import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; -import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @@ -32,15 +30,9 @@ public ForceHeightChallenge() { super(MenuType.CHALLENGES, SettingCategory.FORCE, 2, 15, new ItemStack(Material.IRON_BOOTS), "force-height"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSecondsRange(getValue() * 60, 30); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java index cfada5bcf..64b53515f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java @@ -2,11 +2,11 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; @@ -20,7 +20,6 @@ import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Bukkit; import org.bukkit.Material; -import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -43,15 +42,9 @@ public ForceItemChallenge() { super(MenuType.CHALLENGES, SettingCategory.FORCE, 2, 15, new ItemStack(Material.LEATHER_BOOTS), "force-item"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSecondsRange(getValue() * 60, 30); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java index 139a15cd0..d8c519478 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java @@ -2,10 +2,10 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.CompletableForceChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; @@ -14,7 +14,6 @@ import net.codingarea.commons.common.config.Document; import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; -import org.bukkit.boss.BarColor; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; @@ -38,15 +37,9 @@ public ForceMobChallenge() { super(MenuType.CHALLENGES, SettingCategory.FORCE, 2, 15, new ItemStack(Material.DIAMOND_BOOTS), "force-mob"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return ChallengeHelper.getTimeRangeSettingsDescription(this, 60, 30); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSecondsRange(getValue() * 60, 30); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java index 115e8d238..cffd6d7e7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/MissingItemsChallenge.java @@ -4,8 +4,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -47,15 +48,9 @@ public MissingItemsChallenge() { super(MenuType.CHALLENGES, SettingCategory.INVENTORY, 1, 10, 5, false, new ItemStack(Material.FISHING_ROD), "missing-items"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 10, getValue() * 60 + 10); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 10, getValue() * 60 + 10); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionIntervalSecondsRange(getValue() * 60, 10); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java index ca611c085..86aebbb0c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java @@ -2,6 +2,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; @@ -22,11 +24,10 @@ public UncraftItemsChallenge() { super(MenuType.CHALLENGES, null, 5, 60, 20, new ItemStack(Material.CRAFTING_TABLE), "uncraft-items"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue()); -// } + @Override + public @NotNull LocalizableMessage getChallengeDescription() { + return ChallengeHelper.getSettingsDescriptionIntervalSeconds(getValue()); + } public static void uncraftInventory(@NotNull Player player) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java index 7a3e30311..69afa7231 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/EnderGamesChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -25,15 +26,9 @@ public EnderGamesChallenge() { super(MenuType.CHALLENGES, null, 1, 10, 5, false, new ItemStack(Material.ENDER_PEARL), "ender-games"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 20, getValue() * 60 + 20); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionIntervalSecondsRange(getValue() * 60, 20); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java index d3cee10a9..4a0e85d99 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java @@ -2,8 +2,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java index 7fb510c51..43b35ee0a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/InvertHealthChallenge.java @@ -1,11 +1,11 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.miscellaneous; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; +import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Bukkit; @@ -21,6 +21,11 @@ public InvertHealthChallenge() { super(MenuType.CHALLENGES, null, 1, 10, 5, false, new ItemStack(Material.POPPY), "invert-health"); } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionIntervalSecondsRange(getValue() * 60, 20); + } + public static void invertHealth(Player player) { double health = player.getMaxHealth() - player.getHealth(); if (health <= 0) { @@ -30,17 +35,6 @@ public static void invertHealth(Player player) { player.setHealth(health); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); -// } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 20, getValue() * 60 + 20); - } - @Override protected int getSecondsUntilNextActivation() { return globalRandom.around(getValue() * 60, 20); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java index e3b14bda8..3283a2910 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java @@ -2,7 +2,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.misc.NameHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java index fba6ae032..6f4915b64 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java @@ -3,15 +3,14 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; -import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java index b2b9351d0..122dff1bf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java @@ -3,7 +3,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java index 09a186df3..a831f60e0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java @@ -3,7 +3,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.CanInstaKillOnEnable; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java index c25897f97..c6c870e25 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java @@ -3,7 +3,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java index 7443db9a6..9055b5ddb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java @@ -3,7 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -12,7 +12,6 @@ import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; -import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -31,15 +30,9 @@ public TrafficLightChallenge() { super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, 1, 10, 5, new ItemStack(Material.LIME_STAINED_GLASS), "traffic-light"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 20, getValue() * 60 + 20); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 20, getValue() * 60 + 20); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionIntervalSecondsRange(getValue() * 60, 20); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index 94938b4e1..2a1440e01 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -5,9 +5,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.spigot.events.PlayerJumpEvent; @@ -24,7 +24,6 @@ import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; import org.bukkit.attribute.AttributeInstance; -import org.bukkit.boss.BarColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java index 6ef84e5e4..b2ffd3a0b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/HotBarRandomizerChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; @@ -33,12 +34,10 @@ public HotBarRandomizerChallenge() { super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 10, 5, new ItemStack(Material.HOPPER_MINECART), "hotbar-randomizer"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-minutes-description").asArray(getValue()); -// } - + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionIntervalSeconds(getValue() * 60); + } /** * @param force if true only sets items if inventory is empty @@ -61,11 +60,6 @@ protected int getSecondsUntilNextActivation() { return getValue() * 60; } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeMinutesValueChangeTitle(this, getValue()); - } - @Override protected void onTimeActivation() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java index 3a1bee28b..ba678b0c3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomChallengeChallenge.java @@ -9,6 +9,7 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.ChallengeAnnotations; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -28,15 +29,9 @@ public RandomChallengeChallenge() { super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 3, 60, 6, false, new ItemStack(Material.REDSTONE), "random-challenge"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue() * 10); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 10); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionIntervalSeconds(getValue() * 10); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java index cef9209fe..f18707c99 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomEventChallenge.java @@ -3,8 +3,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; @@ -40,15 +41,15 @@ public RandomEventChallenge() { }; } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-range-description").asArray(getValue() * 60 - 30, getValue() * 60 + 30); -// } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionIntervalSecondsRange(getValue() * 60, 30); + } + @NotNull @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 - 30, getValue() * 60 + 30); + public LocalizableMessage getChallengeDescription() { + return super.getChallengeDescription().withArgs(events.length); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java index 56caa6a5c..6501d6374 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemChallenge.java @@ -4,6 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; @@ -16,15 +17,9 @@ public RandomItemChallenge() { super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 60, 30, false, new ItemStack(Material.BEACON), "random-item"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue()); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionIntervalSeconds(getValue()); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java index 18bd8d480..c478f0643 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemDroppingChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; @@ -21,11 +22,10 @@ public RandomItemDroppingChallenge() { super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 60, 5, new ItemStack(Material.DISPENSER), "random-dropping"); } - // @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue()); -// } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionIntervalSeconds(getValue()); + } public static void dropRandomItem(Player player) { if (player.getInventory().getContents().length == 0) return; @@ -42,11 +42,6 @@ public static void dropRandomItem(@NotNull Location location, @NotNull Inventory InventoryUtils.dropItemByPlayer(location, item); } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); - } - @Override protected int getSecondsUntilNextActivation() { return getValue(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java index a7196e700..6c09433c5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemRemovingChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; @@ -10,6 +11,7 @@ import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; @Since("2.0") public class RandomItemRemovingChallenge extends TimedChallenge { @@ -18,15 +20,10 @@ public RandomItemRemovingChallenge() { super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 30, 30, new ItemStack(Material.DROPPER), "random-item-removing"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue() * 10); -// } - + @Nullable @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 10); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionIntervalSeconds(getValue()); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java index 071d8a7e0..8200b2e58 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomItemSwappingChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; @@ -20,11 +21,10 @@ public RandomItemSwappingChallenge() { super(MenuType.CHALLENGES, SettingCategory.RANDOMIZER, 1, 60, 5, new ItemStack(Material.HOPPER), "random-swapping"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue()); -// } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionIntervalSeconds(getValue()); + } public static void swapRandomItems(Player player) { if (player.getInventory().getContents().length == 0) return; @@ -45,11 +45,6 @@ private static void swapItemToRandomSlot(@NotNull Inventory inventory, int slot1 inventory.setItem(slot2, item1); } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); - } - @Override protected int getSecondsUntilNextActivation() { return getValue(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java index b10b76e8f..d3cdf8232 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/RandomizedHPChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.item.DefaultItems; @@ -38,11 +39,10 @@ public RandomizedHPChallenge() { randomizeExistingEntityHealth(); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-max-health-description").asArray(getValue() * 50); -// } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionMaxHealth(getValue() * 100); + } @Override protected void onDisable() { @@ -62,8 +62,7 @@ protected void onValueChange() { @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onSpawn(@NotNull EntitySpawnEvent event) { if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof LivingEntity)) return; - LivingEntity entity = (LivingEntity) event.getEntity(); + if (!(event.getEntity() instanceof LivingEntity entity)) return; randomizeEntityHealth(entity); } @@ -76,8 +75,6 @@ private void randomizeEntityHealth(@NotNull LivingEntity entity) { if (!isEnabled()) { attribute.setBaseValue(attribute.getDefaultValue()); entity.setHealth(attribute.getDefaultValue()); -// entity.resetMaxHealth(); -// entity.setHealth(entity.getMaxHealth()); return; } @@ -124,12 +121,7 @@ private double getDefaultHealth(@NotNull EntityType entityType) { @NotNull @Override public ItemStack getSettingsItemPreset() { - return DefaultItems.createEnabledValuePreset(getValue() * 5); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() * 100); + return DefaultItems.createEnabledValuePreset(getValue() * 10); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java index 9bb578e91..09db702f3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxBiomeTimeChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; @@ -22,6 +23,11 @@ public MaxBiomeTimeChallenge() { super(MenuType.CHALLENGES, SettingCategory.LIMITED_TIME, 3, 20, new ItemStack(Material.SPRUCE_SAPLING), "max-biome-time"); } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSeconds(getValue() * 60); + } + @Override protected void onEnable() { bossbar.setContent((bossbar, player) -> { @@ -44,17 +50,6 @@ protected void onValueChange() { bossbar.update(); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue() * 60); -// } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 60); - } - @EventHandler public void onPlayerMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java index 30bee71d8..5d187dad9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/time/MaxHeightTimeChallenge.java @@ -3,14 +3,13 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Bukkit; import org.bukkit.Material; -import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerMoveEvent; @@ -24,6 +23,11 @@ public MaxHeightTimeChallenge() { super(MenuType.CHALLENGES, SettingCategory.LIMITED_TIME, 3, 20, new ItemStack(Material.PARROT_SPAWN_EGG), "max-height-time"); } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSeconds(getValue() * 60); + } + @Override protected void onEnable() { bossbar.setContent((bossbar, player) -> { @@ -46,17 +50,6 @@ protected void onValueChange() { bossbar.update(); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue() * 60); -// } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 60); - } - @EventHandler public void onPlayerMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java index 1838330b2..c530e2951 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BedrockWallChallenge.java @@ -1,6 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; @@ -21,6 +23,11 @@ public BedrockWallChallenge() { super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 60, 30, new ItemStack(Material.BEDROCK), "bedrock-walls"); } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSeconds(getValue()); + } + @EventHandler public void onMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; @@ -51,10 +58,4 @@ public void onMove(@NotNull PlayerMoveEvent event) { } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue()); -// } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java index a21ca586a..db1b6824d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/BlocksDisappearAfterTimeChallenge.java @@ -2,6 +2,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Bukkit; @@ -27,11 +29,10 @@ public BlocksDisappearAfterTimeChallenge() { super(MenuType.CHALLENGES, SettingCategory.WORLD, 60, 300, new ItemStack(Material.STRING), "blocks-disappear-time"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue()); -// } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSeconds(getValue()); + } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPlace(@NotNull BlockPlaceEvent event) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java index 897296e33..5abe4d542 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeconstructionChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; @@ -21,15 +22,9 @@ public ChunkDeconstructionChallenge() { super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 60, 20, new ItemStack(Material.DIAMOND_PICKAXE), "chunk-deconstruction"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue()); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue()); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSeconds(getValue()); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java index 0e4a809bd..c2dbdf1c0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/ChunkDeletionChallenge.java @@ -1,6 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -10,7 +12,6 @@ import org.bukkit.*; import org.bukkit.World.Environment; import org.bukkit.block.Block; -import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -29,10 +30,10 @@ public ChunkDeletionChallenge() { super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 120, 60, new ItemStack(Material.GOLDEN_PICKAXE), "chunk-deletion"); } -// @Override -// protected @Nullable String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue()); -// } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSeconds(getValue()); + } @Override protected void onEnable() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java index 6e7607724..2f02cf051 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/FloorIsLavaChallenge.java @@ -1,6 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; @@ -19,6 +21,11 @@ public FloorIsLavaChallenge() { super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 60, 30, new ItemStack(Material.MAGMA_BLOCK), "floor-is-lava"); } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSeconds(getValue()); + } + @EventHandler public void onMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; @@ -43,10 +50,4 @@ private void createLavaFloor(@NotNull Location to) { BlockUtils.setBlockNatural(BlockUtils.getBlockBelow(to), Material.LAVA, true); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue()); -// } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java index 9be56df19..7a311c1bb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/IceFloorChallenge.java @@ -3,7 +3,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -12,7 +11,6 @@ import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; -import org.bukkit.boss.BarColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java index ae94f3a74..3cc1ff3d6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LevelBorderChallenge.java @@ -5,7 +5,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.ExcludeFromRandomChallenges; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java index 9ac40035d..10a1c870a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/LoopChallenge.java @@ -3,7 +3,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index 3a6803057..230783946 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -2,7 +2,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java index 4c1d2fd7b..cf5f4b105 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SurfaceHoleChallenge.java @@ -1,6 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; @@ -21,6 +23,11 @@ public SurfaceHoleChallenge() { super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 60, 30, new ItemStack(Material.BARRIER), "surface-hole"); } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSeconds(getValue()); + } + @EventHandler public void onMove(@NotNull PlayerMoveEvent event) { if (!shouldExecuteEffect()) return; @@ -53,10 +60,4 @@ public void onMove(@NotNull PlayerMoveEvent event) { } -// @Nullable // TODO! -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue()); -// } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java index 76614efd7..ccd06a490 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/TsunamiChallenge.java @@ -4,7 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.ListBuilder; @@ -17,7 +17,6 @@ import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.block.Block; -import org.bukkit.boss.BarColor; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerMoveEvent; @@ -46,15 +45,9 @@ public TsunamiChallenge() { super(MenuType.CHALLENGES, SettingCategory.WORLD, 1, 40, 4, new ItemStack(Material.ICE), "tsunami"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-time-seconds-description").asArray(getValue() * 15); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsValueChangeTitle(this, getValue() * 15); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSeconds(getValue() * 15); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java index 249c0e1d2..7c7992654 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java @@ -2,13 +2,15 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.content.i18n.CustomTranslatable; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.Arrays; @@ -20,8 +22,8 @@ public class DamageRuleSetting extends Setting { private final String name; - public DamageRuleSetting(@NotNull LegacyItemBuilder preset, @NotNull String name, @NotNull DamageCause... causes) { - super(MenuType.DAMAGE, null, true, preset.build(), "TITLE!"); + public DamageRuleSetting(@NotNull ItemStack displayItemPreset, @NotNull String name, @NotNull DamageCause... causes) { + super(MenuType.DAMAGE, null, true, displayItemPreset, "damage-rule." + name); this.causes = Arrays.asList(causes); this.name = name; } @@ -32,6 +34,13 @@ public String getUniqueName() { return super.getUniqueName() + name; } + @NotNull + @Override + public LocalizableMessage getChallengeDescription() { + return super.getChallengeDescription() + .withArgs(LocalizableMessage.joinList(3, causes.stream().map(CustomTranslatable::of).toList())); + } + @EventHandler(priority = EventPriority.NORMAL) public void onDamage(@NotNull EntityDamageEvent event) { if (ChallengeAPI.isWorldInUse()) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java index 601833d16..2d0e3c373 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/AllAdvancementGoal.java @@ -5,7 +5,6 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.GoalHelper; import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index 2d391bc11..0bb7e8d36 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -7,7 +7,6 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Updated; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.content.i18n.impl.format.ComponentArguments; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java index a6379ac49..304916a0e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectWoodGoal.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.challenges.implementation.goal; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierCollectionGoal; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java index 1e90a4ee9..6c9e8eed4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/MostOresGoal.java @@ -2,8 +2,8 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.PointsGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java index 911e7196c..137013a5d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java @@ -5,9 +5,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifierGoal; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java index 1c02e3c03..8cdb170b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java @@ -6,12 +6,11 @@ import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; import net.codingarea.commons.common.config.Document; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java index cf6b386a9..a705d8efc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/targets/ForceTarget.java @@ -3,7 +3,6 @@ import lombok.Getter; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.ExtremeForceBattleGoal; import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.content.legacy.Message; import org.bukkit.Material; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java index e4f08eeba..176a9bb34 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java @@ -2,10 +2,10 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.spigot.events.PlayerPickupItemEvent; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import org.bukkit.Location; import org.bukkit.Material; @@ -17,28 +17,27 @@ import org.jetbrains.annotations.NotNull; import java.util.Arrays; +import java.util.List; public class BlockMaterialSetting extends Setting { private final String name; - private final Object[] replacements; - private final Material[] materials; + private final List materials; - public BlockMaterialSetting(@NotNull String name, @NotNull LegacyItemBuilder preset, @NotNull Object[] replacements, @NotNull Material... materials) { - super(MenuType.ITEMS, null, true, preset.build(), "lol"); + public BlockMaterialSetting(@NotNull String name, @NotNull ItemStack displayItemPreset, @NotNull Material... materials) { + super(MenuType.ITEMS, null, true, displayItemPreset, "material-rule." + name); this.name = name; - this.replacements = replacements; - this.materials = materials; + this.materials = Arrays.asList(materials); } -// @NotNull -// @Override -// public LegacyItemBuilder createDisplayItem() { -// return preset.clone().applyFormat(Message.forName(name).asItemDescription(replacements)); -// } + @NotNull + @Override + public LocalizableMessage getChallengeDescription() { + return super.getChallengeDescription().withArgs(LocalizableMessage.joinList(3, materials)); + } - private boolean blockMaterial(Material material) { - return Arrays.asList(materials).contains(material); + private boolean isMaterialAllowed(Material material) { + return !materials.contains(material); } @EventHandler(priority = EventPriority.HIGH) @@ -46,9 +45,9 @@ public void onPlayerInteract(@NotNull PlayerInteractEvent event) { if (isEnabled()) return; if (ChallengeAPI.isWorldInUse()) return; if (ignorePlayer(event.getPlayer())) return; - if (!blockMaterial(event.getMaterial())) { + if (isMaterialAllowed(event.getMaterial())) { if (event.getClickedBlock() == null) return; - if (!blockMaterial(event.getClickedBlock().getType())) return; + if (isMaterialAllowed(event.getClickedBlock().getType())) return; event.setCancelled(true); return; } @@ -65,7 +64,7 @@ public void onPlayerInventoryClick(@NotNull PlayerInventoryClickEvent event) { if (event.getCurrentItem() == null) return; if (event.getClickedInventory() == null) return; if (event.getClickedInventory().getHolder() != event.getPlayer()) return; - if (!blockMaterial(event.getCurrentItem().getType())) return; + if (isMaterialAllowed(event.getCurrentItem().getType())) return; event.setCancelled(true); dropMaterial(event.getPlayer().getLocation(), event.getClickedInventory()); @@ -76,7 +75,7 @@ public void onPlayerPickupItem(@NotNull PlayerPickupItemEvent event) { if (isEnabled()) return; if (ignorePlayer(event.getPlayer())) return; if (ChallengeAPI.isWorldInUse()) return; - if (!blockMaterial(event.getItem().getItemStack().getType())) return; + if (isMaterialAllowed(event.getItem().getItemStack().getType())) return; event.setCancelled(true); } @@ -84,17 +83,16 @@ public void dropMaterial(@NotNull Location location, @NotNull Inventory inventor for (int slot = 0; slot < inventory.getSize(); slot++) { ItemStack item = inventory.getItem(slot); if (item == null) continue; - if (!blockMaterial(item.getType())) continue; + if (isMaterialAllowed(item.getType())) continue; InventoryUtils.dropItemByPlayer(location, item); inventory.setItem(slot, null); } - } @NotNull @Override public String getUniqueName() { - return "blockmaterial" + materials[0].name().toLowerCase(); + return "blockmaterial" + name; } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java index db31f5179..0b4585835 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java @@ -5,9 +5,10 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeConfigHelper; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; @@ -43,30 +44,17 @@ public BackpackSetting() { @NotNull @Override public ItemStack getSettingsItemPreset() { - return super.getSettingsItemPreset(); + if (getValue() == SHARED) + return new ItemStack(Material.ENDER_CHEST); + return new ItemStack(Material.PLAYER_HEAD); } -// @NotNull -// @Override -// public LegacyItemBuilder createSettingsItem() { -// if (getValue() == SHARED) -// return DefaultItem.create(Material.ENDER_CHEST, Message.forName("item-backpack-setting-team")); -// return DefaultItem.create(Material.PLAYER_HEAD, Message.forName("item-backpack-setting-player")); -// } - - + @NotNull @Override - public void playValueChangeTitle() { - switch (getValue()) { - case SHARED: - ChallengeHelper.playChallengeValueTitle(this, Message.forName("item-backpack-setting-team")); - break; - case PLAYER: - ChallengeHelper.playChallengeValueTitle(this, Message.forName("item-backpack-setting-player")); - break; - default: - ChallengeHelper.playChallengeToggleTitle(this, false); - } + public LocalizableMessage getSettingsName() { + if (getValue() == SHARED) + return getChallengeMessageKey("settings.shared"); + return getChallengeMessageKey("settings.player"); } @Override @@ -116,7 +104,7 @@ protected void loadChecked(@NotNull Document document, @NotNull String key, @Not if (value == null) return; BukkitSerialization.fromBase64(inventory, value); } catch (IOException exception) { - Challenges.getInstance().getILogger().error("", exception); + Challenges.getInstance().getILogger().error(exception); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java index 1140d1a4e..3265e550d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageDisplaySetting.java @@ -2,10 +2,10 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.annotation.Updated; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import org.bukkit.Material; @@ -17,6 +17,7 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +@Updated("2.4") public class DamageDisplaySetting extends Setting { public DamageDisplaySetting() { @@ -32,6 +33,6 @@ public void onDamage(@NotNull EntityDamageEvent event) { LocalizableMessage damageDisplay = ArgumentFormat.HEARTS_LIMITED.apply(event.getFinalDamage()); LocalizableMessage causeDisplay = ArgumentFormat.DAMAGE_CAUSE.apply(event); - MessageKey.of("player-damage-display").broadcast(Prefix.DAMAGE, event.getEntity(), damageDisplay, causeDisplay); + getChallengeMessageKey("message").broadcast(Prefix.DAMAGE, event.getEntity(), damageDisplay, causeDisplay); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java index 4050cd412..cc7964dc9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DamageMultiplierModifier.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -17,11 +18,11 @@ public DamageMultiplierModifier() { super(MenuType.SETTINGS, null, 10, new ItemStack(Material.STONE_SWORD), "damage-multiplier"); } -// @NotNull -// @Override -// public LocalizableMessage getSettingsName() { -// return super.getSettingsName(); // TODO format -// } + @NotNull + @Override + public LocalizableMessage getSettingsName() { + return ChallengeHelper.getSettingsDescriptionModifierMultiplier(getValue()); + } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onDamage(@NotNull EntityDamageEvent event) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java index 1ba0d43d9..d07fe02ba 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathMessageSetting.java @@ -1,15 +1,16 @@ package net.codingarea.challenges.plugin.challenges.implementation.setting; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; +import net.codingarea.challenges.plugin.challenges.type.annotation.Updated; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.content.legacy.Message; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -21,6 +22,7 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +@Updated("2.4") public class DeathMessageSetting extends Modifier { public static final int @@ -37,24 +39,20 @@ public DeathMessageSetting() { @Override public ItemStack getSettingsItemPreset() { return switch (getValue()) { - case VANILLA -> new ItemStack(MinecraftNameWrapper.SIGN); + case VANILLA -> new ItemStack(MinecraftNameWrapper.YELLOW_DYE); case ENABLED -> DefaultItems.createEnabledPreset(); default -> DefaultItems.createDisabledPreset(); }; } + @NotNull @Override - public void playValueChangeTitle() { - switch (getValue()) { - case ENABLED: - ChallengeHelper.playChallengeToggleTitle(this, true); - return; - case VANILLA: - ChallengeHelper.playChallengeValueTitle(this, Message.forName("item-death-message-setting-vanilla")); - return; - default: - ChallengeHelper.playChallengeToggleTitle(this, false); - } + public LocalizableMessage getSettingsName() { + return switch (getValue()) { + case VANILLA -> getChallengeMessageKey("vanilla"); + case ENABLED -> ChallengeHelper.getChallengeEnabledName(); + default -> ChallengeHelper.getChallengeDisabledName(); + }; } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @@ -69,16 +67,16 @@ public void onDeath(@NotNull PlayerDeathEvent event) { case ENABLED -> { EntityDamageEvent cause = player.getLastDamageCause(); if (cause != null && cause.getCause() != DamageCause.CUSTOM) { - MessageKey.of("death-message-cause").broadcast(Prefix.CHALLENGES, player, ArgumentFormat.DAMAGE_CAUSE.apply(cause)); + getChallengeMessageKey("message-cause").broadcast(Prefix.CHALLENGES, player, ArgumentFormat.DAMAGE_CAUSE.apply(cause)); } else { - MessageKey.of("death-message").broadcast(Prefix.CHALLENGES, player); + getChallengeMessageKey("message").broadcast(Prefix.CHALLENGES, player); } } case VANILLA -> { Component original = event.deathMessage(); if (original != null) { for (Player target : Bukkit.getOnlinePlayers()) { - target.sendMessage(Component.text().append(Prefix.CHALLENGES.getKey().asComponent(player)).append(original)); + target.sendMessage(Prefix.CHALLENGES.getKey().asComponent(player).append(original.colorIfAbsent(NamedTextColor.GRAY))); } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HardcoreHeartsSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HardcoreHeartsSetting.java index 066f4a9eb..f1ea381fd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HardcoreHeartsSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/HardcoreHeartsSetting.java @@ -66,6 +66,7 @@ public void onPacketSending(PacketEvent event) { /** * Finds the ProtocolLib boolean index for the 'hardcore' flag. * * @param packet The packet container to scan (e.g., LOGIN or RESPAWN) + * * @return The integer index for .getBooleans(), or -1 if not found. */ public int getHardcoreFieldIndex(PacketContainer packet) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java index 0867c5d1c..cb22597da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/KeepInventorySetting.java @@ -2,7 +2,10 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.management.menu.MenuType; -import org.bukkit.*; +import org.bukkit.Bukkit; +import org.bukkit.GameRule; +import org.bukkit.Material; +import org.bukkit.World; import org.bukkit.inventory.ItemStack; public class KeepInventorySetting extends Setting { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java index 0a5e3286a..868607f7d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/MaxHealthSetting.java @@ -54,11 +54,6 @@ public void onValueChange() { broadcast(this::updateHealth); } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - @EventHandler public void onJoin(@NotNull PlayerJoinEvent event) { updateHealth(event.getPlayer()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java index 132be2419..2edd86866 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java @@ -4,9 +4,8 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeConfigHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java index 2c80a0594..da0f704e6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java @@ -2,9 +2,9 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java index 36c5fa95e..baf4814a3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/SlotLimitSetting.java @@ -24,8 +24,6 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.Locale; - @Since("2.0") public class SlotLimitSetting extends Modifier { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java index bff77a10b..62f148611 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/TimberSetting.java @@ -3,9 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.commons.bukkit.utils.item.ItemUtils; @@ -42,12 +40,7 @@ public ItemStack getSettingsItemPreset() { @NotNull @Override public LocalizableMessage getSettingsName() { - return getValue() == LOGS_LEAVES ? MessageKey.of("item-timber-setting-logs-and-leaves") : MessageKey.of("item-timber-setting-logs"); - } - - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeValueTitle(this, getValue() == LOGS_LEAVES ? Message.forName("item-timber-setting-logs-and-leaves") : Message.forName("item-timber-setting-logs")); + return getValue() == LOGS_LEAVES ? getChallengeMessageKey("settings.logs-leaves") : getChallengeMessageKey("settings.logs"); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java index 1709c9005..51a532534 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java @@ -175,8 +175,8 @@ protected ItemStack getDisabledSettingsItemPreset() { /** * @implNote Only used if {@link #isEnabled()}. - * Name/Lore will be overwritten by formatting. - * Set name in {@link #getSettingsName()} and lore in {@link #getSettingsDescription()} + * Name/Lore will be overwritten by formatting. + * Set name in {@link #getSettingsName()} and lore in {@link #getSettingsDescription()} */ @NotNull public ItemStack getSettingsItemPreset() { @@ -186,11 +186,11 @@ public ItemStack getSettingsItemPreset() { /** * @implNote Only used if {@link #isEnabled()}, format will be applied dynamically * @implSpec Should ideally either return a {@link LocalizableMessage}, {@link MessageKey} - * or {@link net.kyori.adventure.text.Component} for dynamic (e.g. translatable) styling + * or {@link net.kyori.adventure.text.Component} for dynamic (e.g. translatable) styling */ @NotNull public Object getSettingsName() { - return MessageKey.of("generic.enabled"); + return ChallengeHelper.getChallengeEnabledName(); } /** diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java index 5237147b9..94a7b346f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java @@ -3,7 +3,6 @@ import lombok.Getter; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.SettingCategory; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java index 9f21d80d7..25323177d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java @@ -3,9 +3,9 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ForceTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.menu.MenuGoal; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java index 33f605bbe..0e10afd09 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/KillMobsGoal.java @@ -1,14 +1,13 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import net.codingarea.challenges.plugin.ChallengeAPI; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.commons.common.config.Document; import net.kyori.adventure.bossbar.BossBar; -import org.bukkit.boss.BarColor; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java index 7ee9195da..ad08b774a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/NetherPortalSpawnSetting.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.commons.common.config.Document; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java index d6cab8510..425bcb18f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifier.java @@ -59,6 +59,12 @@ public ItemStack getSettingsItemPreset() { return DefaultItems.createEnabledValuePreset(getValue()); } + @NotNull + @Override + public Object getSettingsName() { + return ChallengeHelper.getChallengeEnabledName(); + } + @Override public final boolean isEnabled() { return enabled; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java index f1814747b..5459dae9d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/SettingModifierCollectionGoal.java @@ -2,8 +2,6 @@ import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; import org.bukkit.inventory.ItemStack; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java index 2cbe4f2ee..d5ed90bf1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/TimedChallenge.java @@ -72,6 +72,11 @@ public void setValue(int value) { } } + @Override + protected void onValueChange() { + restartTimer(); + } + // Don't execute async to prevent sync issues with timer @ScheduledTask(ticks = 20, async = false) public final void handleTimedChallengeSecond() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java index 498e09d38..73bf3772f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java @@ -1,10 +1,9 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction.menu; -import lombok.AccessLevel; import lombok.Getter; -import lombok.Setter; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; @@ -105,7 +104,7 @@ public abstract class SubSetting implements Listener { protected final ItemStack displayItemPreset; - public SubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace) { + public SubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace) { this.displayItemPreset = displayItemPreset; this.nameMessageKeySpace = nameMessageKeySpace; } @@ -137,8 +136,8 @@ public ItemBuilder getSettingsItem(@NotNull Locale locale) { /** * @implNote Only used if {@link #isEnabled()}. - * Name/Lore will be overwritten by formatting. - * Set name in {@link #getSettingsName()} and lore in {@link #getSettingsDescription()} + * Name/Lore will be overwritten by formatting. + * Set name in {@link #getSettingsName()} and lore in {@link #getSettingsDescription()} */ @NotNull public abstract ItemStack getSettingsItemPreset(); @@ -155,7 +154,7 @@ public LocalizableMessage getDisplayDescription() { @NotNull protected LocalizableMessage getSettingsName() { - return MessageKey.of("generic.enabled"); + return ChallengeHelper.getChallengeEnabledName(); } @Nullable diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index c80f0b4d2..c2c269833 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -8,11 +8,15 @@ import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; +import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.generator.IChallengesMenuGenerator; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import net.codingarea.commons.common.collection.pair.Tuple; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; @@ -25,6 +29,7 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -173,41 +178,85 @@ public static void playGoalToggleTitle(@NotNull IGoal goal, boolean enabled) { } public static void playChallengeValueTitle(@NotNull T modifier) { - playChallengeValueTitle(modifier, modifier.getValue()); + LocalizableMessage description = modifier.getSettingsDescription(); + playChallengeValueTitle(modifier, description != null ? description : modifier.getSettingsName()); // TODO or #getValue instead of#getSettingsName } public static void playChallengeValueTitle(@NotNull AbstractChallenge challenge, @NotNull Object value) { Challenges.getInstance().getTitleManager().sendChallengeValueTitle(challenge, value); } + @Deprecated public static void playChallengeHeartsValueChangeTitle(@NotNull AbstractChallenge challenge, int health) { playChallengeValueTitle(challenge, (health / 2f) + " §c❤"); } + @Deprecated public static void playChallengeHeartsValueChangeTitle(@NotNull Modifier modifier) { playChallengeHeartsValueChangeTitle(modifier, modifier.getValue()); } + @Deprecated public static void playChallengeSecondsValueChangeTitle(@NotNull AbstractChallenge challenge, int seconds) { playChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds").asString(seconds)); } + @Deprecated public static void playChallengeSecondsRangeValueChangeTitle(@NotNull AbstractChallenge challenge, int min, int max) { playChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds-range").asString(min, max)); } + @Deprecated public static void playChallengeMinutesValueChangeTitle(@NotNull AbstractChallenge challenge, int seconds) { playChallengeValueTitle(challenge, Message.forName("subtitle-time-minutes").asString(seconds)); } @NotNull - public static String[] getTimeRangeSettingsDescription(@NotNull Modifier modifier, int multiplier, int range) { - return Message.forName("item-time-seconds-range-description").asArray(modifier.getValue() * multiplier - range, modifier.getValue() * multiplier + range); + @Contract(pure = true) + public static LocalizableMessage getSettingsDescriptionModifierMultiplier(int value) { + return MessageKey.of("challenge.settings-modifier-multiplier").withArgs(value); + } + + @NotNull + @Contract(pure = true) + public static LocalizableMessage getSettingsDescriptionIntervalSecondsRange(int baseSeconds, int rangeSecondsAround) { + return MessageKey.of("challenge.settings-modifier-interval").withArgs(ArgumentFormat.SECONDS_RANGE.apply(Tuple.of(baseSeconds, rangeSecondsAround))); + } + + @NotNull + @Contract(pure = true) + public static LocalizableMessage getSettingsDescriptionIntervalSeconds(int timeInSeconds) { + return MessageKey.of("challenge.settings-modifier-interval").withArgs(ArgumentFormat.TIME.apply(timeInSeconds)); + } + + @NotNull + @Contract(pure = true) + public static LocalizableMessage getSettingsDescriptionTimeSeconds(int timeInSeconds) { + return MessageKey.of("challenge.settings-modifier-time").withArgs(ArgumentFormat.TIME.apply(timeInSeconds)); + } + + @NotNull + @Contract(pure = true) + public static LocalizableMessage getSettingsDescriptionTimeSecondsRange(int baseSeconds, int rangeSecondsAround) { + return MessageKey.of("challenge.settings-modifier-time").withArgs(ArgumentFormat.SECONDS_RANGE.apply(Tuple.of(baseSeconds, rangeSecondsAround))); + } + + @NotNull + @Contract(pure = true) + public static LocalizableMessage getSettingsDescriptionMaxHealth(int hp) { + return MessageKey.of("challenge.settings-modifier-max-health").withArgs(ArgumentFormat.HP.apply(hp)); + } + + @NotNull + @Contract(pure = true) + public static LocalizableMessage getChallengeEnabledName() { + return MessageKey.of("generic.enabled"); } @NotNull - public static String[] getTimeRangeSettingsDescription(@NotNull Modifier modifier, int range) { - return getTimeRangeSettingsDescription(modifier, 1, range); + @Contract(pure = true) + public static LocalizableMessage getChallengeDisabledName() { + return MessageKey.of("generic.disabled"); } public static boolean finalDamageIsNull(@NotNull EntityDamageEvent event) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java index ea5fe055e..d83c468de 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/GoalHelper.java @@ -6,9 +6,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeScoreboard.ScoreboardInstance; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.common.collection.NumberFormatter; import org.bukkit.Bukkit; import org.bukkit.GameMode; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java index 9b0ad8538..6f7afa60e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java @@ -3,7 +3,6 @@ import lombok.RequiredArgsConstructor; import net.codingarea.commons.common.collection.NumberFormatter; import net.codingarea.commons.common.collection.pair.Tuple; -import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; @@ -16,6 +15,8 @@ import org.jspecify.annotations.NonNull; import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; import java.util.Map; import java.util.function.Function; @@ -42,7 +43,7 @@ public interface ArgumentFormat { }); @SuppressWarnings({"unchecked", "rawtypes"}) - ArgumentFormat SECONDS_RANGE = register(Tuple.class, "minute_range", arg -> { + ArgumentFormat SECONDS_RANGE = register(Tuple.class, "time_range", arg -> { Tuple range = (Tuple) arg; int seconds = range.getFirst(); int secondsRange = range.getSecond(); @@ -59,9 +60,33 @@ public interface ArgumentFormat { NumberFormatter.DEFAULT.format(secondsRange), MessageKey.pluralize("generic.second", secondsRange)); }); + ArgumentFormat TIME = register(Number.class, "time", arg -> { + long time = arg.longValue(); + long s = time % 60; + long m = (time / 60) % 60; + long h = (time / 3_600) % 24; + long d = time / 86_400; + + List components = new LinkedList<>(); + if (s > 0 || time == 0) { // show 0s + components.add(MessageKey.of("arg-format.time").withArgs(s, MessageKey.pluralize("generic.second", s))); + } + if (m > 0) { + components.addFirst(MessageKey.of("arg-format.time").withArgs(m, MessageKey.pluralize("generic.minute", m))); + } + if (h > 0) { + components.addFirst(MessageKey.of("arg-format.time").withArgs(h, MessageKey.pluralize("generic.hour", h))); + } + if (d > 0) { + components.addFirst(MessageKey.of("arg-format.time").withArgs(d, MessageKey.pluralize("generic.day", d))); + } + + return LocalizableMessage.joinList(components); + }); + ArgumentFormat DAMAGE_CAUSE = register(EntityDamageEvent.class, "damage_cause", event -> { if (event.getCause() == EntityDamageEvent.DamageCause.CUSTOM) return MessageKey.of("generic.undefined"); - String cause = StringUtils.getEnumName(event.getCause()); // DamageCause is not a Translatable, impl custom translations? + MessageKey cause = CustomTranslatable.of(event.getCause()); if (event instanceof EntityDamageByBlockEvent damageEvent) { if (damageEvent.getDamager() != null) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/CustomTranslatable.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/CustomTranslatable.java new file mode 100644 index 000000000..0ea95da75 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/CustomTranslatable.java @@ -0,0 +1,23 @@ +package net.codingarea.challenges.plugin.content.i18n; + +import org.bukkit.event.entity.EntityDamageEvent; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +/** + * Provides translation keys for common minecraft values that have no client side translation key + * (don't implement {@link net.kyori.adventure.translation.Translatable}). + */ +@ApiStatus.Experimental +public final class CustomTranslatable { + + public CustomTranslatable() { + } + + @NotNull + public static MessageKey of(@NotNull EntityDamageEvent.DamageCause damageCause) { + String key = damageCause.name().toLowerCase(); + return MessageKey.of("translatable.damage-cause." + key); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java index 7e73d899a..e3a340be1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/LocalizableMessage.java @@ -46,12 +46,6 @@ public interface LocalizableMessage { @ApiStatus.Internal Object[] getLocalizableArgs(); - @NotNull - @CheckReturnValue - static LocalizableMessage of(@NotNull String messageKey, @NotNull Object[] args) { - return MessageKey.of(messageKey).withArgs(args); - } - @NotNull @CheckReturnValue static LocalizableMessage join(@NotNull MessageKey delimiter, @NotNull MessageKey remainingPlaceholder, int limit, @NotNull Object... elements) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java index 44209c7ee..193a50635 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java @@ -6,7 +6,6 @@ import net.codingarea.challenges.plugin.content.i18n.MessageKey; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.Locale; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/WrappedObjMessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/WrappedObjMessageImpl.java index 3fff8c2d7..0542b0ea8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/WrappedObjMessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/WrappedObjMessageImpl.java @@ -39,7 +39,8 @@ public MessageHolder localize(@NotNull Player playerLocale) { @NotNull @Override public LocalizableMessage withArgs(@NotNull Object... args) { - if (args.length != 1) throw new IllegalArgumentException("WrappedObjMessageImpl must wrap a single object, but got " + args.length + " arguments."); + if (args.length != 1) + throw new IllegalArgumentException("WrappedObjMessageImpl must wrap a single object, but got " + args.length + " arguments."); return new WrappedObjMessageImpl(args); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java index a1983a558..99798aac1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java @@ -1,7 +1,6 @@ package net.codingarea.challenges.plugin.content.i18n.impl.format; import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.TextReplacementConfig; import net.kyori.adventure.text.format.TextDecoration; import net.kyori.adventure.text.minimessage.MiniMessage; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/MessageFormatter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/MessageFormatter.java index 85ec1ce8b..747fae427 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/MessageFormatter.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/MessageFormatter.java @@ -206,18 +206,34 @@ private static void resolveReferenceInto(@NotNull String originKey, @NotNull Map @CheckReturnValue private static String qualifyRelativeKey(@NotNull String relativeReferenceName, @NotNull String[] originSubDocumentPath, @NotNull Map messagesBundle) { - String qualifiedReferenceName = relativeReferenceName; - for (int path = 0; path < originSubDocumentPath.length && !messagesBundle.containsKey(qualifiedReferenceName); path++) { - StringBuilder pathQualifierUntilX = new StringBuilder(originSubDocumentPath.length * 12); - for (int j = 0; j <= path; j++) { - pathQualifierUntilX.append(originSubDocumentPath[j]).append(SUB_DOCUMENT_DELIMITER); - } - String pathQualifierUntilXString = pathQualifierUntilX.toString(); - if (!qualifiedReferenceName.startsWith(pathQualifierUntilXString)) { - qualifiedReferenceName = pathQualifierUntilXString + relativeReferenceName; + // pre-build the full path prefix once; prefix lengths per depth let us "truncate" cheaply + StringBuilder fullPrefix = new StringBuilder(originSubDocumentPath.length * 12); + int[] prefixLengthAtDepth = new int[originSubDocumentPath.length]; + for (int depth = 0; depth < originSubDocumentPath.length; depth++) { + fullPrefix.append(originSubDocumentPath[depth]).append(SUB_DOCUMENT_DELIMITER); + prefixLengthAtDepth[depth] = fullPrefix.length(); + } + + String mostSpecificKey = fullPrefix + relativeReferenceName; + if (messagesBundle.containsKey(mostSpecificKey)) { + return mostSpecificKey; + } + + // walk from the second-deepest scope toward global + for (int depth = originSubDocumentPath.length - 2; depth >= 0; depth--) { + String candidate = fullPrefix.substring(0, prefixLengthAtDepth[depth]) + relativeReferenceName; + if (messagesBundle.containsKey(candidate)) { + return candidate; } } - return qualifiedReferenceName; + + // finally the global (unqualified) scope + if (messagesBundle.containsKey(relativeReferenceName)) { + return relativeReferenceName; + } + + // nothing found anywhere -> return the fully qualified (most specific) key anyway + return mostSpecificKey; } private static String[] extractSubDocumentPath(@NotNull String key) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/MessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/MessageImpl.java index f23a1d362..cd8845e00 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/MessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/legacy/MessageImpl.java @@ -2,9 +2,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.utils.bukkit.misc.BukkitStringUtils; -import net.codingarea.challenges.plugin.utils.misc.FontUtils; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.misc.StringUtils; import net.md_5.bungee.api.chat.BaseComponent; @@ -15,8 +13,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.LinkedList; -import java.util.List; import java.util.function.BiConsumer; import java.util.function.Consumer; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java index 07d053bb3..9272f13ca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java @@ -18,8 +18,8 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.*; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.*; import net.codingarea.challenges.plugin.challenges.implementation.setting.*; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder.PotionBuilder; import net.codingarea.challenges.plugin.utils.misc.ArmorUtils; +import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import org.bukkit.Material; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; @@ -257,24 +257,30 @@ public void enable() { registerDamageRule("projectile", Material.ARROW, DamageCause.PROJECTILE); registerDamageRule("fall", Material.FEATHER, DamageCause.FALL); registerDamageRule("explosion", Material.TNT, DamageCause.ENTITY_EXPLOSION, DamageCause.BLOCK_EXPLOSION); - registerDamageRule("drowning", PotionBuilder.createWaterBottle(), DamageCause.DROWNING); + registerDamageRule("drowning", StandardItemBuilder.PotionBuilder.createWaterBottle().build(), DamageCause.DROWNING); registerDamageRule("block", Material.SAND, DamageCause.FALLING_BLOCK, DamageCause.SUFFOCATION, DamageCause.CONTACT); registerDamageRule("magic", Material.BREWING_STAND, DamageCause.MAGIC, DamageCause.POISON, DamageCause.WITHER); registerDamageRule("freeze", Material.POWDER_SNOW_BUCKET, DamageCause.FREEZE); // 1.17+ // Material Rules - registerMaterialRule("§cArmor", "Armor", ArmorUtils.getArmor()); - registerMaterialRule("§6Golden Apple", "Golden Apple", Material.GOLDEN_APPLE, Material.ENCHANTED_GOLDEN_APPLE); - registerMaterialRule("§6Crafting Table", "Crafting Table", Material.CRAFTING_TABLE); - registerMaterialRule("§6Chest", "Chest", Material.CHEST); - registerMaterialRule("§cFurnace", "Furnace", Material.FURNACE, Material.FURNACE_MINECART); - registerMaterialRule("§5Enchanting Table", "Enchanting Table", Material.ENCHANTING_TABLE); - registerMaterialRule("§cAnvil", "Anvil", Material.ANVIL, Material.CHIPPED_ANVIL, Material.DAMAGED_ANVIL); - registerMaterialRule("§dBrewing Stand", "Brewing Stand", Material.BREWING_STAND); - registerMaterialRule("§cBow", "Bow", Material.BOW); - registerMaterialRule("§fSnowball", "Snowball", Material.SNOWBALL); - registerMaterialRule("§cFlint and Steel", "Flint and Steel", Material.FLINT_AND_STEEL); - registerMaterialRule("§cBucket", "Bucket", Material.BUCKET); + registerMaterialRule("armor", ArmorUtils.getArmor()); + registerMaterialRule("golden_apple", Material.GOLDEN_APPLE, Material.ENCHANTED_GOLDEN_APPLE); + registerMaterialRule("crafting_table", Material.CRAFTING_TABLE); + registerMaterialRule("chest", Material.CHEST, Material.CHEST_MINECART, Material.TRAPPED_CHEST); + registerMaterialRule("furnace", Material.FURNACE, Material.FURNACE_MINECART); + registerMaterialRule("enchant", Material.ENCHANTING_TABLE); + registerMaterialRule("anvil", Material.ANVIL, Material.CHIPPED_ANVIL, Material.DAMAGED_ANVIL); + registerMaterialRule("brewing_stand", Material.BREWING_STAND); + registerMaterialRule("bow", Material.BOW, Material.CROSSBOW); + registerMaterialRule("throwable", Material.SNOWBALL, Material.EGG); + registerMaterialRule("flint_and_steel", Material.FLINT_AND_STEEL, Material.FIRE_CHARGE); + registerMaterialRule("bucket", ArmorUtils.getBuckets()); + registerMaterialRule("sword", ArmorUtils.getSwords()); + registerMaterialRule("pickaxe", ArmorUtils.getPickaxes()); + registerMaterialRule("elytra", Material.ELYTRA); + registerMaterialRule("shield", Material.SHIELD); + registerMaterialRule("totem", Material.TOTEM_OF_UNDYING); + registerMaterialRule("ender_pearl", Material.ENDER_PEARL); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java index 8cc176185..d5fc2e89a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeManager.java @@ -155,8 +155,7 @@ public void resetGamestate() { try { challenge.loadGameState(Document.empty()); - if (challenge instanceof AbstractChallenge) { - AbstractChallenge abstractChallenge = (AbstractChallenge) challenge; + if (challenge instanceof AbstractChallenge abstractChallenge) { if (abstractChallenge.getBossbar().isShown()) { abstractChallenge.getBossbar().update(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java index 6a5cb33bf..3de546117 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ModuleChallengeLoader.java @@ -6,7 +6,6 @@ import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.RequireDepend; import net.codingarea.challenges.plugin.challenges.type.annotation.RequireVersion; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.core.BukkitModule; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; @@ -15,6 +14,7 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Constructor; @@ -102,27 +102,22 @@ public final void registerWithCommand(@NotNull Class class registerWithCommand(classOfChallenge, commandNames, new Class[0]); } - public final void registerDamageRule(@NotNull String name, @NotNull Material material, @NotNull DamageCause... causes) { - registerDamageRule(name, new LegacyItemBuilder(material), causes); + public final void registerDamageRule(@NotNull String name, @NotNull Material displayItemMaterial, @NotNull DamageCause... causes) { + registerDamageRule(name, new ItemStack(displayItemMaterial), causes); } - public final void registerDamageRule(@NotNull String name, @NotNull LegacyItemBuilder preset, @NotNull DamageCause... causes) { - register(DamageRuleSetting.class, new Class[]{LegacyItemBuilder.class, String.class, DamageCause[].class}, preset, name, causes); + public final void registerDamageRule(@NotNull String name, @NotNull ItemStack displayItemPreset, @NotNull DamageCause... causes) { + register(DamageRuleSetting.class, new Class[]{ItemStack.class, String.class, DamageCause[].class}, displayItemPreset, name, causes); } - public final void registerMaterialRule(@NotNull String title, @NotNull String replacement, @NotNull Material... materials) { - registerMaterialRule("item-block-material", new Object[]{title, replacement}, materials); + public final void registerMaterialRule(@NotNull String name, @NotNull Material... materials) { + registerMaterialRule(name, new ItemStack(materials[0]), materials); } - public final void registerMaterialRule(@NotNull String name, Object[] replacements, @NotNull Material... materials) { - registerMaterialRule(name, new LegacyItemBuilder(materials[0]), replacements, materials); + public final void registerMaterialRule(@NotNull String name, @NotNull ItemStack preset, @NotNull Material... materials) { + register(BlockMaterialSetting.class, new Class[]{String.class, ItemStack.class, Material[].class}, name, preset, materials); } - public final void registerMaterialRule(@NotNull String name, @NotNull LegacyItemBuilder preset, Object[] replacements, @NotNull Material... materials) { - register(BlockMaterialSetting.class, new Class[]{String.class, LegacyItemBuilder.class, Object[].class, Material[].class}, name, preset, replacements, materials); - } - - /** * Unregisters an existing challenge and deletes its settings. * It does not unregister commands! diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java index 32bbf4948..15aa74c4e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/inventory/PlayerInventoryManager.java @@ -3,8 +3,8 @@ import lombok.Getter; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IMenuGenerator.java index 71d87492e..c60537334 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/IMenuGenerator.java @@ -17,7 +17,7 @@ default void openMenu(@NotNull Player player) { /** * @implSpec regenerates all pages (only for locales already generated!) - * use {@link #updateOrGeneratePages(Locale)} to create the menu for a new locale + * use {@link #updateOrGeneratePages(Locale)} to create the menu for a new locale */ void updatePages(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java index 02f203623..e696f83e5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/MultiPageMenuGenerator.java @@ -1,7 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator; import com.google.common.base.Preconditions; -import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java index 470885ede..ac7844aa8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java @@ -157,15 +157,15 @@ private static CompiledFormat compile(@NotNull String template) { @Nullable private static Token getTokenByTag(@NotNull String tag) { return switch (tag) { - case "{d}" -> TOKEN_D; - case "{dd}" -> TOKEN_DD; - case "{h}" -> TOKEN_H; - case "{hh}" -> TOKEN_HH; - case "{m}" -> TOKEN_M; - case "{mm}" -> TOKEN_MM; - case "{s}" -> TOKEN_S; - case "{ss}" -> TOKEN_SS; - default -> null; + case "{d}" -> TOKEN_D; + case "{dd}" -> TOKEN_DD; + case "{h}" -> TOKEN_H; + case "{hh}" -> TOKEN_HH; + case "{m}" -> TOKEN_M; + case "{mm}" -> TOKEN_MM; + case "{s}" -> TOKEN_S; + case "{ss}" -> TOKEN_SS; + default -> null; }; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java index 944c06a62..a4b9dcae1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/TitleManager.java @@ -4,8 +4,8 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IChallenge; import net.codingarea.challenges.plugin.challenges.type.IGoal; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.commons.common.config.Document; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java index 749f203b0..f1dce6a1b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/WorldManager.java @@ -5,11 +5,9 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.bukkit.container.PlayerData; import net.codingarea.challenges.plugin.utils.bukkit.nms.ReflectionUtil; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.logging.Logger; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.collection.pair.Tuple; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java index 7cc2f76cb..d3e94a94d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/scoreboard/ChallengeBossBar.java @@ -8,7 +8,6 @@ import net.codingarea.commons.bukkit.utils.logging.Logger; import net.kyori.adventure.bossbar.BossBar; import net.kyori.adventure.text.Component; -import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java index 10737f73f..6a8f3fccf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java @@ -4,9 +4,8 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.challenges.implementation.setting.PregameMovementSetting; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import org.bukkit.GameMode; import org.bukkit.Location; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java index ca29de20d..e05df3646 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java index 8133b2c89..5a3b913d8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java @@ -2,8 +2,8 @@ import com.google.common.collect.Lists; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java index 6de840741..79cfd82d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FeedCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java index 659517856..583db9e18 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/FlyCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java index 99e2f49b6..4370eac09 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java index 26c92c8ba..4f6056d05 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java index c397fc8d5..b99b5e2a5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GodModeCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java index 4e0f4e229..3132993cc 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/HealCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.CommandHelper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java index 7d2610cec..31e868946 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java @@ -1,14 +1,13 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.spigot.events.PlayerInventoryClickEvent; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.commons.bukkit.utils.menu.positions.SlottedMenuPosition; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java index 14ea42bf4..6ed4abe5b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/LeaderboardCommand.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.cloud.CloudSupportManager; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.stats.PlayerStats; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java index df40dcf42..ec4cce162 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResetCommand.java @@ -3,9 +3,8 @@ import com.google.common.collect.Lists; import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java index 3498fb983..c1a039189 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ResultCommand.java @@ -4,8 +4,8 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IGoal; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java index 38c7a396d..59e4cef59 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.RegisteredDrops; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java index 2202dc7b9..428d961ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SkipTimerCommand.java @@ -6,12 +6,9 @@ import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.content.i18n.impl.format.ComponentArguments; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; -import org.bukkit.Material; import org.bukkit.command.CommandSender; -import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java index 5628e3aa2..4228b40e2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java @@ -1,9 +1,9 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.cloud.CloudSupportManager; import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; import net.codingarea.challenges.plugin.management.stats.LeaderboardInfo; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java index 431907fd8..8e6f82bdf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java index c6fb1cc9c..eef1644f9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java @@ -2,8 +2,8 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.SenderCommand; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java index acd7a35c7..d401da813 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/VillageCommand.java @@ -1,8 +1,8 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import org.bukkit.Bukkit; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java index 04295220e..77608b975 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.Completer; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java index 512d2d746..01f79761b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java @@ -3,8 +3,8 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.implementation.setting.PositionSetting; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.misc.Utils; import org.bukkit.Location; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java index 4cd37dfad..3c89cd5e0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/HelpListener.java @@ -2,8 +2,6 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.content.loader.LanguageLoader; -import net.codingarea.challenges.plugin.utils.misc.FontUtils; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index 13c0e5782..e740ea614 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -2,9 +2,9 @@ import net.codingarea.challenges.plugin.ChallengeAPI; import net.codingarea.challenges.plugin.Challenges; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.content.loader.UpdateLoader; import net.codingarea.challenges.plugin.utils.misc.DatabaseHelper; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java index 6a185f8ee..bfb5a8714 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/command/PlayerCommand.java @@ -1,7 +1,7 @@ package net.codingarea.challenges.plugin.utils.bukkit.command; -import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java index 4d2b9d449..30379b1c1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/ItemBuilder.java @@ -6,8 +6,6 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.content.i18n.impl.format.ComponentFormatter; -import net.codingarea.challenges.plugin.content.i18n.impl.format.MessageFormatter; import net.codingarea.commons.bukkit.utils.item.BannerPattern; import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import net.kyori.adventure.text.Component; @@ -23,7 +21,10 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.UUID; public class ItemBuilder extends StandardItemBuilder { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java index 44db4456d..bc9cebbc6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java @@ -20,4 +20,30 @@ public static Material[] getArmor() { }; } + // TODO wrong class... + public static Material[] getBuckets() { + return new Material[]{ + Material.BUCKET, Material.WATER_BUCKET, Material.LAVA_BUCKET, Material.MILK_BUCKET, + Material.FISHING_ROD, Material.SALMON_BUCKET, Material.COD_BUCKET, Material.PUFFERFISH_BUCKET, + Material.SALMON_BUCKET, Material.TROPICAL_FISH_BUCKET, Utils.getMaterial("AXOLOTL_BUCKET"), + Utils.getMaterial("POWDER_SNOW_BUCKET") + }; + } + + // TODO wrong class... + public static Material[] getSwords() { + return new Material[]{ + Material.WOODEN_SWORD, Material.STONE_SWORD, Material.IRON_SWORD, Material.DIAMOND_SWORD, + Material.GOLDEN_SWORD, Material.NETHERITE_SWORD + }; + } + + // TODO wrong class... + public static Material[] getPickaxes() { + return new Material[]{ + Material.WOODEN_PICKAXE, Material.STONE_PICKAXE, Material.IRON_PICKAXE, Material.DIAMOND_PICKAXE, + Material.GOLDEN_PICKAXE, Material.NETHERITE_PICKAXE + }; + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java index 868401c27..5c92b629c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/InventoryUtils.java @@ -4,8 +4,6 @@ import net.codingarea.challenges.plugin.utils.item.DefaultItem; import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import net.codingarea.commons.bukkit.utils.animation.AnimationFrame; -import net.codingarea.commons.bukkit.utils.animation.SoundSample; -import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.commons.common.collection.IRandom; import org.bukkit.Location; import org.bukkit.Material; From e0d2c830b700d9d9fb9b3266681c076fbfa47cd4 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Fri, 10 Jul 2026 19:24:47 +0200 Subject: [PATCH 108/119] refactor: port backpack, brought to you by claude opus --- language/locales/de.json | 16 +++-- language/locales/en.json | 14 ++-- language/locales/global.json | 4 +- .../setting/BackpackSetting.java | 70 ++++++++++++++----- 4 files changed, 75 insertions(+), 29 deletions(-) diff --git a/language/locales/de.json b/language/locales/de.json index ef873b231..73be6b526 100644 --- a/language/locales/de.json +++ b/language/locales/de.json @@ -440,11 +440,19 @@ ] }, "backpack": { - "name": "*Backpack*", + "name": "*Rucksack*", "desc": [ "Erlaubt es dir, *deinen Backpack* oder den", "*Team Backpack* mit */backpack* zu öffnen" - ] + ], + "settings": { + "player": "Pro Spieler", + "shared": "Gemeinsam" + }, + "disabled": "Rucksäcke sind derzeit deaktiviert", + "opened": "Du hast den {0} geöffnet", + "player-name": "Spieler Rucksack", + "inventory-player": "{@menu.title-format('{@player-name}')}" }, "enderchest-command": { "name": "*Enderchest Command*", @@ -2161,8 +2169,6 @@ "death-collected": "Todesgrund {0} wurde registriert", "item-collected": "Item {0} wurde registriert", "items-to-collect": "Items zu sammeln » {0}", - "backpacks-disabled": "Rucksäcke sind derzeit deaktiviert", - "backpack-opened": "Du hast den {0} geöffnet", "top-to-overworld": "Du wurdest zur Overworld teleportiert", "top-to-surface": "Du wurdest zur Oberfläche teleportiert", "all-items-skipped": "Item {0} geskippt", @@ -2315,8 +2321,6 @@ ], "item-language-setting-german": "Deutsch", "item-language-setting-english": "English", - "item-backpack-setting-team": "Team", - "item-backpack-setting-player": "Player", "menu-cut-clean-setting-settings": "CutClean", "item-regeneration-setting-not_natural": "Nicht natürlich", "menu-all-blocks-disappear-challenge-settings": "Alle Blöcke verschwinden", diff --git a/language/locales/en.json b/language/locales/en.json index e84a6e6c2..d240837dd 100644 --- a/language/locales/en.json +++ b/language/locales/en.json @@ -102,7 +102,15 @@ "desc": [ "Allows you to open *your backpack* or", "the *team backpack* with */backpack*" - ] + ], + "settings": { + "player": "Player", + "shared": "Team" + }, + "disabled": "Backpacks are currently deactivated", + "opened": "You opened the {0}", + "player-name": "Player Backpack", + "inventory-player": "{@menu.title-format('{@player-name}')}" }, "enderchest-command": { "name": "*Enderchest Command*", @@ -1372,8 +1380,6 @@ "death-collected": "Death reason {0} registered", "item-collected": "Item {0} registered", "items-to-collect": "Items to collect » {0}", - "backpacks-disabled": "Backpacks are currently deactivated", - "backpack-opened": "You opened the {0}", "top-to-overworld": "You have been teleported to the overworld", "top-to-surface": "You have been teleported to the top", "random-challenge-enabled": "The challenge {0} has been activated", @@ -1653,8 +1659,6 @@ "item-language-setting-german": "Deutsch", "item-language-setting-english": "English", "item-death-message-setting-vanilla": "Vanilla", - "item-backpack-setting-team": "Team", - "item-backpack-setting-player": "Player", "menu-cut-clean-setting-settings": "CutClean", "item-cut-clean-gold-setting": [ "Gold", diff --git a/language/locales/global.json b/language/locales/global.json index 75061e1bc..b7ecb32f7 100644 --- a/language/locales/global.json +++ b/language/locales/global.json @@ -255,7 +255,9 @@ "*colorize*": "{0}" }, "backpack": { - "*colorize*": "{0}" + "*colorize*": "{0}", + "shared-name": "Team Backpack", + "inventory-shared": "{@menu.title-format('{@shared-name}')}" }, "enderchest-command": { "*colorize*": "{0}" diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java index 0b4585835..b77b74b19 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/BackpackSetting.java @@ -4,17 +4,17 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeConfigHelper; -import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.management.menu.InventoryTitleManager; +import net.codingarea.challenges.plugin.content.i18n.TranslationManager; +import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.bukkit.container.BukkitSerialization; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.common.config.Document; +import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -24,6 +24,7 @@ import java.io.IOException; import java.util.HashMap; +import java.util.Locale; import java.util.Map; import java.util.UUID; @@ -38,23 +39,21 @@ public class BackpackSetting extends SettingModifier implements PlayerCommand { public BackpackSetting() { super(MenuType.SETTINGS, null, 1, 2, SHARED, new ItemStack(Material.CHEST), "backpack"); size = Math.clamp(ChallengeConfigHelper.getSettingsDocument().getInt("backpack-size") * 9L, 9, 6 * 9); - sharedBackpack = createInventory("§5Team Backpack"); + // The shared backpack is a single inventory used by every player, so its title cannot depend + // on the viewer. It is resolved once with the server language via a locale-independent key. + sharedBackpack = createInventory(getSharedBackpackTitle()); } @NotNull @Override public ItemStack getSettingsItemPreset() { - if (getValue() == SHARED) - return new ItemStack(Material.ENDER_CHEST); - return new ItemStack(Material.PLAYER_HEAD); + return new ItemStack(getValue() == SHARED ? Material.ENDER_CHEST : Material.PLAYER_HEAD); } @NotNull @Override public LocalizableMessage getSettingsName() { - if (getValue() == SHARED) - return getChallengeMessageKey("settings.shared"); - return getChallengeMessageKey("settings.player"); + return getChallengeMessageKey(getValue() == SHARED ? "settings.shared" : "settings.player"); } @Override @@ -66,17 +65,17 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) { } if (!isEnabled()) { - MessageKey.of("backpacks-disabled").send(player, Prefix.BACKPACK); + getChallengeMessageKey("disabled").send(player, Prefix.BACKPACK); SoundSample.BASS_OFF.play(player); return; } if (getValue() == SHARED || getValue() == PLAYER) { - MessageKey.of("backpack-opened").send(player, Prefix.BACKPACK, getValue() == SHARED ? "§5Team Backpack" : "§6Player Backpack"); + getChallengeMessageKey("opened").send(player, Prefix.BACKPACK, getBackpackName()); player.openInventory(getCurrentBackpack(player)); SoundSample.OPEN.play(player); } else { - MessageKey.of("backpacks-disabled").send(player, Prefix.BACKPACK); + getChallengeMessageKey("disabled").send(player, Prefix.BACKPACK); SoundSample.BASS_OFF.play(player); } } @@ -89,7 +88,8 @@ public void loadGameState(@NotNull Document document) { Document players = document.getDocument("players"); for (String key : players.keys()) { - loadChecked(players, key, backpacks.computeIfAbsent(UUID.fromString(key), k -> createInventory("§6Backpack"))); + loadChecked(players, key, backpacks.computeIfAbsent(UUID.fromString(key), playerId -> + createInventory(getPlayerBackpackTitle(getPlayerLanguageOrServer(playerId))))); } } @@ -139,13 +139,49 @@ protected void write(@NotNull Document document, @NotNull String key, @NotNull I } @NotNull - protected Inventory createInventory(@NotNull String title) { - return Bukkit.createInventory(null, size, InventoryTitleManager.getTitle(title)); + protected Inventory createInventory(@NotNull Component title) { + return Bukkit.createInventory(null, size, title); } @NotNull protected Inventory getCurrentBackpack(@NotNull Player player) { - return (getValue() == SHARED) ? sharedBackpack : backpacks.computeIfAbsent(player.getUniqueId(), key -> createInventory("§6Backpack")); + return (getValue() == SHARED) ? sharedBackpack : backpacks.computeIfAbsent(player.getUniqueId(), key -> createInventory(getPlayerBackpackTitle(player))); + } + + @NotNull + protected LocalizableMessage getBackpackName() { + return getChallengeMessageKey(getValue() == SHARED ? "shared-name" : "player-name"); + } + + // TODO (hopefully) temp solution for translation port; brought to you by claude :D + @NotNull + protected Component getSharedBackpackTitle() { + // lives in global.json + return getChallengeMessageKey("inventory-shared").asComponent(getServerLanguage()); + } + + @NotNull + protected Component getPlayerBackpackTitle(@NotNull Player player) { + return getChallengeMessageKey("inventory-player").asComponent(player); + } + + @NotNull + protected Component getPlayerBackpackTitle(@NotNull Locale locale) { + return getChallengeMessageKey("inventory-player").asComponent(locale); + } + + @NotNull + private Locale getServerLanguage() { + return Challenges.getInstance().getLoaderRegistry().getFirstLoaderByClass(LanguageLoader.class) + .map(LanguageLoader::getConfigLanguage) + .orElse(TranslationManager.FALLBACK_LOCALE); + } + + @NotNull + private Locale getPlayerLanguageOrServer(@NotNull UUID playerId) { + Player player = Bukkit.getPlayer(playerId); + if (player == null) return getServerLanguage(); + return Challenges.getInstance().getTranslationManager().getLanguageProvider().getPlayerLanguage(player); } } From edb0becf13d4dcbba6b3ba845afc426b9b4e8f87 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Fri, 10 Jul 2026 20:45:37 +0200 Subject: [PATCH 109/119] refactor: migrate localization usage (part 6) --- language/locales/de.json | 330 ++++++++++++++---- language/locales/global.json | 157 ++++++++- .../challenges/custom/CustomChallenge.java | 56 +-- .../action/impl/CancelEventAction.java | 2 + .../inventory/UncraftItemsChallenge.java | 2 +- .../miscellaneous/OneDurabilityChallenge.java | 7 +- .../challenge/world/AnvilRainChallenge.java | 2 - .../damage/DamageRuleSetting.java | 2 +- .../goal/CollectAllItemsGoal.java | 2 +- .../material/BlockMaterialSetting.java | 2 +- .../setting/DeathPositionSetting.java | 2 +- .../setting/ImmediateRespawnSetting.java | 1 - .../setting/PositionSetting.java | 13 +- .../setting/RegenerationSetting.java | 18 +- .../type/abstraction/AbstractChallenge.java | 2 + .../plugin/content/i18n/ArgumentFormat.java | 3 +- .../plugin/content/i18n/MessageKey.java | 6 + .../i18n/impl/LocalizableMessageImpl.java | 2 +- .../content/i18n/impl/MessageKeyImpl.java | 41 ++- .../i18n/impl/dynamic/DynamicMessageImpl.java | 2 +- .../i18n/impl/dynamic/JoinedMessageImpl.java | 11 +- .../i18n/impl/format/ComponentArguments.java | 31 +- .../i18n/impl/format/MessageFormatter.java | 13 +- .../challenges/ChallengeLoader.java | 12 +- .../impl/custom/CustomHomeMenuGenerator.java | 9 +- .../CustomChooseMaterialMenuGenerator.java | 5 +- .../scheduler/timer/ChallengeTimer.java | 100 ++++-- .../scheduler/timer/TimerFormat.java | 2 + .../plugin/spigot/command/SearchCommand.java | 4 +- .../plugin/utils/misc/ColorConversions.java | 1 + ...rmorUtils.java => MaterialCategories.java} | 20 +- plugin/src/main/resources/config.yml | 4 +- 32 files changed, 661 insertions(+), 203 deletions(-) rename plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/{ArmorUtils.java => MaterialCategories.java} (73%) diff --git a/language/locales/de.json b/language/locales/de.json index 73be6b526..5427c0044 100644 --- a/language/locales/de.json +++ b/language/locales/de.json @@ -28,9 +28,15 @@ }, "timer": { "bar": { - "up": "{@actionbar.format('Zeit: {0}')}", - "down": "{@actionbar.format('Zeit: {0}')}", - "paused": "{@actionbar.format('Timer pausiert')}" + "up": { + "display": "{@actionbar.format('Zeit: *{0}*')}" + }, + "down": { + "display": "{@actionbar.format('Zeit: *{0}*')}" + }, + "paused": { + "display": "{@actionbar.format('Timer *pausiert*')}" + } }, "messages": { "started": "Der Timer wurde gestartet", @@ -327,7 +333,8 @@ "desc": [ "Stellt ein, *ob* und", "*wie* man *regeneriert*" - ] + ], + "not_natural": "Nicht natürlich" }, "one-life": { "name": "*Ein Teamleben*", @@ -1658,7 +1665,7 @@ "desc": [ "Finde *alle Items*, die es *in Minecraft gibt*" ], - "bossbar-current": "{@bossbar.format-arg('{3}{0}', '{1} / {2}')}", + "bossbar-current": "{@bossbar.format-arg('{0}', '{1} / {2}')}", "bossbar-finished": "{@bossbar.format('Alle Items gefunden')}" }, "damage-teleport": { @@ -1687,7 +1694,8 @@ "name": "*Genereller Schaden*", "desc": [ "Stellt ein, ob du Schaden bekommen kannst", - "Du kannst *weiterhin* Schaden durch *Challenges* bekommen" + "Du kannst *weiterhin* Schaden durch", + "*Challenges* sterben" ] }, "fire": { @@ -1909,29 +1917,26 @@ "name": "*Intervall*" }, "jump": { - "name": "Spieler Springt" + "name": "*Spieler springt*" }, "sneak": { - "name": "Spieler Schleicht" + "name": "*Spieler schleicht*" }, "move_block": { - "name": "Spieler Läuft Einen Block" + "name": "*Spieler läuft einen Block*" + }, + "death": { + "name": "*Entity stirbt*" + }, + "damage": { + "name": "*Entity erleidet Schaden*" }, - "death": [ - "Entity Stirbt" - ], - "item-custom-trigger-damage": [ - "Entity Erleidet Schaden" - ], "item-custom-trigger-damage-any": [ "Jeglicher Grund" ], "item-custom-trigger-damage_by_player": [ "Entity Bekommt Schaden Von Spieler" ], - "item-custom-trigger-intervall": [ - "Intervall" - ], "item-custom-trigger-intervall-second": [ "Jede Sekunde" ], @@ -1941,67 +1946,245 @@ "item-custom-trigger-intervall-minutes": [ "Alle {0} Minuten" ], - "item-custom-trigger-block_place": [ - "Block Platziert" - ], - "item-custom-trigger-block_break": [ - "Block Zerstört" - ], - "item-custom-trigger-consume_item": [ - "Item Konsumieren" - ], - "item-custom-trigger-pickup_item": [ - "Item Aufheben" - ], - "item-custom-trigger-drop_item": [ - "Spieler Droppt Item" - ], - "item-custom-trigger-advancement": [ - "Spieler Erhält Errungenschaft" - ], - "item-custom-trigger-hunger": [ - "Spieler Verliert Hunger" - ], - "item-custom-trigger-move_down": [ - "Block Nach Unten Bewegen" - ], - "item-custom-trigger-move_up": [ - "Block Nach Oben Bewegen" - ], - "item-custom-trigger-move_camera": [ - "Kamera Bewegen" - ], - "item-custom-trigger-stands_on_specific_block": [ - "Spieler Ist Auf Bestimmten Block" - ], - "item-custom-trigger-stands_not_on_specific_block": [ - "Spieler Ist Nicht Auf Bestimmten Block" - ], - "item-custom-trigger-gain_xp": [ - "Spieler Bekommt XP" - ], - "item-custom-trigger-level_up": [ - "Spieler Levelt Auf" - ], - "item-custom-trigger-item_craft": [ - "Spieler Craftet Item" - ], - "item-custom-trigger-in_liquid": [ - "Spieler In Flüssigkeit" - ], - "item-custom-trigger-get_item": [ - "Item bekommen", - "Aktion wird für *jedes* anklicken oder aufheben ausgeführt" - ] + "block_place": { + "name": "*Block platziert*" + }, + "block_break": { + "name": "*Block zerstört*" + }, + "consume_item": { + "name": "*Item konsumieren*" + }, + "pickup_item": { + "name": "*Item aufheben*" + }, + "drop_item": { + "name": "*Spieler droppt Item*" + }, + "advancement": { + "name": "*Spieler erhält Errungenschaft*" + }, + "hunger": { + "name": "*Spieler verliert Hunger*" + }, + "move_down": { + "name": "*Block nach unten bewegen*" + }, + "move_up": { + "name": "*Block nach oben bewegen*" + }, + "move_camera": { + "name": "*Kamera bewegen*" + }, + "stands_on_specific_block": { + "name": "*Spieler ist auf bestimmten Block*" + }, + "stands_not_on_specific_block": { + "name": "*Spieler ist nicht auf bestimmten Block*" + }, + "gain_xp": { + "name": "*Spieler bekommt XP*" + }, + "level_up": { + "name": "*Spieler levelt auf*" + }, + "item_craft": { + "name": "*Spieler craftet Item*" + }, + "in_liquid": { + "name": "*Spieler in Flüssigkeit*" + }, + "get_item": { + "name": "*Item bekommen*", + "desc": "Aktion wird für *jedes* anklicken oder aufheben ausgeführt" + } }, "action": { "cancel": { - "name": "*Auslöser Abbrechen*", + "name": "*Auslöser abbrechen*", "desc": [ "Verhindert, dass der Auslöser ausgeführt wird.", "Nicht abrechenbare Auslöser: *Springen*, *Sneaken*, *Töten*", "*Advancement*, *Auf Leveln*, *In Flüssigkeit*" ] + }, + "command": { + "name": "*Befehl ausführen*", + "desc": [ + "Lasse Spieler einen Command ausführen lassen", + "Die Commands werden für Spieler mit */execute as* von", + "der Konsole ausgeführt.", + "Erlaubte Commands werden in der Config eingestellt.", + "Der Spieler braucht *keine Rechte* auf den Command haben.", + "Spieler können *keine Plugin Commands* ausführen." + ] + }, + "kill": { + "name": "*Töten*", + "desc": [ + "Töte *Kreaturen* oder *Spieler*" + ] + }, + "damage": { + "name": "*Schaden*", + "desc": [ + "Füge *Kreaturen* oder *Spielern* Schaden zu" + ] + }, + "heal": { + "name": "*Heilen*", + "desc": [ + "Heile *Kreaturen* oder *Spieler*" + ] + }, + "hunger": { + "name": "*Hunger*", + "desc": [ + "Füge *Spielern* Hunger hinzu" + ] + }, + "max_health": { + "name": "*Maximale Leben*", + "desc": [ + "Verändere die Maximalen Leben von Spielern", + "Wird mit einem */gamestate reset* zurückgesetzt" + ] + }, + "spawn_entity": { + "name": "*Kreatur spawnen*", + "desc": [ + "Spawne eine Kreatur einer *bestimmten Art*" + ] + }, + "random_mob": { + "name": "*Zufällige Kreatur*", + "desc": [ + "Spawne eine *zufälliges Kreatur*" + ] + }, + "random_item": { + "name": "*Zufälliges Item*", + "desc": [ + "Gebe Spielern ein *zufällige Items*" + ] + }, + "uncraft_inventory": { + "name": "*Inventar zurück craften*", + "desc": [ + "Lasse das *Inventar von Spielern* zurück craften" + ] + }, + "boost_in_air": { + "name": "*In Luft schleudern*", + "desc": [ + "Schleudere *Kreaturen* oder *Spieler* in die Luft" + ] + }, + "potion_effect": { + "name": "*Trank Effekt*", + "desc": [ + "Gebe *Kreaturen* oder *Spielern* einen Trank Effekt" + ] + }, + "permanent_effect": { + "name": "*Permanenter Effekt*", + "desc": [ + "Füge *Spielern* einen permanenten Effekt hinzu", + "Die Aktion nutzt die Einstellungen", + "von der *Permanenten Effekt Challenge*" + ] + }, + "random_effect": { + "name": "*Zufälliger Trank Effekt*", + "desc": [ + "Gebe *Kreaturen* oder *Spielern* einen *zufälligen Trank* Effekt" + ] + }, + "clear_inventory": { + "name": "*Inventar leeren*", + "desc": [ + "Leere das *Inventar von Spielern* komplett" + ] + }, + "drop_random_item": { + "name": "*Zufälliges Item droppen*", + "desc": [ + "Lasse *Spieler* ein *zufälliges Item* aus", + "ihrem Inventar auf *den Boden* fallen" + ] + }, + "remove_random_item": { + "name": "*Zufälliges Item entfernen*", + "desc": [ + "Entferne ein *zufälliges Item* aus dem Inventar von Spielern" + ] + }, + "swap_random_item": { + "name": "*Items tauschen*", + "desc": [ + "Tausche zwei *zufälliges Items* im dem Inventar von Spielern" + ] + }, + "freeze": { + "name": "*Einfrieren*", + "desc": [ + "Friere Mobs *zeitweise* ein", + "Die Aktion nutzt die Einstellungen", + "von der *Freeze On Damage Challenge*" + ] + }, + "invert_health": { + "name": "*Herzen invertieren*", + "desc": [ + "Invertiere die Herzen eines *Spielers*", + "Wenn du *8 Herzen* hast,", + "hast du danach *2 Herzen* und umgekehrt" + ] + }, + "water_mlg": { + "name": "*Water MLG*", + "desc": [ + "Alle Spieler müssen einen Water MLG machen" + ] + }, + "win": { + "name": "*Gewinnen*", + "desc": [ + "Die Challenge wird von *bestimmten Spielern* gewonnen" + ] + }, + "random_hotbar": { + "name": "*Zufällige Hotbar*", + "desc": [ + "Das Inventar wird *geleert* und der *Spieler*", + "bekommt *zufällige Items* in die HotBar" + ] + }, + "modify_border": { + "name": "*World Border verändern*", + "desc": [ + "Mache die World Border *größer* oder *kleiner*" + ] + }, + "swap_mobs": { + "name": "*Kreaturen tauschen*", + "desc": [ + "Tausche eine Kreatur mit einer *zufälligen*", + "anderen Kreatur aus *der gleichen Welt*" + ] + }, + "place_structure": { + "name": "*Struktur platzieren*", + "desc": [ + "Platziere eine *Struktur an der Position* von Spielern" + ] + }, + "jnr": { + "name": "*Jump and Run*", + "desc": [ + "Ein *zufälliger* Spieler muss ein *Jump And Run*", + "absolvieren oder er *stirbt*" + ] } } }, @@ -2322,7 +2505,6 @@ "item-language-setting-german": "Deutsch", "item-language-setting-english": "English", "menu-cut-clean-setting-settings": "CutClean", - "item-regeneration-setting-not_natural": "Nicht natürlich", "menu-all-blocks-disappear-challenge-settings": "Alle Blöcke verschwinden", "item-all-blocks-disappear-break-challenge": [ "Beim Abbauen", @@ -2652,7 +2834,7 @@ "lava": "Lava", "drowning": "Ertrinken", "block_explosion": "Blockexplosion", - "entity_explosion": "Kreaturenexplosion", + "entity_explosion": "Kreaturexplosion", "void": "Leere", "lightning": "Blitzeinschlag", "suicide": "Selbstmord", @@ -2667,7 +2849,7 @@ "hot_floor": "Heißen Boden", "campfire": "Lagerfeuer", "cramming": "Überfüllung", - "dried_out": "Austrocknen", + "dryout": "Austrocknen", "freeze": "Erfrieren", "sonic_boom": "Schallknall", "custom": "unbekannte Ursache" diff --git a/language/locales/global.json b/language/locales/global.json index b7ecb32f7..bc800584a 100644 --- a/language/locales/global.json +++ b/language/locales/global.json @@ -44,7 +44,7 @@ "format-with-command": "{@format('{0} {@symbol.vertical} {1}')}" }, "actionbar": { - "format": "{@symbol.dot} {0} {@symbol.dot}" + "format": "{@symbol.dot} {0} {@symbol.dot}" }, "bossbar": { "format": "{@symbol.arrow} {0}", @@ -61,6 +61,10 @@ }, "timer": { "bar": { + "*colorize*": "{0}", + "paused": { + "*colorize*": "{0}" + }, "format": { "seconds": "{mm}:{ss}", "minutes": "{mm}:{ss}", @@ -475,10 +479,10 @@ "*colorize*": "{0}" }, "bedrock-walls": { - "*colorize*": "{0}" + "*colorize*": "{0}" }, "bedrock-path": { - "*colorize*": "{0}" + "*colorize*": "{0}" }, "floor-is-lava": { "*colorize*": "{0}" @@ -835,11 +839,158 @@ "trigger": { "interval": { "*colorize*": "{0}" + }, + "jump": { + "*colorize*": "{0}" + }, + "sneak": { + "*colorize*": "{0}" + }, + "move_block": { + "*colorize*": "{0}" + }, + "death": { + "*colorize*": "{0}" + }, + "damage": { + "*colorize*": "{0}" + }, + "block_place": { + "*colorize*": "{0}" + }, + "block_break": { + "*colorize*": "{0}" + }, + "consume_item": { + "*colorize*": "{0}" + }, + "pickup_item": { + "*colorize*": "{0}" + }, + "drop_item": { + "*colorize*": "{0}" + }, + "advancement": { + "*colorize*": "{0}" + }, + "hunger": { + "*colorize*": "{0}" + }, + "move_down": { + "*colorize*": "{0}" + }, + "move_up": { + "*colorize*": "{0}" + }, + "move_camera": { + "*colorize*": "{0}" + }, + "stands_on_specific_block": { + "*colorize*": "{0}" + }, + "stands_not_on_specific_block": { + "*colorize*": "{0}" + }, + "gain_xp": { + "*colorize*": "{0}" + }, + "level_up": { + "*colorize*": "{0}" + }, + "item_craft": { + "*colorize*": "{0}" + }, + "in_liquid": { + "*colorize*": "{0}" + }, + "get_item": { + "*colorize*": "{0}" } }, "action": { "cancel": { "*colorize*": "{0}" + }, + "command": { + "*colorize*": "{0}" + }, + "kill": { + "*colorize*": "{0}" + }, + "damage": { + "*colorize*": "{0}" + }, + "heal": { + "*colorize*": "{0}" + }, + "hunger": { + "*colorize*": "{0}" + }, + "max_health": { + "*colorize*": "{0}" + }, + "spawn_entity": { + "*colorize*": "{0}" + }, + "random_mob": { + "*colorize*": "{0}" + }, + "random_item": { + "*colorize*": "{0}" + }, + "uncraft_inventory": { + "*colorize*": "{0}" + }, + "boost_in_air": { + "*colorize*": "{0}" + }, + "potion_effect": { + "*colorize*": "{0}" + }, + "permanent_effect": { + "*colorize*": "{0}" + }, + "random_effect": { + "*colorize*": "{0}" + }, + "clear_inventory": { + "*colorize*": "{0}" + }, + "drop_random_item": { + "*colorize*": "{0}" + }, + "remove_random_item": { + "*colorize*": "{0}" + }, + "swap_random_item": { + "*colorize*": "{0}" + }, + "freeze": { + "*colorize*": "{0}" + }, + "invert_health": { + "*colorize*": "{0}" + }, + "water_mlg": { + "*colorize*": "{0}" + }, + "win": { + "*colorize*": "{0}" + }, + "random_hotbar": { + "*colorize*": "{0}" + }, + "modify_border": { + "*colorize*": "{0}" + }, + "swap_mobs": { + "*colorize*": "{0}" + }, + "place_structure": { + "*colorize*": "{0}" + }, + "jnr": { + "*colorize*": "{0}" } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index a1a76170b..9dde5d698 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -5,10 +5,11 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; +import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.common.config.Document; @@ -17,11 +18,8 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.List; -import java.util.Locale; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.UUID; @Getter @ToString @@ -37,7 +35,7 @@ public class CustomChallenge extends Setting { public CustomChallenge(MenuType menuType, UUID uuid, Material displayItem, String displayName, ChallengeTrigger trigger, Map subTriggers, ChallengeAction action, Map subActions) { - super(menuType, null, new ItemStack(displayItem), "custom-challenge"); + super(menuType, null, new ItemStack(Material.BARRIER), "custom-challenge"); this.uuid = uuid; this.material = displayItem; this.name = displayName; @@ -47,44 +45,48 @@ public CustomChallenge(MenuType menuType, UUID uuid, Material displayItem, Strin this.subActions = subActions; } + @Override + public ItemStack getDisplayItemPreset() { + if (displayItemPreset != null) return displayItemPreset; + Material material = this.material; + if (material == null) material = Material.BARRIER; + return this.displayItemPreset = new ItemStack(material); + } + @NotNull @Override - public ItemBuilder getDisplayItem(@NotNull Locale locale) { // TODO - ItemBuilder item = new ItemBuilder(locale, displayItemPreset, MessageKey.of("custom.display-format"), name); + public ItemBuilder getDisplayItem(@NotNull Locale locale) { + ItemBuilder item = new ItemBuilder(locale, getDisplayItemPreset(), MessageKey.of("custom.display-format"), name); // ADDING CONDITION INFO if (getTrigger() != null) { -// List triggerDisplay = SubSettingsBuilder -// .getSubSettingsDisplay(getTrigger().getSubSettingsBuilder(), getSubTriggers()); -// -// String triggerName = Message.forName(getTrigger().getMessageKey()).asItemDescription().getName(); -// builder.appendLore(Message.forName("custom-info-trigger").asString() + " " + triggerName); -// builder.appendLore(triggerDisplay); - item.appendBlankLoreLine() - .appendLore(MessageKey.of("menu.custom.trigger-format"), getTrigger().getSettingName()); + .appendLore(MessageKey.of("menu.custom.trigger-format"), trigger.getSettingName()); + + Collection display = trigger.getSubSettingsBuilder().getCurrentDisplayFor(subTriggers); + for (SubSettingsBuilder.SubSettingDisplay subSettingDisplay : display) { + item.appendLore(MessageKey.of("menu.custom.subsetting-format"), subSettingDisplay.keyName(), subSettingDisplay.valueFormatted()); + } } // ADDING ACTION INFO if (getAction() != null) { -// builder.appendLore(" "); -// List actionDisplay = SubSettingsBuilder -// .getSubSettingsDisplay(getAction().getSubSettingsBuilder(), getSubActions()); -// -// String actionName = Message.forName(getAction().getMessageKey()).asItemDescription().getName(); -// builder.appendLore(Message.forName("custom-info-action").asString() + " " + actionName); -// builder.appendLore(actionDisplay); - item.appendBlankLoreLine() - .appendLore(MessageKey.of("menu.custom.action-format"), getAction().getSettingName()); + .appendLore(MessageKey.of("menu.custom.action-format"), action.getSettingName()); + + Collection display = action.getSubSettingsBuilder().getCurrentDisplayFor(subActions); + for (SubSettingsBuilder.SubSettingDisplay subSettingDisplay : display) { + item.appendLore(MessageKey.of("menu.custom.subsetting-format"), subSettingDisplay.keyName(), subSettingDisplay.valueFormatted()); + } } return item; } + @NotNull @Override - public void playStatusUpdateTitle() { - Challenges.getInstance().getTitleManager().sendChallengeStatusTitle(enabled ? Message.forName("title-challenge-enabled") : Message.forName("title-challenge-disabled"), getDisplayName()); + public LocalizableMessage getChallengeName() { + return LocalizableMessage.wrap(getDisplayName()); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java index 2fb034f66..13e712b09 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import org.bukkit.Material; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -27,6 +28,7 @@ public static boolean shouldCancel() { } @Override + @NotNull public Material getMaterial() { return Material.BARRIER; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java index 86aebbb0c..b28107182 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/inventory/UncraftItemsChallenge.java @@ -25,7 +25,7 @@ public UncraftItemsChallenge() { } @Override - public @NotNull LocalizableMessage getChallengeDescription() { + public @NotNull LocalizableMessage getSettingsDescription() { return ChallengeHelper.getSettingsDescriptionIntervalSeconds(getValue()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java index 4c6caaeee..e1179bbaa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/OneDurabilityChallenge.java @@ -39,8 +39,7 @@ public void onInteract(PlayerInteractEvent event) { @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onInteract(EntityPickupItemEvent event) { - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); + if (!(event.getEntity() instanceof Player player)) return; if (!shouldExecuteEffect()) return; if (ignorePlayer(player)) return; setDurability(event.getItem().getItemStack()); @@ -48,10 +47,10 @@ public void onInteract(EntityPickupItemEvent event) { private void setDurability(@NotNull ItemStack item) { ItemMeta meta = item.getItemMeta(); - if (meta instanceof Damageable) { + if (meta instanceof Damageable damageable) { meta.setUnbreakable(false); int durability = item.getType().getMaxDurability() - 1; - ((Damageable) meta).setDamage(durability); + damageable.setDamage(durability); item.setItemMeta(meta); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java index af4decef3..40cacb6a2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java @@ -27,7 +27,6 @@ public class AnvilRainChallenge extends MenuSetting { int currentTime = 0; public AnvilRainChallenge() { -// super(Message.forName("menu-anvil-rain-challenge-settings")); super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.ANVIL), "anvil-rain"); // registerSetting("time", new NumberSubSetting( // () -> new LegacyItemBuilder(Material.CLOCK, Message.forName("item-anvil-rain-time-challenge")), @@ -218,5 +217,4 @@ private int getHeight(int currentHeight) { return currentHeight + 50; } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java index 7c7992654..e8ed0a37e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/damage/DamageRuleSetting.java @@ -38,7 +38,7 @@ public String getUniqueName() { @Override public LocalizableMessage getChallengeDescription() { return super.getChallengeDescription() - .withArgs(LocalizableMessage.joinList(3, causes.stream().map(CustomTranslatable::of).toList())); + .withArgs(LocalizableMessage.joinList(2, causes.stream().map(CustomTranslatable::of).toList())); } @EventHandler(priority = EventPriority.NORMAL) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java index 0bb7e8d36..57609a216 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/CollectAllItemsGoal.java @@ -84,7 +84,7 @@ protected void onEnable() { } int foundItemsCount = totalItemsCount - itemsToFind.size() + 1; bossbar.setTitle(getChallengeMessageKey("bossbar-current"), - currentItem, foundItemsCount, totalItemsCount, new ItemStack(currentItem)); + currentItem, foundItemsCount, totalItemsCount); }); bossbar.show(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java index 176a9bb34..a87defa38 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/material/BlockMaterialSetting.java @@ -33,7 +33,7 @@ public BlockMaterialSetting(@NotNull String name, @NotNull ItemStack displayItem @NotNull @Override public LocalizableMessage getChallengeDescription() { - return super.getChallengeDescription().withArgs(LocalizableMessage.joinList(3, materials)); + return super.getChallengeDescription().withArgs(LocalizableMessage.joinList(2, materials)); } private boolean isMaterialAllowed(Material material) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java index 9a2ff981e..db2a70826 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DeathPositionSetting.java @@ -32,7 +32,7 @@ public void onDeath(@NotNull PlayerDeathEvent event) { } Player player = event.getEntity(); - player.performCommand("pos " + POSITION_PREFIX + index); + setting.setPosition(POSITION_PREFIX + index, player); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java index 9a6f4ce36..21f15ee3e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/ImmediateRespawnSetting.java @@ -56,5 +56,4 @@ public void onPlayerDeath(@NotNull PlayerDeathEvent event) { Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> event.getEntity().spigot().respawn(), 1); } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java index 2edd86866..ceb40be2b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java @@ -89,10 +89,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) { MessageKey.of("timer-not-started").send(player, Prefix.POSITION); SoundSample.BASS_OFF.play(player); } else { - positions.put(name, position = player.getLocation()); - MessageKey.of("position-set").broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, player); - SoundSample.BASS_ON.play(player); - broadcastParticleLine(position); + setPosition(name, player); } } else { @@ -123,6 +120,14 @@ public boolean containsPosition(@NotNull String name) { return positions.containsKey(name); } + public void setPosition(@NotNull String name, @NotNull Player player) { + Location position = player.getLocation(); + positions.put(name, position); + MessageKey.of("position-set").broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, player); + SoundSample.BASS_ON.play(player); + broadcastParticleLine(position); + } + private void broadcastParticleLine(@NotNull Location location) { broadcast(player -> playParticleLine(player, location)); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java index da0f704e6..5c0930af5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/RegenerationSetting.java @@ -2,9 +2,6 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Modifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; @@ -38,20 +35,11 @@ public ItemStack getSettingsItemPreset() { @NotNull @Override - public LocalizableMessage getSettingsName() { + public Object getSettingsName() { if (getValue() == NOT_NATURAL) { - return MessageKey.of("item-regeneration-setting-not_natural"); + return getChallengeMessageKey("not_natural"); } - return MessageKey.of("enabled"); - } - - @Override - public void playValueChangeTitle() { - if (getValue() == 1) { - ChallengeHelper.playChallengeToggleTitle(this, false); - return; - } - ChallengeHelper.playChallengeValueTitle(this, getValue() == 2 ? Message.forName("enabled") : Message.forName("item-regeneration-setting-not_natural")); + return ChallengeHelper.getChallengeEnabledName(); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java index 51a532534..f4bc9904a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java @@ -22,6 +22,7 @@ import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.CheckReturnValue; +import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -148,6 +149,7 @@ public LocalizableMessage getChallengeDescription() { } @NotNull + @Contract(pure = true) protected MessageKey getChallengeMessageKey(@NotNull String keySuffix) { return MessageKey.of("challenge." + nameMessageKey + "." + keySuffix); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java index 6f7afa60e..54e2d08c6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java @@ -12,7 +12,6 @@ import org.bukkit.projectiles.ProjectileSource; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jspecify.annotations.NonNull; import java.util.HashMap; import java.util.LinkedList; @@ -136,7 +135,7 @@ class ArgumentFormatImpl implements ArgumentFormat { @NotNull @Override - public LocalizableMessage apply(@NonNull T arg) { + public LocalizableMessage apply(@NotNull T arg) { return formatter.apply(arg); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java index 2feb5ed66..378cf453b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/MessageKey.java @@ -144,6 +144,12 @@ default MessageKey getChildKey(@NotNull String child) { @NotNull String localizeRawValueAsSingleLine(@NotNull Locale locale); + @NotNull + String[] localizeWithPrimitiveArgs(@NotNull Locale locale, @NotNull Object... args); + + @NotNull + String localizeWithPrimitiveArgAsSingleLine(@NotNull Locale locale, @NotNull Object... args); + @NotNull @Contract(pure = true) LocalizableMessage withArgs(@NotNull Object... args); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java index 193a50635..a3b52a558 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/LocalizableMessageImpl.java @@ -18,7 +18,7 @@ public class LocalizableMessageImpl implements LocalizableMessage { @NotNull @Override public MessageHolder localize(@NotNull Locale locale) { - return new MessageHolder(messageKey.localizeRawValue(locale), MessageKeyImpl.localizeArgsAsCopy(locale, args)); + return new MessageHolder(messageKey.localizeWithPrimitiveArgs(locale, args), MessageKeyImpl.localizeArgsAsCopy(locale, args)); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java index 6a4054832..98e3942af 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/MessageKeyImpl.java @@ -5,6 +5,7 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.content.i18n.*; import net.codingarea.challenges.plugin.content.i18n.impl.format.ComponentFormatter; +import net.codingarea.challenges.plugin.content.i18n.impl.format.MessageFormatter; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.management.server.TitleManager; import net.codingarea.commons.common.collection.IRandom; @@ -70,6 +71,34 @@ public String[] localizeRawValue(@NotNull Locale locale) { public String localizeRawValueAsSingleLine(@NotNull Locale locale) { String[] value = values.get(locale); if (value == null || value.length == 0) return MessageKey.formatMissingTranslation(key, locale); + return asSingleLine(value); + } + + @NotNull + @Override + public String[] localizeWithPrimitiveArgs(@NotNull Locale locale, @NotNull Object... args) { + String[] rawValue = localizeRawValue(locale); + if (args.length == 0) return rawValue; + + Object[] primitiveArgsCopy = new Object[args.length]; + for (int i = 0; i < primitiveArgsCopy.length; i++) { + if (MessageFormatter.isPrimitiveArg(args[i])) { + primitiveArgsCopy[i] = args[i]; + } + // else leave null + } + // embedPositionalArgs will skip null arguments + return MessageFormatter.embedPositionalArgs(rawValue, primitiveArgsCopy); + } + + @NotNull + @Override + public String localizeWithPrimitiveArgAsSingleLine(@NotNull Locale locale, @NotNull Object... args) { + return asSingleLine(localizeWithPrimitiveArgs(locale, args)); + } + + @NotNull + private String asSingleLine(@NotNull String[] value) { if (value.length == 1) return value[0]; return String.join("\n", value); } @@ -183,7 +212,7 @@ public void send(@NotNull Player target, @Nullable Prefix prefix, @NotNull Objec public void sendRandom(@NotNull Player target, @Nullable Prefix prefix, @NotNull Object... args) { Locale locale = getPlayerLocale(target); localizeArgs(locale, args); - String raw = random.choose(localizeRawValue(locale)); + String raw = random.choose(localizeWithPrimitiveArgs(locale, args)); target.sendMessage(ComponentFormatter.deserializeLinesWithArgs(localizePrefix(locale, prefix), arrayOf(raw), args)); } @@ -196,7 +225,7 @@ public void broadcast(@Nullable Prefix prefix, @NotNull Object... args) { public void broadcastRandom(@Nullable Prefix prefix, @NotNull Object... args) { int index = random.nextInt(getMinValueLengthIncludingFallback()); doBroadcast0(Player::sendMessage, locale -> - ComponentFormatter.deserializeLinesWithArgs(localizePrefix(locale, prefix), arrayOf(localizeRawValue(locale)[index]), localizeArgsAsCopy(locale, args))); + ComponentFormatter.deserializeLinesWithArgs(localizePrefix(locale, prefix), arrayOf(localizeWithPrimitiveArgs(locale, args)[index]), localizeArgsAsCopy(locale, args))); } @Override @@ -245,12 +274,12 @@ protected Title createTitleFromComponentList(@NotNull List components protected void doBroadcast(@Nullable Prefix prefix, @NotNull Object[] args, @NotNull BiConsumer messageSender) { doBroadcast0(messageSender, locale -> - ComponentFormatter.deserializeLinesWithArgs(localizePrefix(locale, prefix), localizeRawValue(locale), localizeArgsAsCopy(locale, args))); + ComponentFormatter.deserializeLinesWithArgs(localizePrefix(locale, prefix), localizeWithPrimitiveArgs(locale, args), localizeArgsAsCopy(locale, args))); } protected void doBroadcastAsList(@NotNull Object[] args, @NotNull BiConsumer> messageSender) { doBroadcast0(messageSender, locale -> - ComponentFormatter.deserializeLinesAsListWithArgs(localizeRawValue(locale), localizeArgsAsCopy(locale, args))); + ComponentFormatter.deserializeLinesAsListWithArgs(localizeWithPrimitiveArgs(locale, args), localizeArgsAsCopy(locale, args))); } protected void doBroadcast0(@NotNull BiConsumer messageSender, @NotNull Function compute) { @@ -286,14 +315,14 @@ protected int getMinValueLengthIncludingFallback() { @Override public Component asComponent(@NotNull Locale locale, @Nullable Prefix prefix, @NotNull Object... args) { localizeArgs(locale, args); - return ComponentFormatter.deserializeLinesWithArgs(localizePrefix(locale, prefix), localizeRawValue(locale), args); + return ComponentFormatter.deserializeLinesWithArgs(localizePrefix(locale, prefix), localizeWithPrimitiveArgs(locale, args), args); } @NotNull @Override public List asComponents(@NotNull Locale locale, @NotNull Object... args) { localizeArgs(locale, args); - return ComponentFormatter.deserializeLinesAsListWithArgs(localizeRawValue(locale), args); + return ComponentFormatter.deserializeLinesAsListWithArgs(localizeWithPrimitiveArgs(locale, args), args); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/DynamicMessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/DynamicMessageImpl.java index f4d5e1a99..8020f7d98 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/DynamicMessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/DynamicMessageImpl.java @@ -33,7 +33,7 @@ public MessageHolder localize(@NotNull Player playerLocale) { @NotNull @Override - public LocalizableMessage withArgs(@NonNull @NotNull Object... args) { + public LocalizableMessage withArgs(@NotNull Object... args) { return new DynamicMessageImpl(valueFunction, args); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/JoinedMessageImpl.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/JoinedMessageImpl.java index 1117246f3..bb821fb29 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/JoinedMessageImpl.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/dynamic/JoinedMessageImpl.java @@ -36,14 +36,13 @@ public MessageHolder localize(@NotNull Locale locale) { if (i > 0) raw.append(localizedDelimiter); raw.append(START_ARG_CHAR).append(i).append(END_ARG_CHAR); } - - Object[] args = new Object[shown + (remaining > 0 ? 1 : 0)]; - System.arraycopy(elements, 0, args, 0, shown); if (remaining > 0) { - raw.append(START_ARG_CHAR).append(shown).append(END_ARG_CHAR); - args[shown] = remainingPlaceholder.withArgs(remaining); + raw.append(remainingPlaceholder.localizeWithPrimitiveArgAsSingleLine(locale, remaining)); } + Object[] args = new Object[shown]; + System.arraycopy(elements, 0, args, 0, shown); + MessageKeyImpl.localizeArgs(locale, args); return new MessageHolder(arrayOf(raw.toString()), args); } @@ -56,7 +55,7 @@ public MessageHolder localize(@NotNull Player playerLocale) { @NotNull @Override - public LocalizableMessage withArgs(@NonNull @NotNull Object... args) { + public LocalizableMessage withArgs(@NotNull Object... args) { return new JoinedMessageImpl(delimiter, remainingPlaceholder, limit, args); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java index 0757b446a..cce5d50ed 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentArguments.java @@ -4,6 +4,7 @@ import net.codingarea.commons.bukkit.utils.misc.MinecraftVersion; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.ComponentLike; +import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.translation.Translatable; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -23,8 +24,7 @@ public static Component convertToComponent(@Nullable Object obj) { case Component component -> component; case ComponentLike like -> like.asComponent(); case MessageHolder holder -> convertMessageHolderToComponent(holder); - case Material material -> getDetailedMaterialTranslatable(material); - case ItemStack item -> getItemSpriteOrEmpty(item); + case Material material -> getDetailedMaterialWithSprite(material); case Translatable translatable -> // net.kyori.adventure.translation.Translatable Component.translatable(translatable); case Player player -> player.displayName(); @@ -40,18 +40,37 @@ public static Component convertMessageHolderToComponent(@NotNull MessageHolder h return ComponentFormatter.deserializeLinesWithArgs(null, holder.rawValue(), holder.positionalArgs()); } + @NotNull + public static Component getDetailedMaterialWithSprite(@NotNull Material material) { + return Component.text().append(getItemSpriteOrEmpty(material)).append(getDetailedMaterialTranslatable(material)).asComponent(); + } + @NotNull public static Component getItemSpriteOrEmpty(@NotNull ItemStack item) { try { - Component sprite = ItemSprites.sprite(item); - if (sprite.equals(Component.empty())) return sprite; // don't append space - return sprite.appendSpace(); - } catch (Throwable ignored) { + return formatSpriteOrEmpty(ItemSprites.sprite(item)); + } catch (Throwable _) { // not yet available in this version return Component.empty(); } } + @NotNull + public static Component getItemSpriteOrEmpty(@NotNull Material item) { + try { + return formatSpriteOrEmpty(ItemSprites.sprite(item)); + } catch (Throwable _) { + // not yet available in this version + return Component.empty(); + } + } + + @NotNull + private static Component formatSpriteOrEmpty(@NotNull Component sprite) throws Error { + if (sprite.equals(Component.empty())) return sprite; // don't append space + return sprite.color(NamedTextColor.WHITE).appendSpace(); + } + @NotNull public static Component getDetailedMaterialTranslatable(@NotNull Material material) { String key = material.translationKey(); // e.g., "item.minecraft.music_disc_strad" diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/MessageFormatter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/MessageFormatter.java index 747fae427..09fab53b1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/MessageFormatter.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/MessageFormatter.java @@ -3,6 +3,7 @@ import net.codingarea.commons.common.logging.ILogger; import org.jetbrains.annotations.CheckReturnValue; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.regex.Pattern; @@ -254,7 +255,7 @@ public static String[] embedPositionalArgs(@NotNull String[] origin, @NotNull Ob @NotNull @CheckReturnValue - public static String embedPositionalArgs(@NotNull String sequence, @NotNull Object[] args) { + public static String embedPositionalArgs(@NotNull String sequence, Object[] args) { if (args.length == 0) return sequence; // faster (maybe more error-prone) impl than regex matching @@ -276,7 +277,11 @@ public static String embedPositionalArgs(@NotNull String sequence, @NotNull Obje int argIndex = parsePositiveInt(argument); if (argIndex >= 0 && argIndex < args.length) { - builder.append(args[argIndex]); // String.valueOf + if (args[argIndex] != null) { + builder.append(args[argIndex]); // String.valueOf + } else { + builder.append(START_ARG_CHAR).append(argument).append(END_ARG_CHAR); // leave null values as is + } } else { // fallback if index is invalid or out of bounds logger.warn("Invalid argument index '{}' in '{}'", argument, sequence); @@ -373,4 +378,8 @@ public static int parsePositiveInt(@NotNull StringBuilder sb) { return num; } + public static boolean isPrimitiveArg(@Nullable Object arg) { + return arg instanceof String || arg instanceof Number || arg instanceof Character; + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java index 9272f13ca..f78a33bfb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/challenges/ChallengeLoader.java @@ -18,7 +18,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.*; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.*; import net.codingarea.challenges.plugin.challenges.implementation.setting.*; -import net.codingarea.challenges.plugin.utils.misc.ArmorUtils; +import net.codingarea.challenges.plugin.utils.misc.MaterialCategories; import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import org.bukkit.Material; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; @@ -263,7 +263,7 @@ public void enable() { registerDamageRule("freeze", Material.POWDER_SNOW_BUCKET, DamageCause.FREEZE); // 1.17+ // Material Rules - registerMaterialRule("armor", ArmorUtils.getArmor()); + registerMaterialRule("armor", MaterialCategories.getArmor()); registerMaterialRule("golden_apple", Material.GOLDEN_APPLE, Material.ENCHANTED_GOLDEN_APPLE); registerMaterialRule("crafting_table", Material.CRAFTING_TABLE); registerMaterialRule("chest", Material.CHEST, Material.CHEST_MINECART, Material.TRAPPED_CHEST); @@ -272,11 +272,11 @@ public void enable() { registerMaterialRule("anvil", Material.ANVIL, Material.CHIPPED_ANVIL, Material.DAMAGED_ANVIL); registerMaterialRule("brewing_stand", Material.BREWING_STAND); registerMaterialRule("bow", Material.BOW, Material.CROSSBOW); - registerMaterialRule("throwable", Material.SNOWBALL, Material.EGG); + registerMaterialRule("throwable", MaterialCategories.getSnowballAndEggs()); registerMaterialRule("flint_and_steel", Material.FLINT_AND_STEEL, Material.FIRE_CHARGE); - registerMaterialRule("bucket", ArmorUtils.getBuckets()); - registerMaterialRule("sword", ArmorUtils.getSwords()); - registerMaterialRule("pickaxe", ArmorUtils.getPickaxes()); + registerMaterialRule("bucket", MaterialCategories.getBuckets()); + registerMaterialRule("sword", MaterialCategories.getSwords()); + registerMaterialRule("pickaxe", MaterialCategories.getPickaxes()); registerMaterialRule("elytra", Material.ELYTRA); registerMaterialRule("shield", Material.SHIELD); registerMaterialRule("totem", Material.TOTEM_OF_UNDYING); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomHomeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomHomeMenuGenerator.java index 20ef007d7..9971f3213 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomHomeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomHomeMenuGenerator.java @@ -14,7 +14,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.Locale; @@ -64,17 +63,17 @@ public int getInventorySize() { } @Override - public void addToCache(@NonNull IChallenge element) { + public void addToCache(@NotNull IChallenge element) { listGenerator.addToCache(element); } @Override - public void removeFromCache(@NonNull IChallenge element) { + public void removeFromCache(@NotNull IChallenge element) { listGenerator.removeFromCache(element); } @Override - public boolean isCached(@NonNull IChallenge element) { + public boolean isCached(@NotNull IChallenge element) { return listGenerator.isCached(element); } @@ -89,7 +88,7 @@ public void resetCache() { } @Override - public void updateElementDisplay(@NonNull IChallenge element) { + public void updateElementDisplay(@NotNull IChallenge element) { listGenerator.updateElementDisplay(element); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMaterialMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMaterialMenuGenerator.java index d4a16226e..fa6b51367 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMaterialMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseMaterialMenuGenerator.java @@ -15,7 +15,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import org.jspecify.annotations.NonNull; import java.util.ArrayList; import java.util.Locale; @@ -55,13 +54,13 @@ public LocalizableMessage getMenuName() { } @Override - public void handleElementClick(@NonNull Material element, @NotNull MenuClickInfo info) { + public void handleElementClick(@NotNull Material element, @NotNull MenuClickInfo info) { parent.accept(info.getPlayer(), SettingType.MATERIAL, MapUtils.createStringArrayMap("material", element.name())); } @NotNull @Override - public ItemStack createDisplayItem(@NonNull Material element, @NotNull Locale locale) { + public ItemStack createDisplayItem(@NotNull Material element, @NotNull Locale locale) { return new ItemBuilder(locale, element, MessageKey.of("menu.custom.material.format"), element).build(); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java index c9157345f..dd8eecf87 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/ChallengeTimer.java @@ -8,6 +8,7 @@ import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.content.i18n.TranslationManager; import net.codingarea.challenges.plugin.content.loader.LanguageLoader; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.generator.impl.TimerMenuGenerator; @@ -35,6 +36,10 @@ public final class ChallengeTimer { private final Map compiledFormats = new HashMap<>(); private final boolean specificStartSounds, defaultStartSound; + private final boolean gradientEnabled; + private final int gradientDuration; + private final TimerActionBarUpdateScheduler updateActionbarScheduler; + @Getter private long time = 0; @Getter @@ -49,8 +54,17 @@ public ChallengeTimer() { Document pluginConfig = Challenges.getInstance().getConfigDocument(); specificStartSounds = pluginConfig.getBoolean("enable-specific-start-sounds"); defaultStartSound = pluginConfig.getBoolean("enable-default-start-sounds"); + gradientEnabled = pluginConfig.getBoolean("timer.gradient.enabled"); + gradientDuration = pluginConfig.getInt("timer.gradient.duration"); + + if (gradientEnabled) { + updateActionbarScheduler = new GradientActionBarUpdateScheduler(); + } else { + updateActionbarScheduler = new DefaultActionBarUpdateScheduler(); + } Challenges.getInstance().getScheduler().register(this); + Challenges.getInstance().getScheduler().register(updateActionbarScheduler); Challenges.getInstance().getLoaderRegistry().subscribe(LanguageLoader.class, this::precompileFormat); } @@ -87,23 +101,6 @@ public void incrementTimerSecond() { } } - @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.ALWAYS, playerPolicy = PlayerCountPolicy.ALWAYS, worldPolicy = ExtraWorldPolicy.ALWAYS) - public void updateActionbar() { - if (sentEmpty && hidden) return; - - ChallengeActionBar currentActionBar = Challenges.getInstance().getScoreboardManager().getCurrentActionBar(); - if (currentActionBar != null) { - currentActionBar.send(); - } else if (!hidden) { - this.getCurrentActionbarMessage().broadcastActionBar(getFormattedTime()); - } else { - sentEmpty = true; - for (Player player : Bukkit.getOnlinePlayers()) { - player.sendActionBar(Component.empty()); - } - } - } - @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.PAUSED) public void playPausedParticles() { for (Player player : Bukkit.getOnlinePlayers()) { @@ -114,6 +111,10 @@ public void playPausedParticles() { } } + public void updateActionbar() { + updateActionbarScheduler.updateActionbar(); + } + private void handleHitZero() { ChallengeAPI.endChallenge(ChallengeEndCause.TIMER_HIT_ZERO); } @@ -177,9 +178,9 @@ public void reset() { @NotNull private MessageKey getCurrentActionbarMessage() { // TODO save references? - if (paused) return MessageKey.of("timer.bar.paused"); - if (countingUp) return MessageKey.of("timer.bar.up"); - return MessageKey.of("timer.bar.down"); + if (paused) return MessageKey.of("timer.bar.paused.display"); + if (countingUp) return MessageKey.of("timer.bar.up.display"); + return MessageKey.of("timer.bar.down.display"); } public synchronized void loadSession() { @@ -256,4 +257,63 @@ public void setCountingUp(boolean countingUp) { SoundSample.BASS_ON.broadcast(); } + private abstract class TimerActionBarUpdateScheduler { + + public abstract void updateActionbar(); + + protected boolean shouldNotSendActionbarOrSendEmpty() { + if (sentEmpty && hidden) return true; + + ChallengeActionBar currentActionBar = Challenges.getInstance().getScoreboardManager().getCurrentActionBar(); + if (currentActionBar == null && !hidden) { + return false; + } + + if (currentActionBar != null) { + currentActionBar.send(); + } else { + sentEmpty = true; + for (Player player : Bukkit.getOnlinePlayers()) { + player.sendActionBar(Component.empty()); + } + } + + return true; + } + + } + + public class DefaultActionBarUpdateScheduler extends TimerActionBarUpdateScheduler { + + @Override + @ScheduledTask(ticks = 20, timerPolicy = TimerPolicy.ALWAYS, playerPolicy = PlayerCountPolicy.ALWAYS, worldPolicy = ExtraWorldPolicy.ALWAYS) + public void updateActionbar() { + if (shouldNotSendActionbarOrSendEmpty()) return; + getCurrentActionbarMessage().broadcastActionBar(getFormattedTime(), 0); // default phase to 0 if present + } + + } + + public class GradientActionBarUpdateScheduler extends TimerActionBarUpdateScheduler { + + private final int maxGradientTickProgress = gradientDuration * 2; + private int currentGradientTickProgress; + + @Override + @ScheduledTask(ticks = 1, timerPolicy = TimerPolicy.ALWAYS, playerPolicy = PlayerCountPolicy.ALWAYS, worldPolicy = ExtraWorldPolicy.ALWAYS) + public void updateActionbar() { + if (shouldNotSendActionbarOrSendEmpty()) return; + + if (currentGradientTickProgress == maxGradientTickProgress) { + currentGradientTickProgress = 0; + } else { + currentGradientTickProgress++; + } + + float phase = (float) currentGradientTickProgress / gradientDuration - 1; // [-1; 1] + getCurrentActionbarMessage().broadcastActionBar(getFormattedTime(), phase); + } + + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java index ac7844aa8..cf1366168 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/timer/TimerFormat.java @@ -38,6 +38,8 @@ private interface Token { public static final TimerFormat SIMPLE_FORMAT = new TimerFormat(); + // TODO impl primitive args token? + private record LiteralToken(String text) implements Token { @Override public void append(@NotNull StringBuilder sb, long d, long h, long m, long s) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java index 59e4cef59..a8102eb5d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.spigot.command; import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.blocks.BlockDropManager.RegisteredDrops; @@ -56,7 +57,8 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr if (blocks.isEmpty()) { MessageKey.of("command-search-nothing").send(sender, Prefix.CHALLENGES, material); } else { - MessageKey.of("command-search-result").send(sender, Prefix.CHALLENGES, material, StringUtils.getIterableAsString(blocks, ", ", StringUtils::getEnumName)); + System.out.println(blocks); + MessageKey.of("command-search-result").send(sender, Prefix.CHALLENGES, material, LocalizableMessage.joinList(blocks)); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java index a8de5057e..e6850eab7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ColorConversions.java @@ -10,6 +10,7 @@ import java.util.Map; import java.util.Optional; +@Deprecated public final class ColorConversions { private static final Map colorsByChatColor = new HashMap<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MaterialCategories.java similarity index 73% rename from plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java rename to plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MaterialCategories.java index bc9cebbc6..cca3146da 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ArmorUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/MaterialCategories.java @@ -2,9 +2,9 @@ import org.bukkit.Material; -public final class ArmorUtils { +public final class MaterialCategories { - private ArmorUtils() { + private MaterialCategories() { } public static Material[] getArmor() { @@ -20,17 +20,22 @@ public static Material[] getArmor() { }; } - // TODO wrong class... public static Material[] getBuckets() { return new Material[]{ Material.BUCKET, Material.WATER_BUCKET, Material.LAVA_BUCKET, Material.MILK_BUCKET, - Material.FISHING_ROD, Material.SALMON_BUCKET, Material.COD_BUCKET, Material.PUFFERFISH_BUCKET, - Material.SALMON_BUCKET, Material.TROPICAL_FISH_BUCKET, Utils.getMaterial("AXOLOTL_BUCKET"), - Utils.getMaterial("POWDER_SNOW_BUCKET") + Material.COD_BUCKET, Material.SALMON_BUCKET, Material.PUFFERFISH_BUCKET, Material.TROPICAL_FISH_BUCKET, // 1.13 + Material.AXOLOTL_BUCKET, Material.POWDER_SNOW_BUCKET, // 1.17 + Utils.getMaterial("TADPOLE_BUCKET"), // 1.19 + Utils.getMaterial("SULFUR_CUBE_BUCKET") // 26.2 + }; + } + + public static Material[] getSnowballAndEggs() { + return new Material[]{ + Material.SNOWBALL, Material.EGG, Utils.getMaterial("BLUE_EGG"), Utils.getMaterial("BROWN_EGG") }; } - // TODO wrong class... public static Material[] getSwords() { return new Material[]{ Material.WOODEN_SWORD, Material.STONE_SWORD, Material.IRON_SWORD, Material.DIAMOND_SWORD, @@ -38,7 +43,6 @@ public static Material[] getSwords() { }; } - // TODO wrong class... public static Material[] getPickaxes() { return new Material[]{ Material.WOODEN_PICKAXE, Material.STONE_PICKAXE, Material.IRON_PICKAXE, Material.DIAMOND_PICKAXE, diff --git a/plugin/src/main/resources/config.yml b/plugin/src/main/resources/config.yml index 0fd912529..1a9a8508a 100644 --- a/plugin/src/main/resources/config.yml +++ b/plugin/src/main/resources/config.yml @@ -33,10 +33,12 @@ language: "de" # on every load. Defaults to off so the plugin doesn't make outbound HTTP calls without consent. language-online-update: false +# In order to use a timer gradient, you must edit the '*colorize*' values in the global.json of "timer.bar.up/down/paused" +# and replace the value with a "MiniMessage gradient tag" like "{0}" timer: gradient: enabled: false - duration: 20 + duration: 30 # When the worlds are reset using /reset, the given seed will be used, if enabled, to generate the new worlds # When a seed is written in the reset command, the seed of the command will be taken From 58190f8a74aaf738697860d63eaa257b3f9d1f25 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Sat, 11 Jul 2026 01:10:43 +0200 Subject: [PATCH 110/119] fix: arg replacement inside gradients MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit generated by claude opus Insert positional arguments at MiniMessage parse time to allow placeholders (e.g. {0}) to render correctly inside / tags. Adds ARG_TAG_PREFIX and rewritePositionalPlaceholders to convert {n} into parse-time tags, plus PositionalArgResolver (TagResolver) to resolve and cache converted components. Keeps legacy (§) deserialization as a fallback and preserves post-parse replacement for legacy text. This fixes issues where replaceText couldn't match multi-character placeholders split across text nodes (see linked adventure issue). --- .../i18n/impl/format/ComponentFormatter.java | 172 +++++++++++++++--- 1 file changed, 150 insertions(+), 22 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java index 99798aac1..9b874bbc0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java @@ -3,7 +3,11 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextReplacementConfig; import net.kyori.adventure.text.format.TextDecoration; +import net.kyori.adventure.text.minimessage.Context; import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.minimessage.tag.Tag; +import net.kyori.adventure.text.minimessage.tag.resolver.ArgumentQueue; +import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -19,6 +23,21 @@ public final class ComponentFormatter { public static final MiniMessage MINI_MESSAGE = MiniMessage.miniMessage(); public static final LegacyComponentSerializer LEGACY_SECTION = LegacyComponentSerializer.legacySection(); // temp migration impl + /** + * MiniMessage tag name prefix used to insert positional arguments ({@code {0}}, {@code {1}}, ...) + * at parse time instead of substituting them into the already parsed component. + *

    + * Post-parse {@link Component#replaceText} cannot reach a placeholder that sits inside a + * {@code } or {@code } tag: those tags split their content into one component + * per character, so a multi-character match such as {@code "{0}"} is scattered across + * several text nodes ({@code "{"}, {@code "0"}, {@code "}"}) and is silently left untouched. + * Resolving the argument as a MiniMessage {@link Tag#inserting(Component) inserting} tag while + * parsing sidesteps the problem entirely and lets the gradient colorize the inserted content. + * + * @see PaperMC/adventure#1133 + */ + static final String ARG_TAG_PREFIX = "_carg_"; // e.g. {0} -> <_carg_0> + private static final Map prefixCache = new ConcurrentHashMap<>(); private ComponentFormatter() { @@ -26,16 +45,19 @@ private ComponentFormatter() { @NotNull public static Component deserializeLinesWithArgs(@Nullable String prefix, @NotNull String[] textLines, @NotNull Object[] positionalArgs) { - return replacePositionalArgs(deserializeLines(prefix, textLines), positionalArgs); + if (positionalArgs.length == 0) { + return deserializeLines(prefix, textLines); + } + return deserializeLines(prefix, textLines, new PositionalArgResolver(positionalArgs)); } @NotNull - public static Component deserializeLineWithArgs(@NotNull String line, @NotNull Object[] positionalArgs) { - return replacePositionalArgs(deserializeText(line), positionalArgs); + public static Component deserializeLines(@Nullable String prefix, @NotNull String[] textLines) { + return deserializeLines(prefix, textLines, null); } @NotNull - public static Component deserializeLines(@Nullable String prefix, @NotNull String[] textLines) { + private static Component deserializeLines(@Nullable String prefix, @NotNull String[] textLines, @Nullable PositionalArgResolver args) { if (textLines.length == 0) return Component.empty(); // Component.text() (Builder) incompatible in version change 26.1.2 -> 26.2 @@ -51,7 +73,8 @@ public static Component deserializeLines(@Nullable String prefix, @NotNull Strin continue; } - Component lineComponent = deserializeText(textLines[i]); + // args (if any) are inserted at parse time so they render correctly inside / + Component lineComponent = args == null ? deserializeText(textLines[i]) : deserializeText(textLines[i], args); if (prefixComponent != null) { rootComponent = rootComponent.append(prefixComponent).append(lineComponent); @@ -71,20 +94,31 @@ public static Component deserializeLines(@Nullable String prefix, @NotNull Strin public static List deserializeLinesAsListWithArgs(@NotNull String[] textLines, @NotNull Object[] args) { if (textLines.length == 0) return Collections.emptyList(); - boolean hasArgs = args.length > 0; // don't waste time on processing otherwise + if (args.length == 0) { // don't waste time on processing otherwise + List components = new ArrayList<>(textLines.length); + for (String textLine : textLines) { + components.add(deserializeText(textLine)); + } + return components; + } + + PositionalArgResolver resolver = new PositionalArgResolver(args); List components = new ArrayList<>(textLines.length + args.length); // might grow with args; extending is more expensive for (String textLine : textLines) { - Component line = deserializeText(textLine); - if (hasArgs) { - List replaced = replacePositionalArgsAsList(line, args); - components.addAll(replaced); - } else { - components.add(line); - } + // an inserted arg (e.g. a multi-line MessageHolder) can introduce newlines, so we still + // split the parsed component into separate lines afterwards + components.addAll(ComponentSplitter.split(deserializeText(textLine, resolver))); } return components; } + /** + * Replaces {@code {n}} placeholders in an already parsed component. + *

    + * Kept for the legacy ({@code §}) deserialization path only. It cannot reach placeholders inside + * {@code }/{@code } tags (see {@link #ARG_TAG_PREFIX}); the MiniMessage path + * inserts arguments at parse time instead via {@link PositionalArgResolver}. + */ @NotNull public static Component replacePositionalArgs(@NotNull Component component, @Nullable Object[] positionalArgs) { if (positionalArgs == null || positionalArgs.length == 0) { @@ -103,18 +137,13 @@ public static Component replacePositionalArgs(@NotNull Component component, @Nul } @NotNull - public static List replacePositionalArgsAsList(@NotNull Component component, @Nullable Object[] positionalArgs) { - if (positionalArgs == null || positionalArgs.length == 0) { - return List.of(component); - } - - Component replaced = replacePositionalArgs(component, positionalArgs); - return ComponentSplitter.split(replaced); + static Component deserializeText(@NotNull String textLine) { + return applyDecorationIfAbsent(deserializeText0(textLine), TextDecoration.ITALIC, TextDecoration.State.FALSE); } @NotNull - static Component deserializeText(@NotNull String textLine) { - return applyDecorationIfAbsent(deserializeText0(textLine), TextDecoration.ITALIC, TextDecoration.State.FALSE); + static Component deserializeText(@NotNull String textLine, @NotNull PositionalArgResolver args) { + return applyDecorationIfAbsent(deserializeText0(textLine, args), TextDecoration.ITALIC, TextDecoration.State.FALSE); } @NotNull @@ -139,6 +168,59 @@ private static Component deserializeText0(@NotNull String textLine) { } } + @NotNull + private static Component deserializeText0(@NotNull String textLine, @NotNull PositionalArgResolver args) { + // legacy text cannot carry MiniMessage placeholders (and never contains gradients), + // so fall back to post-parse replacement for it + if (isProbablyLegacyText(textLine)) { + return replacePositionalArgs(LEGACY_SECTION.deserialize(textLine), args.args); + } + try { + // rewrite {n} -> <_carg_n> so args are inserted while parsing (works inside gradients/rainbows) + return MINI_MESSAGE.deserialize(rewritePositionalPlaceholders(textLine, args.args.length), args); + } catch (Exception ex) { // maybe heuristic failed, try legacy on the original (un-rewritten) line + return replacePositionalArgs(LEGACY_SECTION.deserialize(textLine), args.args); + } + } + + /** + * Rewrites every in-bounds positional placeholder {@code {n}} into its MiniMessage tag form + * {@code <_carg_n>} so it can be resolved at parse time by {@link PositionalArgResolver}. + * Out-of-bounds indices, empty braces and non-numeric braces (e.g. {@code {mm}}) are left + * untouched. Returns the original instance unchanged when there is nothing to rewrite. + */ + @NotNull + static String rewritePositionalPlaceholders(@NotNull String line, int argCount) { + int len = line.length(); + StringBuilder builder = null; // lazily allocated: zero-copy when the line has no placeholder + int copiedUpTo = 0; + int i = 0; + while (i < len) { + if (line.charAt(i) == MessageFormatter.START_ARG_CHAR) { + int j = i + 1; + int index = 0; + boolean hasDigit = false; + while (j < len) { + char digit = line.charAt(j); + if (digit < '0' || digit > '9') break; + index = index * 10 + (digit - '0'); + hasDigit = true; + j++; + } + if (hasDigit && j < len && line.charAt(j) == MessageFormatter.END_ARG_CHAR && index < argCount) { + if (builder == null) builder = new StringBuilder(len + 8); + builder.append(line, copiedUpTo, i).append('<').append(ARG_TAG_PREFIX).append(index).append('>'); + i = j + 1; + copiedUpTo = i; + continue; + } + } + i++; + } + if (builder == null) return line; + return builder.append(line, copiedUpTo, len).toString(); + } + private static boolean isProbablyLegacyText(@NotNull String text) { // legacy texts often start/end with a '§' color; heuristic so we don't have to check the full string if (text.length() < 2) return false; @@ -146,4 +228,50 @@ private static boolean isProbablyLegacyText(@NotNull String text) { return text.charAt(text.length() - 2) == '§'; } + /** + * Resolves the {@code <_carg_n>} tags produced by {@link #rewritePositionalPlaceholders} into the + * matching positional argument, converted via {@link ComponentArguments#convertToComponent(Object)}. + * Converted components are cached per index, so a placeholder used multiple times is only converted + * once. A single instance is reused across all lines of one message. + */ + static final class PositionalArgResolver implements TagResolver { + + private final Object[] args; + private final Component[] cache; + + PositionalArgResolver(@NotNull Object[] args) { + this.args = args; + this.cache = new Component[args.length]; + } + + @Override + public boolean has(@NotNull String name) { + return argIndex(name) >= 0; + } + + @Nullable + @Override + public Tag resolve(@NotNull String name, @NotNull ArgumentQueue arguments, @NotNull Context ctx) { + int index = argIndex(name); + if (index < 0) return null; // not ours -> let MiniMessage try its standard tags + Component component = cache[index]; + if (component == null) { + component = ComponentArguments.convertToComponent(args[index]); + cache[index] = component; + } + return Tag.inserting(component); + } + + private int argIndex(@NotNull String name) { + int prefixLength = ARG_TAG_PREFIX.length(); + if (name.length() <= prefixLength || !name.startsWith(ARG_TAG_PREFIX)) return -1; + int index = 0; + for (int i = prefixLength; i < name.length(); i++) { + char digit = name.charAt(i); + if (digit < '0' || digit > '9') return -1; + index = index * 10 + (digit - '0'); + } + return index < args.length ? index : -1; + } + } } From 94c14e8022fe4a57ada47e94489bfc56700776a2 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Sat, 11 Jul 2026 17:19:15 +0200 Subject: [PATCH 111/119] refactor: migrate localization usage (part 7) --- language/locales/de.json | 396 ++++++++---------- language/locales/global.json | 96 ++++- .../challenges/custom/CustomChallenge.java | 10 +- .../settings/action/ChallengeAction.java | 9 +- .../custom/settings/sub/SelectableKey.java | 52 +-- .../builder/ChooseItemSubSettingsBuilder.java | 2 +- .../ChooseMultipleItemSubSettingBuilder.java | 2 +- .../settings/trigger/ChallengeTrigger.java | 9 +- .../trigger/impl/ConsumeItemTrigger.java | 4 +- .../trigger/impl/EntityDamageTrigger.java | 2 +- .../trigger/impl/InLiquidTrigger.java | 5 +- .../trigger/impl/IntervallTrigger.java | 25 +- .../forcebattle/ExtremeForceBattleGoal.java | 31 +- .../ForceAdvancementBattleGoal.java | 1 - .../forcebattle/ForceBiomeBattleGoal.java | 1 - .../forcebattle/ForceBlockBattleGoal.java | 17 +- .../forcebattle/ForceDamageBattleGoal.java | 1 - .../forcebattle/ForceHeightBattleGoal.java | 1 - .../goal/forcebattle/ForceItemBattleGoal.java | 17 +- .../goal/forcebattle/ForceMobBattleGoal.java | 1 - .../abstraction/ForceBattleDisplayGoal.java | 6 + .../type/abstraction/ForceBattleGoal.java | 11 +- .../type/abstraction/menu/MenuSetting.java | 1 + .../type/helper/ChallengeHelper.java | 5 +- .../type/helper/SubSettingsHelper.java | 37 +- .../plugin/utils/misc/ExperimentalUtils.java | 34 +- .../utils/misc/FeatureDependentAccessor.java | 22 + 27 files changed, 436 insertions(+), 362 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FeatureDependentAccessor.java diff --git a/language/locales/de.json b/language/locales/de.json index 5427c0044..50745d281 100644 --- a/language/locales/de.json +++ b/language/locales/de.json @@ -1291,16 +1291,16 @@ ] }, "jump-and-run": { - "name": "*JumpAndRun*", + "name": "*Jump and Run*", "desc": [ "In einem gesetzten *Intervall* muss ein", - "*zufälliger Spieler* ein *JumpAndRun* absolvieren", + "*zufälliger Spieler* ein *Jump and Run* absolvieren", "Schafft er es *nicht*, *stirbt* er" ], "actionbar": "{@actionbar.format('*Jump & Run* {@symbol.vertical} {0} / {1}')}", - "countdown": "Nächstes JumpAndRun in {0} Sekunden", - "countdown-one": "Nächstes JumpAndRun in einer Sekunde", - "finished": "{0} hat das JumpAndRun geschafft" + "countdown": "Nächstes {@name} in {0} Sekunden", + "countdown-one": "Nächstes {@name} in einer Sekunde", + "finished": "{0} hat das {@name} geschafft" }, "one-durability": { "name": "*Eine Haltbarkeit*", @@ -1590,69 +1590,122 @@ "The first player to gain full health wins." ] }, + "force-battles": { + "sub": { + "goal-jokers": { + "name": "*Anzahl der Joker*", + "desc": [ + "Die *Anzahl* der *Joker*,", + "die jeder Spieler hat um das", + "aktuelle Ziel zu *überspringen*" + ] + }, + "scoreboard": { + "name": "*Scoreboard anzeigen*", + "desc": [ + "Ob das *Scoreboard* angezeigt,", + "mit der *aktuellen Bestenliste*", + "angezeigt werden soll" + ] + }, + "duped-targets": { + "name": "*Doppelte Ziele*", + "desc": [ + "Ob Ziele *mehrfach vorkommen* können" + ] + } + } + }, "force-item-battle": { - "name": "*Force Item Battle*", + "name": "*{@menu}*", "desc": [ "Jeder Spieler bekommt ein *zufälliges Item*,", "das er finden muss.", "Wer am Ende die *meisten Items* hat, gewinnt" - ] + ], + "menu": "Force Item Battle", + "sub": { + "give-item": { + "name": "*Item geben*", + "desc": [ + "Wenn ein Spieler ein Item *skippt*,", + "wird dieses in sein *Inventar hinzugefügt*" + ] + } + } }, "force-mob-battle": { - "name": "*Force Mob Battle*", + "name": "*{@menu}*", "desc": [ "Jeder Spieler bekommt ein *zufälliges Mob*,", "das er töten muss." - ] + ], + "menu": "Force Mob Battle" }, "force-advancement-battle": { - "name": "*Force Advancement Battle*", + "name": "*{@menu}*", "desc": [ "Jeder Spieler bekommt ein *zufälliges*", "*Advancement*, welches er erreichen muss." - ] + ], + "menu": "Force Advancement Battle" }, "force-block-battle": { - "name": "*Force Block Battle*", + "name": "*{@menu}*", "desc": [ "Jeder Spieler bekommt einen *zufälligen*", "*Block*, auf welchem er stehen muss" - ] + ], + "menu": "Force Block Battle", + "sub": { + "give-block": { + "name": "*Block geben*", + "desc": [ + "Wenn ein Spieler einen Block *skippt*,", + "wird dieser in sein *Inventar hinzugefügt*" + ] + } + } }, "force-biome-battle": { - "name": "*Force Biome Battle*", + "name": "*{@menu}*", "desc": [ "Jeder Spieler bekommt ein *zufälliges Biom*,", "das er betreten muss" - ] + ], + "menu": "Force Biome Battle" }, "force-damage-battle": { - "name": "*Force Damage Battle*", + "name": "*{@menu}*", "desc": [ "Jeder Spieler bekommt eine *zufällige Anzahl Schaden*,", "die er *erhalten* muss" - ] + ], + "menu": "Force Damage Battle" }, "force-height-battle": { - "name": "*Force Height Battle*", + "name": "*{@menu}*", "desc": [ "Jeder Spieler bekommt eine *zufällige Höhe*,", "auf der er sich befinden muss." - ] + ], + "menu": "Force Height Battle" }, "force-position-battle": { - "name": "*Force Position Battle*", + "name": "*{@menu}*", "desc": [ "Jeder Spieler bekommt eine *zufällige Position*,", "die er erreichen muss." - ] + ], + "menu": "Force Position Battle" }, "extreme-force-battle": { - "name": "*Extreme Force Battle*", + "name": "*{@menu}*", "desc": [ "Jeder Spieler bekommt ein *zufälliges Ziel*,", "welches er erreichen muss" - ] + ], + "menu": "Extreme Force Battle" }, "last-man-standing": { "name": "*Last Man Standing*", @@ -1694,8 +1747,7 @@ "name": "*Genereller Schaden*", "desc": [ "Stellt ein, ob du Schaden bekommen kannst", - "Du kannst *weiterhin* Schaden durch", - "*Challenges* sterben" + "Du kannst *weiterhin* durch *Challenges* sterben" ] }, "fire": { @@ -1934,18 +1986,9 @@ "item-custom-trigger-damage-any": [ "Jeglicher Grund" ], - "item-custom-trigger-damage_by_player": [ - "Entity Bekommt Schaden Von Spieler" - ], - "item-custom-trigger-intervall-second": [ - "Jede Sekunde" - ], - "item-custom-trigger-intervall-seconds": [ - "Alle {0} Sekunden" - ], - "item-custom-trigger-intervall-minutes": [ - "Alle {0} Minuten" - ], + "damage_by_player": { + "name": "*Entity bekommt Schaden von Spieler*" + }, "block_place": { "name": "*Block platziert*" }, @@ -2186,6 +2229,95 @@ "absolvieren oder er *stirbt*" ] } + }, + "setting": { + "interval": { + "second": { + "name": "*Jede* Sekunde" + }, + "seconds": { + "name": "*Alle {0} Sekunden*" + }, + "minutes": { + "name": "*Alle {0} Minuten*" + } + }, + "target": { + "console": { + "name": "*Konsole*", + "desc": [ + "Die Aktion wird für die *Serverkonsole* ausgeführt", + "Wenn die Aktion nur für Kreaturen ausgeführt werden kann,", + "wird nicht passieren" + ] + }, + "current": { + "name": "*Auslösende Kreatur*", + "desc": [ + "Die Aktion wird für *die Kreatur* ausgeführt,", + "die den *Auslöser* ausgeführt hat" + ] + }, + "current_player": { + "name": "*Auslösender Spieler*", + "desc": [ + "Die Aktion wird für *den Spieler* ausgeführt,", + "der den *Auslöser* ausgeführt hat", + "Wenn die auslösende Kreatur kein Spieler ist,", + "wird nicht passieren" + ] + }, + "random_player": { + "name": "*Zufälliger Spieler*", + "desc": [ + "Die Aktion wird für einen *zufällig*", + "ausgewählten *Spieler* ausgeführt" + ] + }, + "every_player": { + "name": "*Alle Spieler*", + "desc": [ + "Die Aktion wird für *alle Spieler* ausgeführt" + ] + }, + "every_mob": { + "name": "*Jeder Kreatur*", + "desc": [ + "Die Aktion wird für *alle Kreaturen*", + "(inklusive *Spieler*) ausgeführt" + ] + }, + "every_mob_except_current": { + "name": "*Alle Kreaturen außer Auslösendes*", + "desc": [ + "Die Aktion wird für *alle Kreaturen*", + "(inklusive *Spieler*) ausgeführt,", + "außer der *auslösenden Kreatur*" + ] + }, + "every_mob_except_players": { + "name": "*Alle Kreaturen außer Spieler*", + "desc": [ + "Die Aktion wird für *alle Kreaturen*", + "aber keine *Spieler* ausgeführt" + ] + } + }, + "block": { + "any": { + "name": "*Jeglicher Block*" + } + }, + "item": { + "any": { + "name": "*Jegliches Item*" + } + }, + "structure_type": { + "random": { + "name": "*Zufällige Struktur*" + } + } } }, "syntax": "Bitte nutze /{0}", @@ -2604,208 +2736,18 @@ "Speichere vorm verlassen manuell /db save customs", " " ], - "custom-main-view-challenges": "Challenges Ansehen", - "custom-main-create-challenge": "Challenge Erstellen", - "custom-title-trigger": "Auslöser", - "custom-title-action": "Aktion", "custom-title-view": "Gespeichert", "custom-sub-finish": "Fertig", - "item-custom-info-delete": [ - "Löschen", - "*Achtung* diese Aktion kann *nicht*", - "rückgängig gemacht werden" - ], - "item-custom-info-save": "Speichern", - "item-custom-info-trigger": [ - "Auslöser", - "*Klicke* um einzustellen, was passieren", - "muss, damit die *Aktion* ausgeführt wird" - ], - "item-custom-info-action": [ - "Aktion", - "*Klicke* um einzustellen, was passieren", - "soll, wenn der *Auslöser* erfüllt ist" - ], - "item-custom-info-material": [ - "Anzeige Item", - "*Klicke* um das Anzeigeitem zu ändern" - ], - "item-custom-info-name": [ - "Name", - "*Klicke* um den Namen über den Chat zu ändern", - "Maximale Zeichenanzahl: 50" - ], - "custom-info-currently": "Eingestellt » ", - "custom-info-trigger": "Auslöser", - "custom-info-action": "Aktion", - "item-custom-action-command": [ - "Command Ausführen", - "Lasse Spieler einen Command ausführen lassen", - "Die Commands werden für Spieler mit */execute as* von", - "der Konsole ausgeführt.", - "Erlaubte Commands werden in der Config eingestellt.", - "Der Spieler braucht *keine Rechte* auf den Command haben.", - "Spieler können *keine Plugin Commands* ausführen." - ], - "item-custom-action-kill": [ - "Töten", - "Töte Entities" - ], - "item-custom-action-damage": [ - "Schaden", - "Füge Entities Schaden zu" - ], - "item-custom-action-heal": [ - "Heilen", - "Heile Entities" - ], - "item-custom-action-hunger": [ - "Hunger", - "Füge Spielern Hunger hinzu" - ], - "item-custom-action-max_health": [ - "Maximale Leben Verändern", - "Verändere die Maximalen Leben von Spielern", - "Wird mit einem */gamestate reset* zurückgesetzt" - ], "item-custom-action-max_health-offset": [ "Veränderung", "Wähle aus wie viele Leben verändert werden sollen" ], - "item-custom-action-spawn_entity": [ - "Entity Spawnen", - "Spawne ein Entity bestimmten Types" - ], - "item-custom-action-random_mob": [ - "Zufälliges Entity", - "Spawne ein zufälliges Entity" - ], - "item-custom-action-random_item": [ - "Zufälliges Item", - "Gebe Spielern zufällige Items" - ], - "item-custom-action-uncraft_inventory": [ - "Inventar Zurück-Craften", - "Lasse das Inventar von Spielern Zurück-Craften" - ], - "item-custom-action-boost_in_air": [ - "In Luft Schleudern", - "Schleudere Entities in die Luft" - ], "item-custom-action-boost_in_air-strength": [ "Stärke" ], - "item-custom-action-potion_effect": [ - "Trank Effekt", - "Gebe Entities einen bestimmten Trank Effekt" - ], - "item-custom-action-permanent_effect": [ - "Permanenten Trank Effekt", - "Füge Spieler einen Permanenten Effekt hinzu.", - "Die Aktion nutzt die Einstellungen", - "von der Permanenten Effekt Challenge." - ], - "item-custom-action-random_effect": [ - "Zufälliger Trank Effekt", - "Gebe Entities einen zufälligen Trank Effekt" - ], - "item-custom-action-clear_inventory": [ - "Inventar Leeren", - "Leere das Inventar von Spielern komplett" - ], - "item-custom-action-drop_random_item": [ - "Item Aus Inventar Droppen", - "Droppe ein Item aus dem Inventar auf den Boden" - ], - "item-custom-action-remove_random_item": [ - "Item Aus Inventar Entfernen", - "Entferne ein Item aus dem Inventar" - ], - "item-custom-action-swap_random_item": [ - "Items Im Inventar Tauschen", - "Tausche zwei Item im Inventar" - ], - "item-custom-action-freeze": [ - "Freeze", - "Friere Mobs Zeitweise ein.", - "Die Aktion nutzt die Einstellungen", - "von der Freeze On Damage Challenge." - ], - "item-custom-action-invert_health": [ - "Invert Health", - "Invertiere die Herzen eines Spielers.", - "Wenn du *8 Herzen* hast,", - "hast du danach *2 Herzen* und umgekehrt." - ], - "item-custom-action-water_mlg": [ - "Water MLG", - "Alle Spieler müssen einen Water MLG machen" - ], - "item-custom-action-win": [ - "Gewinnen", - "Die Challenge wird von *bestimmten Spielern* gewonnen" - ], - "item-custom-action-random_hotbar": [ - "Zufällige Hotbar", - "Das Inventar wird geleert und der Spieler", - "bekommt zufällige Items in die HotBar" - ], - "item-custom-action-modify_border": [ - "World Border Verändern", - "Mache die Worldborder *größer* oder *kleiner*" - ], "item-custom-action-modify_border-change": [ "Veränderung" ], - "item-custom-action-swap_mobs": [ - "Mobs tauschen", - "Tausche ein Mob mit einem zufälligen", - "anderem Mob aus der gleichen Welt" - ], - "item-custom-action-place_structure": [ - "Struktur Platzieren", - "Platziert eine Struktur" - ], - "item-custom-action-place_structure-random": "Zufällige Struktur", - "item-custom-setting-target-current": [ - "Aktives Entity", - "Die Aktion wird für das *aktive Entity* ausgeführt" - ], - "item-custom-setting-target-every_mob": [ - "Alle Mobs", - "Die Aktion wird für *alle Mobs* ausgeführt" - ], - "item-custom-setting-target-every_mob_except_current": [ - "Alle Mobs Außer Aktives", - "Die Aktion wird für *alle Mobs*", - "*außer* das Aktive ausgeführt ausgeführt" - ], - "item-custom-setting-target-every_mob_except_players": [ - "Alle Mobs Außer Spieler", - "Die Aktion wird für *alle Mobs*", - "*außer* Spieler ausgeführt" - ], - "item-custom-setting-target-random_player": [ - "Zufälliger Spieler", - "Die Aktion wird für einen *zufälligen Spieler* ausgeführt" - ], - "item-custom-setting-target-every_player": [ - "Alle Spieler", - "Die Aktion wird für *jeden Spieler* ausgeführt" - ], - "item-custom-setting-target-current_player": [ - "Aktiver Spieler", - "Die Aktion wird für den *aktiven Spieler* ausgeführt", - "Wenn das Entity kein Spieler ist, wird nichts passieren" - ], - "item-custom-setting-target-console": [ - "Konsole", - "Die Aktion wird für die *Konsole* ausgeführt" - ], - "item-custom-setting-entity_type-any": "Jegliches Entity", - "item-custom-setting-entity_type-player": "Spieler", - "item-custom-setting-block-any": "Jeglicher Block", - "item-custom-setting-item-any": "Jegliches Item", "custom-subsetting-target_entity": "Ziel Entity", "custom-subsetting-entity_type": "Entity Typ", "custom-subsetting-liquid": "Flüssigkeit", diff --git a/language/locales/global.json b/language/locales/global.json index bc800584a..70d30aebf 100644 --- a/language/locales/global.json +++ b/language/locales/global.json @@ -81,7 +81,7 @@ "title-format": "{@title-prefix}{@title-colored('{0}')}", "title-format-page": "{@title-format('{0}')}{@title-delimiter}{@title-colored('{1}')}", "title-name-format-sub": "{@title-colored('{0}')}{@title-delimiter}{@title-colored('{1}')}", - "item-format": "{@symbol.arrow} {0}", + "item-format": "{@symbol.arrow} {0}", "goal": { "display": "{@name}" }, @@ -706,8 +706,26 @@ "get-full-health": { "*colorize*": "{0}" }, + "force-battles": { + "sub": { + "goal-jokers": { + "*colorize*": "{0}" + }, + "scoreboard": { + "*colorize*": "{0}" + }, + "duped-targets": { + "*colorize*": "{0}" + } + } + }, "force-item-battle": { - "*colorize*": "{0}" + "*colorize*": "{0}", + "sub": { + "give-item": { + "*colorize*": "{0}" + } + } }, "force-mob-battle": { "*colorize*": "{0}" @@ -716,7 +734,12 @@ "*colorize*": "{0}" }, "force-block-battle": { - "*colorize*": "{0}" + "*colorize*": "{0}", + "sub": { + "give-block": { + "*colorize*": "{0}" + } + } }, "force-biome-battle": { "*colorize*": "{0}" @@ -855,6 +878,9 @@ "damage": { "*colorize*": "{0}" }, + "damage_by_player": { + "*colorize*": "{0}" + }, "block_place": { "*colorize*": "{0}" }, @@ -877,7 +903,7 @@ "*colorize*": "{0}" }, "move_down": { - "*colorize*": "{0}" + "*colorize*": "{0}" }, "move_up": { "*colorize*": "{0}" @@ -992,6 +1018,68 @@ "jnr": { "*colorize*": "{0}" } + }, + "setting": { + "interval": { + "*colorize*": "{0}" + }, + "material": { + "format": { + "*colorize*": "{0}", + "name": "*{0}*" + } + }, + "structure_type": { + "format": { + "*colorize*": "{0}", + "name": "*{0}*" + }, + "random": { + "*colorize*": "{0}" + } + }, + "block": { + "any": { + "*colorize*": "{0}" + } + }, + "target": { + "console": { + "*colorize*": "{0}" + }, + "current": { + "*colorize*": "{0}" + }, + "current_player": { + "*colorize*": "{0}" + }, + "random_player": { + "*colorize*": "{0}" + }, + "every_player":{ + "*colorize*": "{0}" + }, + "every_mob": { + "*colorize*": "{0}" + }, + "every_mob_except_current": { + "*colorize*": "{0}" + }, + "every_mob_except_players": { + "*colorize*": "{0}" + } + }, + "liquid": { + "water": { + "*colorize*": "{0}" + }, + "lava": { + "*colorize*": "{0}" + }, + "powder_snow": { + "*colorize*": "{0}" + } + } } } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index 9dde5d698..18e8e2072 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -13,18 +13,25 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.common.config.Document; +import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; +import org.intellij.lang.annotations.RegExp; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.Map.Entry; +import java.util.regex.Pattern; @Getter @ToString public class CustomChallenge extends Setting { + @RegExp + public static final String ALLOWED_NAME_REGEX = "^[A-Za-z0-9()\\[\\]\",.;:'+@#%$!? -]*$"; + public static final Pattern ALLOWED_NAME_PATTERN = Pattern.compile(ALLOWED_NAME_REGEX); + private final UUID uuid; private Material material; private String name; @@ -86,7 +93,8 @@ public ItemBuilder getDisplayItem(@NotNull Locale locale) { @NotNull @Override public LocalizableMessage getChallengeName() { - return LocalizableMessage.wrap(getDisplayName()); + // wrap user input in TextComponent to escape + return LocalizableMessage.wrap(Component.text(getDisplayName())); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java index b9013ff88..dd3f51db4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/ChallengeAction.java @@ -37,12 +37,17 @@ public static Map getMenuItems() { @NotNull @Override public LocalizableMessage getSettingName() { - return MessageKey.of("custom.action." + getRelativeMessageKey() + ".name"); + return getSettingMessageKey("name"); } @NotNull @Override public LocalizableMessage getSettingDescription() { - return MessageKey.of("custom.action." + getRelativeMessageKey() + ".desc"); + return getSettingMessageKey("desc"); + } + + @NotNull + protected LocalizableMessage getSettingMessageKey(@NotNull String keySuffix) { + return MessageKey.of("custom.action." + getRelativeMessageKey() + "." + keySuffix); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java index 743cfa385..6adbaa7ee 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java @@ -7,12 +7,11 @@ import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.translation.Translatable; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Locale; @@ -28,62 +27,57 @@ public interface SelectableKey { @NotNull ItemBuilder getDisplayItem(@NotNull Locale locale); - // TODO rename factories to represent args - - @Contract(pure = true) - static SelectableKey.Option of(@NotNull String key, @NotNull Material displayMaterial, @NotNull LocalizableMessage name) { - return new SelectableKey.Option(key, new ItemStack(displayMaterial), name); - } - - @Contract(pure = true) - static SelectableKey.Option of(@NotNull String key, @NotNull Material displayMaterial, @NotNull Translatable name) { - return new SelectableKey.Option(key, new ItemStack(displayMaterial), name); - } - + @NotNull @Contract(pure = true) - static SelectableKey.Option of(@NotNull String key, @NotNull Material displayMaterial, @NotNull Component name) { - return new SelectableKey.Option(key, new ItemStack(displayMaterial), name); + static SelectableKey.Option of(@NotNull String key, @NotNull ItemStack displayPreset, @NotNull LocalizableMessage name, @Nullable LocalizableMessage description) { + return new SelectableKey.Option(key, displayPreset, name, description); } + @NotNull @Contract(pure = true) - static SelectableKey.Option of(@NotNull String key, @NotNull Material displayMaterial, @NotNull String nameKey, @NotNull Object... nameArgs) { - return of(key, displayMaterial, MessageKey.of(nameKey).withArgs(nameArgs)); + static SelectableKey.Option of(@NotNull String key, @NotNull Material displayMaterial, @NotNull LocalizableMessage name) { + return of(key, new ItemStack(displayMaterial), name); } + @NotNull @Contract(pure = true) static SelectableKey.Option of(@NotNull String key, @NotNull ItemStack displayPreset, @NotNull LocalizableMessage name) { - return new SelectableKey.Option(key, displayPreset, name); + return of(key, displayPreset, name, null); } + @NotNull @Contract(pure = true) - static SelectableKey.Option of(@NotNull String key, @NotNull ItemStack displayPreset, @NotNull Translatable name) { - return new SelectableKey.Option(key, displayPreset, name); + static SelectableKey.Option ofMaterial(@NotNull String key, @NotNull Material material) { + return ofName(key, material, "material.format", material); } + @NotNull @Contract(pure = true) - static SelectableKey.Option of(@NotNull String key, @NotNull ItemStack displayPreset, @NotNull Component name) { - return new SelectableKey.Option(key, displayPreset, name); + static SelectableKey.Option ofName(@NotNull String key, @NotNull Material displayMaterial, @NotNull String nameKey, @NotNull Object... nameArgs) { + String baseKey = "custom.setting." + nameKey; + return of(key, new ItemStack(displayMaterial), MessageKey.of(baseKey + ".name").withArgs(nameArgs), null); } + @NotNull @Contract(pure = true) - static SelectableKey.Option of(@NotNull String key, @NotNull ItemStack displayPreset, @NotNull String nameKey, @NotNull Object... nameArgs) { - return of(key, displayPreset, MessageKey.of(nameKey).withArgs(nameArgs)); + static SelectableKey.Option ofNameDesc(@NotNull String key, @NotNull Material displayMaterial, @NotNull String nameKey, @NotNull Object... nameArgs) { + String baseKey = "custom.setting." + nameKey; + return of(key, new ItemStack(displayMaterial), MessageKey.of(baseKey + ".name").withArgs(nameArgs), MessageKey.of(baseKey + ".desc").withArgs(nameArgs)); } @Getter @RequiredArgsConstructor(access = AccessLevel.PRIVATE) class Option implements SelectableKey { - // TODO DESCRIPTION? - private final String key; private final ItemStack displayItemPreset; - private final Object localizableNameArg; + private final LocalizableMessage localizableName; + private final LocalizableMessage localizableDescription; @NotNull @Override public ItemBuilder getDisplayItem(@NotNull Locale locale) { - return DefaultItems.createMenuDisplayFormat(displayItemPreset, localizableNameArg, locale); + return DefaultItems.createChallengeDisplayFormat(displayItemPreset, localizableName, localizableDescription, locale); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java index 0e510f1ac..006672729 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseItemSubSettingsBuilder.java @@ -41,7 +41,7 @@ public Collection getCurrentDisplayFor(@NotNull Map valueNameArgs = new ArrayList<>(values.length); for (String value : values) { SelectableKey.Option option = settings.get(value); - if (option != null) valueNameArgs.add(option.getLocalizableNameArg()); + if (option != null) valueNameArgs.add(option.getLocalizableName()); } SubSettingDisplay display = new SubSettingDisplay(getKeyTranslation(this.getKey()), LocalizableMessage.joinList(2, valueNameArgs)); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java index 3b03355c9..3cdc03e0e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ChooseMultipleItemSubSettingBuilder.java @@ -40,7 +40,7 @@ public Collection getCurrentDisplayFor(@NotNull Map valueNameArgs = new ArrayList<>(values.length); for (String value : values) { SelectableKey.Option option = settings.get(value); - if (option != null) valueNameArgs.add(option.getLocalizableNameArg()); + if (option != null) valueNameArgs.add(option.getLocalizableName()); } SubSettingDisplay display = new SubSettingDisplay(getKeyTranslation(this.getKey()), LocalizableMessage.joinList(2, valueNameArgs)); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java index 60039ac6b..b21614edf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/ChallengeTrigger.java @@ -34,13 +34,18 @@ public static Map getMenuItems() { @NotNull @Override public LocalizableMessage getSettingName() { - return MessageKey.of("custom.trigger." + getRelativeMessageKey() + ".name"); + return getSettingMessageKey("name"); } @NotNull @Override public LocalizableMessage getSettingDescription() { - return MessageKey.of("custom.trigger." + getRelativeMessageKey() + ".desc"); + return getSettingMessageKey("desc"); + } + + @NotNull + protected LocalizableMessage getSettingMessageKey(@NotNull String keySuffix) { + return MessageKey.of("custom.trigger." + getRelativeMessageKey() + "." + keySuffix); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java index bd05cdbcb..aa5a619c3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/ConsumeItemTrigger.java @@ -9,6 +9,7 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.PlayerItemConsumeEvent; +import org.jetbrains.annotations.NotNull; public class ConsumeItemTrigger extends ChallengeTrigger { @@ -16,12 +17,13 @@ public ConsumeItemTrigger(String name) { super(name, SubSettingsBuilder.createChooseMultipleItem(SubSettingsHelper.ITEM).fill(builder -> { for (Material material : ExperimentalUtils.getMaterials()) { if (material.isEdible()) { - builder.addSetting(SelectableKey.of(material.name(), material, material)); + builder.addSetting(SelectableKey.ofMaterial(material.name(), material)); } } })); } + @NotNull @Override public Material getMaterial() { return Material.COOKED_BEEF; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java index f558b3402..5028d341e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/EntityDamageTrigger.java @@ -26,7 +26,7 @@ public EntityDamageTrigger(String name) { Arrays.asList(PotionEffectType.values())); Collections.shuffle(types, new Random(1)); - builder.addSetting(SelectableKey.of(SubSettingsHelper.ANY, Material.NETHER_STAR, "item-custom-trigger-damange-any")); + builder.addSetting(SelectableKey.ofName(SubSettingsHelper.ANY, Material.NETHER_STAR, "item-custom-trigger-damange-any")); DamageCause[] values = DamageCause.values(); for (int i = 0; i < values.length; i++) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java index 0723a0108..47ff562d1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/InLiquidTrigger.java @@ -5,7 +5,6 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.trigger.ChallengeTrigger; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import org.bukkit.Bukkit; @@ -19,8 +18,8 @@ public class InLiquidTrigger extends ChallengeTrigger { public InLiquidTrigger(String name) { super(name, SubSettingsBuilder.createChooseMultipleItem(SubSettingsHelper.LIQUID).fill(builder -> { - builder.addSetting(SelectableKey.of("LAVA", Material.LAVA_BUCKET, LocalizableMessage.wrap("§cLava"))); - builder.addSetting(SelectableKey.of("WATER", Material.WATER_BUCKET, LocalizableMessage.wrap("§9Water"))); + builder.addSetting(SelectableKey.ofName("LAVA", Material.LAVA_BUCKET, "custom.setting.liquid.lava")); + builder.addSetting(SelectableKey.ofName("WATER", Material.WATER_BUCKET, "custom.setting.liquid.water")); })); Challenges.getInstance().getScheduler().register(this); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java index e6d5fd20d..532cbe37a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/trigger/impl/IntervallTrigger.java @@ -18,23 +18,22 @@ public class IntervallTrigger extends ChallengeTrigger { public IntervallTrigger(@NotNull String name) { super(name, SubSettingsBuilder.createChooseItem("time").fill(builder -> { - builder.addSetting(SelectableKey.of("1", Material.MUSIC_DISC_13, "item-custom-trigger-intervall-second", "1")); - String seconds = "item-custom-trigger-intervall-seconds"; - builder.addSetting(SelectableKey.of("2", Material.MUSIC_DISC_CAT, seconds, "2")); - builder.addSetting(SelectableKey.of("5", Material.MUSIC_DISC_BLOCKS, seconds, "5")); - builder.addSetting(SelectableKey.of("10", Material.MUSIC_DISC_CHIRP, seconds, "10")); - builder.addSetting(SelectableKey.of("20", Material.MUSIC_DISC_FAR, seconds, "20")); - builder.addSetting(SelectableKey.of("30", Material.MUSIC_DISC_MALL, seconds, "30")); - builder.addSetting(SelectableKey.of("60", Material.MUSIC_DISC_MELLOHI, seconds, "60")); - String minutes = "item-custom-trigger-intervall-minutes"; - builder.addSetting(SelectableKey.of("120", Material.MUSIC_DISC_STAL, minutes, "2")); - builder.addSetting(SelectableKey.of("180", Material.MUSIC_DISC_STRAD, minutes, "3")); - builder.addSetting(SelectableKey.of("240", Material.MUSIC_DISC_WARD, minutes, "4")); - builder.addSetting(SelectableKey.of("300", Material.MUSIC_DISC_11, minutes, "5")); + builder.addSetting(SelectableKey.ofName("1", Material.MUSIC_DISC_13, "interval.second", "1")); + builder.addSetting(SelectableKey.ofName("2", Material.MUSIC_DISC_CAT, "interval.seconds", "2")); + builder.addSetting(SelectableKey.ofName("5", Material.MUSIC_DISC_BLOCKS, "interval.seconds", "5")); + builder.addSetting(SelectableKey.ofName("10", Material.MUSIC_DISC_CHIRP, "interval.seconds", "10")); + builder.addSetting(SelectableKey.ofName("20", Material.MUSIC_DISC_FAR, "interval.seconds", "20")); + builder.addSetting(SelectableKey.ofName("30", Material.MUSIC_DISC_MALL, "interval.seconds", "30")); + builder.addSetting(SelectableKey.ofName("60", Material.MUSIC_DISC_MELLOHI, "interval.seconds", "60")); + builder.addSetting(SelectableKey.ofName("120", Material.MUSIC_DISC_STAL, "interval.minutes", "2")); + builder.addSetting(SelectableKey.ofName("180", Material.MUSIC_DISC_STRAD, "interval.minutes", "3")); + builder.addSetting(SelectableKey.ofName("240", Material.MUSIC_DISC_WARD, "interval.minutes", "4")); + builder.addSetting(SelectableKey.ofName("300", Material.MUSIC_DISC_11, "interval.minutes", "5")); })); Challenges.getInstance().getScheduler().register(this); } + @NotNull @Override public Material getMaterial() { return Material.CLOCK; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java index 8cdb170b8..7b66b40a6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ExtremeForceBattleGoal.java @@ -35,18 +35,19 @@ public class ExtremeForceBattleGoal extends ForceBattleDisplayGoal> { + private final BooleanSubSetting giveItemSetting, giveBlockSetting; + public ExtremeForceBattleGoal() { -// super(Message.forName("menu-extreme-force-battle-goal-settings")); super(new ItemStack(Material.BOOK), "extreme-force-battle"); -// registerSetting("give-item", new BooleanSubSetting( -// () -> new LegacyItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), -// false -// )); -// registerSetting("give-block", new BooleanSubSetting( -// () -> new LegacyItemBuilder(Material.CHEST, Message.forName("item-force-block-battle-goal-give-block")), -// false -// )); + giveItemSetting = registerSetting("give-item", new BooleanSubSetting( + new ItemStack(Material.CHEST), MessageKey.of("challenge.force-item-battle.sub.give-item"), + false + )); + giveBlockSetting = registerSetting("give-block", new BooleanSubSetting( + new ItemStack(Material.CHEST), MessageKey.of("challenge.force-block-battle.sub.give-block"), + false + )); } @Override @@ -167,9 +168,9 @@ protected boolean shouldRegisterDupedTargetsSetting() { @Override public void handleJokerUse(Player player) { ForceTarget target = currentTarget.get(player.getUniqueId()); - if (giveItemOnSkip() && target instanceof ItemTarget itemTarget) { + if (shouldGiveItemOnSkip() && target instanceof ItemTarget itemTarget) { InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), itemTarget.getTarget()); - } else if (giveBlockOnSkip() && target instanceof BlockTarget blockTarget) { + } else if (shouldBlockOnSkip() && target instanceof BlockTarget blockTarget) { InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), blockTarget.getTarget()); } super.handleJokerUse(player); @@ -265,12 +266,12 @@ public void onDamage(@NotNull EntityDamageEvent event) { } } - private boolean giveItemOnSkip() { - return getSetting("give-item").getAsBoolean(); + private boolean shouldGiveItemOnSkip() { + return giveItemSetting.getAsBoolean(); } - private boolean giveBlockOnSkip() { - return getSetting("give-block").getAsBoolean(); + private boolean shouldBlockOnSkip() { + return giveBlockSetting.getAsBoolean(); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java index a5e86db9c..734058950 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceAdvancementBattleGoal.java @@ -25,7 +25,6 @@ public class ForceAdvancementBattleGoal extends ForceBattleGoal { public ForceAdvancementBattleGoal() { -// super(Message.forName("menu-force-advancement-battle-goal-settings")); super(new ItemStack(Material.EXPERIENCE_BOTTLE), "force-advancement-battle"); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java index 1155e6a27..ff90d43a2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBiomeBattleGoal.java @@ -19,7 +19,6 @@ public class ForceBiomeBattleGoal extends ForceBattleGoal { public ForceBiomeBattleGoal() { -// super(Message.forName("menu-force-biome-battle-goal-settings")); super(new ItemStack(Material.FILLED_MAP), "force-biome-battle"); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java index b7feb8341..9e325725a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceBlockBattleGoal.java @@ -18,14 +18,15 @@ @Since("2.2.0") public class ForceBlockBattleGoal extends ForceBattleDisplayGoal { + private final BooleanSubSetting giveBlockSetting; + public ForceBlockBattleGoal() { -// super(Message.forName("menu-force-block-battle-goal-settings")); super(new ItemStack(Material.CHEST), "force-block-battle"); -// registerSetting("give-block", new BooleanSubSetting( -// () -> new LegacyItemBuilder(Material.CHEST, Message.forName("item-force-block-battle-goal-give-block")), -// false -// )); + giveBlockSetting = registerSetting("give-block", new BooleanSubSetting( + new ItemStack(Material.CHEST), getChallengeMessageKey("sub.give-block"), + false + )); } @Override @@ -52,7 +53,7 @@ public Message getLeaderboardTitleMessage() { @Override public void handleJokerUse(Player player) { super.handleJokerUse(player); - if (giveBlockOnSkip()) { + if (shouldGiveBlockOnSkip()) { InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), currentTarget.get(player.getUniqueId()).getTarget()); } } @@ -68,8 +69,8 @@ public void checkBlocks() { }); } - private boolean giveBlockOnSkip() { - return getSetting("give-block").getAsBoolean(); + private boolean shouldGiveBlockOnSkip() { + return giveBlockSetting.getAsBoolean(); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java index 99e812b57..4dd5ec687 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java @@ -19,7 +19,6 @@ public class ForceDamageBattleGoal extends ForceBattleGoal { public ForceDamageBattleGoal() { -// super(Message.forName("menu-force-damage-battle-goal-settings")); super(new ItemStack(Material.TOTEM_OF_UNDYING), "force-damage-battle"); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java index e00b26a4b..0bb6edc3b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceHeightBattleGoal.java @@ -18,7 +18,6 @@ public class ForceHeightBattleGoal extends ForceBattleGoal { public ForceHeightBattleGoal() { -// super(Message.forName("menu-force-height-battle-goal-settings")); super(new ItemStack(Material.RABBIT_FOOT), "force-height-battle"); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java index bb63dfc6d..4a9691be5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceItemBattleGoal.java @@ -20,14 +20,15 @@ @Since("2.1.3") public class ForceItemBattleGoal extends ForceBattleDisplayGoal { + private final BooleanSubSetting giveItemSetting; + public ForceItemBattleGoal() { -// super(Message.forName("menu-force-item-battle-goal-settings")); super(new ItemStack(Material.ITEM_FRAME), "force-item-battle"); -// registerSetting("give-item", new BooleanSubSetting( -// () -> new LegacyItemBuilder(Material.CHEST, Message.forName("item-force-item-battle-goal-give-item")), -// false -// )); + giveItemSetting = registerSetting("give-item", new BooleanSubSetting( + new ItemStack(Material.CHEST), getChallengeMessageKey("sub.give-item"), + false + )); } @Override @@ -53,7 +54,7 @@ public Message getLeaderboardTitleMessage() { @Override public void handleJokerUse(Player player) { - if (giveItemOnSkip()) { + if (shouldGiveItemOnSkip()) { InventoryUtils.dropOrGiveItem(player.getInventory(), player.getLocation(), currentTarget.get(player.getUniqueId()).getTarget()); } super.handleJokerUse(player); @@ -83,8 +84,8 @@ public void onPickup(PlayerPickupItemEvent event) { } } - private boolean giveItemOnSkip() { - return getSetting("give-item").getAsBoolean(); + private boolean shouldGiveItemOnSkip() { + return giveItemSetting.getAsBoolean(); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java index b7e9e24c3..ae197d0d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceMobBattleGoal.java @@ -22,7 +22,6 @@ public class ForceMobBattleGoal extends ForceBattleDisplayGoal { public ForceMobBattleGoal() { -// super(Message.forName("menu-force-mob-battle-goal-settings")); super(new ItemStack(Material.BOW), "force-mob-battle"); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java index ef159023e..db0e639d9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.type.abstraction; import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.ForceTarget; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; import net.codingarea.commons.common.config.Document; import org.bukkit.World; @@ -15,6 +16,7 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Objects; @@ -42,6 +44,10 @@ protected void onDisable() { } public void updateDisplayStand(Player player) { + // EntityTeleportEvent may only be triggered synchronously; tested on 26.1.2 + // TODO hotfix; trigger should already only be scheduled sync? + if (ChallengeHelper.runSyncIfConcurrent(() -> updateDisplayStand(player))) return; + ArmorStand armorStand = displayStands.computeIfAbsent(player, player1 -> { World world = player1.getWorld(); ArmorStand entity = (ArmorStand) world diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java index 25323177d..0720ed259 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java @@ -50,20 +50,17 @@ public abstract class ForceBattleGoal> extends MenuGoal public ForceBattleGoal(@NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { super(MenuType.GOAL, SettingCategory.FORCE_BATTLE, displayItemPreset, nameMessageKey); - // TODO ! registerSetting("jokers", new NumberSubSetting( - new ItemStack(Material.BARRIER), MessageKey.of("challenge.force-battle.sub.goal-jokers"), - 1, - 32, - 5 + new ItemStack(Material.BARRIER), MessageKey.of("challenge.force-battles.sub.goal-jokers"), + 1, 32, 5 )); registerSetting("showScoreboard", new BooleanSubSetting( - new ItemStack(Material.BOOK), MessageKey.of("challenge.force-battle.sub.scoreboard"), + new ItemStack(Material.BOOK), MessageKey.of("challenge.force-battles.sub.scoreboard"), true )); if (shouldRegisterDupedTargetsSetting()) { registerSetting("dupedTargets", new BooleanSubSetting( - new ItemStack(Material.PAPER), MessageKey.of("challenge.force-battle.sub.duped-targets"), + new ItemStack(Material.PAPER), MessageKey.of("challenge.force-battles.sub.duped-targets"), true )); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java index 73bf3772f..77ee0c72b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java @@ -51,6 +51,7 @@ public final SubSetting getSetting(@NotNull String name) { public void handleClick(@NotNull ChallengeMenuClickInfo info) { if (isEnabled() && !info.isRightClick() && info.isLowerItemClick()) { openMenu(info); + SoundSample.CLICK.play(info.getPlayer()); } else { super.handleClick(info); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index c2c269833..f7c98aa96 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -61,7 +61,10 @@ public static boolean runSyncIfConcurrent(Runnable task) { if (Bukkit.isPrimaryThread()) { return false; } - Bukkit.getScheduler().runTask(Challenges.getInstance(), task); + Bukkit.getScheduler().callSyncMethod(Challenges.getInstance(), () -> { + task.run(); + return null; + }); return true; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java index bdc24296d..c33ab7af4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java @@ -36,10 +36,10 @@ public static ChooseMultipleItemSubSettingBuilder createEntityTypeSettingsBuilde return SubSettingsBuilder.createChooseMultipleItem(ENTITY_TYPE).fill(builder -> { if (any) { - builder.addSetting(SelectableKey.of(ANY, Material.NETHER_STAR, "item-custom-setting-entity_type-any")); + builder.addSetting(SelectableKey.ofName(ANY, Material.NETHER_STAR, "entity_type.any")); } if (player) { - builder.addSetting(SelectableKey.of("PLAYER", Material.PLAYER_HEAD, "item-custom-setting-entity_type-player")); + builder.addSetting(SelectableKey.ofName("PLAYER", Material.PLAYER_HEAD, "entity_type.player")); } for (EntityType type : EntityType.values()) { if (!type.isSpawnable() || !type.isAlive()) continue; @@ -50,17 +50,17 @@ public static ChooseMultipleItemSubSettingBuilder createEntityTypeSettingsBuilde displayMaterial = Material.STRUCTURE_VOID; } - builder.addSetting(SelectableKey.of(type.name(), displayMaterial, type)); + builder.addSetting(SelectableKey.ofName(type.name(), displayMaterial, "entity_type.format", type)); } }); } public static ChooseMultipleItemSubSettingBuilder createBlockSettingsBuilder() { return SubSettingsBuilder.createChooseMultipleItem(BLOCK).fill(builder -> { - builder.addSetting(SelectableKey.of(ANY, Material.NETHER_STAR, "item-custom-setting-block-any")); + builder.addSetting(SelectableKey.ofName(ANY, Material.NETHER_STAR, "block.any")); for (Material material : ExperimentalUtils.getMaterials()) { if (material.isBlock() && material.isItem() && !BukkitReflectionUtils.isAir(material)) { - builder.addSetting(SelectableKey.of(material.name(), material, material)); + builder.addSetting(SelectableKey.ofMaterial(material.name(), material)); } } }); @@ -68,10 +68,10 @@ public static ChooseMultipleItemSubSettingBuilder createBlockSettingsBuilder() { public static ChooseMultipleItemSubSettingBuilder createItemSettingsBuilder() { return SubSettingsBuilder.createChooseMultipleItem(ITEM).fill(builder -> { - builder.addSetting(SelectableKey.of(ANY, Material.NETHER_STAR, "item-custom-setting-item-any")); + builder.addSetting(SelectableKey.ofName(ANY, Material.NETHER_STAR, "item.any")); for (Material material : ExperimentalUtils.getMaterials()) { if (material.isItem() && !BukkitReflectionUtils.isAir(material)) { - builder.addSetting(SelectableKey.of(material.name(), material, material)); + builder.addSetting(SelectableKey.ofMaterial(material.name(), material)); } } }); @@ -89,22 +89,22 @@ public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean every ChooseItemSubSettingsBuilder builder = SubSettingsBuilder.createChooseItem(TARGET_ENTITY); if (console) { - // TODO generic translation; constant keys? - builder.addSetting(SelectableKey.of("console", Material.COMMAND_BLOCK_MINECART, "item-custom-setting-target-console")); + // TODO constant keys? + builder.addSetting(SelectableKey.ofNameDesc("console", Material.COMMAND_BLOCK_MINECART, "target.console")); } if (!onlyPlayer) { - builder.addSetting(SelectableKey.of("current", Material.DRAGON_HEAD, "item-custom-setting-target-current")); + builder.addSetting(SelectableKey.ofNameDesc("current", Material.DRAGON_HEAD, "target.current")); } - builder.addSetting(SelectableKey.of("current_player", Material.PLAYER_HEAD, "item-custom-setting-target-current_player")); - builder.addSetting(SelectableKey.of("random_player", Material.ZOMBIE_HEAD, "item-custom-setting-target-random_player")); - builder.addSetting(SelectableKey.of("every_player", Material.PLAYER_HEAD, "item-custom-setting-target-every_player")); + builder.addSetting(SelectableKey.ofNameDesc("current_player", Material.PLAYER_HEAD, "target.current_player")); + builder.addSetting(SelectableKey.ofNameDesc("random_player", Material.ZOMBIE_HEAD, "target.random_player")); + builder.addSetting(SelectableKey.ofNameDesc("every_player", Material.PLAYER_HEAD, "target.every_player")); if (everyMob && !onlyPlayer) { - builder.addSetting(SelectableKey.of("every_mob", Material.WITHER_SKELETON_SKULL, "item-custom-setting-target-every_mob")); - builder.addSetting(SelectableKey.of("every_mob_except_current", Material.SKELETON_SKULL, "item-custom-setting-target-every_mob_except_current")); - builder.addSetting(SelectableKey.of("every_mob_except_players", Material.SKELETON_SKULL, "item-custom-setting-target-every_mob_except_players")); + builder.addSetting(SelectableKey.ofNameDesc("every_mob", Material.WITHER_SKELETON_SKULL, "target.every_mob")); + builder.addSetting(SelectableKey.ofNameDesc("every_mob_except_current", Material.SKELETON_SKULL, "target.every_mob_except_current")); + builder.addSetting(SelectableKey.ofNameDesc("every_mob_except_players", Material.SKELETON_SKULL, "target.every_mob_except_players")); } return builder; } @@ -146,9 +146,10 @@ public static SubSettingsBuilder createPotionSettingsBuilder(boolean potionType, public static SubSettingsBuilder createStructureSettingsBuilder() { return SubSettingsBuilder.createChooseItem(STRUCTURE).fill(builder -> { - builder.addSetting(SelectableKey.of("random_structure", Material.STRUCTURE_BLOCK, "item-custom-action-place_structure-random")); + builder.addSetting(SelectableKey.ofName("random_structure", Material.STRUCTURE_BLOCK, "structure_type.random")); for (StructureType structure : StructureType.getStructureTypes().values()) { - builder.addSetting(SelectableKey.of(structure.getName(), StructureUtils.getStructureIcon(structure), StringUtils.getEnumName(structure.getName()))); + builder.addSetting(SelectableKey.ofName(structure.getName(), StructureUtils.getStructureIcon(structure), + "structure_type.format", StringUtils.getEnumName(structure.getName()))); } }); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java index f993d627e..846dfc683 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/ExperimentalUtils.java @@ -1,10 +1,10 @@ package net.codingarea.challenges.plugin.utils.misc; -import io.papermc.paper.world.flag.FeatureDependant; import net.codingarea.challenges.plugin.Challenges; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.EntityType; +import org.jetbrains.annotations.NotNull; import java.util.LinkedList; import java.util.List; @@ -26,19 +26,20 @@ private static void loadMaterials() { World world = Challenges.getInstance().getGameWorldStorage().getWorld(World.Environment.NORMAL); for (Material material : Material.values()) { - try { - FeatureDependant feature = material.isItem() ? material.asItemType() : material.asBlockType(); - if (feature != null && !world.isEnabled(feature)) { - continue; - } - } catch (NoSuchMethodError ignored) { - } // only NoSuchMethodException - + if (!isMaterialFeatureEnabled(material, world)) continue; materials.add(material); } ExperimentalUtils.materials = materials.toArray(new Material[0]); } + private static boolean isMaterialFeatureEnabled(@NotNull Material material, @NotNull World world) { + try { + return FeatureDependentAccessor.isMaterialFeatureEnabled(material, world); + } catch (Throwable _) { + return true; + } + } + public static EntityType[] getEntityTypes() { if (entityTypes == null) { loadEntityTypes(); @@ -51,16 +52,19 @@ private static void loadEntityTypes() { World world = Challenges.getInstance().getGameWorldStorage().getWorld(World.Environment.NORMAL); for (EntityType type : EntityType.values()) { - try { - if (!world.isEnabled(type)) { - continue; - } - } catch (NoSuchMethodError | IllegalArgumentException ignored) { - } // only NoSuchMethodException + if (!isEntityTypeFeatureEnabled(type, world)) continue; entityTypes.add(type); } ExperimentalUtils.entityTypes = entityTypes.toArray(new EntityType[0]); } + private static boolean isEntityTypeFeatureEnabled(@NotNull EntityType entityType, @NotNull World world) { + try { + return FeatureDependentAccessor.isEntityTypeFeatureEnabled(entityType, world); + } catch (Throwable _) { + return true; + } + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FeatureDependentAccessor.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FeatureDependentAccessor.java new file mode 100644 index 000000000..4f19b0fae --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/FeatureDependentAccessor.java @@ -0,0 +1,22 @@ +package net.codingarea.challenges.plugin.utils.misc; + +import io.papermc.paper.world.flag.FeatureDependant; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.entity.EntityType; +import org.jetbrains.annotations.NotNull; + +// io.papermc.paper.world.flag.FeatureDependant was only added in 1.20.2 +// for versions below the import will result in a NoClassDefFoundError +final class FeatureDependentAccessor { + + static boolean isMaterialFeatureEnabled(@NotNull Material material, @NotNull World world) { + FeatureDependant feature = material.isItem() ? material.asItemType() : material.asBlockType(); + return feature == null || world.isEnabled(feature); + } + + static boolean isEntityTypeFeatureEnabled(@NotNull EntityType entityType, @NotNull World world) { + return world.isEnabled(entityType); + } + +} From ef0e8cb8d268a869c604658b2b31562be2d2d6af Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Sun, 12 Jul 2026 01:10:29 +0200 Subject: [PATCH 112/119] refactor: migrate localization usage (part 8) + infinite potion effects --- gradle/libs.versions.toml | 4 --- language/locales/de.json | 31 +++++++++++++++-- language/locales/en.json | 4 ++- language/locales/global.json | 33 ++++++++++++++++--- .../effect/BlockEffectChallenge.java | 3 +- .../effect/ChunkRandomEffectChallenge.java | 8 ++--- .../effect/EntityRandomEffectChallenge.java | 3 +- .../challenge/quiz/QuizChallenge.java | 2 +- .../EntityLootRandomizerChallenge.java | 2 +- .../world/AllBlocksDisappearChallenge.java | 20 +++++------ .../setting/DifficultySetting.java | 2 +- .../setting/LanguageSetting.java | 2 +- .../setting/PlayerGlowSetting.java | 3 +- .../setting/PositionSetting.java | 8 ++--- .../abstraction/ForceBattleDisplayGoal.java | 4 --- .../type/abstraction/menu/MenuSetting.java | 1 + .../i18n/impl/format/MessageFormatter.java | 7 ++-- .../management/server/ServerManager.java | 20 +++++------ .../plugin/spigot/command/BackCommand.java | 2 +- .../spigot/command/ChallengesCommand.java | 2 +- .../spigot/command/DatabaseCommand.java | 4 +-- .../spigot/command/GamemodeCommand.java | 4 +-- .../spigot/command/GamestateCommand.java | 4 +-- .../plugin/spigot/command/InvseeCommand.java | 2 +- .../plugin/spigot/command/SearchCommand.java | 2 +- .../plugin/spigot/command/StatsCommand.java | 2 +- .../plugin/spigot/command/TimeCommand.java | 14 ++++---- .../plugin/spigot/command/TimerCommand.java | 6 ++-- .../plugin/spigot/command/WeatherCommand.java | 4 +-- .../plugin/spigot/command/WorldCommand.java | 6 ++-- .../listener/PlayerConnectionListener.java | 6 ++-- .../utils/bukkit/misc/BukkitStringUtils.java | 1 + .../plugin/utils/misc/PotionEffectUtils.java | 23 +++++++++++++ 33 files changed, 156 insertions(+), 83 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/PotionEffectUtils.java diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 6a036156d..f402b2263 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -7,7 +7,6 @@ spigot = "26.1.2-R0.1-SNAPSHOT" paper = "26.2.build.+" # 1.21.4-R0.1-SNAPSHOT authlib = "1.5.21" -adventure = "4.8.0" protocol-lib = "5.4.0" # utilities @@ -39,9 +38,6 @@ authlib = { group = "com.mojang", name = "authlib", version.ref = "authlib" } protocol-lib = { group = "net.dmulloy2", name = "ProtocolLib", version.ref = "protocol-lib" } -adventure-text-minimessage = { module = "net.kyori:adventure-text-minimessage", version.ref = "adventure" } -adventure-text-serializer-legacy = { module = "net.kyori:adventure-text-serializer-legacy", version.ref = "adventure" } - # utilities slf4j-api = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" } gson = { group = "com.google.code.gson", name = "gson", version.ref = "gson" } diff --git a/language/locales/de.json b/language/locales/de.json index 50745d281..64abecaee 100644 --- a/language/locales/de.json +++ b/language/locales/de.json @@ -188,7 +188,7 @@ ] }, "material": { - "name": "Anzeige-Item", + "name": "Anzeige Item", "format": "{@item-format('{0}')}" } } @@ -1059,7 +1059,24 @@ "Bei verschiedenen *Interaktionen*", "verschwinden alle *Blöcke* im *Chunk*", "eines *bestimmten Types*" - ] + ], + "menu": "Blöcke entfernen", + "sub": { + "break": { + "name": "*Beim abbauen*", + "desc": [ + "Wenn du einen Block *abbaust*, werden", + "*alle Blöcke* des *selben Types zerstört*" + ] + }, + "place": { + "name": "*Beim platzieren*", + "desc": [ + "Wenn du einen Block *platzierst*, werden", + "*alle Blöcke* des *selben Types zerstört*" + ] + } + } }, "anvil-rain": { "name": "*Amboss Regen*", @@ -1899,6 +1916,7 @@ ] }, "command": { + "syntax": "Bitte nutze /{0}", "skip-timer": { "none": "Es ist keine Challenge aktiviert, dessen Timer übersprungen werden könnte", "done": "Die Timer folgender Challenges wurden übersprungen: {0}" @@ -2317,10 +2335,17 @@ "random": { "name": "*Zufällige Struktur*" } + }, + "entity_type": { + "any": { + "name": "*Jegliche Kreatur*" + }, + "player": { + "name": "*Spieler*" + } } } }, - "syntax": "Bitte nutze /{0}", "reload": "Challenges Plugin wird neu geladen...", "reload-failed": "Ein Fehler ist während dem Reload aufgetreten", "reload-success": "Challenges Plugin wurde erfolgreich neu geladen", diff --git a/language/locales/en.json b/language/locales/en.json index d240837dd..e4085ab51 100644 --- a/language/locales/en.json +++ b/language/locales/en.json @@ -11,6 +11,9 @@ "de": "German", "en": "English" }, + "command": { + "syntax": "Please use /{0}" + }, "challenge": { "regeneration": { "name": "*Regeneration*", @@ -1199,7 +1202,6 @@ "bossbar": "{@symbol.arrow} Protection time {@symbol.vertical} {0}s" } }, - "syntax": "Please use /{0}", "reload": "Challenges Plugin is reloading...", "reload-failed": "An error &7occurred while reloading the plugin", "reload-success": "Challenges Plugin successfully reloaded", diff --git a/language/locales/global.json b/language/locales/global.json index 70d30aebf..77154330c 100644 --- a/language/locales/global.json +++ b/language/locales/global.json @@ -61,9 +61,14 @@ }, "timer": { "bar": { - "*colorize*": "{0}", + "up": { + "*colorize*": "{0}" + }, + "down": { + "*colorize*": "{0}" + }, "paused": { - "*colorize*": "{0}" + "*colorize*": "{0}" }, "format": { "seconds": "{mm}:{ss}", @@ -491,7 +496,15 @@ "*colorize*": "{0}" }, "all-blocks-disappear": { - "*colorize*": "{0}" + "*colorize*": "{0}", + "sub": { + "break": { + "*colorize*": "{0}" + }, + "place": { + "*colorize*": "{0}" + } + } }, "anvil-rain": { "*colorize*": "{0}" @@ -1038,6 +1051,18 @@ "*colorize*": "{0}" } }, + "entity_type": { + "any": { + "*colorize*": "{0}" + }, + "player": { + "*colorize*": "{0}" + }, + "format": { + "*colorize*": "{0}", + "name": "*{0}*" + } + }, "block": { "any": { "*colorize*": "{0}" @@ -1056,7 +1081,7 @@ "random_player": { "*colorize*": "{0}" }, - "every_player":{ + "every_player": { "*colorize*": "{0}" }, "every_mob": { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java index 37a8a7223..2f2b3522a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/BlockEffectChallenge.java @@ -10,6 +10,7 @@ import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; +import net.codingarea.challenges.plugin.utils.misc.PotionEffectUtils; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.collection.SeededRandomWrapper; import org.bukkit.Location; @@ -155,7 +156,7 @@ private PotionEffect getEffect(Material material) { IRandom random = new SeededRandomWrapper(seed / material.ordinal()); PotionEffectType[] types = PotionEffectType.values(); PotionEffectType type = types[random.nextInt(types.length)]; - return type.createEffect(Integer.MAX_VALUE, random.nextInt(type.isInstant() ? 1 : 4)); + return type.createEffect(PotionEffectUtils.INFINITE_DURATION, random.nextInt(type.isInstant() ? 1 : 4)); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java index 9f795095f..43c3eb513 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java @@ -7,8 +7,10 @@ import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; +import net.codingarea.challenges.plugin.utils.misc.PotionEffectUtils; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.collection.SeededRandomWrapper; +import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; @@ -90,9 +92,7 @@ public void onTeleport(PlayerTeleportEvent event) { @ScheduledTask(ticks = 20, async = false) public void onSecond() { - broadcastFiltered(player -> { - addEffect(player, player.getLocation()); - }); + broadcastFiltered(player -> addEffect(player, player.getLocation())); } public void removeEffect(Player player, Location location) { @@ -128,7 +128,7 @@ public PotionEffect getEffect(Chunk chunk) { PotionEffectType[] types = PotionEffectType.values(); PotionEffectType type = types[random.nextInt(types.length)]; - return type.createEffect(Integer.MAX_VALUE, random.nextInt(type.isInstant() ? 1 : 4)); + return type.createEffect(PotionEffectUtils.INFINITE_DURATION, random.nextInt(type.isInstant() ? 1 : 4)); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java index e87d8106c..238d75332 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/EntityRandomEffectChallenge.java @@ -5,6 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; +import net.codingarea.challenges.plugin.utils.misc.PotionEffectUtils; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.EntityType; @@ -55,7 +56,7 @@ public void addRandomEffect(LivingEntity entity) { if (entity.getType() == EntityType.PLAYER) return; PotionEffectType[] types = PotionEffectType.values(); PotionEffectType type = globalRandom.choose(types); - entity.addPotionEffect(type.createEffect(Integer.MAX_VALUE, 255)); + entity.addPotionEffect(type.createEffect(PotionEffectUtils.INFINITE_DURATION, 255)); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index 2a1440e01..da20e983c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -184,7 +184,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc } if (args.length == 0) { - MessageKey.of("syntax").send(player, prefix, "guess "); + MessageKey.of("command.syntax").send(player, prefix, "guess "); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java index 763e760a8..160006d0d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/randomizer/EntityLootRandomizerChallenge.java @@ -124,7 +124,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr } if (args.length == 0) { - MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "searchloot "); + MessageKey.of("command.syntax").send(sender, Prefix.CHALLENGES, "searchloot "); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java index e926af2f6..e592ffe57 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AllBlocksDisappearChallenge.java @@ -30,17 +30,17 @@ public class AllBlocksDisappearChallenge extends MenuSetting { private final int stackDropLimit; + private final BooleanSubSetting breakSetting, placeSetting; public AllBlocksDisappearChallenge() { -// super(Message.forName("menu-all-blocks-disappear-challenge-settings")); super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.TNT), "all-blocks-disappear"); -// registerSetting("break", new BooleanSubSetting( -// () -> new LegacyItemBuilder(Material.DIAMOND_PICKAXE, Message.forName("item-all-blocks-disappear-break-challenge")), -// true -// )); -// registerSetting("place", new BooleanSubSetting( -// () -> new LegacyItemBuilder(Material.DIAMOND_BLOCK, Message.forName("item-all-blocks-disappear-place-challenge")) -// )); + breakSetting = registerSetting("break", new BooleanSubSetting( + new ItemStack(Material.DIAMOND_PICKAXE), getChallengeMessageKey("sub.break"), + true + )); + placeSetting = registerSetting("place", new BooleanSubSetting( + new ItemStack(Material.DIAMOND_BLOCK), getChallengeMessageKey("sub.place") + )); Document document = ChallengeConfigHelper.getSettingsDocument(); stackDropLimit = document.contains("all-block-disappear-stack-drop-limit") ? document.getInt("all-block-disappear-stack-drop-limit") : 50; @@ -49,7 +49,7 @@ public AllBlocksDisappearChallenge() { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockBreak(@NotNull BlockBreakEvent event) { if (!shouldExecuteEffect()) return; - if (!getSetting("break").getAsBoolean()) return; + if (!breakSetting.getAsBoolean()) return; if (ignorePlayer(event.getPlayer())) return; PlayerInventory inventory = event.getPlayer().getInventory(); event.setDropItems(false); @@ -59,7 +59,7 @@ public void onBlockBreak(@NotNull BlockBreakEvent event) { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPlace(@NotNull BlockPlaceEvent event) { if (!shouldExecuteEffect()) return; - if (!getSetting("place").getAsBoolean()) return; + if (!placeSetting.getAsBoolean()) return; if (ignorePlayer(event.getPlayer())) return; if (event.getBlockAgainst().getType() == Material.BEDROCK) return; if (event.getBlockAgainst().getType() == Material.END_PORTAL) return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java index 7d28de2a0..4c7b17b27 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/DifficultySetting.java @@ -98,7 +98,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr int difficulty = getDifficultyValue(args[0]); if (difficulty == -1) { - MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "difficulty "); + MessageKey.of("command.syntax").send(sender, Prefix.CHALLENGES, "difficulty "); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java index bf61ab083..28ea899b6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java @@ -114,7 +114,7 @@ public void writeSettings(@NotNull Document document) { @Override public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (args.length < 1) { - MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "setlang "); + MessageKey.of("command.syntax").send(sender, Prefix.CHALLENGES, "setlang "); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java index 6bad8e255..88f7f8659 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PlayerGlowSetting.java @@ -6,6 +6,7 @@ import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; +import net.codingarea.challenges.plugin.utils.misc.PotionEffectUtils; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerJoinEvent; @@ -37,7 +38,7 @@ public void updateEffects() { broadcast(player -> player.removePotionEffect(PotionEffectType.GLOWING)); return; } - broadcast(player -> player.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, Integer.MAX_VALUE, 1, true, false, false))); + broadcast(player -> player.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, PotionEffectUtils.INFINITE_DURATION, 1, true, false, false))); } @EventHandler diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java index ceb40be2b..1e8a067d8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java @@ -93,7 +93,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) { } } else { - MessageKey.of("syntax").send(player, Prefix.POSITION, "position [name]"); + MessageKey.of("command.syntax").send(player, Prefix.POSITION, "position [name]"); } } @@ -204,7 +204,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc } } else { - MessageKey.of("syntax").send(player, Prefix.POSITION, "delposition "); + MessageKey.of("command.syntax").send(player, Prefix.POSITION, "delposition "); } } @@ -234,7 +234,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc } if (args.length < 5) { - MessageKey.of("syntax").send(player, Prefix.POSITION, "setposition "); + MessageKey.of("command.syntax").send(player, Prefix.POSITION, "setposition "); return; } @@ -267,7 +267,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc broadcastParticleLine(position); } catch (Exception exception) { - MessageKey.of("syntax").send(player, Prefix.POSITION, "setposition "); + MessageKey.of("command.syntax").send(player, Prefix.POSITION, "setposition "); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java index db0e639d9..517b1f07d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleDisplayGoal.java @@ -44,10 +44,6 @@ protected void onDisable() { } public void updateDisplayStand(Player player) { - // EntityTeleportEvent may only be triggered synchronously; tested on 26.1.2 - // TODO hotfix; trigger should already only be scheduled sync? - if (ChallengeHelper.runSyncIfConcurrent(() -> updateDisplayStand(player))) return; - ArmorStand armorStand = displayStands.computeIfAbsent(player, player1 -> { World world = player1.getWorld(); ArmorStand entity = (ArmorStand) world diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java index 77ee0c72b..1eca73ce7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java @@ -43,6 +43,7 @@ protected final T registerSetting(@NotNull String name, @ return setting; } + @Nullable public final SubSetting getSetting(@NotNull String name) { return settings.get(name); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/MessageFormatter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/MessageFormatter.java index 09fab53b1..f6e3cf2a3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/MessageFormatter.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/MessageFormatter.java @@ -245,7 +245,7 @@ private static String[] extractSubDocumentPath(@NotNull String key) { @NotNull @CheckReturnValue - public static String[] embedPositionalArgs(@NotNull String[] origin, @NotNull Object[] args) { + public static String[] embedPositionalArgs(@NotNull String[] origin, @Nullable Object[] args) { String[] result = new String[origin.length]; for (int i = 0; i < origin.length; i++) { result[i] = embedPositionalArgs(origin[i], args); @@ -255,7 +255,7 @@ public static String[] embedPositionalArgs(@NotNull String[] origin, @NotNull Ob @NotNull @CheckReturnValue - public static String embedPositionalArgs(@NotNull String sequence, Object[] args) { + public static String embedPositionalArgs(@NotNull String sequence, @Nullable Object[] args) { if (args.length == 0) return sequence; // faster (maybe more error-prone) impl than regex matching @@ -339,7 +339,8 @@ private static void colorize(@NotNull String[] value, @NotNull String[] originSu if (c == COLORIZE_CHAR) { if (colorizing) { colorizing = false; - String[] embeddedColorized = embedPositionalArgs(colorizeValue, new Object[]{argument.toString()}); + // hotfix: null value in arra to allow {1} in *colorize* for gradient phase; more robust solution required + String[] embeddedColorized = embedPositionalArgs(colorizeValue, new Object[]{argument.toString(), null}); for (String s : embeddedColorized) { builder.append(s); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java index dd55325bf..3a9014547 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java @@ -62,16 +62,16 @@ public boolean hasCheated() { } public void endChallenge(@NotNull ChallengeEndCause endCause, Supplier> winnerGetter) { -// if (!Bukkit.isPrimaryThread()) { // TODO -// // calling end challenge logic async results in all kinds of issues as bukkit/paper does not allow certain actions -// // to be performed async (in some versions): PlayerGameModeChangeEvent may only be triggered synchronously -// Logger.debug("End challenge called from async thread, scheduling sync task (Caller: {}", ReflectionUtils.getCallerName(1)); -// Bukkit.getScheduler().callSyncMethod(Challenges.getInstance(), (Callable) () -> { -// endChallenge(endCause, winnerGetter); -// return null; -// }); -// return; -// } + if (!Bukkit.isPrimaryThread()) { + // calling end challenge logic async results in all kinds of issues as bukkit/paper does not allow certain actions + // to be performed async (in some versions): PlayerGameModeChangeEvent may only be triggered synchronously + Logger.debug("End challenge called from async thread, scheduling sync task (Caller: {}", ReflectionUtils.getCallerName(1)); + Bukkit.getScheduler().callSyncMethod(Challenges.getInstance(), () -> { + endChallenge(endCause, winnerGetter); + return null; + }); + return; + } if (ChallengeAPI.isPaused()) { Logger.warn("{} tried to end challenge while timer was paused", ReflectionUtils.getCallerName(1)); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java index 6a8f3fccf..c3403b8c2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/BackCommand.java @@ -39,7 +39,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc count = Integer.parseInt(args[0]); } } catch (NumberFormatException formatException) { - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "back [count]"); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "back [count]"); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java index e05df3646..5b2e559f3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/ChallengesCommand.java @@ -20,7 +20,7 @@ public class ChallengesCommand implements PlayerCommand, Completer { @Override public void onCommand(@NotNull Player player, @NotNull String[] args) { if (args.length > 1) { - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "challenges [menu]"); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "challenges [menu]"); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java index 5a3b913d8..adcc92e97 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/DatabaseCommand.java @@ -101,7 +101,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc } if (args.length != 2 || !databaseExecutors.containsKey(args[1])) { - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "database "); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "database "); return; } @@ -119,7 +119,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc executor.reset(player); break; default: - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "database "); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "database "); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java index 4370eac09..f7a6954b2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamemodeCommand.java @@ -22,14 +22,14 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr List targets = new ArrayList<>(); if (args.length == 0) { - MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); + MessageKey.of("command.syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); return; } GameMode gamemode = getGameMode(args[0]); if (gamemode == null) { - MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); + MessageKey.of("command.syntax").send(sender, Prefix.CHALLENGES, "gm [player]"); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java index 4f6056d05..9acda7399 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/GamestateCommand.java @@ -20,7 +20,7 @@ public class GamestateCommand implements SenderCommand, Completer { public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (args.length != 1) { - MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "gamestate "); + MessageKey.of("command.syntax").send(sender, Prefix.CHALLENGES, "gamestate "); return; } @@ -38,7 +38,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr MessageKey.of("command-gamestate-reload").send(sender, Prefix.CHALLENGES); break; default: - MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "gamestate "); + MessageKey.of("commmand.syntax").send(sender, Prefix.CHALLENGES, "gamestate "); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java index 31e868946..0ce07b1dd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/InvseeCommand.java @@ -46,7 +46,7 @@ public class InvseeCommand implements PlayerCommand, Listener { public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (args.length < 1) { - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "invsee "); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "invsee "); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java index a8102eb5d..d0d0ca502 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java @@ -29,7 +29,7 @@ public class SearchCommand implements SenderCommand, Completer { public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) throws Exception { if (args.length == 0) { - MessageKey.of("syntax").send(sender, Prefix.CHALLENGES, "search "); + MessageKey.of("command.syntax").send(sender, Prefix.CHALLENGES, "search "); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java index 4228b40e2..d144a0632 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/StatsCommand.java @@ -58,7 +58,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) { handleCommand(player, args[0]); break; default: - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "stats [player]"); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "stats [player]"); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java index 8e6f82bdf..c70940361 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimeCommand.java @@ -32,7 +32,7 @@ public TimeCommand() { public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (args.length == 0) { - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "time "); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "time "); return; } World world = player.getWorld(); @@ -52,12 +52,12 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc break; case "set": { if (args.length == 1) { - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "time set "); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "time set "); break; } long time = getTime(args[1]); if (time < 0) { - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "time set "); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "time set "); break; } world.setTime(time); @@ -72,12 +72,12 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc } case "add": { if (args.length == 1) { - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "time add "); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "time add "); break; } long time = getLongFromString(args[1]); if (time < 0) { - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "time add "); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "time add "); break; } player.performCommand("time set " + (world.getTime() + time)); @@ -85,12 +85,12 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc } case "subtract": { if (args.length == 1) { - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "time subtract "); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "time subtract "); break; } long time = getLongFromString(args[1]); if (time < 0) { - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "time subtract "); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "time subtract "); break; } player.performCommand("time set " + (world.getTime() - time)); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java index eef1644f9..333959068 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/TimerCommand.java @@ -35,7 +35,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { switch (args[0].toLowerCase()) { default: - MessageKey.of("syntax").send(sender, Prefix.TIMER, "timer "); + MessageKey.of("command.syntax").send(sender, Prefix.TIMER, "timer "); return; case "resume": case "start": @@ -74,7 +74,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { break; case "mode": if (args.length != 2) { - MessageKey.of("syntax").send(sender, Prefix.TIMER, "timer mode "); + MessageKey.of("command.syntax").send(sender, Prefix.TIMER, "timer mode "); break; } switch (args[1].toLowerCase()) { @@ -88,7 +88,7 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) { Challenges.getInstance().getChallengeTimer().setCountingUp(false); break; default: - MessageKey.of("syntax").send(sender, Prefix.TIMER, "timer mode "); + MessageKey.of("command.syntax").send(sender, Prefix.TIMER, "timer mode "); break; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java index 77608b975..48e67934f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WeatherCommand.java @@ -20,7 +20,7 @@ public class WeatherCommand implements PlayerCommand, Completer { public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (args.length == 0) { - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "weather "); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "weather "); return; } @@ -45,7 +45,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc MessageKey.of("command-weather-set-thunder").send(player, Prefix.CHALLENGES); break; default: - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "weather "); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "weather "); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java index 01f79761b..b27f4baeb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/WorldCommand.java @@ -25,7 +25,7 @@ public class WorldCommand implements PlayerCommand, TabCompleter { public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exception { if (args.length < 1) { - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "world "); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "world "); return; } @@ -35,13 +35,13 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc boolean targetIsVoidMap = worldName.equalsIgnoreCase("void"); if (environment == null && !targetIsVoidMap) { - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "world "); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "world "); return; } World world = targetIsVoidMap ? Challenges.getInstance().getGameWorldStorage().getOrCreateVoidWorld() : ChallengeAPI.getGameWorld(environment); if (world == null) { - MessageKey.of("syntax").send(player, Prefix.CHALLENGES, "world "); + MessageKey.of("command.syntax").send(player, Prefix.CHALLENGES, "world "); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java index e740ea614..9846329ec 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/PlayerConnectionListener.java @@ -139,10 +139,10 @@ public void onQuit(@NotNull PlayerQuitEvent event) { DatabaseHelper.clearCache(event.getPlayer().getUniqueId()); if (Challenges.getInstance().getWorldManager().isShutdownBecauseOfReset()) { - event.setQuitMessage(null); + event.quitMessage(null); } else if (messages) { - event.setQuitMessage(null); - MessageKey.of("quit-message").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + event.quitMessage(null); + MessageKey.of("quit-message").broadcast(Prefix.CHALLENGES, event.getPlayer()); } } catch (Exception exception) { Challenges.getInstance().getILogger().error("Error while handling disconnect", exception); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java index ddf90965e..e7e7aa578 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/bukkit/misc/BukkitStringUtils.java @@ -21,6 +21,7 @@ import java.util.concurrent.Callable; import java.util.function.Supplier; +@Deprecated public class BukkitStringUtils { @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/PotionEffectUtils.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/PotionEffectUtils.java new file mode 100644 index 000000000..9eab9de55 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/misc/PotionEffectUtils.java @@ -0,0 +1,23 @@ +package net.codingarea.challenges.plugin.utils.misc; + +import org.bukkit.potion.PotionEffect; + +public final class PotionEffectUtils { + + private PotionEffectUtils() { + } + + public static final int INFINITE_DURATION; + + static { + int value; + try { + // introduced in 1.19.4 + value = PotionEffect.INFINITE_DURATION; + } catch (Error _) { + value = Integer.MAX_VALUE; + } + INFINITE_DURATION = value; + } + +} From 04a4506ded80d70fe9ed3b79c49c0987cbd8fcfa Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Sun, 12 Jul 2026 01:58:05 +0200 Subject: [PATCH 113/119] fix: scheduler synchronization issue introduced by 4d7b53c --- .../plugin/management/scheduler/AbstractTaskConfig.java | 6 ++++++ .../plugin/management/scheduler/ScheduledTaskConfig.java | 2 +- .../plugin/management/scheduler/TimerTaskConfig.java | 2 ++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java index 793f86dc9..f12b6816d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/AbstractTaskConfig.java @@ -1,8 +1,14 @@ package net.codingarea.challenges.plugin.management.scheduler; +import lombok.EqualsAndHashCode; import lombok.Getter; +// EqualsAndHashCode over `async` is intentional and load-bearing: subclass configs are used as +// map keys to look up the shared task executor. If two configs at the same rate but different +// thread affinity (sync vs async) compared equal, a sync task could be dispatched onto the async +// executor (or vice versa). See ScheduledTaskConfig#callSuper. @Getter +@EqualsAndHashCode public abstract class AbstractTaskConfig { protected final boolean async; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java index 73141a1a4..1f6e6d78b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/ScheduledTaskConfig.java @@ -6,7 +6,7 @@ import org.jetbrains.annotations.NotNull; @Getter -@EqualsAndHashCode(callSuper = false) +@EqualsAndHashCode(callSuper = true) // MUST include super.async - see AbstractTaskConfig public final class ScheduledTaskConfig extends AbstractTaskConfig { private final int rate; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java index d8ddec095..eb567887f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/scheduler/TimerTaskConfig.java @@ -1,11 +1,13 @@ package net.codingarea.challenges.plugin.management.scheduler; +import lombok.EqualsAndHashCode; import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; import org.jetbrains.annotations.NotNull; import java.util.Arrays; +@EqualsAndHashCode(callSuper = true) // MUST include super.async - see AbstractTaskConfig public final class TimerTaskConfig extends AbstractTaskConfig { private final TimerStatus[] status; From 813cfffbfc7ce599a913a06f28473c76a42e2745 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Sun, 12 Jul 2026 02:34:36 +0200 Subject: [PATCH 114/119] feat: custom challenge name color via ampersand --- .../challenges/custom/CustomChallenge.java | 38 +++++++++++++------ .../effect/ChunkRandomEffectChallenge.java | 1 - .../i18n/impl/format/ComponentFormatter.java | 1 + .../custom/CustomChallengeMenuGenerator.java | 11 ++---- .../management/server/ServerManager.java | 3 +- 5 files changed, 34 insertions(+), 20 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index 18e8e2072..987f9e369 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -10,28 +10,24 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.impl.format.ComponentFormatter; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.common.config.Document; import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; -import org.intellij.lang.annotations.RegExp; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.Map.Entry; -import java.util.regex.Pattern; @Getter @ToString public class CustomChallenge extends Setting { - @RegExp - public static final String ALLOWED_NAME_REGEX = "^[A-Za-z0-9()\\[\\]\",.;:'+@#%$!? -]*$"; - public static final Pattern ALLOWED_NAME_PATTERN = Pattern.compile(ALLOWED_NAME_REGEX); - private final UUID uuid; private Material material; private String name; @@ -40,9 +36,12 @@ public class CustomChallenge extends Setting { private ChallengeAction action; private Map subActions; + private Component cachedNameFormatted; + + @SuppressWarnings("ConstantConditions") // passing null as "displayItemPreset" intentionally public CustomChallenge(MenuType menuType, UUID uuid, Material displayItem, String displayName, ChallengeTrigger trigger, Map subTriggers, ChallengeAction action, Map subActions) { - super(menuType, null, new ItemStack(Material.BARRIER), "custom-challenge"); + super(menuType, null, null, "custom-challenge"); this.uuid = uuid; this.material = displayItem; this.name = displayName; @@ -63,7 +62,7 @@ public ItemStack getDisplayItemPreset() { @NotNull @Override public ItemBuilder getDisplayItem(@NotNull Locale locale) { - ItemBuilder item = new ItemBuilder(locale, getDisplayItemPreset(), MessageKey.of("custom.display-format"), name); + ItemBuilder item = new ItemBuilder(locale, getDisplayItemPreset(), MessageKey.of("custom.display-format"), getDisplayName()); // ADDING CONDITION INFO if (getTrigger() != null) { @@ -93,8 +92,7 @@ public ItemBuilder getDisplayItem(@NotNull Locale locale) { @NotNull @Override public LocalizableMessage getChallengeName() { - // wrap user input in TextComponent to escape - return LocalizableMessage.wrap(Component.text(getDisplayName())); + return LocalizableMessage.wrap(getDisplayName()); } @Override @@ -167,6 +165,8 @@ public void applySettings(@NotNull Material material, @NotNull String name, @Not this.subTriggers = subTriggers; this.action = action; this.subActions = subActions; + this.cachedNameFormatted = null; + this.displayItemPreset = null; } public UUID getUniqueId() { @@ -174,14 +174,30 @@ public UUID getUniqueId() { } @NotNull - public String getDisplayName() { + public String getDisplayNameValue() { return name; } + @NotNull + public Component getDisplayName() { + if (cachedNameFormatted != null) return cachedNameFormatted; + return cachedNameFormatted = formatChallengeName(name); + } + @NotNull @Override public String getUniqueName() { return uuid.toString(); } + @NotNull + public static Component formatChallengeName(@NotNull String rawName) { + try { + return ComponentFormatter.LEGACY_AMPERSAND.deserialize(rawName).colorIfAbsent(NamedTextColor.WHITE); + } catch (Exception _) { + // malformatted + return Component.text(rawName).colorIfAbsent(NamedTextColor.WHITE); + } + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java index 43c3eb513..50f1fbabd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java @@ -10,7 +10,6 @@ import net.codingarea.challenges.plugin.utils.misc.PotionEffectUtils; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.collection.SeededRandomWrapper; -import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java index 9b874bbc0..122647883 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java @@ -22,6 +22,7 @@ public final class ComponentFormatter { public static final MiniMessage MINI_MESSAGE = MiniMessage.miniMessage(); public static final LegacyComponentSerializer LEGACY_SECTION = LegacyComponentSerializer.legacySection(); // temp migration impl + public static final LegacyComponentSerializer LEGACY_AMPERSAND = LegacyComponentSerializer.legacyAmpersand(); // custom user input /** * MiniMessage tag name prefix used to insert positional arguments ({@code {0}}, {@code {1}}, ...) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java index c29d11b12..78adc4cd6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java @@ -20,7 +20,6 @@ import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.commons.common.collection.IRandom; import org.bukkit.Bukkit; -import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Player; @@ -62,7 +61,7 @@ public CustomChallengeMenuGenerator(@NotNull CustomChallenge customChallenge) { this.menuType = MenuType.CUSTOM; this.uuid = customChallenge.getUniqueId(); this.material = customChallenge.getMaterial(); - this.name = customChallenge.getDisplayName(); + this.name = customChallenge.getDisplayNameValue(); this.trigger = customChallenge.getTrigger(); this.subTriggers = customChallenge.getSubTriggers(); this.action = customChallenge.getAction(); @@ -80,8 +79,7 @@ public CustomChallengeMenuGenerator() { this.subActions = new HashMap<>(); this.uuid = UUID.randomUUID(); this.material = IRandom.threadLocal().choose(CustomChooseMaterialMenuGenerator.MATERIALS); - this.name = "§7Custom §e#" + - (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() + 1); + this.name = "&7Custom &e#" + (Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().size() + 1); } @NotNull @@ -125,10 +123,9 @@ public void updateInventoryContent(@NotNull Inventory inventory, @NotNull Locale MessageKey.of("menu.custom.info.item-material"), material != null ? material : MessageKey.of("generic.none")).build()); // Name Item - // TODO escape, format? int maxNameLength = Challenges.getInstance().getCustomChallengesLoader().getMaxNameLength(); inventory.setItem(NAME_SLOT, new ItemBuilder(locale, Material.NAME_TAG, MessageKey.of("menu.custom.info.item-name"), - name, maxNameLength).build()); + CustomChallenge.formatChallengeName(name), maxNameLength).build()); } protected void appendSubSettingDisplay(@NotNull ItemBuilder item, @NotNull Collection display) { @@ -228,7 +225,7 @@ public boolean handleMenuClick(@NotNull MenuClickInfo info) { return; } Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - setName(ChatColor.translateAlternateColorCodes('&', event.getMessage())); + setName(event.getMessage()); openMenu(event.getPlayer()); }); }); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java index 3a9014547..d12a547a2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/server/ServerManager.java @@ -18,6 +18,7 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.LinkedList; import java.util.List; @@ -127,7 +128,7 @@ private void dropItems(@NotNull Player player) { player.getInventory().clear(); } - private void dropItems(@NotNull Location location, @NotNull ItemStack[] items) { + private void dropItems(@NotNull Location location, @Nullable ItemStack[] items) { for (ItemStack item : items) { if (item == null) continue; if (BukkitReflectionUtils.isAir(item.getType())) continue; From 88489cebe5c10e6cb12d2f39efc1188840e33d6d Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Sun, 12 Jul 2026 03:12:05 +0200 Subject: [PATCH 115/119] feat: chat input handlers with modern paper event + cancelable --- language/locales/de.json | 9 ++- .../challenges/plugin/Challenges.java | 2 +- .../action/impl/ExecuteCommandAction.java | 10 ++-- .../settings/sub/SubSettingsBuilder.java | 7 +-- .../builder/TextInputSubSettingsBuilder.java | 55 ++++++++++++------- .../custom/CustomChallengeMenuGenerator.java | 38 ++++++++----- .../command/CancelChatInputCommand.java | 27 +++++++++ .../spigot/listener/ChatInputListener.java | 43 --------------- .../commons/bukkit/core/BukkitModule.java | 4 +- .../bukkit/utils/chat/ChatInputHandler.java | 46 ++++++++++++++++ .../bukkit/utils/chat/ChatInputListener.java | 35 ++++++++++++ .../bukkit/utils/menu/MenuPosition.java | 2 +- .../utils/menu/MenuPositionListener.java | 4 ++ plugin/src/main/resources/plugin.yml | 3 + 14 files changed, 195 insertions(+), 90 deletions(-) create mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/CancelChatInputCommand.java delete mode 100644 plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/chat/ChatInputHandler.java create mode 100644 plugin/src/main/java/net/codingarea/commons/bukkit/utils/chat/ChatInputListener.java diff --git a/language/locales/de.json b/language/locales/de.json index 64abecaee..abbbc4250 100644 --- a/language/locales/de.json +++ b/language/locales/de.json @@ -185,6 +185,10 @@ "Maximale Zeichenanzahl: {1}", " ", "{@selected-format}" + ], + "name-info": [ + "Schreibe den Namen der Challenge in den Chat", + "Klicke hier um die Eingabe abzubrechen" ] }, "material": { @@ -1920,6 +1924,10 @@ "skip-timer": { "none": "Es ist keine Challenge aktiviert, dessen Timer übersprungen werden könnte", "done": "Die Timer folgender Challenges wurden übersprungen: {0}" + }, + "cancel-input": { + "none": "Es gibt keine Chateingabe, die du abbrechen könntest", + "done": "Die Chateingabe wurde abgebrochen" } }, "challenge-end": { @@ -2745,7 +2753,6 @@ "Achtung: Alte Einstellungen werden dabei überschrieben!" ], "custom-no-changes": "Du hast an der Challenge keine Änderungen gemacht", - "custom-name-info": "Schreibe den Namen der Challenge in den Chat", "custom-command-info": [ "Schreibe den Command den der Spieler ausführen soll ohne / in den Chat", "Erlaubte Commands: {0}", diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java index 99bc9ac2d..07c7a5562 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/Challenges.java @@ -174,6 +174,7 @@ private void registerCommands() { registerCommand(new ResultCommand(), "result"); registerCommand(new SkipTimerCommand(), "skiptimer"); registerListenerCommand(new GodModeCommand(), "godmode"); + registerCommand(new CancelChatInputCommand(), "cancelinput"); } private void registerListeners() { @@ -185,7 +186,6 @@ private void registerListeners() { new BlockDropListener(), new CustomEventListener(), new HelpListener(), - new ChatInputListener(), new GeneratorWorldsListener(), new ScoreboardUpdateListener() ); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java index 62228925f..7ed29ce6a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java @@ -22,16 +22,16 @@ public class ExecuteCommandAction extends PlayerTargetAction { public ExecuteCommandAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true, true, true).createTextInputChild("command", player -> { MessageKey.of("custom-command-info").send(player, Prefix.CUSTOM, "/" + String.join(" /", commandsThatCanBeExecuted)); - }, event -> { - String cmd = event.getMessage().split(" ")[0].toLowerCase(); + }, (player, input) -> { + String cmd = input.split(" ")[0].toLowerCase(); if (!commandsThatCanBeExecuted.contains(cmd)) { - MessageKey.of("custom-command-not-allowed").send(event.getPlayer(), Prefix.CUSTOM, cmd); + MessageKey.of("custom-command-not-allowed").send(player, Prefix.CUSTOM, cmd); return false; } - if (event.getMessage().length() > maxCommandLength) { - MessageKey.of("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxCommandLength); + if (input.length() > maxCommandLength) { + MessageKey.of("custom-chars-max_length").send(player, Prefix.CUSTOM, maxCommandLength); return false; } return true; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java index 9c4d0f146..8a1a57b76 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java @@ -7,12 +7,11 @@ import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.entity.Player; -import org.bukkit.event.player.AsyncPlayerChatEvent; import org.jetbrains.annotations.NotNull; import java.util.*; +import java.util.function.BiPredicate; import java.util.function.Consumer; -import java.util.function.Predicate; @Getter public abstract class SubSettingsBuilder { @@ -45,7 +44,7 @@ public static ChooseMultipleItemSubSettingBuilder createChooseMultipleItem(Strin public static TextInputSubSettingsBuilder createTextInput(String key, Consumer onOpen, - Predicate isValid) { + BiPredicate isValid) { return new TextInputSubSettingsBuilder(key, onOpen, isValid); } @@ -148,7 +147,7 @@ public ChooseMultipleItemSubSettingBuilder createChooseMultipleChild(String key) } public TextInputSubSettingsBuilder createTextInputChild(String key, Consumer onOpen, - Predicate isValid) { + BiPredicate isValid) { TextInputSubSettingsBuilder builder = new TextInputSubSettingsBuilder(key, this, onOpen, isValid); this.child = builder; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java index 699b9bc5e..ca14b4f49 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/TextInputSubSettingsBuilder.java @@ -1,37 +1,38 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder; +import io.papermc.paper.event.player.AsyncChatEvent; +import lombok.RequiredArgsConstructor; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; -import net.codingarea.challenges.plugin.spigot.listener.ChatInputListener; import net.codingarea.challenges.plugin.utils.misc.MapUtils; +import net.codingarea.commons.bukkit.utils.chat.ChatInputHandler; import org.bukkit.Bukkit; import org.bukkit.entity.Player; -import org.bukkit.event.player.AsyncPlayerChatEvent; import org.jetbrains.annotations.NotNull; import java.util.*; +import java.util.function.BiPredicate; import java.util.function.Consumer; -import java.util.function.Predicate; public class TextInputSubSettingsBuilder extends SubSettingsBuilder { private final Consumer onOpen; - private final Predicate isValid; + private final BiPredicate isValid; public TextInputSubSettingsBuilder(String key) { this(key, null); } public TextInputSubSettingsBuilder(String key, SubSettingsBuilder parent) { - this(key, parent, event -> { - }, event -> true); + this(key, parent, _ -> { + }, (_, _) -> true); } public TextInputSubSettingsBuilder(String key, Consumer onOpen, - Predicate isValid) { + BiPredicate isValid) { super(key); this.onOpen = onOpen; this.isValid = isValid; @@ -40,7 +41,7 @@ public TextInputSubSettingsBuilder(String key, public TextInputSubSettingsBuilder(String key, SubSettingsBuilder parent, Consumer onOpen, - Predicate isValid) { + BiPredicate isValid) { super(key, parent); this.onOpen = onOpen; this.isValid = isValid; @@ -50,19 +51,7 @@ public TextInputSubSettingsBuilder(String key, public boolean open(Player player, IParentCustomGenerator parentGenerator, LocalizableMessage title) { player.closeInventory(); onOpen.accept(player); - - ChatInputListener.setInputAction(player, event -> { - if (!isValid.test(event)) { - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - parentGenerator.decline(player); - }); - return; - } - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - parentGenerator.accept(player, null, MapUtils.createStringArrayMap(getKey(), event.getMessage())); - }); - }); - + ChatInputHandler.set(player, new TextInputHandler(parentGenerator)); return true; } @@ -86,4 +75,28 @@ public boolean hasSettings() { return true; } + @RequiredArgsConstructor + public class TextInputHandler implements ChatInputHandler { + + private final IParentCustomGenerator parentGenerator; + + @Override + public void handleChatInput(@NotNull AsyncChatEvent event, @NotNull String input) { + if (!isValid.test(event.getPlayer(), input)) { + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + parentGenerator.decline(event.getPlayer()); + }); + return; + } + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + parentGenerator.accept(event.getPlayer(), null, MapUtils.createStringArrayMap(getKey(), input)); + }); + } + + @Override + public void handleCancel(@NotNull Player player) { + parentGenerator.decline(player); + } + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java index 78adc4cd6..b396e5bd6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java @@ -1,5 +1,6 @@ package net.codingarea.challenges.plugin.management.menu.generator.impl.custom; +import io.papermc.paper.event.player.AsyncChatEvent; import lombok.ToString; import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.custom.CustomChallenge; @@ -14,9 +15,9 @@ import net.codingarea.challenges.plugin.management.menu.generator.SinglePageMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.CustomChooseMaterialMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.CustomMainSettingsMenuGenerator; -import net.codingarea.challenges.plugin.spigot.listener.ChatInputListener; import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.chat.ChatInputHandler; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; import net.codingarea.commons.common.collection.IRandom; import org.bukkit.Bukkit; @@ -216,19 +217,9 @@ public boolean handleMenuClick(@NotNull MenuClickInfo info) { return true; } case NAME_SLOT -> { - MessageKey.of("custom-name-info").send(player, Prefix.CUSTOM); + MessageKey.of("menu.custom.info.name-info").send(player, Prefix.CUSTOM); player.closeInventory(); - ChatInputListener.setInputAction(player, event -> { - int maxNameLength = Challenges.getInstance().getCustomChallengesLoader().getMaxNameLength(); - if (event.getMessage().length() > maxNameLength) { - MessageKey.of("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxNameLength); - return; - } - Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { - setName(event.getMessage()); - openMenu(event.getPlayer()); - }); - }); + ChatInputHandler.set(player, new NameChatInputHandler()); return true; } case DELETE_SLOT -> { @@ -266,4 +257,25 @@ public boolean handleMenuClick(@NotNull MenuClickInfo info) { } + public class NameChatInputHandler implements ChatInputHandler { + + @Override + public void handleChatInput(@NotNull AsyncChatEvent event, @NotNull String input) { + int maxNameLength = Challenges.getInstance().getCustomChallengesLoader().getMaxNameLength(); + if (input.length() > maxNameLength) { + MessageKey.of("custom-chars-max_length").send(event.getPlayer(), Prefix.CUSTOM, maxNameLength); + return; + } + Bukkit.getScheduler().runTask(Challenges.getInstance(), () -> { + setName(input); + openMenu(event.getPlayer()); + }); + } + + @Override + public void handleCancel(@NotNull Player player) { + openMenu(player); + } + } + } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/CancelChatInputCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/CancelChatInputCommand.java new file mode 100644 index 000000000..99c0251a7 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/CancelChatInputCommand.java @@ -0,0 +1,27 @@ +package net.codingarea.challenges.plugin.spigot.command; + +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.content.i18n.Prefix; +import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; +import net.codingarea.commons.bukkit.utils.animation.SoundSample; +import net.codingarea.commons.bukkit.utils.chat.ChatInputHandler; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NonNull; + +public class CancelChatInputCommand implements PlayerCommand { + + @Override + public void onCommand(@NotNull Player player, @NonNull @NotNull String[] args) throws Exception { + ChatInputHandler handler = ChatInputHandler.get(player); + if (handler == null) { + MessageKey.of("command.cancel-input.none").send(player, Prefix.CHALLENGES); + return; + } + + SoundSample.BASS_OFF.play(player); + MessageKey.of("command.cancel-input.done").send(player, Prefix.CHALLENGES); + ChatInputHandler.remove(player); + } + +} diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java deleted file mode 100644 index 6596e1b5c..000000000 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/listener/ChatInputListener.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.codingarea.challenges.plugin.spigot.listener; - -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import org.bukkit.event.player.PlayerQuitEvent; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import java.util.function.Consumer; - -public class ChatInputListener implements Listener { - - private static Map> inputActions = new HashMap<>(); - - public ChatInputListener() { - inputActions = new HashMap<>(); - } - - public static void setInputAction(Player player, Consumer event) { - inputActions.put(player.getUniqueId(), event); - } - - @EventHandler(priority = EventPriority.LOW) - public void onChat(AsyncPlayerChatEvent event) { - - Consumer action = inputActions.remove(event.getPlayer().getUniqueId()); - if (action != null) { - action.accept(event); - event.setCancelled(true); - } - - } - - @EventHandler(priority = EventPriority.LOW) - public void onQuit(PlayerQuitEvent event) { - inputActions.remove(event.getPlayer().getUniqueId()); - } - -} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java index e4b3c26b3..4d7eebcf9 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/core/BukkitModule.java @@ -1,5 +1,6 @@ package net.codingarea.commons.bukkit.core; +import net.codingarea.commons.bukkit.utils.chat.ChatInputListener; import net.codingarea.commons.bukkit.utils.menu.MenuPosition; import net.codingarea.commons.bukkit.utils.menu.MenuPositionListener; import net.codingarea.commons.bukkit.utils.misc.CompatibilityUtils; @@ -330,7 +331,8 @@ public final void checkEnabled() { private void registerAsFirstInstance() { getILogger().info(getName() + " was loaded as the first BukkitModule"); registerListener( - new MenuPositionListener() + new MenuPositionListener(), + new ChatInputListener() ); getILogger().info("Detected server version {} -> {}", MinecraftVersion.currentExact(), MinecraftVersion.current()); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/chat/ChatInputHandler.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/chat/ChatInputHandler.java new file mode 100644 index 000000000..3ea9e7d1e --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/chat/ChatInputHandler.java @@ -0,0 +1,46 @@ +package net.codingarea.commons.bukkit.utils.chat; + +import io.papermc.paper.event.player.AsyncChatEvent; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public interface ChatInputHandler { + + final class Holder { + + private Holder() { + } + + static final Map handlers = new ConcurrentHashMap<>(); + + } + + static void set(@NotNull Player player, @Nullable ChatInputHandler handler) { + ChatInputHandler prev = Holder.handlers.put(player, handler); + if (prev != null) { + prev.handleCancel(player); + } + } + + static void remove(@NotNull Player player) { + ChatInputHandler prev = Holder.handlers.remove(player); + if (prev != null) { + prev.handleCancel(player); + } + } + + @Nullable + static ChatInputHandler get(@NotNull Player player) { + return Holder.handlers.get(player); + } + + void handleChatInput(@NotNull AsyncChatEvent event, @NotNull String input); + + default void handleCancel(@NotNull Player player) { + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/chat/ChatInputListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/chat/ChatInputListener.java new file mode 100644 index 000000000..2f79b3aa9 --- /dev/null +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/chat/ChatInputListener.java @@ -0,0 +1,35 @@ +package net.codingarea.commons.bukkit.utils.chat; + +import io.papermc.paper.event.player.AsyncChatEvent; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerQuitEvent; +import org.jetbrains.annotations.NotNull; + +public final class ChatInputListener implements Listener { + + public ChatInputListener() { + ChatInputHandler.Holder.handlers.clear(); + } + + @EventHandler(priority = EventPriority.LOW) + public void onChat(@NotNull AsyncChatEvent event) { + ChatInputHandler handler = ChatInputHandler.get(event.getPlayer()); + if (handler == null) return; + + Component messageComponent = event.message(); + String rawPlayerInput = PlainTextComponentSerializer.plainText().serialize(messageComponent); + handler.handleChatInput(event, rawPlayerInput); + + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onQuit(@NotNull PlayerQuitEvent event) { + ChatInputHandler.remove(event.getPlayer()); + } + +} diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java index 463c74379..6e3d5d6b3 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPosition.java @@ -17,7 +17,7 @@ final class Holder { private Holder() { } - private static final Map positions = new ConcurrentHashMap<>(); + static final Map positions = new ConcurrentHashMap<>(); } diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java index 14de90f78..b3b5eb19c 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/menu/MenuPositionListener.java @@ -14,6 +14,10 @@ public final class MenuPositionListener implements Listener { + public MenuPositionListener() { + MenuPosition.Holder.positions.clear(); + } + @EventHandler(priority = EventPriority.LOW) public void onClick(@NotNull InventoryClickEvent event) { HumanEntity human = event.getWhoClicked(); diff --git a/plugin/src/main/resources/plugin.yml b/plugin/src/main/resources/plugin.yml index a46368c72..cce271cff 100644 --- a/plugin/src/main/resources/plugin.yml +++ b/plugin/src/main/resources/plugin.yml @@ -236,3 +236,6 @@ commands: aliases: - "setlang" - "language" + cancelinput: + usage: "/cancelinput" + description: "Cancels the current chat input" From caca69623c58d9172564ecbbc1f1dbed0674c42b Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Sun, 12 Jul 2026 22:11:29 +0200 Subject: [PATCH 116/119] refactor: migrate localization usage (part 9) --- language/locales/de.json | 29 ++++++++++++++----- .../sub/builder/ValueSubSettingsBuilder.java | 8 ++--- .../damage/SneakDamageChallenge.java | 14 +++------ .../effect/ChunkRandomEffectChallenge.java | 12 ++++++++ .../challenge/force/ForceBlockChallenge.java | 3 +- .../challenge/force/ForceItemChallenge.java | 2 +- .../challenge/force/ForceMobChallenge.java | 2 +- .../miscellaneous/FoodOnceChallenge.java | 6 ++-- .../miscellaneous/NoExpChallenge.java | 2 +- .../movement/DontStopRunningChallenge.java | 2 +- .../challenge/movement/MoveMouseDamage.java | 2 +- .../challenge/movement/OnlyDirtChallenge.java | 2 +- .../challenge/movement/OnlyDownChallenge.java | 2 +- .../movement/TrafficLightChallenge.java | 3 +- .../challenge/quiz/QuizChallenge.java | 20 +++++-------- .../challenge/world/SnakeChallenge.java | 3 +- .../implementation/goal/RaceGoal.java | 3 +- .../setting/PositionSetting.java | 10 ++----- .../abstraction/FirstPlayerAtHeightGoal.java | 3 +- .../type/helper/ChallengeHelper.java | 6 ++++ .../i18n/impl/format/ComponentFormatter.java | 2 +- .../custom/CustomChallengeMenuGenerator.java | 18 ++++++++---- 22 files changed, 86 insertions(+), 68 deletions(-) diff --git a/language/locales/de.json b/language/locales/de.json index abbbc4250..5ab00215e 100644 --- a/language/locales/de.json +++ b/language/locales/de.json @@ -188,12 +188,32 @@ ], "name-info": [ "Schreibe den Namen der Challenge in den Chat", + "Du kannst Farben mit & benutzen", "Klicke hier um die Eingabe abzubrechen" ] }, "material": { "name": "Anzeige Item", "format": "{@item-format('{0}')}" + }, + "action": { + "name": "Aktion" + }, + "trigger": { + "name": "Auslöser" + }, + "save": { + "done": "Challenge wurde lokal gespeichert", + "done-db": [ + "Um in Datenbank zu speichern benutze /db save customs", + "Achtung: Alte Einstellungen werden dabei überschrieben!" + ], + "no-changes": "Du hast an der Challenge keine Änderungen gemacht", + "missing-settings": "Du musst einen Auslöser und Aktion auswählen" + }, + "delete": { + "done": "Die Challenge {0} wurde gelöscht", + "new": "Die Challenge existiert noch nicht" } } }, @@ -323,6 +343,7 @@ }, "challenge": { "settings-modifier-max-health": "Maximale Leben: {0}", + "settings-modifier-damage": "Schaden: {0}", "difficulty": { "name": "*Schwierigkeit*", "desc": [ @@ -2259,7 +2280,7 @@ "setting": { "interval": { "second": { - "name": "*Jede* Sekunde" + "name": "*Jede Sekunde*" }, "seconds": { "name": "*Alle {0} Sekunden*" @@ -2747,12 +2768,6 @@ ], "custom-limit": "Du hast das Limit von {0} Challenges erreicht", "custom-not-deleted": "Diese Challenge existiert noch nicht!", - "custom-saved": "Challenge wurde lokal gespeichert", - "custom-saved-db": [ - "Um in Datenbank zu Speichern benutze /db save customs", - "Achtung: Alte Einstellungen werden dabei überschrieben!" - ], - "custom-no-changes": "Du hast an der Challenge keine Änderungen gemacht", "custom-command-info": [ "Schreibe den Command den der Spieler ausführen soll ohne / in den Chat", "Erlaubte Commands: {0}", diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java index fbafc5d1f..02ce327fa 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java @@ -14,10 +14,7 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.function.Consumer; import java.util.function.Function; @@ -43,10 +40,13 @@ public AbstractMenuGenerator getGenerator(Player player, IParentCustomGenerator @Override public Collection getCurrentDisplayFor(@NotNull Map activated) { List display = Lists.newLinkedList(); + System.out.println(this.getClass() + " " + activated); // TODO logic ported from legacy code; overhaul system for (ValueSetting setting : defaultSettings.keySet()) { + System.out.println(setting.getKey()); String[] values = activated.get(setting.getKey()); + System.out.println(Arrays.toString(values)); if (values == null || values.length == 0) continue; String value = values[0]; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java index bc7ac00d1..a35e0e98f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/SneakDamageChallenge.java @@ -2,10 +2,10 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; import org.bukkit.Color; import org.bukkit.Material; @@ -21,15 +21,9 @@ public SneakDamageChallenge() { "sneak-damage"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() / 2); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionDamage(getValue()); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @@ -37,7 +31,7 @@ public void onSneak(@NotNull PlayerToggleSneakEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (!event.isSneaking()) return; - getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, event.getPlayer()); event.getPlayer().setNoDamageTicks(0); event.getPlayer().damage(getValue()); event.getPlayer().setNoDamageTicks(0); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java index 50f1fbabd..7c668138d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/effect/ChunkRandomEffectChallenge.java @@ -6,6 +6,8 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; +import net.codingarea.challenges.plugin.management.scheduler.task.TimerTask; +import net.codingarea.challenges.plugin.management.scheduler.timer.TimerStatus; import net.codingarea.challenges.plugin.spigot.events.PlayerIgnoreStatusChangeEvent; import net.codingarea.challenges.plugin.utils.misc.PotionEffectUtils; import net.codingarea.commons.common.collection.IRandom; @@ -94,6 +96,16 @@ public void onSecond() { broadcastFiltered(player -> addEffect(player, player.getLocation())); } + @TimerTask(status = TimerStatus.PAUSED) + public void onTimerPause() { + broadcastFiltered(player -> removeEffect(player, player.getLocation())); + } + + @TimerTask(status = TimerStatus.RUNNING) + public void onTimerStart() { + broadcastFiltered(player -> addEffect(player, player.getLocation())); + } + public void removeEffect(Player player, Location location) { PotionEffectType type = getEffect(location.getChunk()).getType(); player.removePotionEffect(type); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java index 945ede90f..6e116ec9d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceBlockChallenge.java @@ -11,7 +11,6 @@ import net.codingarea.challenges.plugin.management.server.scoreboard.ChallengeBossBar.BossBarInstance; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.item.ItemUtils; import net.codingarea.commons.common.config.Document; import net.kyori.adventure.bossbar.BossBar; @@ -67,7 +66,7 @@ protected boolean isFailing(@NotNull Player player) { @Override protected void broadcastFailedMessage(@NotNull Player player) { - getChallengeMessageKey("fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), player.getLocation().subtract(0, 1, 0).getBlock().getType()); + getChallengeMessageKey("fail").broadcast(Prefix.CHALLENGES, player, player.getLocation().subtract(0, 1, 0).getBlock().getType()); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java index 64b53515f..05d5629c2 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceItemChallenge.java @@ -69,7 +69,7 @@ protected void broadcastFailedMessage() { @Override protected void broadcastSuccessMessage(@NotNull Player player) { - getChallengeMessageKey("success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), item); + getChallengeMessageKey("success").broadcast(Prefix.CHALLENGES, player, item); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java index d8c519478..1c10e9404 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/force/ForceMobChallenge.java @@ -64,7 +64,7 @@ protected void broadcastFailedMessage() { @Override protected void broadcastSuccessMessage(@NotNull Player player) { - getChallengeMessageKey("success").broadcast(Prefix.CHALLENGES, NameHelper.getName(player), entity); + getChallengeMessageKey("success").broadcast(Prefix.CHALLENGES, player, entity); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java index 4a0e85d99..e01ff12ca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/FoodOnceChallenge.java @@ -47,14 +47,14 @@ public void onPlayerItemConsume(@NotNull PlayerItemConsumeEvent event) { Material type = event.getItem().getType(); if (hasEaten(event.getPlayer(), type)) { - getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); + getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, event.getPlayer(), type); ChallengeHelper.kill(event.getPlayer(), 1); } else { addFood(event.getPlayer(), type); if (teamFoodsActivated()) { - getChallengeMessageKey("new-food-team").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); + getChallengeMessageKey("new-food-team").broadcast(Prefix.CHALLENGES, event.getPlayer(), type); } else { - getChallengeMessageKey("new-food").send(event.getPlayer(), Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), type); + getChallengeMessageKey("new-food").send(event.getPlayer(), Prefix.CHALLENGES, event.getPlayer(), type); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java index 3283a2910..5d398003f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/miscellaneous/NoExpChallenge.java @@ -22,7 +22,7 @@ public void onExp(PlayerExpChangeEvent event) { if (!shouldExecuteEffect()) return; if (ignorePlayer(event.getPlayer())) return; if (event.getAmount() <= 0) return; - getChallengeMessageKey("picked-up").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + getChallengeMessageKey("picked-up").broadcast(Prefix.CHALLENGES, event.getPlayer()); ChallengeHelper.kill(event.getPlayer()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java index 6f4915b64..661c97eac 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/DontStopRunningChallenge.java @@ -73,7 +73,7 @@ private void countUpOrKillEveryone() { broadcastFiltered(player -> { Integer count = playerStandingCount.getOrDefault(player, 0); if (count >= getValue()) { - getChallengeMessageKey("stopped-moving").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + getChallengeMessageKey("stopped-moving").broadcast(Prefix.CHALLENGES, player); playerStandingCount.remove(player); ChallengeHelper.kill(player); return; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java index 122dff1bf..d8de5a179 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java @@ -62,7 +62,7 @@ public void onTick() { if (yaw != pair.getKey() || pitch != pair.getValue()) { Bukkit.getScheduler().runTask(plugin, () -> { if (player.getNoDamageTicks() > 0) return; - getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, player); player.damage(getValue()); player.setNoDamageTicks(5); Bukkit.getScheduler().runTaskLater(plugin, () -> lastView.remove(player.getUniqueId()), 3); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java index a831f60e0..8052dabb0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDirtChallenge.java @@ -34,7 +34,7 @@ public void onPlayerMove(@NotNull PlayerMoveEvent event) { Block blockBelow = BlockUtils.getBlockBelow(event.getTo()); if (blockBelow == null) return; if (blockBelow.getType() != Material.DIRT && !BukkitReflectionUtils.isAir(blockBelow.getType())) { - getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, event.getPlayer()); ChallengeHelper.kill(event.getPlayer()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java index c6c870e25..a73699f84 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/OnlyDownChallenge.java @@ -26,7 +26,7 @@ public void onPlayerMove(@NotNull PlayerMoveEvent event) { if (ignorePlayer(event.getPlayer())) return; if (event.getTo() == null) return; if (event.getTo().getBlockY() <= event.getFrom().getBlockY()) return; - getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, event.getPlayer()); ChallengeHelper.kill(event.getPlayer()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java index 9055b5ddb..6a2a5f468 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/TrafficLightChallenge.java @@ -8,7 +8,6 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.kyori.adventure.bossbar.BossBar; import org.bukkit.Material; @@ -103,7 +102,7 @@ public void onPlayerMove(@NotNull PlayerMoveEvent event) { restartTimer(); Player player = event.getPlayer(); - getChallengeMessageKey("fail").broadcast(Prefix.CHALLENGES, NameHelper.getName(player)); + getChallengeMessageKey("fail").broadcast(Prefix.CHALLENGES, player); ChallengeHelper.kill(player); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java index da20e983c..80d80473c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/quiz/QuizChallenge.java @@ -5,6 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.TimedChallenge; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.content.legacy.Message; @@ -14,7 +15,6 @@ import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.TriFunction; import net.codingarea.commons.bukkit.utils.animation.SoundSample; import net.codingarea.commons.bukkit.utils.misc.BukkitReflectionUtils; @@ -62,11 +62,10 @@ public QuizChallenge() { instance = this; } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return ChallengeHelper.getTimeRangeSettingsDescription(this, 60 * 3, 60); -// } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionTimeSecondsRange(getValue() * 60 * 3, 60); + } @Override protected void onEnable() { @@ -79,7 +78,7 @@ protected void onEnable() { String time = "§e" + timeLeft + " §7" + (timeLeft == 1 ? Message.forName("second").asString() : Message.forName("seconds").asString()); if (currentQuestionedPlayer != player) { bossbar.setColor(BossBar.Color.GREEN); - bossbar.setTitle(MessageKey.of("bossbar-quiz-question-other"), time, NameHelper.getName(currentQuestionedPlayer)); + bossbar.setTitle(MessageKey.of("bossbar-quiz-question-other"), time, currentQuestionedPlayer); return; } bossbar.setColor(BossBar.Color.RED); @@ -93,11 +92,6 @@ protected void onDisable() { bossbar.hide(); } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeSecondsRangeValueChangeTitle(this, getValue() * 60 * 3 - 60, getValue() * 60 * 3 + 60); - } - @Override protected int getSecondsUntilNextActivation() { return random.around(getValue() * 60 * 3, 60); @@ -108,7 +102,7 @@ private void broadcastMessage(@NotNull String questionedPlayerMessage, @NotNull if (currentQuestionedPlayer == player1) { MessageKey.of(questionedPlayerMessage).send(player1, prefix, args); } else { - MessageKey.of(othersMessage).send(player1, prefix, NameHelper.getName(currentQuestionedPlayer)); + MessageKey.of(othersMessage).send(player1, prefix, currentQuestionedPlayer); } }); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java index 230783946..c007260e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/SnakeChallenge.java @@ -6,7 +6,6 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.commons.common.config.Document; import org.bukkit.Bukkit; import org.bukkit.GameMode; @@ -69,7 +68,7 @@ public void onMove(@NotNull PlayerMoveEvent event) { } if (blocks.contains(to)) { - getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + getChallengeMessageKey("failed").broadcast(Prefix.CHALLENGES, event.getPlayer()); ChallengeHelper.kill(event.getPlayer()); return; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java index 137013a5d..e8ce0ca62 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/RaceGoal.java @@ -14,7 +14,6 @@ import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; import net.codingarea.commons.common.collection.IRandom; import net.codingarea.commons.common.config.Document; @@ -122,7 +121,7 @@ public void onMove(PlayerMoveEvent event) { if (event.getTo().getWorld() != goal.getWorld()) return; if (event.getTo() == null) return; if (BlockUtils.isSameBlockLocationIgnoreHeight(event.getTo(), goal)) { - MessageKey.of("race-goal-reached").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer())); + MessageKey.of("race-goal-reached").broadcast(Prefix.CHALLENGES, event.getPlayer()); ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); ParticleUtils.spawnParticleCylinderAroundRadius(Challenges.getInstance(), event.getTo(), MinecraftNameWrapper.ENTITY_EFFECT, null, 0.75, 2); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java index 1e8a067d8..fff5f484f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/PositionSetting.java @@ -9,7 +9,6 @@ import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.utils.bukkit.command.PlayerCommand; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import net.codingarea.challenges.plugin.utils.misc.ParticleUtils; import net.codingarea.challenges.plugin.utils.misc.Utils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -198,7 +197,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc positions.remove(name); MessageKey.of("position-deleted").broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), - getWorldName(position), name, NameHelper.getName(player)); + getWorldName(position), name, player); } else { MessageKey.of("position-not-exists").send(player, Prefix.POSITION); } @@ -260,9 +259,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc Location position = new Location(world, doubleX, doubleY, doubleZ); positions.put(name, position); - MessageKey.of("position-set") - .broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), - position.getBlockZ(), getWorldName(position), name, NameHelper.getName(player)); + MessageKey.of("position-set").broadcast(Prefix.POSITION, position.getBlockX(), position.getBlockY(), position.getBlockZ(), getWorldName(position), name, player); SoundSample.BASS_ON.play(player); broadcastParticleLine(position); @@ -275,8 +272,7 @@ public void onCommand(@NotNull Player player, @NotNull String[] args) throws Exc @Nullable @Override public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { - if (!(sender instanceof Player)) return new LinkedList<>(); - Player player = (Player) sender; + if (!(sender instanceof Player player)) return new LinkedList<>(); if (args.length > 5) return new LinkedList<>(); if (args.length > 2) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java index 94a7b346f..5dffe814d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/FirstPlayerAtHeightGoal.java @@ -7,7 +7,6 @@ import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -52,7 +51,7 @@ public void onMove(PlayerMoveEvent event) { if (ignorePlayer(event.getPlayer())) return; if (event.getTo().getBlockY() == event.getFrom().getBlockY()) return; if (event.getTo().getBlockY() == heightToGetTo) { - MessageKey.of("height-reached").broadcast(Prefix.CHALLENGES, NameHelper.getName(event.getPlayer()), getHeightToGetTo()); + MessageKey.of("height-reached").broadcast(Prefix.CHALLENGES, event.getPlayer(), getHeightToGetTo()); ChallengeAPI.endChallenge(ChallengeEndCause.GOAL_REACHED, () -> Collections.singletonList(event.getPlayer())); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index f7c98aa96..c5ec33c6b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -250,6 +250,12 @@ public static LocalizableMessage getSettingsDescriptionMaxHealth(int hp) { return MessageKey.of("challenge.settings-modifier-max-health").withArgs(ArgumentFormat.HP.apply(hp)); } + @NotNull + @Contract(pure = true) + public static LocalizableMessage getSettingsDescriptionDamage(int hp) { + return MessageKey.of("challenge.settings-modifier-damage").withArgs(ArgumentFormat.HP.apply(hp)); + } + @NotNull @Contract(pure = true) public static LocalizableMessage getChallengeEnabledName() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java index 122647883..5789c9d66 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/impl/format/ComponentFormatter.java @@ -61,7 +61,7 @@ public static Component deserializeLines(@Nullable String prefix, @NotNull Strin private static Component deserializeLines(@Nullable String prefix, @NotNull String[] textLines, @Nullable PositionalArgResolver args) { if (textLines.length == 0) return Component.empty(); - // Component.text() (Builder) incompatible in version change 26.1.2 -> 26.2 + // Component.text()#build (Builder) incompatible in version change 26.1.2 -> 26.2 Component rootComponent = Component.empty(); Component prefixComponent = (prefix != null && !prefix.isEmpty()) ? diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java index b396e5bd6..a6febe665 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java @@ -202,7 +202,7 @@ public boolean handleMenuClick(@NotNull MenuClickInfo info) { } case CONDITION_SLOT -> { new CustomMainSettingsMenuGenerator(CustomChallengeMenuGenerator.this, SettingType.CONDITION, "trigger", - MessageKey.of("custom-title-trigger"), ChallengeTrigger.getMenuItems(), + MessageKey.of("menu.custom.trigger.name"), ChallengeTrigger.getMenuItems(), key -> Challenges.getInstance().getCustomSettingsLoader().getTriggerByName(key)) .openMenu(player); SoundSample.CLICK.play(player); @@ -210,7 +210,7 @@ public boolean handleMenuClick(@NotNull MenuClickInfo info) { } case ACTION_SLOT -> { new CustomMainSettingsMenuGenerator(CustomChallengeMenuGenerator.this, SettingType.ACTION, "action", - MessageKey.of("custom-title-action"), ChallengeAction.getMenuItems(), + MessageKey.of("menu.custom.action.name"), ChallengeAction.getMenuItems(), key -> Challenges.getInstance().getCustomSettingsLoader().getActionByName(key)) .openMenu(player); SoundSample.CLICK.play(player); @@ -224,10 +224,11 @@ public boolean handleMenuClick(@NotNull MenuClickInfo info) { } case DELETE_SLOT -> { if (!Challenges.getInstance().getCustomChallengesLoader().getCustomChallenges().containsKey(uuid)) { - MessageKey.of("custom-not-deleted").send(player, Prefix.CUSTOM); + MessageKey.of("menu.custom.delete.new").send(player, Prefix.CUSTOM); SoundSample.BASS_OFF.play(player); return true; } + MessageKey.of("menu.custom.delete.done").send(player, Prefix.CUSTOM, CustomChallenge.formatChallengeName(name)); navigateToChallengeList(player); Challenges.getInstance().getCustomChallengesLoader().unregisterCustomChallenge(uuid); new SoundSample().addSound(Sound.ENTITY_WITHER_BREAK_BLOCK, 0.4f).play(player); @@ -237,15 +238,20 @@ public boolean handleMenuClick(@NotNull MenuClickInfo info) { String defaults = new CustomChallengeMenuGenerator().toString(); String current = CustomChallengeMenuGenerator.this.toString(); if (defaults.equals(current)) { - MessageKey.of("custom-no-changes").send(player, Prefix.CUSTOM); + MessageKey.of("menu.custom.save.no-changes").send(player, Prefix.CUSTOM); + SoundSample.BASS_OFF.play(player); + return true; + } + if (trigger == null || action == null) { + MessageKey.of("menu.custom.save.missing-settings").send(player, Prefix.CUSTOM); SoundSample.BASS_OFF.play(player); return true; } save(); navigateToChallengeList(player); - MessageKey.of("custom-saved").send(player, Prefix.CUSTOM); + MessageKey.of("menu.custom.save.done").send(player, Prefix.CUSTOM); if (savePlayerChallenges) { - MessageKey.of("custom-saved-db").send(player, Prefix.CUSTOM); + MessageKey.of("menu.custom.save.done-db").send(player, Prefix.CUSTOM); } SoundSample.LEVEL_UP.play(player); return true; From 003baf7f42f06d73638c5358505c89977dc530af Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Mon, 13 Jul 2026 00:08:02 +0200 Subject: [PATCH 117/119] refactor: migrate localization usage (part 10) [WIP] --- language/locales/de.json | 66 +++++++++++++++---- .../challenges/custom/CustomChallenge.java | 4 +- .../action/impl/AddPermanentEffectAction.java | 2 + .../action/impl/BoostEntityInAirAction.java | 12 ++-- .../action/impl/CancelEventAction.java | 2 +- .../action/impl/ChangeWorldBorderAction.java | 8 ++- .../action/impl/ClearInventoryAction.java | 2 + .../action/impl/DamageEntityAction.java | 2 + .../action/impl/DropRandomItemAction.java | 2 + .../action/impl/ExecuteCommandAction.java | 2 + .../settings/action/impl/FreezeAction.java | 2 + .../action/impl/HealEntityAction.java | 2 + .../action/impl/HungerPlayerAction.java | 2 + .../action/impl/InvertHealthAction.java | 3 +- .../action/impl/JumpAndRunAction.java | 2 + .../action/impl/KillEntityAction.java | 2 + .../action/impl/ModifyMaxHealthAction.java | 13 ++-- .../action/impl/PlaceStructureAction.java | 2 + .../action/impl/PotionEffectAction.java | 5 +- .../action/impl/RandomHotBarAction.java | 2 + .../action/impl/RandomItemAction.java | 4 +- .../settings/action/impl/RandomMobAction.java | 2 + .../action/impl/RandomPotionEffectAction.java | 5 +- .../action/impl/RemoveRandomItemAction.java | 2 + .../action/impl/SpawnEntityAction.java | 2 + .../action/impl/SwapRandomItemAction.java | 2 + .../action/impl/SwapRandomMobAction.java | 2 + .../action/impl/UncraftInventoryAction.java | 5 +- .../settings/action/impl/WaterMLGAction.java | 2 + .../action/impl/WinChallengeAction.java | 2 + .../custom/settings/sub/SelectableKey.java | 4 -- .../settings/sub/SubSettingsBuilder.java | 2 +- .../custom/settings/sub/ValueSetting.java | 56 +++++++++++++--- .../sub/builder/ValueSubSettingsBuilder.java | 41 +++++------- .../settings/sub/impl/BooleanSetting.java | 23 +++++-- .../settings/sub/impl/ModifierSetting.java | 46 +++++++------ .../type/abstraction/AbstractChallenge.java | 13 +--- .../challenges/type/abstraction/Modifier.java | 3 +- .../type/helper/ChallengeHelper.java | 12 ++++ .../type/helper/SubSettingsHelper.java | 23 +++---- .../plugin/content/i18n/ArgumentFormat.java | 2 +- .../custom/CustomChallengeMenuGenerator.java | 4 +- .../CustomChooseValueMenuGenerator.java | 6 +- .../plugin/spigot/command/SearchCommand.java | 2 - .../plugin/utils/item/DefaultItems.java | 12 ++++ 45 files changed, 276 insertions(+), 138 deletions(-) diff --git a/language/locales/de.json b/language/locales/de.json index 5ab00215e..a6946b532 100644 --- a/language/locales/de.json +++ b/language/locales/de.json @@ -344,6 +344,7 @@ "challenge": { "settings-modifier-max-health": "Maximale Leben: {0}", "settings-modifier-damage": "Schaden: {0}", + "settings-modifier-strength": "Stärke: {0}", "difficulty": { "name": "*Schwierigkeit*", "desc": [ @@ -2138,7 +2139,17 @@ "desc": [ "Verändere die Maximalen Leben von Spielern", "Wird mit einem */gamestate reset* zurückgesetzt" - ] + ], + "sub": { + "offset": { + "sub-name": "Veränderung", + "name": "*{@sub-name}*", + "desc": [ + "Wähle aus wie viele Herzen *addiert*", + "oder *subtrahiert* werden sollen" + ] + } + } }, "spawn_entity": { "name": "*Kreatur spawnen*", @@ -2168,13 +2179,40 @@ "name": "*In Luft schleudern*", "desc": [ "Schleudere *Kreaturen* oder *Spieler* in die Luft" - ] + ], + "sub": { + "strength": { + "sub-name": "Stärke", + "name": "*{@sub-name}*", + "desc": [ + "Die Stärke des *Boosts*", + "Je höher die Zahl, desto *stärker* der Boost" + ] + } + } }, "potion_effect": { "name": "*Trank Effekt*", "desc": [ "Gebe *Kreaturen* oder *Spielern* einen Trank Effekt" - ] + ], + "sub": { + "length": { + "sub-name": "Dauer", + "name": "*{@sub-name}*", + "desc": [ + "Die Dauer des *Trank Effekts*" + ] + }, + "amplifier": { + "sub-name": "Stärke", + "name": "*{@sub-name}*", + "desc": [ + "Die Stärke des *Trank Effekts*", + "Je höher die Zahl, desto *stärker* der Effekt" + ] + } + } }, "permanent_effect": { "name": "*Permanenter Effekt*", @@ -2254,7 +2292,17 @@ "name": "*World Border verändern*", "desc": [ "Mache die World Border *größer* oder *kleiner*" - ] + ], + "sub": { + "change": { + "sub-name": "Veränderung", + "name": "*{@sub-name}*", + "desc": [ + "Wähle aus wie viele Blöcke die *World Border*", + "*vergrößert* oder *verkleinert* werden soll" + ] + } + } }, "swap_mobs": { "name": "*Kreaturen tauschen*", @@ -2785,16 +2833,6 @@ ], "custom-title-view": "Gespeichert", "custom-sub-finish": "Fertig", - "item-custom-action-max_health-offset": [ - "Veränderung", - "Wähle aus wie viele Leben verändert werden sollen" - ], - "item-custom-action-boost_in_air-strength": [ - "Stärke" - ], - "item-custom-action-modify_border-change": [ - "Veränderung" - ], "custom-subsetting-target_entity": "Ziel Entity", "custom-subsetting-entity_type": "Entity Typ", "custom-subsetting-liquid": "Flüssigkeit", diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java index 987f9e369..38b3090d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/CustomChallenge.java @@ -69,7 +69,7 @@ public ItemBuilder getDisplayItem(@NotNull Locale locale) { item.appendBlankLoreLine() .appendLore(MessageKey.of("menu.custom.trigger-format"), trigger.getSettingName()); - Collection display = trigger.getSubSettingsBuilder().getCurrentDisplayFor(subTriggers); + Collection display = trigger.getSubSettingsBuilder().collectCurrentDisplayFor(subTriggers); for (SubSettingsBuilder.SubSettingDisplay subSettingDisplay : display) { item.appendLore(MessageKey.of("menu.custom.subsetting-format"), subSettingDisplay.keyName(), subSettingDisplay.valueFormatted()); } @@ -80,7 +80,7 @@ public ItemBuilder getDisplayItem(@NotNull Locale locale) { item.appendBlankLoreLine() .appendLore(MessageKey.of("menu.custom.action-format"), action.getSettingName()); - Collection display = action.getSubSettingsBuilder().getCurrentDisplayFor(subActions); + Collection display = action.getSubSettingsBuilder().collectCurrentDisplayFor(subActions); for (SubSettingsBuilder.SubSettingDisplay subSettingDisplay : display) { item.appendLore(MessageKey.of("menu.custom.subsetting-format"), subSettingDisplay.keyName(), subSettingDisplay.valueFormatted()); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java index a3d5d0dfc..23aa407ef 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/AddPermanentEffectAction.java @@ -6,6 +6,7 @@ import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -18,6 +19,7 @@ public AddPermanentEffectAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); } + @NotNull @Override public Material getMaterial() { return Material.MAGMA_CREAM; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java index 6933e3526..4ede4e666 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/BoostEntityInAirAction.java @@ -1,14 +1,16 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.action.impl; import net.codingarea.challenges.plugin.challenges.custom.settings.action.EntityTargetAction; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.misc.EntityUtils; import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Material; import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -17,14 +19,14 @@ public class BoostEntityInAirAction extends EntityTargetAction { public BoostEntityInAirAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true).createValueChild().fill(builder -> { builder.addModifierSetting("strength", - new LegacyItemBuilder(Material.FEATHER, Message.forName("item-custom-action-boost_in_air-strength")), + new ItemStack(Material.FEATHER), MessageKey.of("custom.action.boost_in_air.sub.strength"), 1, 1, 10, - value -> Message.forName("amplifier").asString(), - integer -> "" + ChallengeHelper::getSettingsDescriptionModifierStrength ); })); } + @NotNull @Override public Material getMaterial() { return Material.FEATHER; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java index 13e712b09..ae5d5de23 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/CancelEventAction.java @@ -27,8 +27,8 @@ public static boolean shouldCancel() { return false; } - @Override @NotNull + @Override public Material getMaterial() { return Material.BARRIER; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java index 8193c7cd3..50c0727a6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ChangeWorldBorderAction.java @@ -4,12 +4,13 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.ChallengeExecutionData; import net.codingarea.challenges.plugin.challenges.custom.settings.action.ChallengeAction; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.commons.bukkit.utils.logging.Logger; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.WorldBorder; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -19,11 +20,12 @@ public ChangeWorldBorderAction(String name) { super(name, SubSettingsBuilder.createValueItem() .addModifierSetting( "change", - new LegacyItemBuilder(Material.MAGENTA_GLAZED_TERRACOTTA, Message.forName("item-custom-action-modify_border-change")), + new ItemStack(Material.MAGENTA_GLAZED_TERRACOTTA), MessageKey.of("custom.action.modify_border.sub.change"), 1, -10, 10 )); } + @NotNull @Override public Material getMaterial() { return Material.STRUCTURE_VOID; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java index d5408346f..9f41b2afb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ClearInventoryAction.java @@ -4,6 +4,7 @@ import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -13,6 +14,7 @@ public ClearInventoryAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); } + @NotNull @Override public Material getMaterial() { return Material.TRAPPED_CHEST; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java index 31157213f..0e08ef4e9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DamageEntityAction.java @@ -8,6 +8,7 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -31,6 +32,7 @@ public void executeFor(Entity entity, Map subActions) { } } + @NotNull @Override public Material getMaterial() { return Material.FERMENTED_SPIDER_EYE; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java index c8d0d74b6..6bc501883 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/DropRandomItemAction.java @@ -5,6 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -14,6 +15,7 @@ public DropRandomItemAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); } + @NotNull @Override public Material getMaterial() { return Material.DISPENSER; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java index 7ed29ce6a..46d03503d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ExecuteCommandAction.java @@ -9,6 +9,7 @@ import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Map; @@ -53,6 +54,7 @@ public void executeForPlayer(Player player, Map subActions) { Bukkit.getServer().dispatchCommand(sender, fullCommand); } + @NotNull @Override public Material getMaterial() { return Material.COMMAND_BLOCK; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java index 4123e255f..75d2c56a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/FreezeAction.java @@ -7,6 +7,7 @@ import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -19,6 +20,7 @@ public FreezeAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true)); } + @NotNull @Override public Material getMaterial() { return Material.ICE; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java index 239073fdd..2588c2870 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HealEntityAction.java @@ -10,6 +10,7 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -36,6 +37,7 @@ public void executeFor(Entity entity, Map subActions) { } } + @NotNull @Override public Material getMaterial() { return Material.GOLDEN_APPLE; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java index f09445d23..1fe805c70 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/HungerPlayerAction.java @@ -7,6 +7,7 @@ import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -24,6 +25,7 @@ public HungerPlayerAction(String name) { })); } + @NotNull @Override public Material getMaterial() { return Material.ROTTEN_FLESH; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java index 38ed19e6b..229aaffe0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/InvertHealthAction.java @@ -5,6 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -14,12 +15,12 @@ public InvertHealthAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); } + @NotNull @Override public Material getMaterial() { return Material.REDSTONE; } - @Override public void executeForPlayer(Player player, Map subActions) { InvertHealthChallenge.invertHealth(player); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java index a2d6f33fe..896ee09cb 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/JumpAndRunAction.java @@ -5,6 +5,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.challenge.extraworld.JumpAndRunChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import org.bukkit.Material; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -14,6 +15,7 @@ public JumpAndRunAction(String name) { super(name); } + @NotNull @Override public Material getMaterial() { return Material.ACACIA_STAIRS; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java index 74b1ad670..322130268 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/KillEntityAction.java @@ -7,6 +7,7 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -25,6 +26,7 @@ public void executeFor(Entity entity, Map subActions) { } } + @NotNull @Override public Material getMaterial() { return Material.DIAMOND_SWORD; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java index 4f0dfb8c1..d45ddbb17 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/ModifyMaxHealthAction.java @@ -5,11 +5,13 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.misc.MinecraftNameWrapper; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -19,13 +21,14 @@ public ModifyMaxHealthAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true) .createValueChild().fill(builder -> { builder.addModifierSetting("health_offset", - new LegacyItemBuilder(MinecraftNameWrapper.RED_DYE, - Message.forName("item-custom-action-max_health-offset")), + new ItemStack(MinecraftNameWrapper.RED_DYE), MessageKey.of("custom.action.max_health.sub.offset"), 0, -20, 20, - integer -> "", integer -> "HP §8(§e" + (integer / 2f) + " §c❤§8)"); + ArgumentFormat.HP + ); })); } + @NotNull @Override public Material getMaterial() { return MinecraftNameWrapper.RED_DYE; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java index afae8f853..a74131102 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PlaceStructureAction.java @@ -8,6 +8,7 @@ import net.codingarea.commons.common.collection.IRandom; import org.bukkit.*; import org.bukkit.entity.Entity; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Arrays; @@ -26,6 +27,7 @@ public PlaceStructureAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true).addChild(SubSettingsHelper.createStructureSettingsBuilder())); } + @NotNull @Override public Material getMaterial() { return Material.STRUCTURE_BLOCK; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java index bd618a663..fccaf993b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/PotionEffectAction.java @@ -8,6 +8,7 @@ import org.bukkit.entity.LivingEntity; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -20,8 +21,7 @@ public PotionEffectAction(String name) { @Override public void executeFor(Entity entity, Map subActions) { - if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; + if (entity instanceof LivingEntity livingEntity) { try { PotionEffectType effectType = PotionEffectType.getByName(subActions.get("potion_type")[0]); @@ -37,6 +37,7 @@ public void executeFor(Entity entity, Map subActions) { } } + @NotNull @Override public Material getMaterial() { return Material.POTION; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java index 0755dda5e..4f95cc273 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomHotBarAction.java @@ -5,6 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -14,6 +15,7 @@ public RandomHotBarAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(true, true)); } + @NotNull @Override public Material getMaterial() { return Material.ARMOR_STAND; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java index fab3c99d7..408e5e474 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomItemAction.java @@ -29,13 +29,13 @@ public void execute( Map subActions) { for (Entity target : IEntityTargetAction.getTargets(executionData.getEntity(), subActions)) { - if (target instanceof Player) { - Player player = (Player) target; + if (target instanceof Player player) { giveRandomItemToPlayer(player); } } } + @NotNull @Override public Material getMaterial() { return Material.BEACON; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java index 181089413..42a84a320 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomMobAction.java @@ -7,6 +7,7 @@ import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; +import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.LinkedList; @@ -40,6 +41,7 @@ public void executeFor(Entity entity, Map subActions) { entity.getLocation().getWorld().spawnEntity(entity.getLocation(), value); } + @NotNull @Override public Material getMaterial() { return Material.BLAZE_SPAWN_EGG; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java index 1cefa0e5a..a23f9081c 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RandomPotionEffectAction.java @@ -8,6 +8,7 @@ import org.bukkit.entity.LivingEntity; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -20,8 +21,7 @@ public RandomPotionEffectAction(String name) { @Override public void executeFor(Entity entity, Map subActions) { - if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; + if (entity instanceof LivingEntity livingEntity) { PotionEffectType randomEffect = RandomPotionEffectChallenge .getNewRandomEffect(livingEntity); @@ -33,6 +33,7 @@ public void executeFor(Entity entity, Map subActions) { } } + @NotNull @Override public Material getMaterial() { return Material.BREWING_STAND; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java index a1fa56280..1e378fc8a 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/RemoveRandomItemAction.java @@ -5,6 +5,7 @@ import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -14,6 +15,7 @@ public RemoveRandomItemAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); } + @NotNull @Override public Material getMaterial() { return Material.DROPPER; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java index 0e8acac10..e8c14c317 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SpawnEntityAction.java @@ -7,6 +7,7 @@ import org.bukkit.World; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -16,6 +17,7 @@ public SpawnEntityAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false).addChild(SubSettingsHelper.createEntityTypeSettingsBuilder(false, false))); } + @NotNull @Override public Material getMaterial() { return Material.ZOMBIE_SPAWN_EGG; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java index c71c793b1..efeb96fb1 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomItemAction.java @@ -5,6 +5,7 @@ import net.codingarea.challenges.plugin.challenges.type.helper.SubSettingsHelper; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -14,6 +15,7 @@ public SwapRandomItemAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); } + @NotNull @Override public Material getMaterial() { return Material.HOPPER; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java index cdaba090a..6bda478bd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/SwapRandomMobAction.java @@ -11,6 +11,7 @@ import org.bukkit.World; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; +import org.jetbrains.annotations.NotNull; import java.util.Collections; import java.util.List; @@ -23,6 +24,7 @@ public SwapRandomMobAction(String name) { .addChild(SubSettingsHelper.createEntityTargetSettingsBuilder(true).setKey("swap_targets"))); } + @NotNull @Override public Material getMaterial() { return Material.ENDER_PEARL; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java index 3bd858bae..7479f87b0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/UncraftInventoryAction.java @@ -6,6 +6,7 @@ import org.bukkit.Material; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -17,12 +18,12 @@ public UncraftInventoryAction(String name) { @Override public void executeFor(Entity entity, Map subActions) { - if (entity instanceof Player) { - Player player = (Player) entity; + if (entity instanceof Player player) { UncraftItemsChallenge.uncraftInventory(player); } } + @NotNull @Override public Material getMaterial() { return Material.CRAFTING_TABLE; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java index d7348fcfb..7cf3be6c0 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WaterMLGAction.java @@ -5,6 +5,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.challenge.extraworld.WaterMLGChallenge; import net.codingarea.challenges.plugin.challenges.type.abstraction.AbstractChallenge; import org.bukkit.Material; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -14,6 +15,7 @@ public WaterMLGAction(String name) { super(name); } + @NotNull @Override public Material getMaterial() { return Material.WATER_BUCKET; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java index 8a064c9ef..7275b8eb6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/action/impl/WinChallengeAction.java @@ -8,6 +8,7 @@ import net.codingarea.challenges.plugin.management.server.ChallengeEndCause; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Map; @@ -20,6 +21,7 @@ public WinChallengeAction(String name) { super(name, SubSettingsHelper.createEntityTargetSettingsBuilder(false, true)); } + @NotNull @Override public Material getMaterial() { return Material.GOLDEN_HELMET; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java index 6adbaa7ee..49788d459 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SelectableKey.java @@ -15,10 +15,6 @@ import java.util.Locale; -/** - * @see Option - * @see ValueSetting - */ public interface SelectableKey { @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java index 8a1a57b76..d71b6b6c5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/SubSettingsBuilder.java @@ -55,7 +55,7 @@ public static EmptySubSettingsBuilder createEmpty() { public abstract boolean open(Player player, IParentCustomGenerator parentGenerator, LocalizableMessage title); @NotNull - public abstract Collection getCurrentDisplayFor(@NotNull Map activated); + protected abstract Collection getCurrentDisplayFor(@NotNull Map activated); public abstract boolean hasSettings(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java index 505f9b92c..1d3cd8e7f 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/ValueSetting.java @@ -1,30 +1,66 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub; import lombok.Getter; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; +import net.codingarea.challenges.plugin.utils.item.ItemBuilder; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.Locale; public abstract class ValueSetting { @Getter private final String key; - private final LegacyItemBuilder itemBuilder; + private final ItemStack displayItemPreset; + private final MessageKey messageKeyNamespace; - public ValueSetting(String key, LegacyItemBuilder itemBuilder) { + public ValueSetting(@NotNull String key, @NotNull ItemStack displayItemPreset, @NotNull MessageKey messageKeyNamespace) { this.key = key; - this.itemBuilder = itemBuilder; + this.displayItemPreset = displayItemPreset; + this.messageKeyNamespace = messageKeyNamespace; + } + + public abstract String onClick(MenuClickInfo info, String value, int slotIndex); + + @NotNull + public ItemBuilder getDisplayItem(@NotNull String value, @NotNull Locale locale) { + return DefaultItems.createChallengeDisplayFormat(displayItemPreset, getValueSettingName(), getValueSettingDescription(), locale); } - public LegacyItemBuilder createDisplayItem() { - return itemBuilder; + @NotNull + public ItemBuilder getSettingsItem(@NotNull String value, @NotNull Locale locale) { + return DefaultItems.createChallengeSettingFormat(getSettingsItemPreset(value), getSettingsName(value), null, locale); } - public abstract String onClick(MenuClickInfo info, String value, int slotIndex); + @NotNull + public abstract ItemStack getSettingsItemPreset(@NotNull String value); + + @NotNull + public LocalizableMessage getSubName() { + return getValueSettingMessageKey("sub-name"); + } + + @NotNull + public LocalizableMessage getValueSettingName() { + return getValueSettingMessageKey("name"); + } + + @Nullable + public LocalizableMessage getValueSettingDescription() { + return getValueSettingMessageKey("desc"); + } - public LegacyItemBuilder getDisplayItem(String value) { - return createDisplayItem().hideAttributes(); + @NotNull + protected MessageKey getValueSettingMessageKey(@NotNull String keySuffix) { + return messageKeyNamespace.getChildKey(keySuffix); } - public abstract LegacyItemBuilder getSettingsItem(String value); + @NotNull + public abstract LocalizableMessage getSettingsName(@NotNull String value); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java index 02ce327fa..f3110c5b6 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/builder/ValueSubSettingsBuilder.java @@ -7,14 +7,18 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl.BooleanSetting; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl.ModifierSetting; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.generator.AbstractMenuGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.IParentCustomGenerator; import net.codingarea.challenges.plugin.management.menu.generator.impl.custom.choose.SubSettingValueMenuGenerator; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.*; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; @@ -44,49 +48,38 @@ public Collection getCurrentDisplayFor(@NotNull Map prefixGetter, Function suffixGetter) { - defaultSettings.put(new ModifierSetting(key, min, max, displayItem, prefixGetter, suffixGetter), + public ValueSubSettingsBuilder addModifierSetting(@NotNull String key, @NotNull ItemStack displayItemPreset, + @NotNull MessageKey messageKeyNamespace, int defaultValue, int min, int max) { + defaultSettings.put(new ModifierSetting(key, displayItemPreset, messageKeyNamespace, min, max), String.valueOf(defaultValue)); return this; } - public ValueSubSettingsBuilder addModifierSetting(String key, LegacyItemBuilder displayItem, - int defaultValue, int min, int max, Function settingsItemGetter) { - defaultSettings.put(new ModifierSetting(key, min, max, displayItem, settingsItemGetter), + public ValueSubSettingsBuilder addModifierSetting(@NotNull String key, @NotNull ItemStack displayItemPreset, + @NotNull MessageKey messageKeyNamespace, int defaultValue, int min, int max, + @NotNull Function settingsFormatGetter) { + defaultSettings.put(new ModifierSetting(key, displayItemPreset, messageKeyNamespace, min, max, settingsFormatGetter), String.valueOf(defaultValue)); return this; } - public ValueSubSettingsBuilder fill(Consumer actions) { actions.accept(this); return this; diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java index daef04c07..8c5dc2779 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/BooleanSetting.java @@ -1,15 +1,18 @@ package net.codingarea.challenges.plugin.challenges.custom.settings.sub.impl; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; public class BooleanSetting extends ValueSetting { - - public BooleanSetting(String key, LegacyItemBuilder itemBuilder) { - super(key, itemBuilder); + public BooleanSetting(@NotNull String key, @NotNull ItemStack displayItemPreset, @NotNull MessageKey messageKeyNamespace) { + super(key, displayItemPreset, messageKeyNamespace); } @Override @@ -18,9 +21,15 @@ public String onClick(MenuClickInfo info, String value, return value.equals("enabled") ? "disabled" : "enabled"; } + @NotNull @Override - public LegacyItemBuilder getSettingsItem(String value) { - return value.equals("enabled") ? DefaultItem.enabled() : DefaultItem.disabled(); + public ItemStack getSettingsItemPreset(@NotNull String value) { + return value.equals("enabled") ? DefaultItems.createEnabledPreset() : DefaultItems.createDisabledPreset(); } + @NotNull + @Override + public LocalizableMessage getSettingsName(@NotNull String value) { + return value.equals("enabled") ? ChallengeHelper.getChallengeEnabledName() : ChallengeHelper.getChallengeDisabledName(); + } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java index 6a46e8a6a..24798fea5 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/custom/settings/sub/impl/ModifierSetting.java @@ -4,38 +4,36 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.ValueSetting; import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.utils.item.DefaultItem; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; +import net.codingarea.challenges.plugin.utils.item.DefaultItems; import net.codingarea.commons.bukkit.utils.menu.MenuClickInfo; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; import java.util.function.Function; public class ModifierSetting extends ValueSetting implements IModifier { + // TODO unify desc/name space with other selectable options! + private final int min, max; - private final Function settingsItemGetter; + private final Function settingsFormatGetter; private int tempValue; - public ModifierSetting(String key, int min, int max, LegacyItemBuilder displayItem) { - this(key, min, max, displayItem, integer -> "", integer -> ""); - } - - public ModifierSetting(String key, int min, int max, LegacyItemBuilder itemBuilder, Function prefixGetter, Function suffixGetter) { - this(key, min, max, itemBuilder, value -> - { - String prefix = prefixGetter.apply(value); - String suffix = suffixGetter.apply(value); - return DefaultItem.value(value, (prefix.isEmpty() ? "" : "§7" + prefix + " ") + "§e") - .appendName(suffix.isEmpty() ? "" : " " + "§7" + suffix); - }); + public ModifierSetting(@NotNull String key, @NotNull ItemStack displayItemPreset, @NotNull MessageKey messageKeyNamespace, + int min, int max) { + this(key, displayItemPreset, messageKeyNamespace, min, max, ChallengeHelper::getSettingsDescriptionModifierValue); } - public ModifierSetting(String key, int min, int max, LegacyItemBuilder itemBuilder, Function settingsItemGetter) { - super(key, itemBuilder); + public ModifierSetting(@NotNull String key, @NotNull ItemStack displayItemPreset, @NotNull MessageKey messageKeyNamespace, + int min, int max, + @NotNull Function settingsFormatGetter) { + super(key, displayItemPreset, messageKeyNamespace); this.min = min; this.max = max; - this.settingsItemGetter = settingsItemGetter; + this.settingsFormatGetter = settingsFormatGetter; } @Override @@ -75,10 +73,18 @@ public int getMaxValue() { public void playValueChangeTitle() { } + @NotNull + @Override + public ItemStack getSettingsItemPreset(@NotNull String value) { + int intValue = getIntValue(value); + return DefaultItems.createValuePreset(intValue); + } + + @NotNull @Override - public LegacyItemBuilder getSettingsItem(String value) { + public LocalizableMessage getSettingsName(@NotNull String value) { int intValue = getIntValue(value); - return settingsItemGetter.apply(intValue); + return settingsFormatGetter.apply(intValue); } public int getIntValue(String value) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java index f4bc9904a..ac8d6dcf3 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/AbstractChallenge.java @@ -158,16 +158,9 @@ protected MessageKey getChallengeMessageKey(@NotNull String keySuffix) { @Override public ItemBuilder getSettingsItem(@NotNull Locale locale) { ItemStack preset = isEnabled() ? getSettingsItemPreset() : getDisabledSettingsItemPreset(); - // apply formatting dynamically, to prevent duplicate format references - ItemBuilder item = new ItemBuilder(locale, preset, MessageKey.of("challenge.settings-format"), - isEnabled() ? getSettingsName() : MessageKey.of("generic.disabled")); // no need to override disabled name/item - - LocalizableMessage description = getSettingsDescription(); - if (description != null && isEnabled()) { - item.appendLore(MessageKey.of("challenge.settings-format-lore"), description); - } - - return item; + Object nameArg = isEnabled() ? getSettingsName() : ChallengeHelper.getChallengeDisabledName(); + LocalizableMessage description = isEnabled() ? getSettingsDescription() : null; + return DefaultItems.createChallengeSettingFormat(preset, nameArg, description, locale); } @NotNull diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java index 60276e4ea..66b858c95 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/Modifier.java @@ -3,7 +3,6 @@ import net.codingarea.challenges.plugin.Challenges; import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; -import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.menu.info.ChallengeMenuClickInfo; @@ -51,7 +50,7 @@ public ItemStack getSettingsItemPreset() { @NotNull @Override public Object getSettingsName() { - return MessageKey.of("challenge.settings-modifier-value").withArgs(value); + return ChallengeHelper.getSettingsDescriptionModifierValue(value); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index c5ec33c6b..13e6865d4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -214,12 +214,24 @@ public static void playChallengeMinutesValueChangeTitle(@NotNull AbstractChallen playChallengeValueTitle(challenge, Message.forName("subtitle-time-minutes").asString(seconds)); } + @NotNull + @Contract(pure = true) + public static LocalizableMessage getSettingsDescriptionModifierValue(int value) { + return MessageKey.of("challenge.settings-modifier-value").withArgs(value); + } + @NotNull @Contract(pure = true) public static LocalizableMessage getSettingsDescriptionModifierMultiplier(int value) { return MessageKey.of("challenge.settings-modifier-multiplier").withArgs(value); } + @NotNull + @Contract(pure = true) + public static LocalizableMessage getSettingsDescriptionModifierStrength(int value) { + return MessageKey.of("challenge.settings-modifier-strength").withArgs(value); + } + @NotNull @Contract(pure = true) public static LocalizableMessage getSettingsDescriptionIntervalSecondsRange(int baseSeconds, int rangeSecondsAround) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java index c33ab7af4..99ebf7a59 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/SubSettingsHelper.java @@ -4,9 +4,9 @@ import net.codingarea.challenges.plugin.challenges.custom.settings.sub.SubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.ChooseItemSubSettingsBuilder; import net.codingarea.challenges.plugin.challenges.custom.settings.sub.builder.ChooseMultipleItemSubSettingBuilder; +import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; -import net.codingarea.challenges.plugin.content.legacy.Message; -import net.codingarea.challenges.plugin.utils.item.LegacyItemBuilder; +import net.codingarea.challenges.plugin.content.i18n.MessageKey; import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.StructureUtils; import net.codingarea.commons.bukkit.utils.item.StandardItemBuilder; @@ -112,19 +112,16 @@ public static SubSettingsBuilder createEntityTargetSettingsBuilder(boolean every public static SubSettingsBuilder createPotionSettingsBuilder(boolean potionType, boolean potionTime) { SubSettingsBuilder potionSettings = SubSettingsBuilder.createValueItem().fill(builder -> { - // TODO also port if (potionTime) { - builder.addModifierSetting("length", new LegacyItemBuilder(Material.CLOCK, - Message.forName("item-random-effect-length-challenge")), - 30, 1, 60, - value -> "", - value -> Message.forName(value == 1 ? "second" : "seconds").asString()); + builder.addModifierSetting("length", + new ItemStack(Material.CLOCK), MessageKey.of("custom.action.potion_effect.sub.length"), + 30, 1, 60, ArgumentFormat.TIME + ); } - builder.addModifierSetting("amplifier", new LegacyItemBuilder(Material.STONE_SWORD, - Message.forName("item-random-effect-amplifier-challenge")), - 3, 1, 8, - value -> Message.forName("amplifier").asString(), - integer -> ""); + builder.addModifierSetting("amplifier", + new ItemStack(Material.STONE_SWORD), MessageKey.of("custom.action.potion_effect.sub.amplifier"), + 3, 1, 8, ChallengeHelper::getSettingsDescriptionModifierStrength // TOOD correct translation! + ); }); if (potionType) { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java index 54e2d08c6..4e734bf38 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java @@ -19,7 +19,7 @@ import java.util.Map; import java.util.function.Function; -public interface ArgumentFormat { +public interface ArgumentFormat extends Function { @NotNull LocalizableMessage apply(@NotNull T arg); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java index a6febe665..de0eed240 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/CustomChallengeMenuGenerator.java @@ -106,7 +106,7 @@ public void updateInventoryContent(@NotNull Inventory inventory, @NotNull Locale ItemBuilder triggerItem = new ItemBuilder(locale, Material.WITHER_SKELETON_SKULL, MessageKey.of("menu.custom.info.item-trigger"), triggerName); if (trigger != null) { - appendSubSettingDisplay(triggerItem, trigger.getSubSettingsBuilder().getCurrentDisplayFor(subTriggers)); + appendSubSettingDisplay(triggerItem, trigger.getSubSettingsBuilder().collectCurrentDisplayFor(subTriggers)); } inventory.setItem(CONDITION_SLOT, triggerItem.build()); @@ -115,7 +115,7 @@ public void updateInventoryContent(@NotNull Inventory inventory, @NotNull Locale ItemBuilder actionItem = new ItemBuilder(locale, Material.NETHER_STAR, MessageKey.of("menu.custom.info.item-action"), actionName); if (action != null) { - appendSubSettingDisplay(actionItem, action.getSubSettingsBuilder().getCurrentDisplayFor(subActions)); + appendSubSettingDisplay(actionItem, action.getSubSettingsBuilder().collectCurrentDisplayFor(subActions)); } inventory.setItem(ACTION_SLOT, actionItem.build()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java index 1a7486c39..6d58cbe8e 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/management/menu/generator/impl/custom/choose/CustomChooseValueMenuGenerator.java @@ -51,14 +51,14 @@ public LocalizableMessage getMenuName() { @Override protected void setElementItemsAt(@NotNull ValueSetting element, @NotNull Inventory inventory, int slot, @NotNull Locale locale) { String value = settings.get(element); - inventory.setItem(slot, element.getDisplayItem(value).build()); - inventory.setItem(slot + 9, element.getSettingsItem(value).build()); + inventory.setItem(slot, element.getDisplayItem(value, locale).build()); + inventory.setItem(slot + 9, element.getSettingsItem(value, locale).build()); } @NotNull @Override public ItemStack createDisplayItem(@NotNull ValueSetting element, @NotNull Locale locale) { - return element.getDisplayItem(settings.get(element)).build(); + return element.getDisplayItem(settings.get(element), locale).build(); } @Override diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java index d0d0ca502..745e8c619 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/spigot/command/SearchCommand.java @@ -10,7 +10,6 @@ import net.codingarea.challenges.plugin.utils.misc.ExperimentalUtils; import net.codingarea.challenges.plugin.utils.misc.Utils; import net.codingarea.commons.bukkit.utils.item.ItemUtils; -import net.codingarea.commons.common.misc.StringUtils; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; @@ -57,7 +56,6 @@ public void onCommand(@NotNull CommandSender sender, @NotNull String[] args) thr if (blocks.isEmpty()) { MessageKey.of("command-search-nothing").send(sender, Prefix.CHALLENGES, material); } else { - System.out.println(blocks); MessageKey.of("command-search-result").send(sender, Prefix.CHALLENGES, material, LocalizableMessage.joinList(blocks)); } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java index 4133da0c9..8cc07627d 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/utils/item/DefaultItems.java @@ -47,6 +47,18 @@ public static ItemBuilder createChallengeDisplayFormat(@NotNull ItemStack displa return new ItemBuilder(locale, displayItemPreset, MessageKey.of("challenge.display-format"), name, desc); } + public static ItemBuilder createChallengeSettingFormat(@NotNull ItemStack displayItemPreset, @NotNull Object nameArgument, + @Nullable LocalizableMessage desc, @NotNull Locale locale) { + // apply formatting dynamically, to prevent duplicate format references + ItemBuilder item = new ItemBuilder(locale, displayItemPreset, MessageKey.of("challenge.settings-format"), nameArgument); + + if (desc != null) { + item.appendLore(MessageKey.of("challenge.settings-format-lore"), desc); + } + + return item; + } + @Contract("_, _, _ -> new") public static ItemBuilder createMenuDisplayFormat(@NotNull ItemStack displayItemPreset, @NotNull Object nameArg, @NotNull Locale locale) { return new ItemBuilder(locale, displayItemPreset, MessageKey.of("menu.item-format"), nameArg); From d232953da079f590b376cca2780a30cb388d634e Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Fri, 17 Jul 2026 00:23:40 +0200 Subject: [PATCH 118/119] fix: parse new minecraft/paper version pattern correctly --- .../bukkit/utils/misc/MinecraftVersion.java | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java index 289d07d43..a5d339ff2 100644 --- a/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java +++ b/plugin/src/main/java/net/codingarea/commons/bukkit/utils/misc/MinecraftVersion.java @@ -2,7 +2,6 @@ import net.codingarea.commons.common.version.Version; import org.bukkit.Bukkit; -import org.jetbrains.annotations.CheckReturnValue; import org.jetbrains.annotations.NotNull; public enum MinecraftVersion implements Version { @@ -87,13 +86,6 @@ public String toString() { return this.format(); } - @NotNull - @CheckReturnValue - public static Version parseExact(@NotNull String bukkitVersion) { - bukkitVersion = bukkitVersion.substring(0, bukkitVersion.indexOf("-")); - return Version.parse(bukkitVersion); - } - @NotNull public static MinecraftVersion findNearest(@NotNull Version realVersion) { MinecraftVersion[] versions = values(); // ascending order @@ -109,7 +101,7 @@ public static MinecraftVersion findNearest(@NotNull Version realVersion) { @NotNull public static Version currentExact() { - if (currentExact == null) currentExact = parseExact(Bukkit.getBukkitVersion()); + if (currentExact == null) currentExact = Version.parse(getMinecraftVersionString()); return currentExact; } @@ -119,4 +111,15 @@ public static MinecraftVersion current() { return current; } + @NotNull + public static String getMinecraftVersionString() { + try { + // available since 1.19 + return Bukkit.getMinecraftVersion(); + } catch (Error _) { + String bukkitVersion = Bukkit.getBukkitVersion(); + return bukkitVersion.substring(0, bukkitVersion.indexOf("-")); + } + } + } From b17b9dcda1b66c6bbebe3b24d514a4cd38e22f05 Mon Sep 17 00:00:00 2001 From: Angelo <60273047+anweisen@users.noreply.github.com> Date: Fri, 17 Jul 2026 01:02:27 +0200 Subject: [PATCH 119/119] refactor: migrate localization usage (part 11) [WIP] --- language/locales/de.json | 200 ++++++++++++++---- language/locales/global.json | 19 +- .../damage/AdvancementDamageChallenge.java | 11 +- .../damage/BlockBreakDamageChallenge.java | 15 +- .../damage/BlockPlaceDamageChallenge.java | 16 +- .../damage/DamagePerBlockChallenge.java | 15 +- .../challenge/damage/JumpDamageChallenge.java | 11 +- .../damage/WaterAllergyChallenge.java | 15 +- .../entities/MobSightDamageChallenge.java | 11 +- .../extraworld/JumpAndRunChallenge.java | 1 - .../challenge/movement/MoveMouseDamage.java | 12 +- .../challenge/world/AnvilRainChallenge.java | 72 +++---- .../forcebattle/ForceDamageBattleGoal.java | 3 +- .../forcebattle/ForcePositionBattleGoal.java | 19 +- .../setting/LanguageSetting.java | 5 + .../type/abstraction/ForceBattleGoal.java | 18 +- .../type/abstraction/menu/MenuSetting.java | 96 ++++++--- .../type/helper/ChallengeHelper.java | 44 ++-- .../plugin/content/i18n/ArgumentFormat.java | 10 + 19 files changed, 368 insertions(+), 225 deletions(-) diff --git a/language/locales/de.json b/language/locales/de.json index a6946b532..b23a7d2cb 100644 --- a/language/locales/de.json +++ b/language/locales/de.json @@ -13,6 +13,10 @@ "days": "Tage", "time": "Zeit", "interval": "Intervall", + "chunk": "Chunk", + "chunks": "Chunks", + "block": "Block", + "blocks": "Blöcke", "disabled": "Deaktiviert", "enabled": "Aktiviert", "customize": "Anpassen", @@ -345,6 +349,7 @@ "settings-modifier-max-health": "Maximale Leben: {0}", "settings-modifier-damage": "Schaden: {0}", "settings-modifier-strength": "Stärke: {0}", + "settings-modifier-radius": "Umkreis: {0}", "difficulty": { "name": "*Schwierigkeit*", "desc": [ @@ -1105,10 +1110,41 @@ } }, "anvil-rain": { - "name": "*Amboss Regen*", + "name": "*{@menu}*", "desc": [ "Vom *Himmel* fallen *Ambosse*" - ] + ], + "menu": "Amboss Regen", + "sub": { + "time": { + "name": "*Intervall*", + "desc": [ + "Das *Intervall*, in", + "dem *Ambosse* spawnen" + ] + }, + "range": { + "name": "*Umkreis*", + "desc": [ + "Die *Reichweite*, in", + "der *Ambosse* spawnen" + ] + }, + "count": { + "name": "*Anzahl*", + "desc": [ + "Die *Anzahl*, an *Ambossen*,", + "die in einem *Chunk* spawnen" + ] + }, + "damage": { + "name": "*Schaden*", + "desc": [ + "Der *Schaden*, den", + "die *Ambosse* machen" + ] + } + } }, "tsunami": { "name": "*Tsunami*", @@ -2014,76 +2050,169 @@ "custom": { "trigger": { "interval": { - "name": "*Intervall*" + "name": "*Intervall*", + "desc": [ + "Die Aktion wird *regelmäßig*", + "im gewählten Intervall *ausgeführt*" + ] }, "jump": { - "name": "*Spieler springt*" + "name": "*Spieler springt*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler *springt*" + ] }, "sneak": { - "name": "*Spieler schleicht*" + "name": "*Spieler schleicht*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler *anfängt zu schleichen*" + ] }, "move_block": { - "name": "*Spieler läuft einen Block*" + "name": "*Spieler läuft einen Block*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler *einen Block wechselt*" + ] }, "death": { - "name": "*Entity stirbt*" + "name": "*Entity stirbt*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn eine *Kreatur stirbt*" + ] }, "damage": { - "name": "*Entity erleidet Schaden*" + "name": "*Entity erleidet Schaden*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn eine *Kreatur Schaden erleidet*" + ] }, "item-custom-trigger-damage-any": [ "Jeglicher Grund" ], "damage_by_player": { - "name": "*Entity bekommt Schaden von Spieler*" + "name": "*Entity bekommt Schaden von Spieler*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn eine *Kreatur Schaden von einem Spieler* erleidet" + ] }, "block_place": { - "name": "*Block platziert*" + "name": "*Block platziert*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler einen *Block platziert*" + ] }, "block_break": { - "name": "*Block zerstört*" + "name": "*Block zerstört*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler einen *Block abbaut*" + ] }, "consume_item": { - "name": "*Item konsumieren*" + "name": "*Item konsumieren*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler ein *essbares Item konsumiert*" + ] }, "pickup_item": { - "name": "*Item aufheben*" + "name": "*Item aufheben*", + "desc": [ + "Die Aktion wird für *jedes* anklicken oder aufheben ausgeführt" + ] }, "drop_item": { - "name": "*Spieler droppt Item*" + "name": "*Spieler droppt Item*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler ein *Item droppt*" + ] }, "advancement": { - "name": "*Spieler erhält Errungenschaft*" + "name": "*Spieler erhält Errungenschaft*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler eine neue *Errungenschaft* erhält" + ] }, "hunger": { - "name": "*Spieler verliert Hunger*" + "name": "*Spieler verliert Sättigung*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler *Sättigung verliert* bzw. *Hunger bekommt*" + ] }, "move_down": { - "name": "*Block nach unten bewegen*" + "name": "*Block nach unten bewegen*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler *einen Block nach unten* geht" + ] }, "move_up": { - "name": "*Block nach oben bewegen*" + "name": "*Block nach oben bewegen*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler *einen Block nach oben* geht" + ] }, "move_camera": { - "name": "*Kamera bewegen*" + "name": "*Kamera bewegen*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler *seinen Kopf dreht*" + ] }, "stands_on_specific_block": { - "name": "*Spieler ist auf bestimmten Block*" + "name": "*Spieler ist auf bestimmten Block*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler sich einen *ganzen Block bewegt*", + "und auf einem *bestimmten Block* steht" + ] }, "stands_not_on_specific_block": { - "name": "*Spieler ist nicht auf bestimmten Block*" + "name": "*Spieler ist nicht auf bestimmten Block*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler sich einen *ganzen Block bewegt*", + "und *nicht* auf einem *bestimmten Block* steht" + ] }, "gain_xp": { - "name": "*Spieler bekommt XP*" + "name": "*Spieler bekommt XP*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler *XP bekommt*" + ] }, "level_up": { - "name": "*Spieler levelt auf*" + "name": "*Spieler levelt auf*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler *ein Level aufsteigt*" + ] }, "item_craft": { - "name": "*Spieler craftet Item*" + "name": "*Spieler craftet Item*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler ein *Item herstellt*" + ] }, "in_liquid": { - "name": "*Spieler in Flüssigkeit*" + "name": "*Spieler in Flüssigkeit*", + "desc": [ + "Die Aktion wird *jedes Mal* ausgeführt,", + "wenn ein Spieler eine *Flüssigkeit* betritt" + ] }, "get_item": { "name": "*Item bekommen*", @@ -2766,27 +2895,6 @@ "Die *Stärke*, die der", "*Effekt* hat" ], - "menu-anvil-rain-challenge-settings": "Amboss Regen", - "item-anvil-rain-time-challenge": [ - "Intervall", - "Das *Intervall*, in", - "dem *Ambosse* spawnen" - ], - "item-anvil-rain-range-challenge": [ - "Range", - "Die *Reichweite*, in", - "der *Ambosse* spawnen" - ], - "item-anvil-rain-count-challenge": [ - "Anzahl", - "Die *Anzahl*, an *Ambossen*,", - "die in einem *Chunk* spawnen" - ], - "item-anvil-rain-damage-challenge": [ - "Schaden", - "Der *Schaden*, die", - "die *Ambosse* machen" - ], "item-collect-wood-goal-overworld": "Overworld", "item-collect-wood-goal-nether": "Nether", "item-collect-wood-goal-both": "Beide", diff --git a/language/locales/global.json b/language/locales/global.json index 77154330c..08e46fc76 100644 --- a/language/locales/global.json +++ b/language/locales/global.json @@ -28,7 +28,8 @@ "damage-cause": "{0}", "damage-cause-source": "{0} ({1})", "time": "{0} {1}", - "time-range": "{@time} {@symbol.plus-minus} {@time('{2}', '{3}')}" + "time-range": "{@time} {@symbol.plus-minus} {@time('{2}', '{3}')}", + "radius": "{0} {1}" }, "prefix": { "format": "{@symbol.vertical} {0} {@symbol.vertical} ", @@ -507,7 +508,21 @@ } }, "anvil-rain": { - "*colorize*": "{0}" + "*colorize*": "{0}", + "sub": { + "time": { + "*colorize*": "{0}" + }, + "range": { + "*colorize*": "{0}" + }, + "count": { + "*colorize*": "{0}" + }, + "damage": { + "*colorize*": "{0}" + } + } }, "tsunami": { "*colorize*": "{0}" diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java index e6e2d107a..de291b148 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/AdvancementDamageChallenge.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; @@ -17,15 +18,9 @@ public AdvancementDamageChallenge() { super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 40, new ItemStack(Material.BOOK), "advancement-damage"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionDamage(getValue()); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java index 31979f563..6da93e9ba 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockBreakDamageChallenge.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; @@ -15,11 +16,10 @@ public BlockBreakDamageChallenge() { super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 60, new ItemStack(Material.GOLDEN_PICKAXE), "block-break-damage"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); -// } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionDamage(getValue()); + } @EventHandler public void onBreak(BlockBreakEvent event) { @@ -28,9 +28,4 @@ public void onBreak(BlockBreakEvent event) { event.getPlayer().damage(getValue()); } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java index 1583d7af6..c5f3007d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/BlockPlaceDamageChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import org.bukkit.Material; @@ -17,12 +18,10 @@ public BlockPlaceDamageChallenge() { super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 60, new ItemStack(Material.GOLD_BLOCK), "block-place-damage"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); -// } - + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionDamage(getValue()); + } @EventHandler public void onBreak(BlockPlaceEvent event) { @@ -31,9 +30,4 @@ public void onBreak(BlockPlaceEvent event) { event.getPlayer().damage(getValue()); } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java index 8c91c8b73..06e61cdc4 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/DamagePerBlockChallenge.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.utils.misc.BlockUtils; @@ -20,11 +21,10 @@ public DamagePerBlockChallenge() { "damage-per-block"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); -// } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionDamage(getValue()); + } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onMove(@NotNull PlayerMoveEvent event) { @@ -36,9 +36,4 @@ public void onMove(@NotNull PlayerMoveEvent event) { event.getPlayer().damage(getValue()); } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java index 69ced2d66..e785f5839 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/JumpDamageChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; @@ -22,15 +23,9 @@ public JumpDamageChallenge() { "jump-damage"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() / 2); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionDamage(getValue()); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java index d3df9b29e..87a72ecbd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/damage/WaterAllergyChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; @@ -18,11 +19,10 @@ public WaterAllergyChallenge() { super(MenuType.CHALLENGES, SettingCategory.DAMAGE, 1, 40, new ItemStack(Material.CYAN_GLAZED_TERRACOTTA), "water-allergy"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); -// } + @Override + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionDamage(getValue()); + } @ScheduledTask(ticks = 5, async = false) public void onFifthTick() { @@ -34,9 +34,4 @@ public void onFifthTick() { } } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); - } - } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java index 515d5113d..4fbc7f984 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/entities/MobSightDamageChallenge.java @@ -3,6 +3,7 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; @@ -22,15 +23,9 @@ public MobSightDamageChallenge() { super(MenuType.CHALLENGES, SettingCategory.ENTITIES, new ItemStack(Material.SPIDER_EYE), "mob-sight-damage"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionDamage(getValue()); } @ScheduledTask(ticks = 1, async = false) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java index a0e40909f..5cb539c44 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/extraworld/JumpAndRunChallenge.java @@ -32,7 +32,6 @@ import java.util.List; import java.util.UUID; -@Updated("2.4") public class JumpAndRunChallenge extends WorldDependentChallenge { private final List lastPlayers = new ArrayList<>(); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java index d8de5a179..84d7ca7a9 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/movement/MoveMouseDamage.java @@ -3,12 +3,12 @@ import net.codingarea.challenges.plugin.challenges.type.abstraction.SettingModifier; import net.codingarea.challenges.plugin.challenges.type.annotation.Since; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; +import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.Prefix; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; -import net.codingarea.challenges.plugin.utils.misc.NameHelper; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -29,15 +29,9 @@ public MoveMouseDamage() { super(MenuType.CHALLENGES, SettingCategory.MOVEMENT, 60, new ItemStack(Material.COMPASS), "no-mouse-move"); } -// @Nullable -// @Override -// protected String[] getSettingsDescription() { -// return Message.forName("item-heart-damage-description").asArray(getValue() / 2f); -// } - @Override - public void playValueChangeTitle() { - ChallengeHelper.playChallengeHeartsValueChangeTitle(this, getValue() / 2); + public LocalizableMessage getSettingsDescription() { + return ChallengeHelper.getSettingsDescriptionDamage(getValue()); } @ScheduledTask(ticks = 1, timerPolicy = TimerPolicy.ALWAYS) diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java index 40cacb6a2..bf370c8d7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/challenge/world/AnvilRainChallenge.java @@ -1,6 +1,7 @@ package net.codingarea.challenges.plugin.challenges.implementation.challenge.world; import net.codingarea.challenges.plugin.challenges.type.abstraction.menu.MenuSetting; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.management.menu.MenuType; import net.codingarea.challenges.plugin.management.menu.SettingCategory; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; @@ -26,42 +27,29 @@ public class AnvilRainChallenge extends MenuSetting { private final Random random = new Random(); int currentTime = 0; + private final NumberSubSetting timeSetting; + private final NumberSubSetting countSetting; + private final NumberSubSetting rangeSetting; + private final NumberSubSetting damageSetting; + public AnvilRainChallenge() { super(MenuType.CHALLENGES, SettingCategory.WORLD, new ItemStack(Material.ANVIL), "anvil-rain"); -// registerSetting("time", new NumberSubSetting( -// () -> new LegacyItemBuilder(Material.CLOCK, Message.forName("item-anvil-rain-time-challenge")), -// value -> null, -// value -> "§e" + value + " §7" + Message.forName(value == 1 ? "second" : "seconds").asString(), -// 1, -// 30, -// 7 -// ) -// ); -// registerSetting("count", new NumberSubSetting( -// () -> new LegacyItemBuilder(Material.FLINT, Message.forName("item-anvil-rain-count-challenge")), -// 1, -// 30, -// 8 -// ) -// ); -// registerSetting("range", new NumberSubSetting( -// () -> new LegacyItemBuilder(Material.COMPASS, Message.forName("item-anvil-rain-range-challenge")), -// value -> null, -// value -> "§e" + value + " §7" + (value == 1 ? "chunk" : "chunks"), -// 1, -// 3, -// 2 -// ) -// ); -// registerSetting("damage", new NumberSubSetting( -// () -> new LegacyItemBuilder(Material.IRON_SWORD, Message.forName("item-anvil-rain-damage-challenge")), -// value -> null, -// value -> "§e" + Display.HEARTS.formatChat(value), -// 1, -// 60, -// 30 -// ) -// ); + timeSetting = registerSetting("time", new NumberSubSetting( + new ItemStack(Material.CLOCK), getChallengeMessageKey("sub.time"), + 1, 30, 7, ChallengeHelper::getSettingsDescriptionIntervalSeconds + )); + countSetting = registerSetting("count", new NumberSubSetting( + new ItemStack(Material.FLINT), getChallengeMessageKey("sub.count"), + 1, 30, 8 + )); + rangeSetting = registerSetting("range", new NumberSubSetting( + new ItemStack(Material.COMPASS), getChallengeMessageKey("sub.range"), + 1, 3, 2, ChallengeHelper::getSettingsDescriptionRadiusChunks + )); + damageSetting = registerSetting("damage", new NumberSubSetting( + new ItemStack(Material.IRON_SWORD), getChallengeMessageKey("sub.damage"), + 1, 60, 30, ChallengeHelper::getSettingsDescriptionDamage + )); } @Override @@ -89,7 +77,7 @@ private void removeAnvils() { public void onSecond() { currentTime++; - if (currentTime > getSetting("time").getAsInt()) { + if (currentTime > getTime()) { currentTime = 0; handleTimeActivation(); } @@ -105,7 +93,7 @@ private void handleTimeActivation() { for (Chunk targetChunk : targetChunks) { if (chunks.contains(targetChunk)) continue; chunks.add(targetChunk); - spawnAnvils(targetChunk, getHeight(player.getLocation().getBlockY())); + spawnAnvils(targetChunk, getAnvilHeight(player.getLocation().getBlockY())); } } @@ -201,19 +189,23 @@ public void applyDamageToNearEntities(@NotNull Location location) { } + private int getTime() { + return timeSetting.getAsInt(); + } + private int getRange() { - return getSetting("range").getAsInt(); + return rangeSetting.getAsInt(); } private int getCount() { - return getSetting("count").getAsInt(); + return countSetting.getAsInt(); } private int getDamage() { - return getSetting("damage").getAsInt(); + return damageSetting.getAsInt(); } - private int getHeight(int currentHeight) { + private int getAnvilHeight(int currentHeight) { return currentHeight + 50; } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java index 4dd5ec687..8c28d1b8b 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForceDamageBattleGoal.java @@ -55,8 +55,7 @@ protected boolean shouldRegisterDupedTargetsSetting() { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onDamage(@NotNull EntityDamageEvent event) { if (!shouldExecuteEffect()) return; - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); + if (!(event.getEntity() instanceof Player player)) return; if (ignorePlayer(player)) return; if (currentTarget.get(player.getUniqueId()) == null) return; DamageTarget target = currentTarget.get(player.getUniqueId()); diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java index cf08a8a5b..fb09b0bbf 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/goal/forcebattle/ForcePositionBattleGoal.java @@ -2,6 +2,7 @@ import net.codingarea.challenges.plugin.challenges.implementation.goal.forcebattle.targets.PositionTarget; import net.codingarea.challenges.plugin.challenges.type.abstraction.ForceBattleGoal; +import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.scheduler.policy.TimerPolicy; import net.codingarea.challenges.plugin.management.scheduler.task.ScheduledTask; @@ -14,17 +15,15 @@ import java.util.stream.Collectors; public class ForcePositionBattleGoal extends ForceBattleGoal { + + private final NumberSubSetting radiusSetting; + public ForcePositionBattleGoal() { -// super(Message.forName("menu-force-position-battle-goal-settings")); super(new ItemStack(Material.DIAMOND_BOOTS), "force-position-battle"); -// registerSetting("radius", new NumberSubSetting( -// () -> new LegacyItemBuilder(Material.DIAMOND_BOOTS, Message.forName("item-force-position-battle-radius")), -// value -> null, -// value -> "§e" + (value * 100), -// 1, -// 100, -// 15 -// )); + radiusSetting = registerSetting("radius", new NumberSubSetting( + new ItemStack(Material.DIAMOND_BOOTS), getChallengeMessageKey("sub.radius"), + 1, 100, 15, value -> ChallengeHelper.getSettingsDescriptionRadiusBlocks(value * 100) + )); } @Override @@ -72,6 +71,6 @@ public void checkPositions() { } protected int getRadius() { - return getSetting("radius").getAsInt() * 100; + return radiusSetting.getAsInt() * 100; } } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java index 28ea899b6..d26f86619 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/implementation/setting/LanguageSetting.java @@ -97,6 +97,11 @@ protected void onValueChange() { }); } + @Override + public void restoreDefaults() { + // "/reset settings" should not reset the chosen language + } + @Override public void loadSettings(@NotNull Document document) { // will be saved in plugin.yml diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java index 0720ed259..c7755c4b7 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/ForceBattleGoal.java @@ -47,22 +47,28 @@ public abstract class ForceBattleGoal> extends MenuGoal protected T[] targetsPossibleToFind; private ItemStack jokerItem; + protected final NumberSubSetting jokerCountSetting; + protected final BooleanSubSetting scoreboardSetting; + protected final BooleanSubSetting dupedTargetsSetting; + public ForceBattleGoal(@NotNull ItemStack displayItemPreset, @NotNull String nameMessageKey) { super(MenuType.GOAL, SettingCategory.FORCE_BATTLE, displayItemPreset, nameMessageKey); - registerSetting("jokers", new NumberSubSetting( + jokerCountSetting = registerSetting("jokers", new NumberSubSetting( new ItemStack(Material.BARRIER), MessageKey.of("challenge.force-battles.sub.goal-jokers"), 1, 32, 5 )); - registerSetting("showScoreboard", new BooleanSubSetting( + scoreboardSetting = registerSetting("showScoreboard", new BooleanSubSetting( new ItemStack(Material.BOOK), MessageKey.of("challenge.force-battles.sub.scoreboard"), true )); if (shouldRegisterDupedTargetsSetting()) { - registerSetting("dupedTargets", new BooleanSubSetting( + dupedTargetsSetting = registerSetting("dupedTargets", new BooleanSubSetting( new ItemStack(Material.PAPER), MessageKey.of("challenge.force-battles.sub.duped-targets"), true )); + } else { + dupedTargetsSetting = null; } } @@ -214,7 +220,7 @@ public void setRandomTarget(Player player) { protected T getRandomTarget(Player player) { LinkedList list = new LinkedList<>(Arrays.asList(targetsPossibleToFind)); - if (!getSetting("dupedTargets").getAsBoolean()) { + if (shouldRegisterDupedTargetsSetting() && !dupedTargetsSetting.getAsBoolean()) { list.removeAll(foundTargets.getOrDefault(player.getUniqueId(), new LinkedList<>())); } if (!list.isEmpty()) { @@ -433,11 +439,11 @@ public void onPlace(BlockPlaceEvent event) { } private int getJokers() { - return getSetting("jokers").getAsInt(); + return jokerCountSetting.getAsInt(); } private boolean showScoreboard() { - return getSetting("showScoreboard").getAsBoolean(); + return scoreboardSetting.getAsBoolean(); } protected boolean shouldRegisterDupedTargetsSetting() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java index 1eca73ce7..ac9c4a0ca 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/abstraction/menu/MenuSetting.java @@ -2,6 +2,7 @@ import lombok.Getter; import net.codingarea.challenges.plugin.Challenges; +import net.codingarea.challenges.plugin.challenges.type.IModifier; import net.codingarea.challenges.plugin.challenges.type.abstraction.Setting; import net.codingarea.challenges.plugin.challenges.type.helper.ChallengeHelper; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; @@ -22,6 +23,7 @@ import java.util.Locale; import java.util.Map; import java.util.Map.Entry; +import java.util.function.Function; public abstract class MenuSetting extends Setting { @@ -254,26 +256,31 @@ protected void onDisable() { } - public class NumberSubSetting extends SubSetting { + public class NumberSubSetting extends SubSetting implements IModifier { + private final Function settingsNameGetter; private final int max, min; private final int defaultValue; @Getter private int value; - public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace) { - this(displayItemPreset, nameMessageKeySpace, 64); + public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, + @NotNull Function settingsNameGetter) { + this(displayItemPreset, nameMessageKeySpace, 64, settingsNameGetter); } - public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int max) { - this(displayItemPreset, nameMessageKeySpace, max, 1); + public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int max, + @NotNull Function settingsNameGetter) { + this(displayItemPreset, nameMessageKeySpace, max, 1, settingsNameGetter); } - public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int min, int max) { - this(displayItemPreset, nameMessageKeySpace, min, max, min); + public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int min, int max, + @NotNull Function settingsNameGetter) { + this(displayItemPreset, nameMessageKeySpace, min, max, min, settingsNameGetter); } - public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int min, int max, int defaultValue) { + public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int min, int max, int defaultValue, + @NotNull Function settingsNameGetter) { super(displayItemPreset, nameMessageKeySpace); if (max <= min) throw new IllegalArgumentException("max <= min"); if (min < 0) throw new IllegalArgumentException("min < 0"); @@ -283,6 +290,23 @@ public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKe this.defaultValue = defaultValue; this.max = max; this.min = min; + this.settingsNameGetter = settingsNameGetter; + } + + public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace) { + this(displayItemPreset, nameMessageKeySpace, ChallengeHelper::getSettingsDescriptionModifierValue); + } + + public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int max) { + this(displayItemPreset, nameMessageKeySpace, max, ChallengeHelper::getSettingsDescriptionModifierValue); + } + + public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int min, int max) { + this(displayItemPreset, nameMessageKeySpace, min, max, ChallengeHelper::getSettingsDescriptionModifierValue); + } + + public NumberSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int min, int max, int defaultValue) { + this(displayItemPreset, nameMessageKeySpace, min, max, defaultValue, ChallengeHelper::getSettingsDescriptionModifierValue); } @NotNull @@ -291,6 +315,12 @@ public ItemStack getSettingsItemPreset() { return DefaultItems.createValuePreset(value); } + @NotNull + @Override + protected LocalizableMessage getSettingsName() { + return settingsNameGetter.apply(value); + } + @Override public void restoreDefaults() { this.setValue(defaultValue); @@ -304,7 +334,6 @@ public void setValue(int value) { onValueChange(); } - @Override public int getAsInt() { return value; @@ -317,21 +346,7 @@ public boolean getAsBoolean() { @Override public void handleClick(@NotNull ChallengeMenuClickInfo info) { - int amount = info.isShiftClick() ? 10 : 1; - int newValue = value; - if (info.isRightClick()) { - newValue -= amount; - } else { - newValue += amount; - } - - if (newValue > max) - newValue = min; - if (newValue < min) - newValue = max; - - this.setValue(newValue); - SoundSample.CLICK.play(info.getPlayer()); + ChallengeHelper.handleModifierClick(info, this); } @Override @@ -347,6 +362,19 @@ public void writeSettings(@NotNull Document document) { protected void onValueChange() { } + @Override + public final int getMinValue() { + return min; + } + + @Override + public final int getMaxValue() { + return max; + } + + @Override + public final void playValueChangeTitle() { + } } public class NumberAndBooleanSubSetting extends NumberSubSetting { @@ -354,6 +382,26 @@ public class NumberAndBooleanSubSetting extends NumberSubSetting { private final boolean enabledByDefault = false; // Implement in future private boolean enabled; + public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, + @NotNull Function settingsNameGetter) { + super(displayItemPreset, nameMessageKeySpace, settingsNameGetter); + } + + public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int max, + @NotNull Function settingsNameGetter) { + super(displayItemPreset, nameMessageKeySpace, max, settingsNameGetter); + } + + public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int min, int max, + @NotNull Function settingsNameGetter) { + super(displayItemPreset, nameMessageKeySpace, min, max, settingsNameGetter); + } + + public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace, int min, int max, int defaultValue, + @NotNull Function settingsNameGetter) { + super(displayItemPreset, nameMessageKeySpace, min, max, defaultValue, settingsNameGetter); + } + public NumberAndBooleanSubSetting(@NotNull ItemStack displayItemPreset, @NotNull MessageKey nameMessageKeySpace) { super(displayItemPreset, nameMessageKeySpace); } diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java index 13e6865d4..d6dc3f1b8 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/challenges/type/helper/ChallengeHelper.java @@ -11,7 +11,6 @@ import net.codingarea.challenges.plugin.content.i18n.ArgumentFormat; import net.codingarea.challenges.plugin.content.i18n.LocalizableMessage; import net.codingarea.challenges.plugin.content.i18n.MessageKey; -import net.codingarea.challenges.plugin.content.legacy.Message; import net.codingarea.challenges.plugin.management.menu.generator.IChallengesMenuGenerator; import net.codingarea.challenges.plugin.utils.misc.InventoryUtils; import net.codingarea.commons.bukkit.utils.animation.SoundSample; @@ -24,6 +23,7 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; +import org.bukkit.entity.TNTPrimed; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageModifier; import org.bukkit.inventory.Inventory; @@ -153,11 +153,14 @@ public static boolean ignoreDamager(@NotNull Entity damager) { return AbstractChallenge.ignorePlayer(damagerPlayer); } + @Nullable public static Player getDamagerPlayer(@NotNull Entity damager) { - if (damager instanceof Player) return ((Player) damager); - if (damager instanceof Projectile && ((Projectile) damager).getShooter() instanceof Player) - return ((Player) ((Projectile) damager).getShooter()); - return null; + return switch (damager) { + case Player player -> player; + case Projectile projectile when projectile.getShooter() instanceof Player shooter -> shooter; + case TNTPrimed tnt when tnt.getSource() instanceof Player source -> source; + default -> null; + }; } public static List getIngamePlayers() { @@ -199,21 +202,6 @@ public static void playChallengeHeartsValueChangeTitle(@NotNull Modifier modifie playChallengeHeartsValueChangeTitle(modifier, modifier.getValue()); } - @Deprecated - public static void playChallengeSecondsValueChangeTitle(@NotNull AbstractChallenge challenge, int seconds) { - playChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds").asString(seconds)); - } - - @Deprecated - public static void playChallengeSecondsRangeValueChangeTitle(@NotNull AbstractChallenge challenge, int min, int max) { - playChallengeValueTitle(challenge, Message.forName("subtitle-time-seconds-range").asString(min, max)); - } - - @Deprecated - public static void playChallengeMinutesValueChangeTitle(@NotNull AbstractChallenge challenge, int seconds) { - playChallengeValueTitle(challenge, Message.forName("subtitle-time-minutes").asString(seconds)); - } - @NotNull @Contract(pure = true) public static LocalizableMessage getSettingsDescriptionModifierValue(int value) { @@ -268,6 +256,22 @@ public static LocalizableMessage getSettingsDescriptionDamage(int hp) { return MessageKey.of("challenge.settings-modifier-damage").withArgs(ArgumentFormat.HP.apply(hp)); } + @NotNull + @Contract(pure = true) + public static LocalizableMessage getSettingsDescriptionRadiusChunks(int chunks) { + // TODO refactor + return MessageKey.of("challenge.settings-modifier-radius") + .withArgs(MessageKey.of("arg-format.radius").withArgs(chunks, MessageKey.pluralize("generic.chunk", chunks))); + } + + @NotNull + @Contract(pure = true) + public static LocalizableMessage getSettingsDescriptionRadiusBlocks(int blocks) { + // TODO refactor + return MessageKey.of("challenge.settings-modifier-radius") + .withArgs(MessageKey.of("arg-format.radius").withArgs(blocks, MessageKey.pluralize("generic.block", blocks))); + } + @NotNull @Contract(pure = true) public static LocalizableMessage getChallengeEnabledName() { diff --git a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java index 4e734bf38..573c8f3fd 100644 --- a/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java +++ b/plugin/src/main/java/net/codingarea/challenges/plugin/content/i18n/ArgumentFormat.java @@ -6,6 +6,7 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; +import org.bukkit.entity.TNTPrimed; import org.bukkit.event.entity.EntityDamageByBlockEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; @@ -108,6 +109,15 @@ public interface ArgumentFormat extends Function { } else { return MessageKey.of("arg-format.damage-cause").withArgs(projectile.getType()); } + } else if (damageEvent.getDamager() instanceof TNTPrimed tntPrimed) { + Entity source = tntPrimed.getSource(); + if (source instanceof Player sourcePlayer) { + return MessageKey.of("arg-format.damage-cause-source").withArgs(tntPrimed.getType(), sourcePlayer); + } else if (source instanceof Entity sourceEntity) { + return MessageKey.of("arg-format.damage-cause-source").withArgs(tntPrimed.getType(), sourceEntity.getType()); + } else { + return MessageKey.of("arg-format.damage-cause").withArgs(cause, tntPrimed.getType()); + } } else { return MessageKey.of("arg-format.damage-cause-source").withArgs(cause, damageEvent.getDamager().getType()); }